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