fuzzer_pass_add_function_calls.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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::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() != SpvOpVariable ||
  104. inst->opcode() != SpvOpFunctionParameter) {
  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. // We mark the constant as irrelevant so that we can replace it with a
  128. // more interesting value later.
  129. result.push_back(FindOrCreateZeroConstant(param->type_id(), true));
  130. continue;
  131. }
  132. if (type_id_to_result_id.count(param->type_id())) {
  133. // Use an existing pointer if there are any.
  134. const auto& candidates = type_id_to_result_id[param->type_id()];
  135. result.push_back(candidates[GetFuzzerContext()->RandomIndex(candidates)]);
  136. continue;
  137. }
  138. // Make a new variable, at function or global scope depending on the storage
  139. // class of the pointer.
  140. // Get a fresh id for the new variable.
  141. uint32_t fresh_variable_id = GetFuzzerContext()->GetFreshId();
  142. // The id of this variable is what we pass as the parameter to
  143. // the call.
  144. result.push_back(fresh_variable_id);
  145. type_id_to_result_id[param->type_id()].push_back(fresh_variable_id);
  146. // Now bring the variable into existence.
  147. auto storage_class = param_type->AsPointer()->storage_class();
  148. auto pointee_type_id = fuzzerutil::GetPointeeTypeIdFromPointerType(
  149. GetIRContext(), param->type_id());
  150. if (storage_class == SpvStorageClassFunction) {
  151. // Add a new zero-initialized local variable to the current
  152. // function, noting that its pointee value is irrelevant.
  153. ApplyTransformation(TransformationAddLocalVariable(
  154. fresh_variable_id, param->type_id(), caller_function->result_id(),
  155. FindOrCreateZeroConstant(pointee_type_id, false), true));
  156. } else {
  157. assert((storage_class == SpvStorageClassPrivate ||
  158. storage_class == SpvStorageClassWorkgroup) &&
  159. "Only Function, Private and Workgroup storage classes are "
  160. "supported at present.");
  161. // Add a new global variable to the module, zero-initializing it if
  162. // it has Private storage class, and noting that its pointee value is
  163. // irrelevant.
  164. ApplyTransformation(TransformationAddGlobalVariable(
  165. fresh_variable_id, param->type_id(), storage_class,
  166. storage_class == SpvStorageClassPrivate
  167. ? FindOrCreateZeroConstant(pointee_type_id, false)
  168. : 0,
  169. true));
  170. }
  171. }
  172. return result;
  173. }
  174. } // namespace fuzz
  175. } // namespace spvtools