fuzzer_pass_add_function_calls.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. // Copyright (c) 2020 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_add_function_calls.h"
  15. #include "source/fuzz/call_graph.h"
  16. #include "source/fuzz/fuzzer_util.h"
  17. #include "source/fuzz/transformation_add_global_variable.h"
  18. #include "source/fuzz/transformation_add_local_variable.h"
  19. #include "source/fuzz/transformation_function_call.h"
  20. namespace spvtools {
  21. namespace fuzz {
  22. FuzzerPassAddFunctionCalls::FuzzerPassAddFunctionCalls(
  23. opt::IRContext* ir_context, FactManager* fact_manager,
  24. FuzzerContext* fuzzer_context,
  25. protobufs::TransformationSequence* transformations)
  26. : FuzzerPass(ir_context, fact_manager, fuzzer_context, transformations) {}
  27. FuzzerPassAddFunctionCalls::~FuzzerPassAddFunctionCalls() = default;
  28. void FuzzerPassAddFunctionCalls::Apply() {
  29. ForEachInstructionWithInstructionDescriptor(
  30. [this](opt::Function* function, opt::BasicBlock* block,
  31. opt::BasicBlock::iterator inst_it,
  32. const protobufs::InstructionDescriptor& instruction_descriptor)
  33. -> void {
  34. // Check whether it is legitimate to insert a function call before the
  35. // instruction.
  36. if (!fuzzerutil::CanInsertOpcodeBeforeInstruction(SpvOpFunctionCall,
  37. inst_it)) {
  38. return;
  39. }
  40. // Randomly decide whether to try inserting a function call here.
  41. if (!GetFuzzerContext()->ChoosePercentage(
  42. GetFuzzerContext()->GetChanceOfCallingFunction())) {
  43. return;
  44. }
  45. // Compute the module's call graph - we don't cache it since it may
  46. // change each time we apply a transformation. If this proves to be
  47. // a bottleneck the call graph data structure could be made updatable.
  48. CallGraph call_graph(GetIRContext());
  49. // Gather all the non-entry point functions different from this
  50. // function. It is important to ignore entry points as a function
  51. // cannot be an entry point and the target of an OpFunctionCall
  52. // instruction. We ignore this function to avoid direct recursion.
  53. std::vector<opt::Function*> candidate_functions;
  54. for (auto& other_function : *GetIRContext()->module()) {
  55. if (&other_function != function &&
  56. !fuzzerutil::FunctionIsEntryPoint(GetIRContext(),
  57. other_function.result_id())) {
  58. candidate_functions.push_back(&other_function);
  59. }
  60. }
  61. // Choose a function to call, at random, by considering candidate
  62. // functions until a suitable one is found.
  63. opt::Function* chosen_function = nullptr;
  64. while (!candidate_functions.empty()) {
  65. opt::Function* candidate_function =
  66. GetFuzzerContext()->RemoveAtRandomIndex(&candidate_functions);
  67. if (!GetFactManager()->BlockIsDead(block->id()) &&
  68. !GetFactManager()->FunctionIsLivesafe(
  69. candidate_function->result_id())) {
  70. // Unless in a dead block, only livesafe functions can be invoked
  71. continue;
  72. }
  73. if (call_graph.GetIndirectCallees(candidate_function->result_id())
  74. .count(function->result_id())) {
  75. // Calling this function could lead to indirect recursion
  76. continue;
  77. }
  78. chosen_function = candidate_function;
  79. break;
  80. }
  81. if (!chosen_function) {
  82. // No suitable function was found to call. (This can happen, for
  83. // instance, if the current function is the only function in the
  84. // module.)
  85. return;
  86. }
  87. ApplyTransformation(TransformationFunctionCall(
  88. GetFuzzerContext()->GetFreshId(), chosen_function->result_id(),
  89. ChooseFunctionCallArguments(*chosen_function, function, block,
  90. inst_it),
  91. instruction_descriptor));
  92. });
  93. }
  94. std::map<uint32_t, std::vector<opt::Instruction*>>
  95. FuzzerPassAddFunctionCalls::GetAvailableInstructionsSuitableForActualParameters(
  96. opt::Function* function, opt::BasicBlock* block,
  97. const opt::BasicBlock::iterator& inst_it) {
  98. // Find all instructions in scope that could potentially be used as actual
  99. // parameters. Weed out unsuitable pointer arguments immediately.
  100. std::vector<opt::Instruction*> potentially_suitable_instructions =
  101. FindAvailableInstructions(
  102. function, block, inst_it,
  103. [this, block](opt::IRContext* context,
  104. opt::Instruction* inst) -> bool {
  105. if (!inst->HasResultId() || !inst->type_id()) {
  106. // An instruction needs a result id and type in order
  107. // to be suitable as an actual parameter.
  108. return false;
  109. }
  110. if (context->get_def_use_mgr()->GetDef(inst->type_id())->opcode() ==
  111. SpvOpTypePointer) {
  112. switch (inst->opcode()) {
  113. case SpvOpFunctionParameter:
  114. case SpvOpVariable:
  115. // Function parameters and variables are the only
  116. // kinds of pointer that can be used as actual
  117. // parameters.
  118. break;
  119. default:
  120. return false;
  121. }
  122. if (!GetFactManager()->BlockIsDead(block->id()) &&
  123. !GetFactManager()->PointeeValueIsIrrelevant(
  124. inst->result_id())) {
  125. // We can only pass a pointer as an actual parameter
  126. // if the pointee value for the pointer is irrelevant,
  127. // or if the block from which we would make the
  128. // function call is dead.
  129. return false;
  130. }
  131. }
  132. return true;
  133. });
  134. // Group all the instructions that are potentially viable as function actual
  135. // parameters by their result types.
  136. std::map<uint32_t, std::vector<opt::Instruction*>> result;
  137. for (auto inst : potentially_suitable_instructions) {
  138. if (result.count(inst->type_id()) == 0) {
  139. // This is the first instruction of this type we have seen, so populate
  140. // the map with an entry.
  141. result.insert({inst->type_id(), {}});
  142. }
  143. // Add the instruction to the sequence of instructions already associated
  144. // with this type.
  145. result.at(inst->type_id()).push_back(inst);
  146. }
  147. return result;
  148. }
  149. std::vector<uint32_t> FuzzerPassAddFunctionCalls::ChooseFunctionCallArguments(
  150. const opt::Function& callee, opt::Function* caller_function,
  151. opt::BasicBlock* caller_block,
  152. const opt::BasicBlock::iterator& caller_inst_it) {
  153. auto type_to_available_instructions =
  154. GetAvailableInstructionsSuitableForActualParameters(
  155. caller_function, caller_block, caller_inst_it);
  156. opt::Instruction* function_type = GetIRContext()->get_def_use_mgr()->GetDef(
  157. callee.DefInst().GetSingleWordInOperand(1));
  158. assert(function_type->opcode() == SpvOpTypeFunction &&
  159. "The function type does not have the expected opcode.");
  160. std::vector<uint32_t> result;
  161. for (uint32_t arg_index = 1; arg_index < function_type->NumInOperands();
  162. arg_index++) {
  163. auto arg_type_id =
  164. GetIRContext()
  165. ->get_def_use_mgr()
  166. ->GetDef(function_type->GetSingleWordInOperand(arg_index))
  167. ->result_id();
  168. if (type_to_available_instructions.count(arg_type_id)) {
  169. std::vector<opt::Instruction*>& candidate_arguments =
  170. type_to_available_instructions.at(arg_type_id);
  171. // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/3177) The value
  172. // selected here is arbitrary. We should consider adding this
  173. // information as a fact so that the passed parameter could be
  174. // transformed/changed.
  175. result.push_back(candidate_arguments[GetFuzzerContext()->RandomIndex(
  176. candidate_arguments)]
  177. ->result_id());
  178. } else {
  179. // We don't have a suitable id in scope to pass, so we must make
  180. // something up.
  181. auto type_instruction =
  182. GetIRContext()->get_def_use_mgr()->GetDef(arg_type_id);
  183. if (type_instruction->opcode() == SpvOpTypePointer) {
  184. // In the case of a pointer, we make a new variable, at function
  185. // or global scope depending on the storage class of the
  186. // pointer.
  187. // Get a fresh id for the new variable.
  188. uint32_t fresh_variable_id = GetFuzzerContext()->GetFreshId();
  189. // The id of this variable is what we pass as the parameter to
  190. // the call.
  191. result.push_back(fresh_variable_id);
  192. // Now bring the variable into existence.
  193. if (type_instruction->GetSingleWordInOperand(0) ==
  194. SpvStorageClassFunction) {
  195. // Add a new zero-initialized local variable to the current
  196. // function, noting that its pointee value is irrelevant.
  197. ApplyTransformation(TransformationAddLocalVariable(
  198. fresh_variable_id, arg_type_id, caller_function->result_id(),
  199. FindOrCreateZeroConstant(
  200. type_instruction->GetSingleWordInOperand(1)),
  201. true));
  202. } else {
  203. assert(type_instruction->GetSingleWordInOperand(0) ==
  204. SpvStorageClassPrivate &&
  205. "Only Function and Private storage classes are "
  206. "supported at present.");
  207. // Add a new zero-initialized global variable to the module,
  208. // noting that its pointee value is irrelevant.
  209. ApplyTransformation(TransformationAddGlobalVariable(
  210. fresh_variable_id, arg_type_id,
  211. FindOrCreateZeroConstant(
  212. type_instruction->GetSingleWordInOperand(1)),
  213. true));
  214. }
  215. } else {
  216. // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/3177): We use
  217. // constant zero for the parameter, but could consider adding a fact
  218. // to allow further passes to obfuscate it.
  219. result.push_back(FindOrCreateZeroConstant(arg_type_id));
  220. }
  221. }
  222. }
  223. return result;
  224. }
  225. } // namespace fuzz
  226. } // namespace spvtools