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