2
0

fuzzer.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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/fuzzer.h"
  15. #include <cassert>
  16. #include <memory>
  17. #include <sstream>
  18. #include "fuzzer_pass_adjust_memory_operands_masks.h"
  19. #include "source/fuzz/fact_manager.h"
  20. #include "source/fuzz/fuzzer_context.h"
  21. #include "source/fuzz/fuzzer_pass_add_dead_breaks.h"
  22. #include "source/fuzz/fuzzer_pass_add_dead_continues.h"
  23. #include "source/fuzz/fuzzer_pass_add_no_contraction_decorations.h"
  24. #include "source/fuzz/fuzzer_pass_add_useful_constructs.h"
  25. #include "source/fuzz/fuzzer_pass_adjust_function_controls.h"
  26. #include "source/fuzz/fuzzer_pass_adjust_loop_controls.h"
  27. #include "source/fuzz/fuzzer_pass_adjust_selection_controls.h"
  28. #include "source/fuzz/fuzzer_pass_apply_id_synonyms.h"
  29. #include "source/fuzz/fuzzer_pass_construct_composites.h"
  30. #include "source/fuzz/fuzzer_pass_copy_objects.h"
  31. #include "source/fuzz/fuzzer_pass_obfuscate_constants.h"
  32. #include "source/fuzz/fuzzer_pass_permute_blocks.h"
  33. #include "source/fuzz/fuzzer_pass_split_blocks.h"
  34. #include "source/fuzz/protobufs/spirvfuzz_protobufs.h"
  35. #include "source/fuzz/pseudo_random_generator.h"
  36. #include "source/opt/build_module.h"
  37. #include "source/spirv_fuzzer_options.h"
  38. #include "source/util/make_unique.h"
  39. namespace spvtools {
  40. namespace fuzz {
  41. namespace {
  42. const uint32_t kIdBoundGap = 100;
  43. const uint32_t kTransformationLimit = 500;
  44. const uint32_t kChanceOfApplyingAnotherPass = 85;
  45. template <typename T>
  46. void MaybeAddPass(
  47. std::vector<std::unique_ptr<FuzzerPass>>* passes,
  48. opt::IRContext* ir_context, FactManager* fact_manager,
  49. FuzzerContext* fuzzer_context,
  50. protobufs::TransformationSequence* transformation_sequence_out) {
  51. if (fuzzer_context->ChooseEven()) {
  52. passes->push_back(MakeUnique<T>(ir_context, fact_manager, fuzzer_context,
  53. transformation_sequence_out));
  54. }
  55. }
  56. } // namespace
  57. struct Fuzzer::Impl {
  58. explicit Impl(spv_target_env env) : target_env(env) {}
  59. const spv_target_env target_env; // Target environment.
  60. MessageConsumer consumer; // Message consumer.
  61. };
  62. Fuzzer::Fuzzer(spv_target_env env) : impl_(MakeUnique<Impl>(env)) {}
  63. Fuzzer::~Fuzzer() = default;
  64. void Fuzzer::SetMessageConsumer(MessageConsumer c) {
  65. impl_->consumer = std::move(c);
  66. }
  67. Fuzzer::FuzzerResultStatus Fuzzer::Run(
  68. const std::vector<uint32_t>& binary_in,
  69. const protobufs::FactSequence& initial_facts,
  70. spv_const_fuzzer_options options, std::vector<uint32_t>* binary_out,
  71. protobufs::TransformationSequence* transformation_sequence_out) const {
  72. // Check compatibility between the library version being linked with and the
  73. // header files being used.
  74. GOOGLE_PROTOBUF_VERIFY_VERSION;
  75. spvtools::SpirvTools tools(impl_->target_env);
  76. tools.SetMessageConsumer(impl_->consumer);
  77. if (!tools.IsValid()) {
  78. impl_->consumer(SPV_MSG_ERROR, nullptr, {},
  79. "Failed to create SPIRV-Tools interface; stopping.");
  80. return Fuzzer::FuzzerResultStatus::kFailedToCreateSpirvToolsInterface;
  81. }
  82. // Initial binary should be valid.
  83. if (!tools.Validate(&binary_in[0], binary_in.size())) {
  84. impl_->consumer(SPV_MSG_ERROR, nullptr, {},
  85. "Initial binary is invalid; stopping.");
  86. return Fuzzer::FuzzerResultStatus::kInitialBinaryInvalid;
  87. }
  88. // Build the module from the input binary.
  89. std::unique_ptr<opt::IRContext> ir_context = BuildModule(
  90. impl_->target_env, impl_->consumer, binary_in.data(), binary_in.size());
  91. assert(ir_context);
  92. // Make a PRNG, either from a given seed or from a random device.
  93. PseudoRandomGenerator random_generator(
  94. options->has_random_seed ? options->random_seed
  95. : static_cast<uint32_t>(std::random_device()()));
  96. // The fuzzer will introduce new ids into the module. The module's id bound
  97. // gives the smallest id that can be used for this purpose. We add an offset
  98. // to this so that there is a sizeable gap between the ids used in the
  99. // original module and the ids used for fuzzing, as a readability aid.
  100. //
  101. // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/2541) consider the
  102. // case where the maximum id bound is reached.
  103. auto minimum_fresh_id = ir_context->module()->id_bound() + kIdBoundGap;
  104. FuzzerContext fuzzer_context(&random_generator, minimum_fresh_id);
  105. FactManager fact_manager;
  106. fact_manager.AddFacts(impl_->consumer, initial_facts, ir_context.get());
  107. // Add some essential ingredients to the module if they are not already
  108. // present, such as boolean constants.
  109. FuzzerPassAddUsefulConstructs(ir_context.get(), &fact_manager,
  110. &fuzzer_context, transformation_sequence_out)
  111. .Apply();
  112. // Apply some semantics-preserving passes.
  113. std::vector<std::unique_ptr<FuzzerPass>> passes;
  114. while (passes.empty()) {
  115. MaybeAddPass<FuzzerPassAddDeadBreaks>(&passes, ir_context.get(),
  116. &fact_manager, &fuzzer_context,
  117. transformation_sequence_out);
  118. MaybeAddPass<FuzzerPassAddDeadContinues>(&passes, ir_context.get(),
  119. &fact_manager, &fuzzer_context,
  120. transformation_sequence_out);
  121. MaybeAddPass<FuzzerPassApplyIdSynonyms>(&passes, ir_context.get(),
  122. &fact_manager, &fuzzer_context,
  123. transformation_sequence_out);
  124. MaybeAddPass<FuzzerPassConstructComposites>(&passes, ir_context.get(),
  125. &fact_manager, &fuzzer_context,
  126. transformation_sequence_out);
  127. MaybeAddPass<FuzzerPassCopyObjects>(&passes, ir_context.get(),
  128. &fact_manager, &fuzzer_context,
  129. transformation_sequence_out);
  130. MaybeAddPass<FuzzerPassObfuscateConstants>(&passes, ir_context.get(),
  131. &fact_manager, &fuzzer_context,
  132. transformation_sequence_out);
  133. MaybeAddPass<FuzzerPassPermuteBlocks>(&passes, ir_context.get(),
  134. &fact_manager, &fuzzer_context,
  135. transformation_sequence_out);
  136. MaybeAddPass<FuzzerPassSplitBlocks>(&passes, ir_context.get(),
  137. &fact_manager, &fuzzer_context,
  138. transformation_sequence_out);
  139. }
  140. bool is_first = true;
  141. while (static_cast<uint32_t>(
  142. transformation_sequence_out->transformation_size()) <
  143. kTransformationLimit &&
  144. (is_first ||
  145. fuzzer_context.ChoosePercentage(kChanceOfApplyingAnotherPass))) {
  146. is_first = false;
  147. passes[fuzzer_context.RandomIndex(passes)]->Apply();
  148. }
  149. // Now apply some passes that it does not make sense to apply repeatedly,
  150. // as they do not unlock other passes.
  151. std::vector<std::unique_ptr<FuzzerPass>> final_passes;
  152. MaybeAddPass<FuzzerPassAdjustFunctionControls>(
  153. &final_passes, ir_context.get(), &fact_manager, &fuzzer_context,
  154. transformation_sequence_out);
  155. MaybeAddPass<FuzzerPassAdjustLoopControls>(&final_passes, ir_context.get(),
  156. &fact_manager, &fuzzer_context,
  157. transformation_sequence_out);
  158. MaybeAddPass<FuzzerPassAdjustMemoryOperandsMasks>(
  159. &final_passes, ir_context.get(), &fact_manager, &fuzzer_context,
  160. transformation_sequence_out);
  161. MaybeAddPass<FuzzerPassAdjustSelectionControls>(
  162. &final_passes, ir_context.get(), &fact_manager, &fuzzer_context,
  163. transformation_sequence_out);
  164. for (auto& pass : final_passes) {
  165. pass->Apply();
  166. }
  167. if (fuzzer_context.ChooseEven()) {
  168. FuzzerPassAddNoContractionDecorations(ir_context.get(), &fact_manager,
  169. &fuzzer_context,
  170. transformation_sequence_out)
  171. .Apply();
  172. }
  173. // Encode the module as a binary.
  174. ir_context->module()->ToBinary(binary_out, false);
  175. return Fuzzer::FuzzerResultStatus::kComplete;
  176. }
  177. } // namespace fuzz
  178. } // namespace spvtools