fuzzer.cpp 16 KB

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