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