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 auto pointer_type = GetIRContext()->get_def_use_mgr()->GetDef(
96 chosen_pointer->type_id());
97 uint32_t subobject_type_id = pointer_type->GetSingleWordInOperand(1);
98 while (true) {
99 auto subobject_type =
100 GetIRContext()->get_def_use_mgr()->GetDef(subobject_type_id);
101 if (!spvOpcodeIsComposite(subobject_type->opcode())) {
102 break;
103 }
104 if (!GetFuzzerContext()->ChoosePercentage(
105 GetFuzzerContext()
106 ->GetChanceOfGoingDeeperWhenMakingAccessChain())) {
107 break;
108 }
109 uint32_t bound;
110 switch (subobject_type->opcode()) {
111 case SpvOpTypeArray:
112 bound = fuzzerutil::GetArraySize(*subobject_type, GetIRContext());
113 break;
114 case SpvOpTypeMatrix:
115 case SpvOpTypeVector:
116 bound = subobject_type->GetSingleWordInOperand(1);
117 break;
118 case SpvOpTypeStruct:
119 bound = fuzzerutil::GetNumberOfStructMembers(*subobject_type);
120 break;
121 default:
122 assert(false && "Not a composite type opcode.");
123 // Set the bound to a value in order to keep release compilers
124 // happy.
125 bound = 0;
126 break;
127 }
128 if (bound == 0) {
129 // It is possible for a composite type to legitimately have zero
130 // sub-components, at least in the case of a struct, which
131 // can have no fields.
132 break;
133 }
134
135 // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/3179) We
136 // could allow non-constant indices when looking up non-structs,
137 // using clamping to ensure they are in-bounds.
138 uint32_t index_value =
139 GetFuzzerContext()->GetRandomIndexForAccessChain(bound);
140 index_ids.push_back(FindOrCreate32BitIntegerConstant(
141 index_value, GetFuzzerContext()->ChooseEven()));
142 switch (subobject_type->opcode()) {
143 case SpvOpTypeArray:
144 case SpvOpTypeMatrix:
145 case SpvOpTypeVector:
146 subobject_type_id = subobject_type->GetSingleWordInOperand(0);
147 break;
148 case SpvOpTypeStruct:
149 subobject_type_id =
150 subobject_type->GetSingleWordInOperand(index_value);
151 break;
152 default:
153 assert(false && "Not a composite type opcode.");
154 }
155 }
156 // The transformation we are about to create will only apply if a
157 // pointer suitable for the access chain's result type exists, so we
158 // create one if it does not.
159 FindOrCreatePointerType(subobject_type_id,
160 static_cast<SpvStorageClass>(
161 pointer_type->GetSingleWordInOperand(0)));
162 // Apply the transformation to add an access chain.
163 ApplyTransformation(TransformationAccessChain(
164 GetFuzzerContext()->GetFreshId(), chosen_pointer->result_id(),
165 index_ids, instruction_descriptor));
166 });
167 }
168
169 } // namespace fuzz
170 } // namespace spvtools
171