fuzzer.cpp 17 KB

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