fuzzer_pass.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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_pass.h"
  15. #include "source/fuzz/fuzzer_util.h"
  16. #include "source/fuzz/instruction_descriptor.h"
  17. #include "source/fuzz/transformation_add_constant_boolean.h"
  18. #include "source/fuzz/transformation_add_constant_composite.h"
  19. #include "source/fuzz/transformation_add_constant_scalar.h"
  20. #include "source/fuzz/transformation_add_global_undef.h"
  21. #include "source/fuzz/transformation_add_type_boolean.h"
  22. #include "source/fuzz/transformation_add_type_float.h"
  23. #include "source/fuzz/transformation_add_type_function.h"
  24. #include "source/fuzz/transformation_add_type_int.h"
  25. #include "source/fuzz/transformation_add_type_matrix.h"
  26. #include "source/fuzz/transformation_add_type_pointer.h"
  27. #include "source/fuzz/transformation_add_type_vector.h"
  28. namespace spvtools {
  29. namespace fuzz {
  30. FuzzerPass::FuzzerPass(opt::IRContext* ir_context, FactManager* fact_manager,
  31. FuzzerContext* fuzzer_context,
  32. protobufs::TransformationSequence* transformations)
  33. : ir_context_(ir_context),
  34. fact_manager_(fact_manager),
  35. fuzzer_context_(fuzzer_context),
  36. transformations_(transformations) {}
  37. FuzzerPass::~FuzzerPass() = default;
  38. std::vector<opt::Instruction*> FuzzerPass::FindAvailableInstructions(
  39. opt::Function* function, opt::BasicBlock* block,
  40. const opt::BasicBlock::iterator& inst_it,
  41. std::function<bool(opt::IRContext*, opt::Instruction*)>
  42. instruction_is_relevant) const {
  43. // TODO(afd) The following is (relatively) simple, but may end up being
  44. // prohibitively inefficient, as it walks the whole dominator tree for
  45. // every instruction that is considered.
  46. std::vector<opt::Instruction*> result;
  47. // Consider all global declarations
  48. for (auto& global : GetIRContext()->module()->types_values()) {
  49. if (instruction_is_relevant(GetIRContext(), &global)) {
  50. result.push_back(&global);
  51. }
  52. }
  53. // Consider all function parameters
  54. function->ForEachParam(
  55. [this, &instruction_is_relevant, &result](opt::Instruction* param) {
  56. if (instruction_is_relevant(GetIRContext(), param)) {
  57. result.push_back(param);
  58. }
  59. });
  60. // Consider all previous instructions in this block
  61. for (auto prev_inst_it = block->begin(); prev_inst_it != inst_it;
  62. ++prev_inst_it) {
  63. if (instruction_is_relevant(GetIRContext(), &*prev_inst_it)) {
  64. result.push_back(&*prev_inst_it);
  65. }
  66. }
  67. // Walk the dominator tree to consider all instructions from dominating
  68. // blocks
  69. auto dominator_analysis = GetIRContext()->GetDominatorAnalysis(function);
  70. for (auto next_dominator = dominator_analysis->ImmediateDominator(block);
  71. next_dominator != nullptr;
  72. next_dominator =
  73. dominator_analysis->ImmediateDominator(next_dominator)) {
  74. for (auto& dominating_inst : *next_dominator) {
  75. if (instruction_is_relevant(GetIRContext(), &dominating_inst)) {
  76. result.push_back(&dominating_inst);
  77. }
  78. }
  79. }
  80. return result;
  81. }
  82. void FuzzerPass::ForEachInstructionWithInstructionDescriptor(
  83. std::function<
  84. void(opt::Function* function, opt::BasicBlock* block,
  85. opt::BasicBlock::iterator inst_it,
  86. const protobufs::InstructionDescriptor& instruction_descriptor)>
  87. action) {
  88. // Consider every block in every function.
  89. for (auto& function : *GetIRContext()->module()) {
  90. for (auto& block : function) {
  91. // We now consider every instruction in the block, randomly deciding
  92. // whether to apply a transformation before it.
  93. // In order for transformations to insert new instructions, they need to
  94. // be able to identify the instruction to insert before. We describe an
  95. // instruction via its opcode, 'opc', a base instruction 'base' that has a
  96. // result id, and the number of instructions with opcode 'opc' that we
  97. // should skip when searching from 'base' for the desired instruction.
  98. // (An instruction that has a result id is represented by its own opcode,
  99. // itself as 'base', and a skip-count of 0.)
  100. std::vector<std::tuple<uint32_t, SpvOp, uint32_t>>
  101. base_opcode_skip_triples;
  102. // The initial base instruction is the block label.
  103. uint32_t base = block.id();
  104. // Counts the number of times we have seen each opcode since we reset the
  105. // base instruction.
  106. std::map<SpvOp, uint32_t> skip_count;
  107. // Consider every instruction in the block. The label is excluded: it is
  108. // only necessary to consider it as a base in case the first instruction
  109. // in the block does not have a result id.
  110. for (auto inst_it = block.begin(); inst_it != block.end(); ++inst_it) {
  111. if (inst_it->HasResultId()) {
  112. // In the case that the instruction has a result id, we use the
  113. // instruction as its own base, and clear the skip counts we have
  114. // collected.
  115. base = inst_it->result_id();
  116. skip_count.clear();
  117. }
  118. const SpvOp opcode = inst_it->opcode();
  119. // Invoke the provided function, which might apply a transformation.
  120. action(&function, &block, inst_it,
  121. MakeInstructionDescriptor(
  122. base, opcode,
  123. skip_count.count(opcode) ? skip_count.at(opcode) : 0));
  124. if (!inst_it->HasResultId()) {
  125. skip_count[opcode] =
  126. skip_count.count(opcode) ? skip_count.at(opcode) + 1 : 1;
  127. }
  128. }
  129. }
  130. }
  131. }
  132. uint32_t FuzzerPass::FindOrCreateBoolType() {
  133. opt::analysis::Bool bool_type;
  134. auto existing_id = GetIRContext()->get_type_mgr()->GetId(&bool_type);
  135. if (existing_id) {
  136. return existing_id;
  137. }
  138. auto result = GetFuzzerContext()->GetFreshId();
  139. ApplyTransformation(TransformationAddTypeBoolean(result));
  140. return result;
  141. }
  142. uint32_t FuzzerPass::FindOrCreate32BitIntegerType(bool is_signed) {
  143. opt::analysis::Integer int_type(32, is_signed);
  144. auto existing_id = GetIRContext()->get_type_mgr()->GetId(&int_type);
  145. if (existing_id) {
  146. return existing_id;
  147. }
  148. auto result = GetFuzzerContext()->GetFreshId();
  149. ApplyTransformation(TransformationAddTypeInt(result, 32, is_signed));
  150. return result;
  151. }
  152. uint32_t FuzzerPass::FindOrCreate32BitFloatType() {
  153. opt::analysis::Float float_type(32);
  154. auto existing_id = GetIRContext()->get_type_mgr()->GetId(&float_type);
  155. if (existing_id) {
  156. return existing_id;
  157. }
  158. auto result = GetFuzzerContext()->GetFreshId();
  159. ApplyTransformation(TransformationAddTypeFloat(result, 32));
  160. return result;
  161. }
  162. uint32_t FuzzerPass::FindOrCreateFunctionType(
  163. uint32_t return_type_id, const std::vector<uint32_t>& argument_id) {
  164. // FindFunctionType has a sigle argument for OpTypeFunction operands
  165. // so we will have to copy them all in this vector
  166. std::vector<uint32_t> type_ids(argument_id.size() + 1);
  167. type_ids[0] = return_type_id;
  168. std::copy(argument_id.begin(), argument_id.end(), type_ids.begin() + 1);
  169. // Check if type exists
  170. auto existing_id = fuzzerutil::FindFunctionType(GetIRContext(), type_ids);
  171. if (existing_id) {
  172. return existing_id;
  173. }
  174. auto result = GetFuzzerContext()->GetFreshId();
  175. ApplyTransformation(
  176. TransformationAddTypeFunction(result, return_type_id, argument_id));
  177. return result;
  178. }
  179. uint32_t FuzzerPass::FindOrCreateVectorType(uint32_t component_type_id,
  180. uint32_t component_count) {
  181. assert(component_count >= 2 && component_count <= 4 &&
  182. "Precondition: component count must be in range [2, 4].");
  183. opt::analysis::Type* component_type =
  184. GetIRContext()->get_type_mgr()->GetType(component_type_id);
  185. assert(component_type && "Precondition: the component type must exist.");
  186. opt::analysis::Vector vector_type(component_type, component_count);
  187. auto existing_id = GetIRContext()->get_type_mgr()->GetId(&vector_type);
  188. if (existing_id) {
  189. return existing_id;
  190. }
  191. auto result = GetFuzzerContext()->GetFreshId();
  192. ApplyTransformation(
  193. TransformationAddTypeVector(result, component_type_id, component_count));
  194. return result;
  195. }
  196. uint32_t FuzzerPass::FindOrCreateMatrixType(uint32_t column_count,
  197. uint32_t row_count) {
  198. assert(column_count >= 2 && column_count <= 4 &&
  199. "Precondition: column count must be in range [2, 4].");
  200. assert(row_count >= 2 && row_count <= 4 &&
  201. "Precondition: row count must be in range [2, 4].");
  202. uint32_t column_type_id =
  203. FindOrCreateVectorType(FindOrCreate32BitFloatType(), row_count);
  204. opt::analysis::Type* column_type =
  205. GetIRContext()->get_type_mgr()->GetType(column_type_id);
  206. opt::analysis::Matrix matrix_type(column_type, column_count);
  207. auto existing_id = GetIRContext()->get_type_mgr()->GetId(&matrix_type);
  208. if (existing_id) {
  209. return existing_id;
  210. }
  211. auto result = GetFuzzerContext()->GetFreshId();
  212. ApplyTransformation(
  213. TransformationAddTypeMatrix(result, column_type_id, column_count));
  214. return result;
  215. }
  216. uint32_t FuzzerPass::FindOrCreatePointerType(uint32_t base_type_id,
  217. SpvStorageClass storage_class) {
  218. // We do not use the type manager here, due to problems related to isomorphic
  219. // but distinct structs not being regarded as different.
  220. auto existing_id = fuzzerutil::MaybeGetPointerType(
  221. GetIRContext(), base_type_id, storage_class);
  222. if (existing_id) {
  223. return existing_id;
  224. }
  225. auto result = GetFuzzerContext()->GetFreshId();
  226. ApplyTransformation(
  227. TransformationAddTypePointer(result, storage_class, base_type_id));
  228. return result;
  229. }
  230. uint32_t FuzzerPass::FindOrCreatePointerTo32BitIntegerType(
  231. bool is_signed, SpvStorageClass storage_class) {
  232. return FindOrCreatePointerType(FindOrCreate32BitIntegerType(is_signed),
  233. storage_class);
  234. }
  235. uint32_t FuzzerPass::FindOrCreate32BitIntegerConstant(uint32_t word,
  236. bool is_signed) {
  237. auto uint32_type_id = FindOrCreate32BitIntegerType(is_signed);
  238. opt::analysis::IntConstant int_constant(
  239. GetIRContext()->get_type_mgr()->GetType(uint32_type_id)->AsInteger(),
  240. {word});
  241. auto existing_constant =
  242. GetIRContext()->get_constant_mgr()->FindConstant(&int_constant);
  243. if (existing_constant) {
  244. return GetIRContext()
  245. ->get_constant_mgr()
  246. ->GetDefiningInstruction(existing_constant)
  247. ->result_id();
  248. }
  249. auto result = GetFuzzerContext()->GetFreshId();
  250. ApplyTransformation(
  251. TransformationAddConstantScalar(result, uint32_type_id, {word}));
  252. return result;
  253. }
  254. uint32_t FuzzerPass::FindOrCreate32BitFloatConstant(uint32_t word) {
  255. auto float_type_id = FindOrCreate32BitFloatType();
  256. opt::analysis::FloatConstant float_constant(
  257. GetIRContext()->get_type_mgr()->GetType(float_type_id)->AsFloat(),
  258. {word});
  259. auto existing_constant =
  260. GetIRContext()->get_constant_mgr()->FindConstant(&float_constant);
  261. if (existing_constant) {
  262. return GetIRContext()
  263. ->get_constant_mgr()
  264. ->GetDefiningInstruction(existing_constant)
  265. ->result_id();
  266. }
  267. auto result = GetFuzzerContext()->GetFreshId();
  268. ApplyTransformation(
  269. TransformationAddConstantScalar(result, float_type_id, {word}));
  270. return result;
  271. }
  272. uint32_t FuzzerPass::FindOrCreateBoolConstant(bool value) {
  273. auto bool_type_id = FindOrCreateBoolType();
  274. opt::analysis::BoolConstant bool_constant(
  275. GetIRContext()->get_type_mgr()->GetType(bool_type_id)->AsBool(), value);
  276. auto existing_constant =
  277. GetIRContext()->get_constant_mgr()->FindConstant(&bool_constant);
  278. if (existing_constant) {
  279. return GetIRContext()
  280. ->get_constant_mgr()
  281. ->GetDefiningInstruction(existing_constant)
  282. ->result_id();
  283. }
  284. auto result = GetFuzzerContext()->GetFreshId();
  285. ApplyTransformation(TransformationAddConstantBoolean(result, value));
  286. return result;
  287. }
  288. uint32_t FuzzerPass::FindOrCreateGlobalUndef(uint32_t type_id) {
  289. for (auto& inst : GetIRContext()->types_values()) {
  290. if (inst.opcode() == SpvOpUndef && inst.type_id() == type_id) {
  291. return inst.result_id();
  292. }
  293. }
  294. auto result = GetFuzzerContext()->GetFreshId();
  295. ApplyTransformation(TransformationAddGlobalUndef(result, type_id));
  296. return result;
  297. }
  298. std::pair<std::vector<uint32_t>, std::map<uint32_t, std::vector<uint32_t>>>
  299. FuzzerPass::GetAvailableBaseTypesAndPointers(
  300. SpvStorageClass storage_class) const {
  301. // Records all of the base types available in the module.
  302. std::vector<uint32_t> base_types;
  303. // For each base type, records all the associated pointer types that target
  304. // that base type and that have |storage_class| as their storage class.
  305. std::map<uint32_t, std::vector<uint32_t>> base_type_to_pointers;
  306. for (auto& inst : GetIRContext()->types_values()) {
  307. switch (inst.opcode()) {
  308. case SpvOpTypeArray:
  309. case SpvOpTypeBool:
  310. case SpvOpTypeFloat:
  311. case SpvOpTypeInt:
  312. case SpvOpTypeMatrix:
  313. case SpvOpTypeStruct:
  314. case SpvOpTypeVector:
  315. // These types are suitable as pointer base types. Record the type,
  316. // and the fact that we cannot yet have seen any pointers that use this
  317. // as its base type.
  318. base_types.push_back(inst.result_id());
  319. base_type_to_pointers.insert({inst.result_id(), {}});
  320. break;
  321. case SpvOpTypePointer:
  322. if (inst.GetSingleWordInOperand(0) == storage_class) {
  323. // The pointer has the desired storage class, so we are interested in
  324. // it. Associate it with its base type.
  325. base_type_to_pointers.at(inst.GetSingleWordInOperand(1))
  326. .push_back(inst.result_id());
  327. }
  328. break;
  329. default:
  330. break;
  331. }
  332. }
  333. return {base_types, base_type_to_pointers};
  334. }
  335. uint32_t FuzzerPass::FindOrCreateZeroConstant(
  336. uint32_t scalar_or_composite_type_id) {
  337. auto type_instruction =
  338. GetIRContext()->get_def_use_mgr()->GetDef(scalar_or_composite_type_id);
  339. assert(type_instruction && "The type instruction must exist.");
  340. switch (type_instruction->opcode()) {
  341. case SpvOpTypeBool:
  342. return FindOrCreateBoolConstant(false);
  343. case SpvOpTypeFloat:
  344. return FindOrCreate32BitFloatConstant(0);
  345. case SpvOpTypeInt:
  346. return FindOrCreate32BitIntegerConstant(
  347. 0, type_instruction->GetSingleWordInOperand(1) != 0);
  348. case SpvOpTypeArray: {
  349. return GetZeroConstantForHomogeneousComposite(
  350. *type_instruction, type_instruction->GetSingleWordInOperand(0),
  351. fuzzerutil::GetArraySize(*type_instruction, GetIRContext()));
  352. }
  353. case SpvOpTypeMatrix:
  354. case SpvOpTypeVector: {
  355. return GetZeroConstantForHomogeneousComposite(
  356. *type_instruction, type_instruction->GetSingleWordInOperand(0),
  357. type_instruction->GetSingleWordInOperand(1));
  358. }
  359. case SpvOpTypeStruct: {
  360. std::vector<const opt::analysis::Constant*> field_zero_constants;
  361. std::vector<uint32_t> field_zero_ids;
  362. for (uint32_t index = 0; index < type_instruction->NumInOperands();
  363. index++) {
  364. uint32_t field_constant_id = FindOrCreateZeroConstant(
  365. type_instruction->GetSingleWordInOperand(index));
  366. field_zero_ids.push_back(field_constant_id);
  367. field_zero_constants.push_back(
  368. GetIRContext()->get_constant_mgr()->FindDeclaredConstant(
  369. field_constant_id));
  370. }
  371. return FindOrCreateCompositeConstant(
  372. *type_instruction, field_zero_constants, field_zero_ids);
  373. }
  374. default:
  375. assert(false && "Unknown type.");
  376. return 0;
  377. }
  378. }
  379. uint32_t FuzzerPass::FindOrCreateCompositeConstant(
  380. const opt::Instruction& composite_type_instruction,
  381. const std::vector<const opt::analysis::Constant*>& constants,
  382. const std::vector<uint32_t>& constant_ids) {
  383. assert(constants.size() == constant_ids.size() &&
  384. "Precondition: |constants| and |constant_ids| must be in "
  385. "correspondence.");
  386. opt::analysis::Type* composite_type = GetIRContext()->get_type_mgr()->GetType(
  387. composite_type_instruction.result_id());
  388. std::unique_ptr<opt::analysis::Constant> composite_constant;
  389. if (composite_type->AsArray()) {
  390. composite_constant = MakeUnique<opt::analysis::ArrayConstant>(
  391. composite_type->AsArray(), constants);
  392. } else if (composite_type->AsMatrix()) {
  393. composite_constant = MakeUnique<opt::analysis::MatrixConstant>(
  394. composite_type->AsMatrix(), constants);
  395. } else if (composite_type->AsStruct()) {
  396. composite_constant = MakeUnique<opt::analysis::StructConstant>(
  397. composite_type->AsStruct(), constants);
  398. } else if (composite_type->AsVector()) {
  399. composite_constant = MakeUnique<opt::analysis::VectorConstant>(
  400. composite_type->AsVector(), constants);
  401. } else {
  402. assert(false &&
  403. "Precondition: |composite_type| must declare a composite type.");
  404. return 0;
  405. }
  406. uint32_t existing_constant =
  407. GetIRContext()->get_constant_mgr()->FindDeclaredConstant(
  408. composite_constant.get(), composite_type_instruction.result_id());
  409. if (existing_constant) {
  410. return existing_constant;
  411. }
  412. uint32_t result = GetFuzzerContext()->GetFreshId();
  413. ApplyTransformation(TransformationAddConstantComposite(
  414. result, composite_type_instruction.result_id(), constant_ids));
  415. return result;
  416. }
  417. uint32_t FuzzerPass::GetZeroConstantForHomogeneousComposite(
  418. const opt::Instruction& composite_type_instruction,
  419. uint32_t component_type_id, uint32_t num_components) {
  420. std::vector<const opt::analysis::Constant*> zero_constants;
  421. std::vector<uint32_t> zero_ids;
  422. uint32_t zero_component = FindOrCreateZeroConstant(component_type_id);
  423. const opt::analysis::Constant* registered_zero_component =
  424. GetIRContext()->get_constant_mgr()->FindDeclaredConstant(zero_component);
  425. for (uint32_t i = 0; i < num_components; i++) {
  426. zero_constants.push_back(registered_zero_component);
  427. zero_ids.push_back(zero_component);
  428. }
  429. return FindOrCreateCompositeConstant(composite_type_instruction,
  430. zero_constants, zero_ids);
  431. }
  432. } // namespace fuzz
  433. } // namespace spvtools