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/transformation_access_chain.h"
16
17 #include <vector>
18
19 #include "source/fuzz/fuzzer_util.h"
20 #include "source/fuzz/instruction_descriptor.h"
21
22 namespace spvtools {
23 namespace fuzz {
24
TransformationAccessChain(const spvtools::fuzz::protobufs::TransformationAccessChain & message)25 TransformationAccessChain::TransformationAccessChain(
26 const spvtools::fuzz::protobufs::TransformationAccessChain& message)
27 : message_(message) {}
28
TransformationAccessChain(uint32_t fresh_id,uint32_t pointer_id,const std::vector<uint32_t> & index_id,const protobufs::InstructionDescriptor & instruction_to_insert_before)29 TransformationAccessChain::TransformationAccessChain(
30 uint32_t fresh_id, uint32_t pointer_id,
31 const std::vector<uint32_t>& index_id,
32 const protobufs::InstructionDescriptor& instruction_to_insert_before) {
33 message_.set_fresh_id(fresh_id);
34 message_.set_pointer_id(pointer_id);
35 for (auto id : index_id) {
36 message_.add_index_id(id);
37 }
38 *message_.mutable_instruction_to_insert_before() =
39 instruction_to_insert_before;
40 }
41
IsApplicable(opt::IRContext * ir_context,const TransformationContext &) const42 bool TransformationAccessChain::IsApplicable(
43 opt::IRContext* ir_context, const TransformationContext& /*unused*/) const {
44 // The result id must be fresh
45 if (!fuzzerutil::IsFreshId(ir_context, message_.fresh_id())) {
46 return false;
47 }
48 // The pointer id must exist and have a type.
49 auto pointer = ir_context->get_def_use_mgr()->GetDef(message_.pointer_id());
50 if (!pointer || !pointer->type_id()) {
51 return false;
52 }
53 // The type must indeed be a pointer
54 auto pointer_type = ir_context->get_def_use_mgr()->GetDef(pointer->type_id());
55 if (pointer_type->opcode() != SpvOpTypePointer) {
56 return false;
57 }
58
59 // The described instruction to insert before must exist and be a suitable
60 // point where an OpAccessChain instruction could be inserted.
61 auto instruction_to_insert_before =
62 FindInstruction(message_.instruction_to_insert_before(), ir_context);
63 if (!instruction_to_insert_before) {
64 return false;
65 }
66 if (!fuzzerutil::CanInsertOpcodeBeforeInstruction(
67 SpvOpAccessChain, instruction_to_insert_before)) {
68 return false;
69 }
70
71 // Do not allow making an access chain from a null or undefined pointer, as
72 // we do not want to allow accessing such pointers. This might be acceptable
73 // in dead blocks, but we conservatively avoid it.
74 switch (pointer->opcode()) {
75 case SpvOpConstantNull:
76 case SpvOpUndef:
77 // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/3185): When
78 // fuzzing for real we would like an 'assert(false)' here. But we also
79 // want to be able to write negative unit tests.
80 return false;
81 default:
82 break;
83 }
84
85 // The pointer on which the access chain is to be based needs to be available
86 // (according to dominance rules) at the insertion point.
87 if (!fuzzerutil::IdIsAvailableBeforeInstruction(
88 ir_context, instruction_to_insert_before, message_.pointer_id())) {
89 return false;
90 }
91
92 // We now need to use the given indices to walk the type structure of the
93 // base type of the pointer, making sure that (a) the indices correspond to
94 // integers, and (b) these integer values are in-bounds.
95
96 // Start from the base type of the pointer.
97 uint32_t subobject_type_id = pointer_type->GetSingleWordInOperand(1);
98
99 // Consider the given index ids in turn.
100 for (auto index_id : message_.index_id()) {
101 // Try to get the integer value associated with this index is. The first
102 // component of the result will be false if the id did not correspond to an
103 // integer. Otherwise, the integer with which the id is associated is the
104 // second component.
105 std::pair<bool, uint32_t> maybe_index_value =
106 GetIndexValue(ir_context, index_id);
107 if (!maybe_index_value.first) {
108 // There was no integer: this index is no good.
109 return false;
110 }
111 // Try to walk down the type using this index. This will yield 0 if the
112 // type is not a composite or the index is out of bounds, and the id of
113 // the next type otherwise.
114 subobject_type_id = fuzzerutil::WalkOneCompositeTypeIndex(
115 ir_context, subobject_type_id, maybe_index_value.second);
116 if (!subobject_type_id) {
117 // Either the type was not a composite (so that too many indices were
118 // provided), or the index was out of bounds.
119 return false;
120 }
121 }
122 // At this point, |subobject_type_id| is the type of the value targeted by
123 // the new access chain. The result type of the access chain should be a
124 // pointer to this type, with the same storage class as for the original
125 // pointer. Such a pointer type needs to exist in the module.
126 //
127 // We do not use the type manager to look up this type, due to problems
128 // associated with pointers to isomorphic structs being regarded as the same.
129 return fuzzerutil::MaybeGetPointerType(
130 ir_context, subobject_type_id,
131 static_cast<SpvStorageClass>(
132 pointer_type->GetSingleWordInOperand(0))) != 0;
133 }
134
Apply(opt::IRContext * ir_context,TransformationContext * transformation_context) const135 void TransformationAccessChain::Apply(
136 opt::IRContext* ir_context,
137 TransformationContext* transformation_context) const {
138 // The operands to the access chain are the pointer followed by the indices.
139 // The result type of the access chain is determined by where the indices
140 // lead. We thus push the pointer to a sequence of operands, and then follow
141 // the indices, pushing each to the operand list and tracking the type
142 // obtained by following it. Ultimately this yields the type of the
143 // component reached by following all the indices, and the result type is
144 // a pointer to this component type.
145 opt::Instruction::OperandList operands;
146
147 // Add the pointer id itself.
148 operands.push_back({SPV_OPERAND_TYPE_ID, {message_.pointer_id()}});
149
150 // Start walking the indices, starting with the pointer's base type.
151 auto pointer_type = ir_context->get_def_use_mgr()->GetDef(
152 ir_context->get_def_use_mgr()->GetDef(message_.pointer_id())->type_id());
153 uint32_t subobject_type_id = pointer_type->GetSingleWordInOperand(1);
154
155 // Go through the index ids in turn.
156 for (auto index_id : message_.index_id()) {
157 // Add the index id to the operands.
158 operands.push_back({SPV_OPERAND_TYPE_ID, {index_id}});
159 // Get the integer value associated with the index id.
160 uint32_t index_value = GetIndexValue(ir_context, index_id).second;
161 // Walk to the next type in the composite object using this index.
162 subobject_type_id = fuzzerutil::WalkOneCompositeTypeIndex(
163 ir_context, subobject_type_id, index_value);
164 }
165 // The access chain's result type is a pointer to the composite component that
166 // was reached after following all indices. The storage class is that of the
167 // original pointer.
168 uint32_t result_type = fuzzerutil::MaybeGetPointerType(
169 ir_context, subobject_type_id,
170 static_cast<SpvStorageClass>(pointer_type->GetSingleWordInOperand(0)));
171
172 // Add the access chain instruction to the module, and update the module's id
173 // bound.
174 fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id());
175 FindInstruction(message_.instruction_to_insert_before(), ir_context)
176 ->InsertBefore(MakeUnique<opt::Instruction>(
177 ir_context, SpvOpAccessChain, result_type, message_.fresh_id(),
178 operands));
179
180 // Conservatively invalidate all analyses.
181 ir_context->InvalidateAnalysesExceptFor(opt::IRContext::kAnalysisNone);
182
183 // If the base pointer's pointee value was irrelevant, the same is true of the
184 // pointee value of the result of this access chain.
185 if (transformation_context->GetFactManager()->PointeeValueIsIrrelevant(
186 message_.pointer_id())) {
187 transformation_context->GetFactManager()->AddFactValueOfPointeeIsIrrelevant(
188 message_.fresh_id());
189 }
190 }
191
ToMessage() const192 protobufs::Transformation TransformationAccessChain::ToMessage() const {
193 protobufs::Transformation result;
194 *result.mutable_access_chain() = message_;
195 return result;
196 }
197
GetIndexValue(opt::IRContext * ir_context,uint32_t index_id) const198 std::pair<bool, uint32_t> TransformationAccessChain::GetIndexValue(
199 opt::IRContext* ir_context, uint32_t index_id) const {
200 auto index_instruction = ir_context->get_def_use_mgr()->GetDef(index_id);
201 if (!index_instruction || !spvOpcodeIsConstant(index_instruction->opcode())) {
202 // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/3179) We could
203 // allow non-constant indices when looking up non-structs, using clamping
204 // to ensure they are in-bounds.
205 return {false, 0};
206 }
207 auto index_type =
208 ir_context->get_def_use_mgr()->GetDef(index_instruction->type_id());
209 if (index_type->opcode() != SpvOpTypeInt ||
210 index_type->GetSingleWordInOperand(0) != 32) {
211 return {false, 0};
212 }
213 return {true, index_instruction->GetSingleWordInOperand(0)};
214 }
215
216 } // namespace fuzz
217 } // namespace spvtools
218