fuzzer.cpp 17 KB

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