fuzzer.cpp 14 KB

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