fuzzer.cpp 16 KB

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