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 i : void HexDump(const uint8* data, size_t size, FILE* out) {
90 i : for (size_t i = 0; i < size; ++i)
91 i : ::fprintf(out, "%02x", data[i]);
92 i : }
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 base::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 i : DumpDataBBToText(block, BasicDataBlock::Cast(bb));
179 i : 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 : if (succ.instruction_size()) {
227 E : _CodeInfo code = {};
228 E : code.codeOffset = 0;
229 E : code.code = block->data() + bb->offset() + bb->GetInstructionSize();
230 E : code.codeLen = succ.instruction_size();
231 E : code.dt = Decode32Bits;
232 E : _DecodedInst decoded = {};
233 E : _DInst instr = {};
234 :
235 E : unsigned int count = 0;
236 E : distorm_decompose64(&code, &instr, 1, &count);
237 E : instr.addr = 0;
238 E : distorm_format(&code, &instr, &decoded);
239 : ::fprintf(out(), " %-14s %s %s",
240 : decoded.instructionHex.p,
241 : decoded.mnemonic.p,
242 E : decoded.operands.p);
243 :
244 E : DumpReference(succ.reference(), out());
245 E : ::fprintf(out(), "\n");
246 : }
247 E : }
248 E : }
249 :
250 : void DecomposeImageToTextApp::DumpDataBBToText(
251 i : const BlockGraph::Block* block, const BasicDataBlock* bb) {
252 : // Here we proceed by dumping a hex chunk up to the next reference, then
253 : // the reference and so on.
254 i : size_t curr_start = 0;
255 :
256 i : while (curr_start < bb->size()) {
257 : BasicBlock::BasicBlockReferenceMap::const_iterator it(
258 i : bb->references().lower_bound(curr_start));
259 :
260 i : size_t next_chunk_end = bb->size();
261 i : if (it != bb->references().end())
262 i : next_chunk_end = it->first;
263 i : if (next_chunk_end == curr_start) {
264 : // We're on a reference, dump it and it's reference.
265 i : switch (it->second.size()) {
266 : case 1:
267 i : ::fprintf(out(), " DB ");
268 i : break;
269 : case 2:
270 i : ::fprintf(out(), " DW ");
271 i : break;
272 : case 4:
273 i : ::fprintf(out(), " DD ");
274 i : break;
275 : default:
276 i : NOTREACHED();
277 : break;
278 : }
279 i : HexDump(bb->data() + curr_start, it->second.size(), out());
280 i : DumpReference(it->second, out());
281 i : ::fprintf(out(), "\n");
282 :
283 i : curr_start += it->second.size();
284 i : } else {
285 i : if (next_chunk_end - curr_start > 16)
286 i : next_chunk_end = curr_start + 16;
287 :
288 i : ::fprintf(out(), " DB ");
289 i : HexDump(bb->data() + curr_start, next_chunk_end - curr_start, out());
290 i : ::fprintf(out(), "\n");
291 :
292 i : curr_start = next_chunk_end;
293 : }
294 i : }
295 i : }
296 :
297 : void DecomposeImageToTextApp::DumpBlockToText(
298 E : core::RelativeAddress addr, const BlockGraph::Block* block) {
299 : ::fprintf(out(), "0x%08X(%d): %s\n",
300 : addr.value(),
301 : block->size(),
302 E : block->name().c_str());
303 :
304 : // Attempt basic block decomposition if BB-dumping is requested.
305 : // Note that on success we return early from here.
306 : // TODO(siggi): Remove the cl consistent check and section contrib checks
307 : // once the BB decomposer is no longer asserting on non-consistent inputs.
308 : if (dump_basic_blocks_ &&
309 : block->type() == BlockGraph::CODE_BLOCK &&
310 : block->attributes() == BlockGraph::SECTION_CONTRIB &&
311 E : pe::CodeBlockIsClConsistent(block)) {
312 E : BasicBlockSubGraph subgraph;
313 E : BasicBlockDecomposer decomposer(block, &subgraph);
314 :
315 E : if (decomposer.Decompose()) {
316 E : DumpSubGraphToText(subgraph);
317 E : return;
318 : }
319 : // Fall through on failure to decompose.
320 i : }
321 :
322 : BlockGraph::Block::LabelMap::const_iterator
323 E : label_it(block->labels().begin());
324 E : for (; label_it != block->labels().end(); ++label_it) {
325 : ::fprintf(out(), "\t+0x%04X: %s\n",
326 : label_it->first,
327 E : label_it->second.ToString().c_str());
328 E : }
329 :
330 : BlockGraph::Block::ReferenceMap::const_iterator ref_it(
331 E : block->references().begin());
332 E : for (; ref_it != block->references().end(); ++ref_it) {
333 E : ++num_refs_;
334 E : const BlockGraph::Reference& ref = ref_it->second;
335 E : if (ref.offset() == 0) {
336 : ::fprintf(out(), "\t+0x%04X->%s(%d)\n",
337 : ref_it->first,
338 : ref.referenced()->name().c_str(),
339 E : ref.size());
340 E : } else {
341 : // See if there's a label at the desination's offset, and if so
342 : // use that in preference to a raw numeric offset.
343 : BlockGraph::Block::LabelMap::const_iterator label =
344 E : ref.referenced()->labels().find(ref.offset());
345 E : if (label != ref.referenced()->labels().end()) {
346 : ::fprintf(out(), "\t+0x%04X->%s:%s[%d]\n",
347 : ref_it->first,
348 : ref.referenced()->name().c_str(),
349 : label->second.ToString().c_str(),
350 E : ref.size());
351 E : } else {
352 : ::fprintf(out(), "\t+0x%04X->%s+0x%04X(%d)\n",
353 : ref_it->first,
354 : ref.referenced()->name().c_str(),
355 : ref.offset(),
356 E : ref.size());
357 : }
358 : }
359 E : }
360 E : }
361 :
362 : bool DecomposeImageToTextApp::DumpImageToText(
363 E : const base::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
|