fuzzer_pass_add_function_calls.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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. bool ignore_inapplicable_transformations)
  27. : FuzzerPass(ir_context, transformation_context, fuzzer_context,
  28. transformations, ignore_inapplicable_transformations) {}
  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(
  38. spv::Op::OpFunctionCall, 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::vector<uint32_t> FuzzerPassAddFunctionCalls::ChooseFunctionCallArguments(
  97. const opt::Function& callee, opt::Function* caller_function,
  98. opt::BasicBlock* caller_block,
  99. const opt::BasicBlock::iterator& caller_inst_it) {
  100. auto available_pointers = FindAvailableInstructions(
  101. caller_function, caller_block, caller_inst_it,
  102. [this, caller_block](opt::IRContext* /*unused*/, opt::Instruction* inst) {
  103. if (inst->opcode() != spv::Op::OpVariable ||
  104. inst->opcode() != spv::Op::OpFunctionParameter) {
  105. // Function parameters and variables are the only
  106. // kinds of pointer that can be used as actual
  107. // parameters.
  108. return false;
  109. }
  110. return GetTransformationContext()->GetFactManager()->BlockIsDead(
  111. caller_block->id()) ||
  112. GetTransformationContext()
  113. ->GetFactManager()
  114. ->PointeeValueIsIrrelevant(inst->result_id());
  115. });
  116. std::unordered_map<uint32_t, std::vector<uint32_t>> type_id_to_result_id;
  117. for (const auto* inst : available_pointers) {
  118. type_id_to_result_id[inst->type_id()].push_back(inst->result_id());
  119. }
  120. std::vector<uint32_t> result;
  121. for (const auto* param :
  122. fuzzerutil::GetParameters(GetIRContext(), callee.result_id())) {
  123. const auto* param_type =
  124. GetIRContext()->get_type_mgr()->GetType(param->type_id());
  125. assert(param_type && "Parameter has invalid type");
  126. if (!param_type->AsPointer()) {
  127. if (fuzzerutil::CanCreateConstant(GetIRContext(), param->type_id())) {
  128. // We mark the constant as irrelevant so that we can replace it with a
  129. // more interesting value later.
  130. result.push_back(FindOrCreateZeroConstant(param->type_id(), true));
  131. } else {
  132. result.push_back(FindOrCreateGlobalUndef(param->type_id()));
  133. }
  134. continue;
  135. }
  136. if (type_id_to_result_id.count(param->type_id())) {
  137. // Use an existing pointer if there are any.
  138. const auto& candidates = type_id_to_result_id[param->type_id()];
  139. result.push_back(candidates[GetFuzzerContext()->RandomIndex(candidates)]);
  140. continue;
  141. }
  142. // Make a new variable, at function or global scope depending on the storage
  143. // class of the pointer.
  144. // Get a fresh id for the new variable.
  145. uint32_t fresh_variable_id = GetFuzzerContext()->GetFreshId();
  146. // The id of this variable is what we pass as the parameter to
  147. // the call.
  148. result.push_back(fresh_variable_id);
  149. type_id_to_result_id[param->type_id()].push_back(fresh_variable_id);
  150. // Now bring the variable into existence.
  151. auto storage_class = param_type->AsPointer()->storage_class();
  152. auto pointee_type_id = fuzzerutil::GetPointeeTypeIdFromPointerType(
  153. GetIRContext(), param->type_id());
  154. if (storage_class == spv::StorageClass::Function) {
  155. // Add a new zero-initialized local variable to the current
  156. // function, noting that its pointee value is irrelevant.
  157. ApplyTransformation(TransformationAddLocalVariable(
  158. fresh_variable_id, param->type_id(), caller_function->result_id(),
  159. FindOrCreateZeroConstant(pointee_type_id, false), true));
  160. } else {
  161. assert((storage_class == spv::StorageClass::Private ||
  162. storage_class == spv::StorageClass::Workgroup) &&
  163. "Only Function, Private and Workgroup storage classes are "
  164. "supported at present.");
  165. // Add a new global variable to the module, zero-initializing it if
  166. // it has Private storage class, and noting that its pointee value is
  167. // irrelevant.
  168. ApplyTransformation(TransformationAddGlobalVariable(
  169. fresh_variable_id, param->type_id(), storage_class,
  170. storage_class == spv::StorageClass::Private
  171. ? FindOrCreateZeroConstant(pointee_type_id, false)
  172. : 0,
  173. true));
  174. }
  175. }
  176. return result;
  177. }
  178. } // namespace fuzz
  179. } // namespace spvtools