• 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_access_chains.h"
16 
17 #include "source/fuzz/fuzzer_util.h"
18 #include "source/fuzz/transformation_access_chain.h"
19 
20 namespace spvtools {
21 namespace fuzz {
22 
FuzzerPassAddAccessChains(opt::IRContext * ir_context,TransformationContext * transformation_context,FuzzerContext * fuzzer_context,protobufs::TransformationSequence * transformations)23 FuzzerPassAddAccessChains::FuzzerPassAddAccessChains(
24     opt::IRContext* ir_context, TransformationContext* transformation_context,
25     FuzzerContext* fuzzer_context,
26     protobufs::TransformationSequence* transformations)
27     : FuzzerPass(ir_context, transformation_context, fuzzer_context,
28                  transformations) {}
29 
30 FuzzerPassAddAccessChains::~FuzzerPassAddAccessChains() = default;
31 
Apply()32 void FuzzerPassAddAccessChains::Apply() {
33   ForEachInstructionWithInstructionDescriptor(
34       [this](opt::Function* function, opt::BasicBlock* block,
35              opt::BasicBlock::iterator inst_it,
36              const protobufs::InstructionDescriptor& instruction_descriptor)
37           -> void {
38         assert(inst_it->opcode() ==
39                    instruction_descriptor.target_instruction_opcode() &&
40                "The opcode of the instruction we might insert before must be "
41                "the same as the opcode in the descriptor for the instruction");
42 
43         // Check whether it is legitimate to insert an access chain
44         // instruction before this instruction.
45         if (!fuzzerutil::CanInsertOpcodeBeforeInstruction(SpvOpAccessChain,
46                                                           inst_it)) {
47           return;
48         }
49 
50         // Randomly decide whether to try inserting a load here.
51         if (!GetFuzzerContext()->ChoosePercentage(
52                 GetFuzzerContext()->GetChanceOfAddingAccessChain())) {
53           return;
54         }
55 
56         // Get all of the pointers that are currently in scope, excluding
57         // explicitly null and undefined pointers.
58         std::vector<opt::Instruction*> relevant_pointer_instructions =
59             FindAvailableInstructions(
60                 function, block, inst_it,
61                 [](opt::IRContext* context,
62                    opt::Instruction* instruction) -> bool {
63                   if (!instruction->result_id() || !instruction->type_id()) {
64                     // A pointer needs both a result and type id.
65                     return false;
66                   }
67                   switch (instruction->opcode()) {
68                     case SpvOpConstantNull:
69                     case SpvOpUndef:
70                       // Do not allow making an access chain from a null or
71                       // undefined pointer.  (We can eliminate these cases
72                       // before actually checking that the instruction is a
73                       // pointer.)
74                       return false;
75                     default:
76                       break;
77                   }
78                   // If the instruction has pointer type, we can legitimately
79                   // make an access chain from it.
80                   return context->get_def_use_mgr()
81                              ->GetDef(instruction->type_id())
82                              ->opcode() == SpvOpTypePointer;
83                 });
84 
85         // At this point, |relevant_instructions| contains all the pointers
86         // we might think of making an access chain from.
87         if (relevant_pointer_instructions.empty()) {
88           return;
89         }
90 
91         auto chosen_pointer =
92             relevant_pointer_instructions[GetFuzzerContext()->RandomIndex(
93                 relevant_pointer_instructions)];
94         std::vector<uint32_t> index_ids;
95 
96         // Each index accessing a non-struct composite will be clamped, thus
97         // needing a pair of fresh ids
98         std::vector<std::pair<uint32_t, uint32_t>> fresh_ids_for_clamping;
99 
100         auto pointer_type = GetIRContext()->get_def_use_mgr()->GetDef(
101             chosen_pointer->type_id());
102         uint32_t subobject_type_id = pointer_type->GetSingleWordInOperand(1);
103         while (true) {
104           auto subobject_type =
105               GetIRContext()->get_def_use_mgr()->GetDef(subobject_type_id);
106           if (!spvOpcodeIsComposite(subobject_type->opcode())) {
107             break;
108           }
109           if (!GetFuzzerContext()->ChoosePercentage(
110                   GetFuzzerContext()
111                       ->GetChanceOfGoingDeeperWhenMakingAccessChain())) {
112             break;
113           }
114           uint32_t bound;
115           switch (subobject_type->opcode()) {
116             case SpvOpTypeArray:
117               bound = fuzzerutil::GetArraySize(*subobject_type, GetIRContext());
118               break;
119             case SpvOpTypeMatrix:
120             case SpvOpTypeVector:
121               bound = subobject_type->GetSingleWordInOperand(1);
122               break;
123             case SpvOpTypeStruct:
124               bound = fuzzerutil::GetNumberOfStructMembers(*subobject_type);
125               break;
126             default:
127               assert(false && "Not a composite type opcode.");
128               // Set the bound to a value in order to keep release compilers
129               // happy.
130               bound = 0;
131               break;
132           }
133           if (bound == 0) {
134             // It is possible for a composite type to legitimately have zero
135             // sub-components, at least in the case of a struct, which
136             // can have no fields.
137             break;
138           }
139 
140           uint32_t index_value =
141               GetFuzzerContext()->GetRandomIndexForAccessChain(bound);
142 
143           switch (subobject_type->opcode()) {
144             case SpvOpTypeArray:
145             case SpvOpTypeMatrix:
146             case SpvOpTypeVector: {
147               // The index will be clamped
148 
149               bool is_signed = GetFuzzerContext()->ChooseEven();
150 
151               // Make the constant ready for clamping. We need:
152               // - an OpTypeBool to be present in the module
153               // - an OpConstant with the same type as the index and value
154               //   the maximum value for an index
155               // - a new pair of fresh ids for the clamping instructions
156               FindOrCreateBoolType();
157               FindOrCreateIntegerConstant({bound - 1}, 32, is_signed, false);
158               std::pair<uint32_t, uint32_t> fresh_pair_of_ids = {
159                   GetFuzzerContext()->GetFreshId(),
160                   GetFuzzerContext()->GetFreshId()};
161               fresh_ids_for_clamping.emplace_back(fresh_pair_of_ids);
162 
163               index_ids.push_back(FindOrCreateIntegerConstant(
164                   {index_value}, 32, is_signed, false));
165               subobject_type_id = subobject_type->GetSingleWordInOperand(0);
166 
167             } break;
168             case SpvOpTypeStruct:
169               index_ids.push_back(FindOrCreateIntegerConstant(
170                   {index_value}, 32, GetFuzzerContext()->ChooseEven(), false));
171               subobject_type_id =
172                   subobject_type->GetSingleWordInOperand(index_value);
173               break;
174             default:
175               assert(false && "Not a composite type opcode.");
176           }
177         }
178         // The transformation we are about to create will only apply if a
179         // pointer suitable for the access chain's result type exists, so we
180         // create one if it does not.
181         FindOrCreatePointerType(subobject_type_id,
182                                 static_cast<SpvStorageClass>(
183                                     pointer_type->GetSingleWordInOperand(0)));
184         // Apply the transformation to add an access chain.
185         ApplyTransformation(TransformationAccessChain(
186             GetFuzzerContext()->GetFreshId(), chosen_pointer->result_id(),
187             index_ids, instruction_descriptor, fresh_ids_for_clamping));
188       });
189 }
190 
191 }  // namespace fuzz
192 }  // namespace spvtools
193