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/pe/decompose_image_to_text_app.h"
16 :
17 : #include "syzygy/block_graph/basic_block_decomposer.h"
18 : #include "syzygy/pe/decomposer.h"
19 : #include "syzygy/pe/pe_file.h"
20 : #include "syzygy/pe/pe_transform_policy.h"
21 :
22 : #include "distorm.h" // NOLINT
23 :
24 : namespace pe {
25 :
26 : using block_graph::BasicBlockDecomposer;
27 : using core::RelativeAddress;
28 : using pe::Decomposer;
29 : using pe::ImageLayout;
30 : using pe::PEFile;
31 : using pe::PETransformPolicy;
32 :
33 : namespace {
34 :
35 : const char kUsageFormatStr[] =
36 : "Usage: %ls [options]\n"
37 : "\n"
38 : " A tool that decomposes a given image file, and decomposes it to a\n"
39 : " human-readable textual description.\n"
40 : "\n"
41 : "Available options\n"
42 : " --basic-blocks\n"
43 : " Breaks each function down to basic blocks and dumps it at that level.\n"
44 : " --image=<image file>\n";
45 :
46 : using block_graph::BlockGraph;
47 : using block_graph::BasicBlock;
48 : using block_graph::BasicCodeBlock;
49 : using block_graph::BasicDataBlock;
50 : using block_graph::BasicBlockReference;
51 :
52 E : void DumpReference(const BasicBlockReference& ref, FILE* out) {
53 E : DCHECK(out != NULL);
54 :
55 E : switch (ref.referred_type()) {
56 : case BasicBlockReference::REFERRED_TYPE_BLOCK: {
57 E : const BlockGraph::Block* block = ref.block();
58 E : if (ref.offset() == 0) {
59 E : ::fprintf(out, " ; (%s)", block->name().c_str());
60 E : } else if (ref.offset() < 0) {
61 E : ::fprintf(out, " ; (%s%d)", block->name().c_str(), ref.offset());
62 E : } else {
63 E : BlockGraph::Label label;
64 E : if (block->GetLabel(ref.offset(), &label)) {
65 : ::fprintf(out, " ; (%s:%s)",
66 : block->name().c_str(),
67 E : label.ToString().c_str());
68 E : } else {
69 E : ::fprintf(out, " ; (%s+%d)", block->name().c_str(), ref.offset());
70 : }
71 E : }
72 : }
73 E : break;
74 :
75 : case BasicBlockReference::REFERRED_TYPE_BASIC_BLOCK: {
76 E : const BasicBlock* bb = ref.basic_block();
77 E : DCHECK_EQ(0, ref.offset());
78 :
79 E : ::fprintf(out, " ; (%s)", bb->name().c_str());
80 : }
81 E : break;
82 :
83 : case BasicBlockReference::REFERRED_TYPE_UNKNOWN:
84 : default:
85 i : NOTREACHED() << "All references should be typed.";
86 : break;
87 : }
88 E : }
89 :
90 E : void HexDump(const uint8* data, size_t size, FILE* out) {
91 E : for (size_t i = 0; i < size; ++i)
92 E : ::fprintf(out, "%02x", data[i]);
93 E : }
94 :
95 : } // namespace
96 :
97 :
98 : DecomposeImageToTextApp::DecomposeImageToTextApp()
99 : : application::AppImplBase("Image To Text Decomposer"),
100 : dump_basic_blocks_(false),
101 E : num_refs_(0) {
102 E : }
103 :
104 : void DecomposeImageToTextApp::PrintUsage(const base::FilePath& program,
105 E : const base::StringPiece& message) {
106 E : if (!message.empty()) {
107 E : ::fwrite(message.data(), 1, message.length(), out());
108 E : ::fprintf(out(), "\n\n");
109 : }
110 :
111 E : ::fprintf(out(), kUsageFormatStr, program.BaseName().value().c_str());
112 E : }
113 :
114 : bool DecomposeImageToTextApp::ParseCommandLine(
115 E : const CommandLine* cmd_line) {
116 E : image_path_ = cmd_line->GetSwitchValuePath("image");
117 E : if (image_path_.empty()) {
118 : PrintUsage(cmd_line->GetProgram(),
119 E : "You must provide the path to an image file.");
120 E : return false;
121 : }
122 :
123 E : dump_basic_blocks_ = cmd_line->HasSwitch("basic-blocks");
124 :
125 E : return true;
126 E : }
127 :
128 E : int DecomposeImageToTextApp::Run() {
129 E : DCHECK(!image_path_.empty());
130 :
131 E : if (!DumpImageToText(image_path_))
132 i : return 1;
133 :
134 E : return 0;
135 E : }
136 :
137 : void DecomposeImageToTextApp::DumpAddressSpaceToText(
138 E : const BlockGraph::AddressSpace& address_space) {
139 : BlockGraph::AddressSpace::RangeMap::const_iterator block_it(
140 E : address_space.address_space_impl().ranges().begin());
141 : BlockGraph::AddressSpace::RangeMap::const_iterator block_end(
142 E : address_space.address_space_impl().ranges().end());
143 :
144 E : for (; block_it != block_end; ++block_it) {
145 E : const BlockGraph::Block* block = block_it->second;
146 E : RelativeAddress addr = block_it->first.start();
147 :
148 E : DumpBlockToText(addr, block);
149 E : }
150 E : }
151 :
152 : void DecomposeImageToTextApp::DumpSubGraphToText(
153 E : BasicBlockSubGraph& subgraph) {
154 : typedef BasicBlockSubGraph::BlockDescription BlockDescription;
155 : typedef BasicBlockSubGraph::BasicBlockOrdering BasicBlockOrdering;
156 : typedef block_graph::BasicBlock BasicBlock;
157 : typedef block_graph::BasicBlockReference BasicBlockReference;
158 :
159 : // Post-decomposition we have a single description only.
160 E : DCHECK_EQ(1U, subgraph.block_descriptions().size());
161 E : DCHECK(subgraph.original_block() != NULL);
162 :
163 E : const BlockGraph::Block* block = subgraph.original_block();
164 E : const BlockDescription& descr = subgraph.block_descriptions().front();
165 E : BasicBlockOrdering::const_iterator bb_it(descr.basic_block_order.begin());
166 E : for (; bb_it != descr.basic_block_order.end(); ++bb_it) {
167 E : const BasicBlock* bb = *bb_it;
168 E : DCHECK(bb != NULL);
169 :
170 : // Print the BB's name for an identifying label.
171 E : ::fprintf(out(), "%s:\n", bb->name().c_str());
172 :
173 E : switch (bb->type()) {
174 : case BasicBlock::BASIC_CODE_BLOCK:
175 E : DumpCodeBBToText(block, BasicCodeBlock::Cast(bb));
176 E : break;
177 :
178 : case BasicBlock::BASIC_DATA_BLOCK:
179 E : DumpDataBBToText(block, BasicDataBlock::Cast(bb));
180 E : break;
181 :
182 : default:
183 E : NOTREACHED();
184 : break;
185 : }
186 E : }
187 E : }
188 :
189 : void DecomposeImageToTextApp::DumpCodeBBToText(
190 E : const BlockGraph::Block* block, const BasicCodeBlock* bb) {
191 : BasicBlock::Instructions::const_iterator instr_it(
192 E : bb->instructions().begin());
193 E : for (; instr_it != bb->instructions().end(); ++instr_it) {
194 E : const block_graph::Instruction& instr = *instr_it;
195 :
196 E : _CodeInfo code = {};
197 E : code.codeOffset = 0;
198 E : code.code = instr.data();
199 E : code.codeLen = instr.size();
200 E : code.dt = Decode32Bits;
201 E : _DecodedInst decoded = {};
202 E : _DInst dinst = instr.representation();
203 :
204 E : dinst.addr = 0;
205 E : distorm_format(&code, &dinst, &decoded);
206 : ::fprintf(out(), " %-14s %s %s",
207 : decoded.instructionHex.p,
208 : decoded.mnemonic.p,
209 E : decoded.operands.p);
210 :
211 : BasicBlock::BasicBlockReferenceMap::const_iterator ref_it(
212 E : instr_it->references().begin());
213 E : for (; ref_it != instr_it->references().end(); ++ref_it) {
214 E : DumpReference(ref_it->second, out());
215 E : }
216 E : ::fprintf(out(), "\n");
217 E : }
218 :
219 E : BasicBlock::Successors::const_iterator succ_it(bb->successors().begin());
220 E : for (; succ_it != bb->successors().end(); ++succ_it) {
221 E : const block_graph::Successor& succ = *succ_it;
222 :
223 : // Shortcut alert! As we know the blocks are in-order right after
224 : // decomposition, we can get away with just disassembling the (sole)
225 : // successor that has a size.
226 : // The other successor, if any, will be fall-through.
227 E : if (succ.instruction_size()) {
228 E : _CodeInfo code = {};
229 E : code.codeOffset = 0;
230 E : code.code = block->data() + bb->offset() + bb->GetInstructionSize();
231 E : code.codeLen = succ.instruction_size();
232 E : code.dt = Decode32Bits;
233 E : _DecodedInst decoded = {};
234 E : _DInst instr = {};
235 :
236 E : unsigned int count = 0;
237 E : distorm_decompose64(&code, &instr, 1, &count);
238 E : instr.addr = 0;
239 E : distorm_format(&code, &instr, &decoded);
240 : ::fprintf(out(), " %-14s %s %s",
241 : decoded.instructionHex.p,
242 : decoded.mnemonic.p,
243 E : decoded.operands.p);
244 :
245 E : DumpReference(succ.reference(), out());
246 E : ::fprintf(out(), "\n");
247 : }
248 E : }
249 E : }
250 :
251 : void DecomposeImageToTextApp::DumpDataBBToText(
252 E : const BlockGraph::Block* block, const BasicDataBlock* bb) {
253 : // Here we proceed by dumping a hex chunk up to the next reference, then
254 : // the reference and so on.
255 E : size_t curr_start = 0;
256 :
257 E : while (curr_start < bb->size()) {
258 : BasicBlock::BasicBlockReferenceMap::const_iterator it(
259 E : bb->references().lower_bound(curr_start));
260 :
261 E : size_t next_chunk_end = bb->size();
262 E : if (it != bb->references().end())
263 E : next_chunk_end = it->first;
264 E : if (next_chunk_end == curr_start) {
265 : // We're on a reference, dump it and it's reference.
266 E : switch (it->second.size()) {
267 : case 1:
268 i : ::fprintf(out(), " DB ");
269 i : break;
270 : case 2:
271 i : ::fprintf(out(), " DW ");
272 i : break;
273 : case 4:
274 E : ::fprintf(out(), " DD ");
275 E : break;
276 : default:
277 i : NOTREACHED();
278 : break;
279 : }
280 E : HexDump(bb->data() + curr_start, it->second.size(), out());
281 E : DumpReference(it->second, out());
282 E : ::fprintf(out(), "\n");
283 :
284 E : curr_start += it->second.size();
285 E : } else {
286 E : if (next_chunk_end - curr_start > 16)
287 E : next_chunk_end = curr_start + 16;
288 :
289 E : ::fprintf(out(), " DB ");
290 E : HexDump(bb->data() + curr_start, next_chunk_end - curr_start, out());
291 E : ::fprintf(out(), "\n");
292 :
293 E : curr_start = next_chunk_end;
294 : }
295 E : }
296 E : }
297 :
298 : void DecomposeImageToTextApp::DumpBlockToText(
299 E : core::RelativeAddress addr, const BlockGraph::Block* block) {
300 : ::fprintf(out(), "0x%08X(%d): %s\n",
301 : addr.value(),
302 : block->size(),
303 E : block->name().c_str());
304 :
305 E : pe::PETransformPolicy policy;
306 :
307 : // Attempt basic block decomposition if BB-dumping is requested.
308 : // Note that on success we return early from here.
309 E : if (dump_basic_blocks_ && policy.BlockIsSafeToBasicBlockDecompose(block)) {
310 E : BasicBlockSubGraph subgraph;
311 E : BasicBlockDecomposer decomposer(block, &subgraph);
312 :
313 E : if (decomposer.Decompose()) {
314 E : DumpSubGraphToText(subgraph);
315 E : return;
316 : }
317 : // Fall through on failure to decompose.
318 i : }
319 :
320 : BlockGraph::Block::LabelMap::const_iterator
321 E : label_it(block->labels().begin());
322 E : for (; label_it != block->labels().end(); ++label_it) {
323 : ::fprintf(out(), "\t+0x%04X: %s\n",
324 : label_it->first,
325 E : label_it->second.ToString().c_str());
326 E : }
327 :
328 : BlockGraph::Block::ReferenceMap::const_iterator ref_it(
329 E : block->references().begin());
330 E : for (; ref_it != block->references().end(); ++ref_it) {
331 E : ++num_refs_;
332 E : const BlockGraph::Reference& ref = ref_it->second;
333 E : if (ref.offset() == 0) {
334 : ::fprintf(out(), "\t+0x%04X->%s(%d)\n",
335 : ref_it->first,
336 : ref.referenced()->name().c_str(),
337 E : ref.size());
338 E : } else {
339 : // See if there's a label at the destination's offset, and if so
340 : // use that in preference to a raw numeric offset.
341 : BlockGraph::Block::LabelMap::const_iterator label =
342 E : ref.referenced()->labels().find(ref.offset());
343 E : if (label != ref.referenced()->labels().end()) {
344 : ::fprintf(out(), "\t+0x%04X->%s:%s[%d]\n",
345 : ref_it->first,
346 : ref.referenced()->name().c_str(),
347 : label->second.ToString().c_str(),
348 E : ref.size());
349 E : } else {
350 : ::fprintf(out(), "\t+0x%04X->%s+0x%04X(%d)\n",
351 : ref_it->first,
352 : ref.referenced()->name().c_str(),
353 : ref.offset(),
354 E : ref.size());
355 : }
356 : }
357 E : }
358 E : }
359 :
360 : bool DecomposeImageToTextApp::DumpImageToText(
361 E : const base::FilePath& image_path) {
362 : // Load the image file.
363 E : PEFile image_file;
364 E : if (!image_file.Init(image_path)) {
365 i : LOG(ERROR) << "Unable to initialize image " << image_path.value();
366 i : return false;
367 : }
368 :
369 E : BlockGraph block_graph;
370 E : ImageLayout image_layout(&block_graph);
371 :
372 : // And decompose it to an ImageLayout.
373 E : Decomposer decomposer(image_file);
374 E : if (!decomposer.Decompose(&image_layout)) {
375 i : LOG(ERROR) << "Unable to decompose image \""
376 : << image_path.value() << "\".";
377 i : return false;
378 : }
379 :
380 E : num_refs_ = 0;
381 E : DumpAddressSpaceToText(image_layout.blocks);
382 :
383 : ::fprintf(out(), "Discovered: %d blocks\nand %d references.\n",
384 : block_graph.blocks().size(),
385 E : num_refs_);
386 :
387 E : return true;
388 E : }
389 :
390 : } // namespace pe
|