fuzzer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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_access_chains.h"
  22. #include "source/fuzz/fuzzer_pass_add_composite_types.h"
  23. #include "source/fuzz/fuzzer_pass_add_dead_blocks.h"
  24. #include "source/fuzz/fuzzer_pass_add_dead_breaks.h"
  25. #include "source/fuzz/fuzzer_pass_add_dead_continues.h"
  26. #include "source/fuzz/fuzzer_pass_add_equation_instructions.h"
  27. #include "source/fuzz/fuzzer_pass_add_function_calls.h"
  28. #include "source/fuzz/fuzzer_pass_add_global_variables.h"
  29. #include "source/fuzz/fuzzer_pass_add_loads.h"
  30. #include "source/fuzz/fuzzer_pass_add_local_variables.h"
  31. #include "source/fuzz/fuzzer_pass_add_no_contraction_decorations.h"
  32. #include "source/fuzz/fuzzer_pass_add_stores.h"
  33. #include "source/fuzz/fuzzer_pass_add_useful_constructs.h"
  34. #include "source/fuzz/fuzzer_pass_adjust_function_controls.h"
  35. #include "source/fuzz/fuzzer_pass_adjust_loop_controls.h"
  36. #include "source/fuzz/fuzzer_pass_adjust_selection_controls.h"
  37. #include "source/fuzz/fuzzer_pass_apply_id_synonyms.h"
  38. #include "source/fuzz/fuzzer_pass_construct_composites.h"
  39. #include "source/fuzz/fuzzer_pass_copy_objects.h"
  40. #include "source/fuzz/fuzzer_pass_donate_modules.h"
  41. #include "source/fuzz/fuzzer_pass_merge_blocks.h"
  42. #include "source/fuzz/fuzzer_pass_obfuscate_constants.h"
  43. #include "source/fuzz/fuzzer_pass_outline_functions.h"
  44. #include "source/fuzz/fuzzer_pass_permute_blocks.h"
  45. #include "source/fuzz/fuzzer_pass_permute_function_parameters.h"
  46. #include "source/fuzz/fuzzer_pass_split_blocks.h"
  47. #include "source/fuzz/fuzzer_pass_swap_commutable_operands.h"
  48. #include "source/fuzz/fuzzer_pass_toggle_access_chain_instruction.h"
  49. #include "source/fuzz/protobufs/spirvfuzz_protobufs.h"
  50. #include "source/fuzz/pseudo_random_generator.h"
  51. #include "source/opt/build_module.h"
  52. #include "source/spirv_fuzzer_options.h"
  53. #include "source/util/make_unique.h"
  54. namespace spvtools {
  55. namespace fuzz {
  56. namespace {
  57. const uint32_t kIdBoundGap = 100;
  58. const uint32_t kTransformationLimit = 500;
  59. const uint32_t kChanceOfApplyingAnotherPass = 85;
  60. // A convenience method to add a fuzzer pass to |passes| with probability 0.5.
  61. // All fuzzer passes take |ir_context|, |fact_manager|, |fuzzer_context| and
  62. // |transformation_sequence_out| as parameters. Extra arguments can be provided
  63. // via |extra_args|.
  64. template <typename T, typename... Args>
  65. void MaybeAddPass(
  66. std::vector<std::unique_ptr<FuzzerPass>>* passes,
  67. opt::IRContext* ir_context, FactManager* fact_manager,
  68. FuzzerContext* fuzzer_context,
  69. protobufs::TransformationSequence* transformation_sequence_out,
  70. Args&&... extra_args) {
  71. if (fuzzer_context->ChooseEven()) {
  72. passes->push_back(MakeUnique<T>(ir_context, fact_manager, fuzzer_context,
  73. transformation_sequence_out,
  74. std::forward<Args>(extra_args)...));
  75. }
  76. }
  77. } // namespace
  78. struct Fuzzer::Impl {
  79. explicit Impl(spv_target_env env, uint32_t random_seed,
  80. bool validate_after_each_pass)
  81. : target_env(env),
  82. seed(random_seed),
  83. validate_after_each_fuzzer_pass(validate_after_each_pass) {}
  84. bool ApplyPassAndCheckValidity(FuzzerPass* pass,
  85. const opt::IRContext& ir_context,
  86. const spvtools::SpirvTools& tools) const;
  87. const spv_target_env target_env; // Target environment.
  88. const uint32_t seed; // Seed for random number generator.
  89. bool validate_after_each_fuzzer_pass; // Determines whether the validator
  90. // should be invoked after every fuzzer pass.
  91. MessageConsumer consumer; // Message consumer.
  92. };
  93. Fuzzer::Fuzzer(spv_target_env env, uint32_t seed,
  94. bool validate_after_each_fuzzer_pass)
  95. : impl_(MakeUnique<Impl>(env, seed, validate_after_each_fuzzer_pass)) {}
  96. Fuzzer::~Fuzzer() = default;
  97. void Fuzzer::SetMessageConsumer(MessageConsumer c) {
  98. impl_->consumer = std::move(c);
  99. }
  100. bool Fuzzer::Impl::ApplyPassAndCheckValidity(
  101. FuzzerPass* pass, const opt::IRContext& ir_context,
  102. const spvtools::SpirvTools& tools) const {
  103. pass->Apply();
  104. if (validate_after_each_fuzzer_pass) {
  105. std::vector<uint32_t> binary_to_validate;
  106. ir_context.module()->ToBinary(&binary_to_validate, false);
  107. if (!tools.Validate(&binary_to_validate[0], binary_to_validate.size())) {
  108. consumer(SPV_MSG_INFO, nullptr, {},
  109. "Binary became invalid during fuzzing (set a breakpoint to "
  110. "inspect); stopping.");
  111. return false;
  112. }
  113. }
  114. return true;
  115. }
  116. Fuzzer::FuzzerResultStatus Fuzzer::Run(
  117. const std::vector<uint32_t>& binary_in,
  118. const protobufs::FactSequence& initial_facts,
  119. const std::vector<fuzzerutil::ModuleSupplier>& donor_suppliers,
  120. std::vector<uint32_t>* binary_out,
  121. protobufs::TransformationSequence* transformation_sequence_out) const {
  122. // Check compatibility between the library version being linked with and the
  123. // header files being used.
  124. GOOGLE_PROTOBUF_VERIFY_VERSION;
  125. spvtools::SpirvTools tools(impl_->target_env);
  126. tools.SetMessageConsumer(impl_->consumer);
  127. if (!tools.IsValid()) {
  128. impl_->consumer(SPV_MSG_ERROR, nullptr, {},
  129. "Failed to create SPIRV-Tools interface; stopping.");
  130. return Fuzzer::FuzzerResultStatus::kFailedToCreateSpirvToolsInterface;
  131. }
  132. // Initial binary should be valid.
  133. if (!tools.Validate(&binary_in[0], binary_in.size())) {
  134. impl_->consumer(SPV_MSG_ERROR, nullptr, {},
  135. "Initial binary is invalid; stopping.");
  136. return Fuzzer::FuzzerResultStatus::kInitialBinaryInvalid;
  137. }
  138. // Build the module from the input binary.
  139. std::unique_ptr<opt::IRContext> ir_context = BuildModule(
  140. impl_->target_env, impl_->consumer, binary_in.data(), binary_in.size());
  141. assert(ir_context);
  142. // Make a PRNG from the seed passed to the fuzzer on creation.
  143. PseudoRandomGenerator random_generator(impl_->seed);
  144. // The fuzzer will introduce new ids into the module. The module's id bound
  145. // gives the smallest id that can be used for this purpose. We add an offset
  146. // to this so that there is a sizeable gap between the ids used in the
  147. // original module and the ids used for fuzzing, as a readability aid.
  148. //
  149. // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/2541) consider the
  150. // case where the maximum id bound is reached.
  151. auto minimum_fresh_id = ir_context->module()->id_bound() + kIdBoundGap;
  152. FuzzerContext fuzzer_context(&random_generator, minimum_fresh_id);
  153. FactManager fact_manager;
  154. fact_manager.AddFacts(impl_->consumer, initial_facts, ir_context.get());
  155. // Add some essential ingredients to the module if they are not already
  156. // present, such as boolean constants.
  157. FuzzerPassAddUsefulConstructs add_useful_constructs(
  158. ir_context.get(), &fact_manager, &fuzzer_context,
  159. transformation_sequence_out);
  160. if (!impl_->ApplyPassAndCheckValidity(&add_useful_constructs, *ir_context,
  161. tools)) {
  162. return Fuzzer::FuzzerResultStatus::kFuzzerPassLedToInvalidModule;
  163. }
  164. // Apply some semantics-preserving passes.
  165. std::vector<std::unique_ptr<FuzzerPass>> passes;
  166. while (passes.empty()) {
  167. MaybeAddPass<FuzzerPassAddAccessChains>(&passes, ir_context.get(),
  168. &fact_manager, &fuzzer_context,
  169. transformation_sequence_out);
  170. MaybeAddPass<FuzzerPassAddCompositeTypes>(&passes, ir_context.get(),
  171. &fact_manager, &fuzzer_context,
  172. transformation_sequence_out);
  173. MaybeAddPass<FuzzerPassAddDeadBlocks>(&passes, ir_context.get(),
  174. &fact_manager, &fuzzer_context,
  175. transformation_sequence_out);
  176. MaybeAddPass<FuzzerPassAddDeadBreaks>(&passes, ir_context.get(),
  177. &fact_manager, &fuzzer_context,
  178. transformation_sequence_out);
  179. MaybeAddPass<FuzzerPassAddDeadContinues>(&passes, ir_context.get(),
  180. &fact_manager, &fuzzer_context,
  181. transformation_sequence_out);
  182. MaybeAddPass<FuzzerPassAddEquationInstructions>(
  183. &passes, ir_context.get(), &fact_manager, &fuzzer_context,
  184. transformation_sequence_out);
  185. MaybeAddPass<FuzzerPassAddFunctionCalls>(&passes, ir_context.get(),
  186. &fact_manager, &fuzzer_context,
  187. transformation_sequence_out);
  188. MaybeAddPass<FuzzerPassAddGlobalVariables>(&passes, ir_context.get(),
  189. &fact_manager, &fuzzer_context,
  190. transformation_sequence_out);
  191. MaybeAddPass<FuzzerPassAddLoads>(&passes, ir_context.get(), &fact_manager,
  192. &fuzzer_context,
  193. transformation_sequence_out);
  194. MaybeAddPass<FuzzerPassAddLocalVariables>(&passes, ir_context.get(),
  195. &fact_manager, &fuzzer_context,
  196. transformation_sequence_out);
  197. MaybeAddPass<FuzzerPassAddStores>(&passes, ir_context.get(), &fact_manager,
  198. &fuzzer_context,
  199. transformation_sequence_out);
  200. MaybeAddPass<FuzzerPassApplyIdSynonyms>(&passes, ir_context.get(),
  201. &fact_manager, &fuzzer_context,
  202. transformation_sequence_out);
  203. MaybeAddPass<FuzzerPassConstructComposites>(&passes, ir_context.get(),
  204. &fact_manager, &fuzzer_context,
  205. transformation_sequence_out);
  206. MaybeAddPass<FuzzerPassCopyObjects>(&passes, ir_context.get(),
  207. &fact_manager, &fuzzer_context,
  208. transformation_sequence_out);
  209. MaybeAddPass<FuzzerPassDonateModules>(
  210. &passes, ir_context.get(), &fact_manager, &fuzzer_context,
  211. transformation_sequence_out, donor_suppliers);
  212. MaybeAddPass<FuzzerPassMergeBlocks>(&passes, ir_context.get(),
  213. &fact_manager, &fuzzer_context,
  214. transformation_sequence_out);
  215. MaybeAddPass<FuzzerPassObfuscateConstants>(&passes, ir_context.get(),
  216. &fact_manager, &fuzzer_context,
  217. transformation_sequence_out);
  218. MaybeAddPass<FuzzerPassOutlineFunctions>(&passes, ir_context.get(),
  219. &fact_manager, &fuzzer_context,
  220. transformation_sequence_out);
  221. MaybeAddPass<FuzzerPassPermuteBlocks>(&passes, ir_context.get(),
  222. &fact_manager, &fuzzer_context,
  223. transformation_sequence_out);
  224. MaybeAddPass<FuzzerPassPermuteFunctionParameters>(
  225. &passes, ir_context.get(), &fact_manager, &fuzzer_context,
  226. transformation_sequence_out);
  227. MaybeAddPass<FuzzerPassSplitBlocks>(&passes, ir_context.get(),
  228. &fact_manager, &fuzzer_context,
  229. transformation_sequence_out);
  230. }
  231. bool is_first = true;
  232. while (static_cast<uint32_t>(
  233. transformation_sequence_out->transformation_size()) <
  234. kTransformationLimit &&
  235. (is_first ||
  236. fuzzer_context.ChoosePercentage(kChanceOfApplyingAnotherPass))) {
  237. is_first = false;
  238. if (!impl_->ApplyPassAndCheckValidity(
  239. passes[fuzzer_context.RandomIndex(passes)].get(), *ir_context,
  240. tools)) {
  241. return Fuzzer::FuzzerResultStatus::kFuzzerPassLedToInvalidModule;
  242. }
  243. }
  244. // Now apply some passes that it does not make sense to apply repeatedly,
  245. // as they do not unlock other passes.
  246. std::vector<std::unique_ptr<FuzzerPass>> final_passes;
  247. MaybeAddPass<FuzzerPassAdjustFunctionControls>(
  248. &final_passes, ir_context.get(), &fact_manager, &fuzzer_context,
  249. transformation_sequence_out);
  250. MaybeAddPass<FuzzerPassAdjustLoopControls>(&final_passes, ir_context.get(),
  251. &fact_manager, &fuzzer_context,
  252. transformation_sequence_out);
  253. MaybeAddPass<FuzzerPassAdjustMemoryOperandsMasks>(
  254. &final_passes, ir_context.get(), &fact_manager, &fuzzer_context,
  255. transformation_sequence_out);
  256. MaybeAddPass<FuzzerPassAdjustSelectionControls>(
  257. &final_passes, ir_context.get(), &fact_manager, &fuzzer_context,
  258. transformation_sequence_out);
  259. MaybeAddPass<FuzzerPassAddNoContractionDecorations>(
  260. &final_passes, ir_context.get(), &fact_manager, &fuzzer_context,
  261. transformation_sequence_out);
  262. MaybeAddPass<FuzzerPassSwapCommutableOperands>(
  263. &final_passes, ir_context.get(), &fact_manager, &fuzzer_context,
  264. transformation_sequence_out);
  265. MaybeAddPass<FuzzerPassToggleAccessChainInstruction>(
  266. &final_passes, ir_context.get(), &fact_manager, &fuzzer_context,
  267. transformation_sequence_out);
  268. for (auto& pass : final_passes) {
  269. if (!impl_->ApplyPassAndCheckValidity(pass.get(), *ir_context, tools)) {
  270. return Fuzzer::FuzzerResultStatus::kFuzzerPassLedToInvalidModule;
  271. }
  272. }
  273. // Encode the module as a binary.
  274. ir_context->module()->ToBinary(binary_out, false);
  275. return Fuzzer::FuzzerResultStatus::kComplete;
  276. }
  277. } // namespace fuzz
  278. } // namespace spvtools