1 // Copyright (c) 2019 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_copy_objects.h"
16
17 #include "source/fuzz/fuzzer_util.h"
18 #include "source/fuzz/transformation_copy_object.h"
19
20 namespace spvtools {
21 namespace fuzz {
22
FuzzerPassCopyObjects(opt::IRContext * ir_context,FactManager * fact_manager,FuzzerContext * fuzzer_context,protobufs::TransformationSequence * transformations)23 FuzzerPassCopyObjects::FuzzerPassCopyObjects(
24 opt::IRContext* ir_context, FactManager* fact_manager,
25 FuzzerContext* fuzzer_context,
26 protobufs::TransformationSequence* transformations)
27 : FuzzerPass(ir_context, fact_manager, fuzzer_context, transformations) {}
28
29 FuzzerPassCopyObjects::~FuzzerPassCopyObjects() = default;
30
Apply()31 void FuzzerPassCopyObjects::Apply() {
32 MaybeAddTransformationBeforeEachInstruction(
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 a copy before this
43 // instruction.
44 if (!fuzzerutil::CanInsertOpcodeBeforeInstruction(SpvOpCopyObject,
45 inst_it)) {
46 return;
47 }
48
49 // Randomly decide whether to try inserting an object copy here.
50 if (!GetFuzzerContext()->ChoosePercentage(
51 GetFuzzerContext()->GetChanceOfCopyingObject())) {
52 return;
53 }
54
55 std::vector<opt::Instruction*> relevant_instructions =
56 FindAvailableInstructions(function, block, inst_it,
57 fuzzerutil::CanMakeSynonymOf);
58
59 // At this point, |relevant_instructions| contains all the instructions
60 // we might think of copying.
61 if (relevant_instructions.empty()) {
62 return;
63 }
64
65 // Choose a copyable instruction at random, and create and apply an
66 // object copying transformation based on it.
67 ApplyTransformation(TransformationCopyObject(
68 relevant_instructions[GetFuzzerContext()->RandomIndex(
69 relevant_instructions)]
70 ->result_id(),
71 instruction_descriptor, GetFuzzerContext()->GetFreshId()));
72 });
73 }
74
75 } // namespace fuzz
76 } // namespace spvtools
77