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