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/block_util.h"
19 : #include "syzygy/pe/decomposer.h"
20 : #include "syzygy/pe/pe_file.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 :
32 : namespace {
33 :
34 : const char kUsageFormatStr[] =
35 : "Usage: %ls [options]\n"
36 : "\n"
37 : " A tool that decomposes a given image file, and decomposes it to a\n"
38 : " human-readable textual description.\n"
39 : "\n"
40 : "Available options\n"
41 : " --basic-blocks\n"
42 : " Breaks each function down to basic blocks and dumps it at that level.\n"
43 : " --image=<image file>\n";
44 :
45 : using block_graph::BlockGraph;
46 : using block_graph::BasicBlock;
47 : using block_graph::BasicCodeBlock;
48 : using block_graph::BasicDataBlock;
49 : using block_graph::BasicBlockReference;
50 :
51 E : void DumpReference(const BasicBlockReference& ref, FILE* out) {
52 E : DCHECK(out != NULL);
53 :
54 E : switch (ref.referred_type()) {
55 : case BasicBlockReference::REFERRED_TYPE_BLOCK: {
56 E : const BlockGraph::Block* block = ref.block();
57 E : if (ref.offset() == 0) {
58 E : ::fprintf(out, " ; (%s)", block->name().c_str());
59 E : } else if (ref.offset() < 0) {
60 E : ::fprintf(out, " ; (%s%d)", block->name().c_str(), ref.offset());
61 E : } else {
62 E : BlockGraph::Label label;
63 E : if (block->GetLabel(ref.offset(), &label)) {
64 : ::fprintf(out, " ; (%s:%s)",
65 : block->name().c_str(),
66 E : label.ToString().c_str());
67 E : } else {
68 E : ::fprintf(out, " ; (%s+%d)", block->name().c_str(), ref.offset());
69 : }
70 E : }
71 : }
72 E : break;
73 :
74 : case BasicBlockReference::REFERRED_TYPE_BASIC_BLOCK: {
75 E : const BasicBlock* bb = ref.basic_block();
76 E : DCHECK(ref.offset() == 0);
77 :
78 E : ::fprintf(out, " ; (%s)", bb->name().c_str());
79 : }
80 E : break;
81 :
82 : case BasicBlockReference::REFERRED_TYPE_UNKNOWN:
83 : default:
84 i : NOTREACHED() << "All references should be typed.";
85 : break;
86 : }
87 E : }
88 :
89 E : void HexDump(const uint8* data, size_t size, FILE* out) {
90 E : for (size_t i = 0; i < size; ++i)
91 E : ::fprintf(out, "%02x", data[i]);
92 E : }
93 :
94 : } // namespace
95 :
96 :
97 : DecomposeImageToTextApp::DecomposeImageToTextApp()
98 : : common::AppImplBase("Image To Text Decomposer"),
99 : dump_basic_blocks_(false),
100 E : num_refs_(0) {
101 E : }
102 :
103 : void DecomposeImageToTextApp::PrintUsage(const FilePath& program,
104 E : const base::StringPiece& message) {
105 E : if (!message.empty()) {
106 E : ::fwrite(message.data(), 1, message.length(), out());
107 E : ::fprintf(out(), "\n\n");
108 : }
109 :
110 E : ::fprintf(out(), kUsageFormatStr, program.BaseName().value().c_str());
111 E : }
112 :
113 : bool DecomposeImageToTextApp::ParseCommandLine(
114 E : const CommandLine* cmd_line) {
115 E : image_path_ = cmd_line->GetSwitchValuePath("image");
116 E : if (image_path_.empty()) {
117 : PrintUsage(cmd_line->GetProgram(),
118 E : "You must provide the path to an image file.");
119 E : return false;
120 : }
121 :
122 E : dump_basic_blocks_ = cmd_line->HasSwitch("basic-blocks");
123 :
124 E : return true;
125 E : }
126 :
127 E : int DecomposeImageToTextApp::Run() {
128 E : DCHECK(!image_path_.empty());
129 :
130 E : if (!DumpImageToText(image_path_))
131 i : return 1;
132 :
133 E : return 0;
134 E : }
135 :
136 : void DecomposeImageToTextApp::DumpAddressSpaceToText(
137 E : const BlockGraph::AddressSpace& address_space) {
138 : BlockGraph::AddressSpace::RangeMap::const_iterator block_it(
139 E : address_space.address_space_impl().ranges().begin());
140 : BlockGraph::AddressSpace::RangeMap::const_iterator block_end(
141 E : address_space.address_space_impl().ranges().end());
142 :
143 E : for (; block_it != block_end; ++block_it) {
144 E : const BlockGraph::Block* block = block_it->second;
145 E : RelativeAddress addr = block_it->first.start();
146 :
147 E : DumpBlockToText(addr, block);
148 E : }
149 E : }
150 :
151 : void DecomposeImageToTextApp::DumpSubGraphToText(
152 E : BasicBlockSubGraph& subgraph) {
153 : typedef BasicBlockSubGraph::BlockDescription BlockDescription;
154 : typedef BasicBlockSubGraph::BasicBlockOrdering BasicBlockOrdering;
155 : typedef block_graph::BasicBlock BasicBlock;
156 : typedef block_graph::BasicBlockReference BasicBlockReference;
157 :
158 : // Post-decomposition we have a single description only.
159 E : DCHECK_EQ(1U, subgraph.block_descriptions().size());
160 E : DCHECK(subgraph.original_block() != NULL);
161 :
162 E : const BlockGraph::Block* block = subgraph.original_block();
163 E : const BlockDescription& descr = subgraph.block_descriptions().front();
164 E : BasicBlockOrdering::const_iterator bb_it(descr.basic_block_order.begin());
165 E : for (; bb_it != descr.basic_block_order.end(); ++bb_it) {
166 E : const BasicBlock* bb = *bb_it;
167 E : DCHECK(bb != NULL);
168 :
169 : // Print the BB's name for an identifying label.
170 E : ::fprintf(out(), "%s:\n", bb->name().c_str());
171 :
172 E : switch (bb->type()) {
173 : case BasicBlock::BASIC_CODE_BLOCK:
174 E : DumpCodeBBToText(block, BasicCodeBlock::Cast(bb));
175 E : break;
176 :
177 : case BasicBlock::BASIC_DATA_BLOCK:
178 E : DumpDataBBToText(block, BasicDataBlock::Cast(bb));
179 E : break;
180 :
181 : default:
182 i : NOTREACHED();
183 : break;
184 : }
185 E : }
186 E : }
187 :
188 : void DecomposeImageToTextApp::DumpCodeBBToText(
189 E : const BlockGraph::Block* block, const BasicCodeBlock* bb) {
190 : BasicBlock::Instructions::const_iterator instr_it(
191 E : bb->instructions().begin());
192 E : for (; instr_it != bb->instructions().end(); ++instr_it) {
193 E : const block_graph::Instruction& instr = *instr_it;
194 :
195 E : _CodeInfo code = {};
196 E : code.codeOffset = 0;
197 E : code.code = instr.data();
198 E : code.codeLen = instr.size();
199 E : code.dt = Decode32Bits;
200 E : _DecodedInst decoded = {};
201 E : _DInst dinst = instr.representation();
202 :
203 E : dinst.addr = 0;
204 E : distorm_format(&code, &dinst, &decoded);
205 : ::fprintf(out(), " %-14s %s %s",
206 : decoded.instructionHex.p,
207 : decoded.mnemonic.p,
208 E : decoded.operands.p);
209 :
210 : BasicBlock::BasicBlockReferenceMap::const_iterator ref_it(
211 E : instr_it->references().begin());
212 E : for (; ref_it != instr_it->references().end(); ++ref_it) {
213 E : DumpReference(ref_it->second, out());
214 E : }
215 E : ::fprintf(out(), "\n");
216 E : }
217 :
218 E : BasicBlock::Successors::const_iterator succ_it(bb->successors().begin());
219 E : for (; succ_it != bb->successors().end(); ++succ_it) {
220 E : const block_graph::Successor& succ = *succ_it;
221 :
222 : // Shortcut alert! As we know the blocks are in-order right after
223 : // decomposition, we can get away with just disassembling the (sole)
224 : // successor that has a size.
225 : // The other successor, if any, will be fall-through.
226 E : const char* opcode = NULL;
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 : // Attempt basic block decomposition if BB-dumping is requested.
306 : // Note that on success we return early from here.
307 : // TODO(siggi): Remove the cl consistent check and section contrib checks
308 : // once the BB decomposer is no longer asserting on non-consistent inputs.
309 : if (dump_basic_blocks_ &&
310 : block->type() == BlockGraph::CODE_BLOCK &&
311 : block->attributes() == BlockGraph::SECTION_CONTRIB &&
312 E : pe::CodeBlockIsClConsistent(block)) {
313 E : BasicBlockSubGraph subgraph;
314 E : BasicBlockDecomposer decomposer(block, &subgraph);
315 :
316 E : if (decomposer.Decompose()) {
317 E : DumpSubGraphToText(subgraph);
318 E : return;
319 : }
320 : // Fall through on failure to decompose.
321 i : }
322 :
323 : BlockGraph::Block::LabelMap::const_iterator
324 E : label_it(block->labels().begin());
325 E : for (; label_it != block->labels().end(); ++label_it) {
326 : ::fprintf(out(), "\t+0x%04X: %s\n",
327 : label_it->first,
328 E : label_it->second.ToString().c_str());
329 E : }
330 :
331 : BlockGraph::Block::ReferenceMap::const_iterator ref_it(
332 E : block->references().begin());
333 E : for (; ref_it != block->references().end(); ++ref_it) {
334 E : ++num_refs_;
335 E : const BlockGraph::Reference& ref = ref_it->second;
336 E : if (ref.offset() == 0) {
337 : ::fprintf(out(), "\t+0x%04X->%s(%d)\n",
338 : ref_it->first,
339 : ref.referenced()->name().c_str(),
340 E : ref.size());
341 E : } else {
342 : // See if there's a label at the desination's offset, and if so
343 : // use that in preference to a raw numeric offset.
344 : BlockGraph::Block::LabelMap::const_iterator label =
345 E : ref.referenced()->labels().find(ref.offset());
346 E : if (label != ref.referenced()->labels().end()) {
347 : ::fprintf(out(), "\t+0x%04X->%s:%s[%d]\n",
348 : ref_it->first,
349 : ref.referenced()->name().c_str(),
350 : label->second.ToString().c_str(),
351 E : ref.size());
352 E : } else {
353 : ::fprintf(out(), "\t+0x%04X->%s+0x%04X(%d)\n",
354 : ref_it->first,
355 : ref.referenced()->name().c_str(),
356 : ref.offset(),
357 E : ref.size());
358 : }
359 : }
360 E : }
361 E : }
362 :
363 E : bool DecomposeImageToTextApp::DumpImageToText(const FilePath& image_path) {
364 : // Load the image file.
365 E : PEFile image_file;
366 E : if (!image_file.Init(image_path)) {
367 i : LOG(ERROR) << "Unable to initialize image " << image_path.value();
368 i : return false;
369 : }
370 :
371 : // And decompose it to an ImageLayout.
372 E : Decomposer decomposer(image_file);
373 E : BlockGraph block_graph;
374 E : ImageLayout image_layout(&block_graph);
375 E : if (!decomposer.Decompose(&image_layout)) {
376 i : LOG(ERROR) << "Unable to decompose image \"" << 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
|