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/replayer.h"
16
17 #include <algorithm>
18 #include <memory>
19 #include <utility>
20
21 #include "source/fuzz/counter_overflow_id_source.h"
22 #include "source/fuzz/fact_manager/fact_manager.h"
23 #include "source/fuzz/protobufs/spirvfuzz_protobufs.h"
24 #include "source/fuzz/transformation.h"
25 #include "source/fuzz/transformation_context.h"
26 #include "source/opt/build_module.h"
27 #include "source/util/make_unique.h"
28
29 namespace spvtools {
30 namespace fuzz {
31
Replayer(spv_target_env target_env,MessageConsumer consumer,const std::vector<uint32_t> & binary_in,const protobufs::FactSequence & initial_facts,const protobufs::TransformationSequence & transformation_sequence_in,uint32_t num_transformations_to_apply,bool validate_during_replay,spv_validator_options validator_options)32 Replayer::Replayer(
33 spv_target_env target_env, MessageConsumer consumer,
34 const std::vector<uint32_t>& binary_in,
35 const protobufs::FactSequence& initial_facts,
36 const protobufs::TransformationSequence& transformation_sequence_in,
37 uint32_t num_transformations_to_apply, bool validate_during_replay,
38 spv_validator_options validator_options)
39 : target_env_(target_env),
40 consumer_(std::move(consumer)),
41 binary_in_(binary_in),
42 initial_facts_(initial_facts),
43 transformation_sequence_in_(transformation_sequence_in),
44 num_transformations_to_apply_(num_transformations_to_apply),
45 validate_during_replay_(validate_during_replay),
46 validator_options_(validator_options) {}
47
48 Replayer::~Replayer() = default;
49
Run()50 Replayer::ReplayerResult Replayer::Run() {
51 // Check compatibility between the library version being linked with and the
52 // header files being used.
53 GOOGLE_PROTOBUF_VERIFY_VERSION;
54
55 if (num_transformations_to_apply_ >
56 static_cast<uint32_t>(
57 transformation_sequence_in_.transformation_size())) {
58 consumer_(SPV_MSG_ERROR, nullptr, {},
59 "The number of transformations to be replayed must not "
60 "exceed the size of the transformation sequence.");
61 return {Replayer::ReplayerResultStatus::kTooManyTransformationsRequested,
62 nullptr, nullptr, protobufs::TransformationSequence()};
63 }
64
65 spvtools::SpirvTools tools(target_env_);
66 if (!tools.IsValid()) {
67 consumer_(SPV_MSG_ERROR, nullptr, {},
68 "Failed to create SPIRV-Tools interface; stopping.");
69 return {Replayer::ReplayerResultStatus::kFailedToCreateSpirvToolsInterface,
70 nullptr, nullptr, protobufs::TransformationSequence()};
71 }
72
73 // Initial binary should be valid.
74 if (!tools.Validate(&binary_in_[0], binary_in_.size(), validator_options_)) {
75 consumer_(SPV_MSG_INFO, nullptr, {},
76 "Initial binary is invalid; stopping.");
77 return {Replayer::ReplayerResultStatus::kInitialBinaryInvalid, nullptr,
78 nullptr, protobufs::TransformationSequence()};
79 }
80
81 // Build the module from the input binary.
82 std::unique_ptr<opt::IRContext> ir_context =
83 BuildModule(target_env_, consumer_, binary_in_.data(), binary_in_.size());
84 assert(ir_context);
85
86 // For replay validation, we track the last valid SPIR-V binary that was
87 // observed. Initially this is the input binary.
88 std::vector<uint32_t> last_valid_binary;
89 if (validate_during_replay_) {
90 last_valid_binary = binary_in_;
91 }
92
93 // We find the smallest id that is (a) not in use by the original module, and
94 // (b) not used by any transformation in the sequence to be replayed. This
95 // serves as a starting id from which to issue overflow ids if they are
96 // required during replay.
97 uint32_t first_overflow_id = ir_context->module()->id_bound();
98 for (auto& transformation : transformation_sequence_in_.transformation()) {
99 auto fresh_ids = Transformation::FromMessage(transformation)->GetFreshIds();
100 if (!fresh_ids.empty()) {
101 first_overflow_id =
102 std::max(first_overflow_id,
103 *std::max_element(fresh_ids.begin(), fresh_ids.end()) + 1);
104 }
105 }
106
107 std::unique_ptr<TransformationContext> transformation_context =
108 MakeUnique<TransformationContext>(
109 MakeUnique<FactManager>(ir_context.get()), validator_options_,
110 MakeUnique<CounterOverflowIdSource>(first_overflow_id));
111 transformation_context->GetFactManager()->AddInitialFacts(consumer_,
112 initial_facts_);
113
114 // We track the largest id bound observed, to ensure that it only increases
115 // as transformations are applied.
116 uint32_t max_observed_id_bound = ir_context->module()->id_bound();
117 (void)(max_observed_id_bound); // Keep release-mode compilers happy.
118
119 protobufs::TransformationSequence transformation_sequence_out;
120
121 // Consider the transformation proto messages in turn.
122 uint32_t counter = 0;
123 for (auto& message : transformation_sequence_in_.transformation()) {
124 if (counter >= num_transformations_to_apply_) {
125 break;
126 }
127 counter++;
128
129 auto transformation = Transformation::FromMessage(message);
130
131 // Check whether the transformation can be applied.
132 if (transformation->IsApplicable(ir_context.get(),
133 *transformation_context)) {
134 // The transformation is applicable, so apply it, and copy it to the
135 // sequence of transformations that were applied.
136 transformation->Apply(ir_context.get(), transformation_context.get());
137 *transformation_sequence_out.add_transformation() = message;
138
139 assert(ir_context->module()->id_bound() >= max_observed_id_bound &&
140 "The module's id bound should only increase due to applying "
141 "transformations.");
142 max_observed_id_bound = ir_context->module()->id_bound();
143
144 if (validate_during_replay_) {
145 std::vector<uint32_t> binary_to_validate;
146 ir_context->module()->ToBinary(&binary_to_validate, false);
147
148 // Check whether the latest transformation led to a valid binary.
149 if (!tools.Validate(&binary_to_validate[0], binary_to_validate.size(),
150 validator_options_)) {
151 consumer_(SPV_MSG_INFO, nullptr, {},
152 "Binary became invalid during replay (set a "
153 "breakpoint to inspect); stopping.");
154 return {Replayer::ReplayerResultStatus::kReplayValidationFailure,
155 nullptr, nullptr, protobufs::TransformationSequence()};
156 }
157
158 // The binary was valid, so it becomes the latest valid binary.
159 last_valid_binary = std::move(binary_to_validate);
160 }
161 }
162 }
163
164 return {Replayer::ReplayerResultStatus::kComplete, std::move(ir_context),
165 std::move(transformation_context),
166 std::move(transformation_sequence_out)};
167 }
168
169 } // namespace fuzz
170 } // namespace spvtools
171