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