fuzzer_pass_add_function_calls.cpp 11 KB

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