1 : // Copyright 2012 Google Inc. All Rights Reserved.
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 "syzygy/relink/relink_app.h"
16 :
17 : #include "base/logging_win.h"
18 : #include "base/string_number_conversions.h"
19 : #include "syzygy/block_graph/orderers/original_orderer.h"
20 : #include "syzygy/block_graph/orderers/random_orderer.h"
21 : #include "syzygy/block_graph/transforms/fuzzing_transform.h"
22 : #include "syzygy/pe/pe_relinker.h"
23 : #include "syzygy/pe/transforms/explode_basic_blocks_transform.h"
24 : #include "syzygy/reorder/orderers/explicit_orderer.h"
25 : #include "syzygy/reorder/transforms/basic_block_layout_transform.h"
26 :
27 : namespace relink {
28 :
29 : namespace {
30 :
31 : const char kUsageFormatStr[] =
32 : "Usage: %ls [options]\n"
33 : " Required Options:\n"
34 : " --input-image=<path> The input image file to relink.\n"
35 : " --output-image=<path> Output path for the rewritten image file.\n"
36 : " Options:\n"
37 : " --basic-blocks Reorder at the basic-block level. At present,\n"
38 : " this is only supported for random reorderings.\n"
39 : " --compress-pdb If --no-augment-pdb is specified, causes the\n"
40 : " augmented PDB stream to be compressed.\n"
41 : " --exclude-bb-padding When randomly reordering basic blocks, exclude\n"
42 : " padding and unreachable code from the relinked\n"
43 : " output binary.\n"
44 : " --input-pdb=<path> The PDB file associated with the input DLL.\n"
45 : " Default is inferred from input-image.\n"
46 : " --no-augment-pdb Indicates that the relinker should not augment\n"
47 : " the PDB with roundtrip decomposition info.\n"
48 : " --no-metadata Prevents the relinker from adding metadata\n"
49 : " to the output DLL.\n"
50 : " --no-strip-strings Causes strings to be output in the augmented\n"
51 : " PDB stream. The default is to omit these to\n"
52 : " make smaller PDBs.\n"
53 : " --order-file=<path> Reorder based on a JSON ordering file.\n"
54 : " --output-pdb=<path> Output path for the rewritten PDB file.\n"
55 : " Default is inferred from output-image.\n"
56 : " --overwrite Allow output files to be overwritten.\n"
57 : " --padding=<integer> Add bytes of padding between blocks.\n"
58 : "\n"
59 : " Testing Options:\n"
60 : " --seed=<integer> Randomly reorder based on the given seed.\n"
61 : " --fuzz Fuzz the binary.\n"
62 : "\n"
63 : " Deprecated Options:\n"
64 : " --input-dll=<path> Aliased to --input-image.\n"
65 : " --output-dll=<path> Aliased to --output-image.\n"
66 : "\n"
67 : " Notes:\n"
68 : " * The --seed and --order-file options are mutually exclusive\n"
69 : " * If --order-file is specified, --input-image is optional.\n"
70 : " * The --compress-pdb and --no-strip-strings options are only\n"
71 : " effective if --no-augment-pdb is not specified.\n"
72 : " * The --exclude-bb-padding option is only effective if\n"
73 : " --basic-blocks is specified.\n";
74 :
75 E : bool ParsePadding(const std::wstring& value_str, size_t* out_value) {
76 E : DCHECK(out_value != NULL);
77 :
78 : int temp;
79 E : if (!base::StringToInt(value_str, &temp) || temp < 0) {
80 i : return false;
81 : }
82 :
83 E : *out_value = static_cast<size_t>(temp);
84 E : return true;
85 E : }
86 :
87 E : bool ParseUInt32(const std::wstring& value_str, uint32* out_value) {
88 E : DCHECK(out_value != NULL);
89 E : return base::StringToInt(value_str, reinterpret_cast<int*>(out_value));
90 E : }
91 :
92 : void GuessPdbPath(const base::FilePath& module_path, base::FilePath* pdb_path) {
93 : DCHECK(pdb_path != NULL);
94 : *pdb_path = module_path.ReplaceExtension(L"pdb");
95 : }
96 :
97 : } // namespace
98 :
99 E : bool RelinkApp::ParseCommandLine(const CommandLine* cmd_line) {
100 E : input_image_path_ = AbsolutePath(cmd_line->GetSwitchValuePath("input-image"));
101 E : if (cmd_line->HasSwitch("input-dll")) {
102 E : if (input_image_path_.empty()) {
103 E : LOG(WARNING) << "Using deprecated switch --input-dll.";
104 : input_image_path_ =
105 E : AbsolutePath(cmd_line->GetSwitchValuePath("input-dll"));
106 E : } else {
107 : return Usage(cmd_line,
108 E : "Can't specify both --input-dll and --input-image.");
109 : }
110 : }
111 E : input_pdb_path_ = AbsolutePath(cmd_line->GetSwitchValuePath("input-pdb"));
112 :
113 E : output_image_path_ = cmd_line->GetSwitchValuePath("output-image");
114 E : if (cmd_line->HasSwitch("output-dll")) {
115 E : if (output_image_path_.empty()) {
116 E : LOG(WARNING) << "Using deprecated switch --output-dll.";
117 : output_image_path_ =
118 E : AbsolutePath(cmd_line->GetSwitchValuePath("output-dll"));
119 E : } else {
120 : return Usage(cmd_line,
121 E : "Can't specify both --output-dll and --output-image.");
122 : }
123 : }
124 :
125 E : output_pdb_path_ = cmd_line->GetSwitchValuePath("output-pdb");
126 E : order_file_path_ = AbsolutePath(cmd_line->GetSwitchValuePath("order-file"));
127 E : no_augment_pdb_ = cmd_line->HasSwitch("no-augment-pdb");
128 E : compress_pdb_ = cmd_line->HasSwitch("compress-pdb");
129 E : no_strip_strings_ = cmd_line->HasSwitch("no-strip-strings");
130 E : output_metadata_ = !cmd_line->HasSwitch("no-metadata");
131 E : overwrite_ = cmd_line->HasSwitch("overwrite");
132 E : basic_blocks_ = cmd_line->HasSwitch("basic-blocks");
133 E : exclude_bb_padding_ = cmd_line->HasSwitch("exclude-bb-padding");
134 E : fuzz_ = cmd_line->HasSwitch("fuzz");
135 :
136 : // The --output-image argument is required.
137 E : if (output_image_path_.empty()) {
138 E : return Usage(cmd_line, "You must specify --output-image.");
139 : }
140 :
141 : // Ensure that we have an input-image, either explicity specified, or to be
142 : // taken from an order file.
143 E : if (input_image_path_.empty() && order_file_path_.empty()) {
144 : return Usage(
145 : cmd_line,
146 E : "You must specify --input-image if --order-file is not given.");
147 : }
148 :
149 : // Parse the random seed, if given. Note that the --seed and --order-file
150 : // arguments are mutually exclusive.
151 E : if (cmd_line->HasSwitch("seed")) {
152 E : if (cmd_line->HasSwitch("order-file")) {
153 : return Usage(cmd_line,
154 i : "The seed and order-file arguments are mutually exclusive.");
155 : }
156 E : std::wstring seed_str(cmd_line->GetSwitchValueNative("seed"));
157 E : if (!ParseUInt32(seed_str, &seed_))
158 i : return Usage(cmd_line, "Invalid seed value.");
159 E : }
160 :
161 : // Parse the padding argument.
162 E : if (cmd_line->HasSwitch("padding")) {
163 E : std::wstring padding_str(cmd_line->GetSwitchValueNative("padding"));
164 E : if (!ParsePadding(padding_str, &padding_))
165 i : return Usage(cmd_line, "Invalid padding value.");
166 E : }
167 :
168 E : return true;
169 E : }
170 :
171 E : bool RelinkApp::SetUp() {
172 E : if (input_image_path_.empty()) {
173 E : DCHECK(!order_file_path_.empty());
174 : if (!reorder::Reorderer::Order::GetOriginalModulePath(order_file_path_,
175 E : &input_image_path_)) {
176 E : LOG(ERROR) << "Unable to infer input-image.";
177 E : return false;
178 : }
179 :
180 i : LOG(INFO) << "Inferring input DLL path from order file: "
181 : << input_image_path_.value();
182 : }
183 :
184 E : DCHECK(!input_image_path_.empty());
185 E : DCHECK(!output_image_path_.empty());
186 E : DCHECK(order_file_path_.empty() || seed_ == 0);
187 :
188 E : return true;
189 E : }
190 :
191 E : int RelinkApp::Run() {
192 E : pe::PERelinker relinker;
193 E : relinker.set_input_path(input_image_path_);
194 E : relinker.set_input_pdb_path(input_pdb_path_);
195 E : relinker.set_output_path(output_image_path_);
196 E : relinker.set_output_pdb_path(output_pdb_path_);
197 E : relinker.set_padding(padding_);
198 E : relinker.set_add_metadata(output_metadata_);
199 E : relinker.set_allow_overwrite(overwrite_);
200 E : relinker.set_augment_pdb(!no_augment_pdb_);
201 E : relinker.set_compress_pdb(compress_pdb_);
202 E : relinker.set_strip_strings(!no_strip_strings_);
203 :
204 : // Initialize the relinker. This does the decomposition, etc.
205 E : if (!relinker.Init()) {
206 i : LOG(ERROR) << "Failed to initialize relinker.";
207 i : return 1;
208 : }
209 :
210 : // Transforms that may be used.
211 E : scoped_ptr<pe::transforms::ExplodeBasicBlocksTransform> bb_explode;
212 E : scoped_ptr<reorder::transforms::BasicBlockLayoutTransform> bb_layout;
213 E : scoped_ptr<block_graph::transforms::FuzzingTransform> fuzzing_transform;
214 :
215 : // Orderers that may be used.
216 E : reorder::Reorderer::Order order;
217 E : scoped_ptr<block_graph::orderers::OriginalOrderer> orig_orderer;
218 E : scoped_ptr<block_graph::BlockGraphOrdererInterface> orderer;
219 :
220 : // If fuzzing is enabled, add it to the relinker.
221 E : if (fuzz_) {
222 E : fuzzing_transform.reset(new block_graph::transforms::FuzzingTransform);
223 E : relinker.AppendTransform(fuzzing_transform.get());
224 : }
225 :
226 : // If an order file is provided we are performing an explicit ordering.
227 E : if (!order_file_path_.empty()) {
228 : if (!order.LoadFromJSON(relinker.input_pe_file(),
229 : relinker.input_image_layout(),
230 E : order_file_path_)) {
231 i : LOG(ERROR) << "Failed to load order file: " << order_file_path_.value();
232 i : return 1;
233 : }
234 :
235 : // Allocate a BB layout transform. This applies the basic block portion of
236 : // the order specification. It will modify it in place so that it is ready
237 : // to be used by the ExplicitOrderer to finish the job.
238 E : bb_layout.reset(new reorder::transforms::BasicBlockLayoutTransform(&order));
239 E : relinker.AppendTransform(bb_layout.get());
240 :
241 : // Append an OriginalOrderer to the relinker. We do this so that the
242 : // original order is preserved entirely for sections that are not
243 : // fully specified by the order file, and therefore not ordered by the
244 : // ExplicitOrderer.
245 E : orig_orderer.reset(new block_graph::orderers::OriginalOrderer());
246 E : relinker.AppendOrderer(orig_orderer.get());
247 :
248 : // Allocate an explicit orderer.
249 E : orderer.reset(new reorder::orderers::ExplicitOrderer(&order));
250 E : } else {
251 : // No order file was provided, so we're doing a random ordering.
252 :
253 : // If we've been asked to go down to the basic block level, then we want to
254 : // use an explode basic blocks transform so that we randomize the entire
255 : // image at the BB level.
256 E : if (basic_blocks_) {
257 E : bb_explode.reset(new pe::transforms::ExplodeBasicBlocksTransform());
258 E : bb_explode->set_exclude_padding(exclude_bb_padding_);
259 E : relinker.AppendTransform(bb_explode.get());
260 : }
261 :
262 : // Allocate the random block orderer.
263 E : orderer.reset(new block_graph::orderers::RandomOrderer(true, seed_));
264 : }
265 :
266 : // Append the orderer to the relinker.
267 E : relinker.AppendOrderer(orderer.get());
268 :
269 : // Perform the actual relink.
270 E : if (!relinker.Relink()) {
271 i : LOG(ERROR) << "Unable to relink input image.";
272 i : return 1;
273 : }
274 :
275 E : return 0;
276 E : }
277 :
278 : bool RelinkApp::Usage(const CommandLine* cmd_line,
279 E : const base::StringPiece& message) const {
280 E : if (!message.empty()) {
281 E : ::fwrite(message.data(), 1, message.length(), err());
282 E : ::fprintf(err(), "\n\n");
283 : }
284 :
285 : ::fprintf(err(),
286 : kUsageFormatStr,
287 E : cmd_line->GetProgram().BaseName().value().c_str());
288 :
289 E : return false;
290 E : }
291 :
292 : } // namespace relink
|