shrinker.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. // Copyright (c) 2019 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "source/fuzz/shrinker.h"
  15. #include <sstream>
  16. #include "source/fuzz/pseudo_random_generator.h"
  17. #include "source/fuzz/replayer.h"
  18. #include "source/spirv_fuzzer_options.h"
  19. #include "source/util/make_unique.h"
  20. namespace spvtools {
  21. namespace fuzz {
  22. namespace {
  23. // A helper to get the size of a protobuf transformation sequence in a less
  24. // verbose manner.
  25. uint32_t NumRemainingTransformations(
  26. const protobufs::TransformationSequence& transformation_sequence) {
  27. return static_cast<uint32_t>(transformation_sequence.transformation_size());
  28. }
  29. // A helper to return a transformation sequence identical to |transformations|,
  30. // except that a chunk of size |chunk_size| starting from |chunk_index| x
  31. // |chunk_size| is removed (or as many transformations as available if the whole
  32. // chunk is not).
  33. protobufs::TransformationSequence RemoveChunk(
  34. const protobufs::TransformationSequence& transformations,
  35. uint32_t chunk_index, uint32_t chunk_size) {
  36. uint32_t lower = chunk_index * chunk_size;
  37. uint32_t upper = std::min((chunk_index + 1) * chunk_size,
  38. NumRemainingTransformations(transformations));
  39. assert(lower < upper);
  40. assert(upper <= NumRemainingTransformations(transformations));
  41. protobufs::TransformationSequence result;
  42. for (uint32_t j = 0; j < NumRemainingTransformations(transformations); j++) {
  43. if (j >= lower && j < upper) {
  44. continue;
  45. }
  46. protobufs::Transformation transformation =
  47. transformations.transformation()[j];
  48. *result.mutable_transformation()->Add() = transformation;
  49. }
  50. return result;
  51. }
  52. } // namespace
  53. struct Shrinker::Impl {
  54. explicit Impl(spv_target_env env, uint32_t limit)
  55. : target_env(env), step_limit(limit) {}
  56. const spv_target_env target_env; // Target environment.
  57. MessageConsumer consumer; // Message consumer.
  58. const uint32_t step_limit; // Step limit for reductions.
  59. };
  60. Shrinker::Shrinker(spv_target_env env, uint32_t step_limit)
  61. : impl_(MakeUnique<Impl>(env, step_limit)) {}
  62. Shrinker::~Shrinker() = default;
  63. void Shrinker::SetMessageConsumer(MessageConsumer c) {
  64. impl_->consumer = std::move(c);
  65. }
  66. Shrinker::ShrinkerResultStatus Shrinker::Run(
  67. const std::vector<uint32_t>& binary_in,
  68. const protobufs::FactSequence& initial_facts,
  69. const protobufs::TransformationSequence& transformation_sequence_in,
  70. const Shrinker::InterestingnessFunction& interestingness_function,
  71. std::vector<uint32_t>* binary_out,
  72. protobufs::TransformationSequence* transformation_sequence_out) const {
  73. // Check compatibility between the library version being linked with and the
  74. // header files being used.
  75. GOOGLE_PROTOBUF_VERIFY_VERSION;
  76. spvtools::SpirvTools tools(impl_->target_env);
  77. if (!tools.IsValid()) {
  78. impl_->consumer(SPV_MSG_ERROR, nullptr, {},
  79. "Failed to create SPIRV-Tools interface; stopping.");
  80. return Shrinker::ShrinkerResultStatus::kFailedToCreateSpirvToolsInterface;
  81. }
  82. // Initial binary should be valid.
  83. if (!tools.Validate(&binary_in[0], binary_in.size())) {
  84. impl_->consumer(SPV_MSG_INFO, nullptr, {},
  85. "Initial binary is invalid; stopping.");
  86. return Shrinker::ShrinkerResultStatus::kInitialBinaryInvalid;
  87. }
  88. std::vector<uint32_t> current_best_binary;
  89. protobufs::TransformationSequence current_best_transformations;
  90. // Run a replay of the initial transformation sequence to (a) check that it
  91. // succeeds, (b) get the binary that results from running these
  92. // transformations, and (c) get the subsequence of the initial transformations
  93. // that actually apply (in principle this could be a strict subsequence).
  94. if (Replayer(impl_->target_env)
  95. .Run(binary_in, initial_facts, transformation_sequence_in,
  96. &current_best_binary, &current_best_transformations) !=
  97. Replayer::ReplayerResultStatus::kComplete) {
  98. return ShrinkerResultStatus::kReplayFailed;
  99. }
  100. // Check that the binary produced by applying the initial transformations is
  101. // indeed interesting.
  102. if (!interestingness_function(current_best_binary, 0)) {
  103. impl_->consumer(SPV_MSG_INFO, nullptr, {},
  104. "Initial binary is not interesting; stopping.");
  105. return ShrinkerResultStatus::kInitialBinaryNotInteresting;
  106. }
  107. uint32_t attempt = 0; // Keeps track of the number of shrink attempts that
  108. // have been tried, whether successful or not.
  109. uint32_t chunk_size =
  110. std::max(1u, NumRemainingTransformations(current_best_transformations) /
  111. 2); // The number of contiguous transformations that the
  112. // shrinker will try to remove in one go; starts
  113. // high and decreases during the shrinking process.
  114. // Keep shrinking until we:
  115. // - reach the step limit,
  116. // - run out of transformations to remove, or
  117. // - cannot make the chunk size any smaller.
  118. while (attempt < impl_->step_limit &&
  119. !current_best_transformations.transformation().empty() &&
  120. chunk_size > 0) {
  121. bool progress_this_round =
  122. false; // Used to decide whether to make the chunk size with which we
  123. // remove transformations smaller. If we managed to remove at
  124. // least one chunk of transformations at a particular chunk
  125. // size, we set this flag so that we do not yet decrease the
  126. // chunk size.
  127. assert(chunk_size <=
  128. NumRemainingTransformations(current_best_transformations) &&
  129. "Chunk size should never exceed the number of transformations that "
  130. "remain.");
  131. // The number of chunks is the ceiling of (#remaining_transformations /
  132. // chunk_size).
  133. const uint32_t num_chunks =
  134. (NumRemainingTransformations(current_best_transformations) +
  135. chunk_size - 1) /
  136. chunk_size;
  137. assert(num_chunks >= 1 && "There should be at least one chunk.");
  138. assert(num_chunks * chunk_size >=
  139. NumRemainingTransformations(current_best_transformations) &&
  140. "All transformations should be in some chunk.");
  141. // We go through the transformations in reverse, in chunks of size
  142. // |chunk_size|, using |chunk_index| to track which chunk to try removing
  143. // next. The loop exits early if we reach the shrinking step limit.
  144. for (int chunk_index = num_chunks - 1;
  145. attempt < impl_->step_limit && chunk_index >= 0; chunk_index--) {
  146. // Remove a chunk of transformations according to the current index and
  147. // chunk size.
  148. auto transformations_with_chunk_removed =
  149. RemoveChunk(current_best_transformations, chunk_index, chunk_size);
  150. // Replay the smaller sequence of transformations to get a next binary and
  151. // transformation sequence. Note that the transformations arising from
  152. // replay might be even smaller than the transformations with the chunk
  153. // removed, because removing those transformations might make further
  154. // transformations inapplicable.
  155. std::vector<uint32_t> next_binary;
  156. protobufs::TransformationSequence next_transformation_sequence;
  157. if (Replayer(impl_->target_env)
  158. .Run(binary_in, initial_facts, transformations_with_chunk_removed,
  159. &next_binary, &next_transformation_sequence) !=
  160. Replayer::ReplayerResultStatus::kComplete) {
  161. // Replay should not fail; if it does, we need to abort shrinking.
  162. return ShrinkerResultStatus::kReplayFailed;
  163. }
  164. assert(NumRemainingTransformations(next_transformation_sequence) >=
  165. chunk_index * chunk_size &&
  166. "Removing this chunk of transformations should not have an effect "
  167. "on earlier chunks.");
  168. if (interestingness_function(next_binary, attempt)) {
  169. // If the binary arising from the smaller transformation sequence is
  170. // interesting, this becomes our current best binary and transformation
  171. // sequence.
  172. current_best_binary = next_binary;
  173. current_best_transformations = next_transformation_sequence;
  174. progress_this_round = true;
  175. }
  176. // Either way, this was a shrink attempt, so increment our count of shrink
  177. // attempts.
  178. attempt++;
  179. }
  180. if (!progress_this_round) {
  181. // If we didn't manage to remove any chunks at this chunk size, try a
  182. // smaller chunk size.
  183. chunk_size /= 2;
  184. }
  185. // Decrease the chunk size until it becomes no larger than the number of
  186. // remaining transformations.
  187. while (chunk_size >
  188. NumRemainingTransformations(current_best_transformations)) {
  189. chunk_size /= 2;
  190. }
  191. }
  192. // The output from the shrinker is the best binary we saw, and the
  193. // transformations that led to it.
  194. *binary_out = current_best_binary;
  195. *transformation_sequence_out = current_best_transformations;
  196. // Indicate whether shrinking completed or was truncated due to reaching the
  197. // step limit.
  198. assert(attempt <= impl_->step_limit);
  199. if (attempt == impl_->step_limit) {
  200. std::stringstream strstream;
  201. strstream << "Shrinking did not complete; step limit " << impl_->step_limit
  202. << " was reached.";
  203. impl_->consumer(SPV_MSG_WARNING, nullptr, {}, strstream.str().c_str());
  204. return Shrinker::ShrinkerResultStatus::kStepLimitReached;
  205. }
  206. return Shrinker::ShrinkerResultStatus::kComplete;
  207. }
  208. } // namespace fuzz
  209. } // namespace spvtools