shrinker.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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, bool validate)
  55. : target_env(env), step_limit(limit), validate_during_replay(validate) {}
  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. const bool validate_during_replay; // Determines whether to check for
  60. // validity during the replaying of
  61. // transformations.
  62. };
  63. Shrinker::Shrinker(spv_target_env env, uint32_t step_limit,
  64. bool validate_during_replay)
  65. : impl_(MakeUnique<Impl>(env, step_limit, validate_during_replay)) {}
  66. Shrinker::~Shrinker() = default;
  67. void Shrinker::SetMessageConsumer(MessageConsumer c) {
  68. impl_->consumer = std::move(c);
  69. }
  70. Shrinker::ShrinkerResultStatus Shrinker::Run(
  71. const std::vector<uint32_t>& binary_in,
  72. const protobufs::FactSequence& initial_facts,
  73. const protobufs::TransformationSequence& transformation_sequence_in,
  74. const Shrinker::InterestingnessFunction& interestingness_function,
  75. std::vector<uint32_t>* binary_out,
  76. protobufs::TransformationSequence* transformation_sequence_out) const {
  77. // Check compatibility between the library version being linked with and the
  78. // header files being used.
  79. GOOGLE_PROTOBUF_VERIFY_VERSION;
  80. spvtools::SpirvTools tools(impl_->target_env);
  81. if (!tools.IsValid()) {
  82. impl_->consumer(SPV_MSG_ERROR, nullptr, {},
  83. "Failed to create SPIRV-Tools interface; stopping.");
  84. return Shrinker::ShrinkerResultStatus::kFailedToCreateSpirvToolsInterface;
  85. }
  86. // Initial binary should be valid.
  87. if (!tools.Validate(&binary_in[0], binary_in.size())) {
  88. impl_->consumer(SPV_MSG_INFO, nullptr, {},
  89. "Initial binary is invalid; stopping.");
  90. return Shrinker::ShrinkerResultStatus::kInitialBinaryInvalid;
  91. }
  92. std::vector<uint32_t> current_best_binary;
  93. protobufs::TransformationSequence current_best_transformations;
  94. // Run a replay of the initial transformation sequence to (a) check that it
  95. // succeeds, (b) get the binary that results from running these
  96. // transformations, and (c) get the subsequence of the initial transformations
  97. // that actually apply (in principle this could be a strict subsequence).
  98. if (Replayer(impl_->target_env, impl_->validate_during_replay)
  99. .Run(binary_in, initial_facts, transformation_sequence_in,
  100. &current_best_binary, &current_best_transformations) !=
  101. Replayer::ReplayerResultStatus::kComplete) {
  102. return ShrinkerResultStatus::kReplayFailed;
  103. }
  104. // Check that the binary produced by applying the initial transformations is
  105. // indeed interesting.
  106. if (!interestingness_function(current_best_binary, 0)) {
  107. impl_->consumer(SPV_MSG_INFO, nullptr, {},
  108. "Initial binary is not interesting; stopping.");
  109. return ShrinkerResultStatus::kInitialBinaryNotInteresting;
  110. }
  111. uint32_t attempt = 0; // Keeps track of the number of shrink attempts that
  112. // have been tried, whether successful or not.
  113. uint32_t chunk_size =
  114. std::max(1u, NumRemainingTransformations(current_best_transformations) /
  115. 2); // The number of contiguous transformations that the
  116. // shrinker will try to remove in one go; starts
  117. // high and decreases during the shrinking process.
  118. // Keep shrinking until we:
  119. // - reach the step limit,
  120. // - run out of transformations to remove, or
  121. // - cannot make the chunk size any smaller.
  122. while (attempt < impl_->step_limit &&
  123. !current_best_transformations.transformation().empty() &&
  124. chunk_size > 0) {
  125. bool progress_this_round =
  126. false; // Used to decide whether to make the chunk size with which we
  127. // remove transformations smaller. If we managed to remove at
  128. // least one chunk of transformations at a particular chunk
  129. // size, we set this flag so that we do not yet decrease the
  130. // chunk size.
  131. assert(chunk_size <=
  132. NumRemainingTransformations(current_best_transformations) &&
  133. "Chunk size should never exceed the number of transformations that "
  134. "remain.");
  135. // The number of chunks is the ceiling of (#remaining_transformations /
  136. // chunk_size).
  137. const uint32_t num_chunks =
  138. (NumRemainingTransformations(current_best_transformations) +
  139. chunk_size - 1) /
  140. chunk_size;
  141. assert(num_chunks >= 1 && "There should be at least one chunk.");
  142. assert(num_chunks * chunk_size >=
  143. NumRemainingTransformations(current_best_transformations) &&
  144. "All transformations should be in some chunk.");
  145. // We go through the transformations in reverse, in chunks of size
  146. // |chunk_size|, using |chunk_index| to track which chunk to try removing
  147. // next. The loop exits early if we reach the shrinking step limit.
  148. for (int chunk_index = num_chunks - 1;
  149. attempt < impl_->step_limit && chunk_index >= 0; chunk_index--) {
  150. // Remove a chunk of transformations according to the current index and
  151. // chunk size.
  152. auto transformations_with_chunk_removed =
  153. RemoveChunk(current_best_transformations, chunk_index, chunk_size);
  154. // Replay the smaller sequence of transformations to get a next binary and
  155. // transformation sequence. Note that the transformations arising from
  156. // replay might be even smaller than the transformations with the chunk
  157. // removed, because removing those transformations might make further
  158. // transformations inapplicable.
  159. std::vector<uint32_t> next_binary;
  160. protobufs::TransformationSequence next_transformation_sequence;
  161. if (Replayer(impl_->target_env, false)
  162. .Run(binary_in, initial_facts, transformations_with_chunk_removed,
  163. &next_binary, &next_transformation_sequence) !=
  164. Replayer::ReplayerResultStatus::kComplete) {
  165. // Replay should not fail; if it does, we need to abort shrinking.
  166. return ShrinkerResultStatus::kReplayFailed;
  167. }
  168. assert(NumRemainingTransformations(next_transformation_sequence) >=
  169. chunk_index * chunk_size &&
  170. "Removing this chunk of transformations should not have an effect "
  171. "on earlier chunks.");
  172. if (interestingness_function(next_binary, attempt)) {
  173. // If the binary arising from the smaller transformation sequence is
  174. // interesting, this becomes our current best binary and transformation
  175. // sequence.
  176. current_best_binary = next_binary;
  177. current_best_transformations = next_transformation_sequence;
  178. progress_this_round = true;
  179. }
  180. // Either way, this was a shrink attempt, so increment our count of shrink
  181. // attempts.
  182. attempt++;
  183. }
  184. if (!progress_this_round) {
  185. // If we didn't manage to remove any chunks at this chunk size, try a
  186. // smaller chunk size.
  187. chunk_size /= 2;
  188. }
  189. // Decrease the chunk size until it becomes no larger than the number of
  190. // remaining transformations.
  191. while (chunk_size >
  192. NumRemainingTransformations(current_best_transformations)) {
  193. chunk_size /= 2;
  194. }
  195. }
  196. // The output from the shrinker is the best binary we saw, and the
  197. // transformations that led to it.
  198. *binary_out = current_best_binary;
  199. *transformation_sequence_out = current_best_transformations;
  200. // Indicate whether shrinking completed or was truncated due to reaching the
  201. // step limit.
  202. assert(attempt <= impl_->step_limit);
  203. if (attempt == impl_->step_limit) {
  204. std::stringstream strstream;
  205. strstream << "Shrinking did not complete; step limit " << impl_->step_limit
  206. << " was reached.";
  207. impl_->consumer(SPV_MSG_WARNING, nullptr, {}, strstream.str().c_str());
  208. return Shrinker::ShrinkerResultStatus::kStepLimitReached;
  209. }
  210. return Shrinker::ShrinkerResultStatus::kComplete;
  211. }
  212. } // namespace fuzz
  213. } // namespace spvtools