1 // Copyright (c) 2020 Vasyl Teliman
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_add_copy_memory.h"
16 
17 #include "source/fuzz/fuzzer_util.h"
18 #include "source/fuzz/instruction_descriptor.h"
19 #include "source/opt/instruction.h"
20 
21 namespace spvtools {
22 namespace fuzz {
23 
TransformationAddCopyMemory(const protobufs::TransformationAddCopyMemory & message)24 TransformationAddCopyMemory::TransformationAddCopyMemory(
25     const protobufs::TransformationAddCopyMemory& message)
26     : message_(message) {}
27 
TransformationAddCopyMemory(const protobufs::InstructionDescriptor & instruction_descriptor,uint32_t fresh_id,uint32_t source_id,SpvStorageClass storage_class,uint32_t initializer_id)28 TransformationAddCopyMemory::TransformationAddCopyMemory(
29     const protobufs::InstructionDescriptor& instruction_descriptor,
30     uint32_t fresh_id, uint32_t source_id, SpvStorageClass storage_class,
31     uint32_t initializer_id) {
32   *message_.mutable_instruction_descriptor() = instruction_descriptor;
33   message_.set_fresh_id(fresh_id);
34   message_.set_source_id(source_id);
35   message_.set_storage_class(storage_class);
36   message_.set_initializer_id(initializer_id);
37 }
38 
IsApplicable(opt::IRContext * ir_context,const TransformationContext &) const39 bool TransformationAddCopyMemory::IsApplicable(
40     opt::IRContext* ir_context, const TransformationContext& /*unused*/) const {
41   // Check that target id is fresh.
42   if (!fuzzerutil::IsFreshId(ir_context, message_.fresh_id())) {
43     return false;
44   }
45 
46   // Check that instruction descriptor is valid. This also checks that
47   // |message_.instruction_descriptor| is not a global instruction.
48   auto* inst = FindInstruction(message_.instruction_descriptor(), ir_context);
49   if (!inst) {
50     return false;
51   }
52 
53   // Check that we can insert OpCopyMemory before |instruction_descriptor|.
54   auto iter = fuzzerutil::GetIteratorForInstruction(
55       ir_context->get_instr_block(inst), inst);
56   if (!fuzzerutil::CanInsertOpcodeBeforeInstruction(SpvOpCopyMemory, iter)) {
57     return false;
58   }
59 
60   // Check that source instruction exists and is valid.
61   auto* source_inst =
62       ir_context->get_def_use_mgr()->GetDef(message_.source_id());
63   if (!source_inst || !IsInstructionSupported(ir_context, source_inst)) {
64     return false;
65   }
66 
67   // |storage_class| is either Function or Private.
68   if (message_.storage_class() != SpvStorageClassFunction &&
69       message_.storage_class() != SpvStorageClassPrivate) {
70     return false;
71   }
72 
73   auto pointee_type_id = fuzzerutil::GetPointeeTypeIdFromPointerType(
74       ir_context, source_inst->type_id());
75 
76   // OpTypePointer with |message_.storage_class| exists.
77   if (!fuzzerutil::MaybeGetPointerType(
78           ir_context, pointee_type_id,
79           static_cast<SpvStorageClass>(message_.storage_class()))) {
80     return false;
81   }
82 
83   // Check that |initializer_id| exists and has valid type.
84   const auto* initializer_inst =
85       ir_context->get_def_use_mgr()->GetDef(message_.initializer_id());
86   if (!initializer_inst || initializer_inst->type_id() != pointee_type_id) {
87     return false;
88   }
89 
90   // Check that domination rules are satisfied.
91   return fuzzerutil::IdIsAvailableBeforeInstruction(ir_context, inst,
92                                                     message_.source_id());
93 }
94 
Apply(opt::IRContext * ir_context,TransformationContext * transformation_context) const95 void TransformationAddCopyMemory::Apply(
96     opt::IRContext* ir_context,
97     TransformationContext* transformation_context) const {
98   // Insert OpCopyMemory before |instruction_descriptor|.
99   auto* insert_before_inst =
100       FindInstruction(message_.instruction_descriptor(), ir_context);
101   assert(insert_before_inst);
102 
103   auto insert_before_iter = fuzzerutil::GetIteratorForInstruction(
104       ir_context->get_instr_block(insert_before_inst), insert_before_inst);
105 
106   insert_before_iter.InsertBefore(MakeUnique<opt::Instruction>(
107       ir_context, SpvOpCopyMemory, 0, 0,
108       opt::Instruction::OperandList{
109           {SPV_OPERAND_TYPE_ID, {message_.fresh_id()}},
110           {SPV_OPERAND_TYPE_ID, {message_.source_id()}}}));
111 
112   // Add global or local variable to copy memory into.
113   auto storage_class = static_cast<SpvStorageClass>(message_.storage_class());
114   auto type_id = fuzzerutil::MaybeGetPointerType(
115       ir_context,
116       fuzzerutil::GetPointeeTypeIdFromPointerType(
117           ir_context, fuzzerutil::GetTypeId(ir_context, message_.source_id())),
118       storage_class);
119 
120   if (storage_class == SpvStorageClassPrivate) {
121     fuzzerutil::AddGlobalVariable(ir_context, message_.fresh_id(), type_id,
122                                   storage_class, message_.initializer_id());
123   } else {
124     assert(storage_class == SpvStorageClassFunction &&
125            "Storage class can be either Private or Function");
126     fuzzerutil::AddLocalVariable(ir_context, message_.fresh_id(), type_id,
127                                  ir_context->get_instr_block(insert_before_inst)
128                                      ->GetParent()
129                                      ->result_id(),
130                                  message_.initializer_id());
131   }
132 
133   fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id());
134 
135   // Make sure our changes are analyzed
136   ir_context->InvalidateAnalysesExceptFor(
137       opt::IRContext::Analysis::kAnalysisNone);
138 
139   // Even though the copy memory instruction will - at least temporarily - lead
140   // to the destination and source pointers referring to identical values, this
141   // fact is not guaranteed to hold throughout execution of the SPIR-V code
142   // since the source pointer could be over-written. We thus assume nothing
143   // about the destination pointer, and record this fact so that the destination
144   // pointer can be used freely by other fuzzer passes.
145   transformation_context->GetFactManager()->AddFactValueOfPointeeIsIrrelevant(
146       message_.fresh_id());
147 }
148 
ToMessage() const149 protobufs::Transformation TransformationAddCopyMemory::ToMessage() const {
150   protobufs::Transformation result;
151   *result.mutable_add_copy_memory() = message_;
152   return result;
153 }
154 
IsInstructionSupported(opt::IRContext * ir_context,opt::Instruction * inst)155 bool TransformationAddCopyMemory::IsInstructionSupported(
156     opt::IRContext* ir_context, opt::Instruction* inst) {
157   if (!inst->result_id() || !inst->type_id() ||
158       inst->opcode() == SpvOpConstantNull || inst->opcode() == SpvOpUndef) {
159     return false;
160   }
161 
162   const auto* type = ir_context->get_type_mgr()->GetType(inst->type_id());
163   assert(type && "Instruction must have a valid type");
164 
165   if (!type->AsPointer()) {
166     return false;
167   }
168 
169   // We do not support copying memory from a pointer to a block-/buffer
170   // block-decorated struct.
171   auto pointee_type_inst = ir_context->get_def_use_mgr()
172                                ->GetDef(inst->type_id())
173                                ->GetSingleWordInOperand(1);
174   if (fuzzerutil::HasBlockOrBufferBlockDecoration(ir_context,
175                                                   pointee_type_inst)) {
176     return false;
177   }
178 
179   return CanUsePointeeWithCopyMemory(*type->AsPointer()->pointee_type());
180 }
181 
CanUsePointeeWithCopyMemory(const opt::analysis::Type & type)182 bool TransformationAddCopyMemory::CanUsePointeeWithCopyMemory(
183     const opt::analysis::Type& type) {
184   switch (type.kind()) {
185     case opt::analysis::Type::kBool:
186     case opt::analysis::Type::kInteger:
187     case opt::analysis::Type::kFloat:
188     case opt::analysis::Type::kArray:
189       return true;
190     case opt::analysis::Type::kVector:
191       return CanUsePointeeWithCopyMemory(*type.AsVector()->element_type());
192     case opt::analysis::Type::kMatrix:
193       return CanUsePointeeWithCopyMemory(*type.AsMatrix()->element_type());
194     case opt::analysis::Type::kStruct:
195       return std::all_of(type.AsStruct()->element_types().begin(),
196                          type.AsStruct()->element_types().end(),
197                          [](const opt::analysis::Type* element) {
198                            return CanUsePointeeWithCopyMemory(*element);
199                          });
200     default:
201       return false;
202   }
203 }
204 
GetFreshIds() const205 std::unordered_set<uint32_t> TransformationAddCopyMemory::GetFreshIds() const {
206   return {message_.fresh_id()};
207 }
208 
209 }  // namespace fuzz
210 }  // namespace spvtools
211