• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
Apply()33 void FuzzerPassAddFunctionCalls::Apply() {
34   ForEachInstructionWithInstructionDescriptor(
35       [this](opt::Function* function, opt::BasicBlock* block,
36              opt::BasicBlock::iterator inst_it,
37              const protobufs::InstructionDescriptor& instruction_descriptor)
38           -> void {
39         // Check whether it is legitimate to insert a function call before the
40         // instruction.
41         if (!fuzzerutil::CanInsertOpcodeBeforeInstruction(SpvOpFunctionCall,
42                                                           inst_it)) {
43           return;
44         }
45 
46         // Randomly decide whether to try inserting a function call here.
47         if (!GetFuzzerContext()->ChoosePercentage(
48                 GetFuzzerContext()->GetChanceOfCallingFunction())) {
49           return;
50         }
51 
52         // Compute the module's call graph - we don't cache it since it may
53         // change each time we apply a transformation.  If this proves to be
54         // a bottleneck the call graph data structure could be made updatable.
55         CallGraph call_graph(GetIRContext());
56 
57         // Gather all the non-entry point functions different from this
58         // function.  It is important to ignore entry points as a function
59         // cannot be an entry point and the target of an OpFunctionCall
60         // instruction.  We ignore this function to avoid direct recursion.
61         std::vector<opt::Function*> candidate_functions;
62         for (auto& other_function : *GetIRContext()->module()) {
63           if (&other_function != function &&
64               !fuzzerutil::FunctionIsEntryPoint(GetIRContext(),
65                                                 other_function.result_id())) {
66             candidate_functions.push_back(&other_function);
67           }
68         }
69 
70         // Choose a function to call, at random, by considering candidate
71         // functions until a suitable one is found.
72         opt::Function* chosen_function = nullptr;
73         while (!candidate_functions.empty()) {
74           opt::Function* candidate_function =
75               GetFuzzerContext()->RemoveAtRandomIndex(&candidate_functions);
76           if (!GetTransformationContext()->GetFactManager()->BlockIsDead(
77                   block->id()) &&
78               !GetTransformationContext()->GetFactManager()->FunctionIsLivesafe(
79                   candidate_function->result_id())) {
80             // Unless in a dead block, only livesafe functions can be invoked
81             continue;
82           }
83           if (call_graph.GetIndirectCallees(candidate_function->result_id())
84                   .count(function->result_id())) {
85             // Calling this function could lead to indirect recursion
86             continue;
87           }
88           chosen_function = candidate_function;
89           break;
90         }
91 
92         if (!chosen_function) {
93           // No suitable function was found to call.  (This can happen, for
94           // instance, if the current function is the only function in the
95           // module.)
96           return;
97         }
98 
99         ApplyTransformation(TransformationFunctionCall(
100             GetFuzzerContext()->GetFreshId(), chosen_function->result_id(),
101             ChooseFunctionCallArguments(*chosen_function, function, block,
102                                         inst_it),
103             instruction_descriptor));
104       });
105 }
106 
ChooseFunctionCallArguments(const opt::Function & callee,opt::Function * caller_function,opt::BasicBlock * caller_block,const opt::BasicBlock::iterator & caller_inst_it)107 std::vector<uint32_t> FuzzerPassAddFunctionCalls::ChooseFunctionCallArguments(
108     const opt::Function& callee, opt::Function* caller_function,
109     opt::BasicBlock* caller_block,
110     const opt::BasicBlock::iterator& caller_inst_it) {
111   auto available_pointers = FindAvailableInstructions(
112       caller_function, caller_block, caller_inst_it,
113       [this, caller_block](opt::IRContext* /*unused*/, opt::Instruction* inst) {
114         if (inst->opcode() != SpvOpVariable ||
115             inst->opcode() != SpvOpFunctionParameter) {
116           // Function parameters and variables are the only
117           // kinds of pointer that can be used as actual
118           // parameters.
119           return false;
120         }
121 
122         return GetTransformationContext()->GetFactManager()->BlockIsDead(
123                    caller_block->id()) ||
124                GetTransformationContext()
125                    ->GetFactManager()
126                    ->PointeeValueIsIrrelevant(inst->result_id());
127       });
128 
129   std::unordered_map<uint32_t, std::vector<uint32_t>> type_id_to_result_id;
130   for (const auto* inst : available_pointers) {
131     type_id_to_result_id[inst->type_id()].push_back(inst->result_id());
132   }
133 
134   std::vector<uint32_t> result;
135   for (const auto* param :
136        fuzzerutil::GetParameters(GetIRContext(), callee.result_id())) {
137     const auto* param_type =
138         GetIRContext()->get_type_mgr()->GetType(param->type_id());
139     assert(param_type && "Parameter has invalid type");
140 
141     if (!param_type->AsPointer()) {
142       if (fuzzerutil::CanCreateConstant(GetIRContext(), param->type_id())) {
143         // We mark the constant as irrelevant so that we can replace it with a
144         // more interesting value later.
145         result.push_back(FindOrCreateZeroConstant(param->type_id(), true));
146       } else {
147         result.push_back(FindOrCreateGlobalUndef(param->type_id()));
148       }
149       continue;
150     }
151 
152     if (type_id_to_result_id.count(param->type_id())) {
153       // Use an existing pointer if there are any.
154       const auto& candidates = type_id_to_result_id[param->type_id()];
155       result.push_back(candidates[GetFuzzerContext()->RandomIndex(candidates)]);
156       continue;
157     }
158 
159     // Make a new variable, at function or global scope depending on the storage
160     // class of the pointer.
161 
162     // Get a fresh id for the new variable.
163     uint32_t fresh_variable_id = GetFuzzerContext()->GetFreshId();
164 
165     // The id of this variable is what we pass as the parameter to
166     // the call.
167     result.push_back(fresh_variable_id);
168     type_id_to_result_id[param->type_id()].push_back(fresh_variable_id);
169 
170     // Now bring the variable into existence.
171     auto storage_class = param_type->AsPointer()->storage_class();
172     auto pointee_type_id = fuzzerutil::GetPointeeTypeIdFromPointerType(
173         GetIRContext(), param->type_id());
174     if (storage_class == SpvStorageClassFunction) {
175       // Add a new zero-initialized local variable to the current
176       // function, noting that its pointee value is irrelevant.
177       ApplyTransformation(TransformationAddLocalVariable(
178           fresh_variable_id, param->type_id(), caller_function->result_id(),
179           FindOrCreateZeroConstant(pointee_type_id, false), true));
180     } else {
181       assert((storage_class == SpvStorageClassPrivate ||
182               storage_class == SpvStorageClassWorkgroup) &&
183              "Only Function, Private and Workgroup storage classes are "
184              "supported at present.");
185       // Add a new global variable to the module, zero-initializing it if
186       // it has Private storage class, and noting that its pointee value is
187       // irrelevant.
188       ApplyTransformation(TransformationAddGlobalVariable(
189           fresh_variable_id, param->type_id(), storage_class,
190           storage_class == SpvStorageClassPrivate
191               ? FindOrCreateZeroConstant(pointee_type_id, false)
192               : 0,
193           true));
194     }
195   }
196 
197   return result;
198 }
199 
200 }  // namespace fuzz
201 }  // namespace spvtools
202