blob: 4804f596b24e7e6f77416156cd731bb95f7613b8 [file] [log] [blame]
Michael J. Spencer92e1deb2011-01-20 06:39:06 +00001//===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This program is a utility that works like binutils "objdump", that is, it
11// dumps out a plethora of information about an object file depending on the
12// flags.
13//
14//===----------------------------------------------------------------------===//
15
Benjamin Kramer685a2502011-07-20 19:37:35 +000016#include "MCFunction.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000017#include "llvm/Object/ObjectFile.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000018#include "llvm/ADT/OwningPtr.h"
19#include "llvm/ADT/Triple.h"
Benjamin Kramer739b65b2011-07-15 18:39:24 +000020#include "llvm/ADT/STLExtras.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000021#include "llvm/MC/MCAsmInfo.h"
22#include "llvm/MC/MCDisassembler.h"
23#include "llvm/MC/MCInst.h"
24#include "llvm/MC/MCInstPrinter.h"
Benjamin Kramer685a2502011-07-20 19:37:35 +000025#include "llvm/MC/MCInstrDesc.h"
26#include "llvm/MC/MCInstrInfo.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000027#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/Format.h"
Benjamin Kramer853b0fd2011-07-25 23:04:36 +000030#include "llvm/Support/GraphWriter.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000031#include "llvm/Support/Host.h"
32#include "llvm/Support/ManagedStatic.h"
33#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000034#include "llvm/Support/MemoryObject.h"
35#include "llvm/Support/PrettyStackTrace.h"
36#include "llvm/Support/Signals.h"
37#include "llvm/Support/SourceMgr.h"
38#include "llvm/Support/raw_ostream.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000039#include "llvm/Support/system_error.h"
40#include "llvm/Target/TargetRegistry.h"
41#include "llvm/Target/TargetSelect.h"
42#include <algorithm>
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000043#include <cstring>
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000044using namespace llvm;
45using namespace object;
46
47namespace {
48 cl::list<std::string>
49 InputFilenames(cl::Positional, cl::desc("<input object files>"),
50 cl::ZeroOrMore);
51
52 cl::opt<bool>
53 Disassemble("disassemble",
54 cl::desc("Display assembler mnemonics for the machine instructions"));
55 cl::alias
56 Disassembled("d", cl::desc("Alias for --disassemble"),
57 cl::aliasopt(Disassemble));
58
Benjamin Kramer685a2502011-07-20 19:37:35 +000059 cl::opt<bool>
60 CFG("cfg", cl::desc("Create a CFG for every symbol in the object file and"
61 "write it to a graphviz file"));
62
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000063 cl::opt<std::string>
64 TripleName("triple", cl::desc("Target triple to disassemble for, "
65 "see -version for available targets"));
66
67 cl::opt<std::string>
68 ArchName("arch", cl::desc("Target arch to disassemble for, "
69 "see -version for available targets"));
70
71 StringRef ToolName;
Michael J. Spencer25b15772011-06-25 17:55:23 +000072
73 bool error(error_code ec) {
74 if (!ec) return false;
75
76 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
77 outs().flush();
78 return true;
79 }
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000080}
81
82static const Target *GetTarget(const ObjectFile *Obj = NULL) {
83 // Figure out the target triple.
84 llvm::Triple TT("unknown-unknown-unknown");
Michael J. Spencerd11699d2011-01-20 07:22:04 +000085 if (TripleName.empty()) {
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000086 if (Obj)
87 TT.setArch(Triple::ArchType(Obj->getArch()));
Michael J. Spencerd11699d2011-01-20 07:22:04 +000088 } else
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000089 TT.setTriple(Triple::normalize(TripleName));
90
91 if (!ArchName.empty())
92 TT.setArchName(ArchName);
93
94 TripleName = TT.str();
95
96 // Get the target specific parser.
97 std::string Error;
98 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
99 if (TheTarget)
100 return TheTarget;
101
102 errs() << ToolName << ": error: unable to get target for '" << TripleName
103 << "', see --version and --triple.\n";
104 return 0;
105}
106
107namespace {
108class StringRefMemoryObject : public MemoryObject {
109private:
110 StringRef Bytes;
111public:
112 StringRefMemoryObject(StringRef bytes) : Bytes(bytes) {}
113
114 uint64_t getBase() const { return 0; }
115 uint64_t getExtent() const { return Bytes.size(); }
116
117 int readByte(uint64_t Addr, uint8_t *Byte) const {
Benjamin Kramer14c92462011-07-19 22:59:25 +0000118 if (Addr >= getExtent())
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000119 return -1;
120 *Byte = Bytes[Addr];
121 return 0;
122 }
123};
124}
125
126static void DumpBytes(StringRef bytes) {
127 static char hex_rep[] = "0123456789abcdef";
128 // FIXME: The real way to do this is to figure out the longest instruction
129 // and align to that size before printing. I'll fix this when I get
130 // around to outputting relocations.
131 // 15 is the longest x86 instruction
132 // 3 is for the hex rep of a byte + a space.
133 // 1 is for the null terminator.
134 enum { OutputSize = (15 * 3) + 1 };
135 char output[OutputSize];
136
137 assert(bytes.size() <= 15
138 && "DumpBytes only supports instructions of up to 15 bytes");
139 memset(output, ' ', sizeof(output));
140 unsigned index = 0;
141 for (StringRef::iterator i = bytes.begin(),
142 e = bytes.end(); i != e; ++i) {
143 output[index] = hex_rep[(*i & 0xF0) >> 4];
144 output[index + 1] = hex_rep[*i & 0xF];
145 index += 3;
146 }
147
148 output[sizeof(output) - 1] = 0;
149 outs() << output;
150}
151
152static void DisassembleInput(const StringRef &Filename) {
153 OwningPtr<MemoryBuffer> Buff;
154
155 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
156 errs() << ToolName << ": " << Filename << ": " << ec.message() << "\n";
157 return;
158 }
159
160 OwningPtr<ObjectFile> Obj(ObjectFile::createObjectFile(Buff.take()));
161
162 const Target *TheTarget = GetTarget(Obj.get());
163 if (!TheTarget) {
164 // GetTarget prints out stuff.
165 return;
166 }
Benjamin Kramer685a2502011-07-20 19:37:35 +0000167 const MCInstrInfo *InstrInfo = TheTarget->createMCInstrInfo();
Benjamin Kramer41ab14b2011-08-08 18:56:44 +0000168 OwningPtr<MCInstrAnalysis>
169 InstrAnalysis(TheTarget->createMCInstrAnalysis(InstrInfo));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000170
171 outs() << '\n';
172 outs() << Filename
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000173 << ":\tfile format " << Obj->getFileFormatName() << "\n\n";
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000174
Michael J. Spencer25b15772011-06-25 17:55:23 +0000175 error_code ec;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000176 for (ObjectFile::section_iterator i = Obj->begin_sections(),
177 e = Obj->end_sections();
Michael J. Spencer25b15772011-06-25 17:55:23 +0000178 i != e; i.increment(ec)) {
179 if (error(ec)) break;
180 bool text;
181 if (error(i->isText(text))) break;
182 if (!text) continue;
183
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000184 // Make a list of all the symbols in this section.
185 std::vector<std::pair<uint64_t, StringRef> > Symbols;
186 for (ObjectFile::symbol_iterator si = Obj->begin_symbols(),
187 se = Obj->end_symbols();
188 si != se; si.increment(ec)) {
189 bool contains;
190 if (!error(i->containsSymbol(*si, contains)) && contains) {
191 uint64_t Address;
192 if (error(si->getAddress(Address))) break;
193 StringRef Name;
194 if (error(si->getName(Name))) break;
195 Symbols.push_back(std::make_pair(Address, Name));
196 }
197 }
198
199 // Sort the symbols by address, just in case they didn't come in that way.
200 array_pod_sort(Symbols.begin(), Symbols.end());
201
Michael J. Spencer25b15772011-06-25 17:55:23 +0000202 StringRef name;
203 if (error(i->getName(name))) break;
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000204 outs() << "Disassembly of section " << name << ':';
205
206 // If the section has no symbols just insert a dummy one and disassemble
207 // the whole section.
208 if (Symbols.empty())
209 Symbols.push_back(std::make_pair(0, name));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000210
211 // Set up disassembler.
Evan Cheng1abf2cb2011-07-14 23:50:31 +0000212 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000213
214 if (!AsmInfo) {
215 errs() << "error: no assembly info for target " << TripleName << "\n";
216 return;
217 }
218
219 OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler());
220 if (!DisAsm) {
221 errs() << "error: no disassembler for target " << TripleName << "\n";
222 return;
223 }
224
225 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
226 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Evan Chengb2627992011-07-06 19:45:42 +0000227 AsmPrinterVariant, *AsmInfo));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000228 if (!IP) {
229 errs() << "error: no instruction printer for target " << TripleName << '\n';
230 return;
231 }
232
Michael J. Spencer25b15772011-06-25 17:55:23 +0000233 StringRef Bytes;
234 if (error(i->getContents(Bytes))) break;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000235 StringRefMemoryObject memoryObject(Bytes);
236 uint64_t Size;
237 uint64_t Index;
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000238 uint64_t SectSize;
239 if (error(i->getSize(SectSize))) break;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000240
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000241 // Disassemble symbol by symbol.
242 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
243 uint64_t Start = Symbols[si].first;
244 uint64_t End = si == se-1 ? SectSize : Symbols[si + 1].first - 1;
245 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000246
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000247#ifndef NDEBUG
248 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
249#else
250 raw_ostream &DebugOut = nulls();
251#endif
252
Benjamin Kramera21d8132011-08-08 18:32:12 +0000253 if (!CFG) {
254 for (Index = Start; Index < End; Index += Size) {
255 MCInst Inst;
256 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
257 DebugOut)) {
258 uint64_t addr;
259 if (error(i->getAddress(addr))) break;
260 outs() << format("%8x:\t", addr + Index);
261 DumpBytes(StringRef(Bytes.data() + Index, Size));
262 IP->printInst(&Inst, outs());
263 outs() << "\n";
264 } else {
265 errs() << ToolName << ": warning: invalid instruction encoding\n";
266 if (Size == 0)
267 Size = 1; // skip illegible bytes
268 }
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000269 }
Benjamin Kramer685a2502011-07-20 19:37:35 +0000270
Benjamin Kramera21d8132011-08-08 18:32:12 +0000271 } else {
272 // Create CFG and use it for disassembly.
Benjamin Kramer685a2502011-07-20 19:37:35 +0000273 MCFunction f =
274 MCFunction::createFunctionFromMC(Symbols[si].second, DisAsm.get(),
Benjamin Kramer41ab14b2011-08-08 18:56:44 +0000275 memoryObject, Start, End,
276 InstrAnalysis.get(), DebugOut);
Benjamin Kramer685a2502011-07-20 19:37:35 +0000277
Benjamin Kramera21d8132011-08-08 18:32:12 +0000278 for (MCFunction::iterator fi = f.begin(), fe = f.end(); fi != fe; ++fi){
279 bool hasPreds = false;
280 // Only print blocks that have predecessors.
281 // FIXME: Slow.
282 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
283 ++pi)
284 if (pi->second.contains(&fi->second)) {
285 hasPreds = true;
286 break;
287 }
288
Benjamin Kramerc13464f2011-08-08 18:41:34 +0000289 // Data block.
290 if (!hasPreds && fi != f.begin()) {
291 uint64_t End = llvm::next(fi) == fe ? SectSize :
292 llvm::next(fi)->first;
293 uint64_t addr;
294 if (error(i->getAddress(addr))) break;
295 outs() << "# " << End-fi->first << " bytes of data:\n";
296 for (unsigned pos = fi->first; pos != End; ++pos) {
297 outs() << format("%8x:\t", addr + pos);
298 DumpBytes(StringRef(Bytes.data() + pos, 1));
299 outs() << format("\t.byte 0x%02x\n", (uint8_t)Bytes[pos]);
300 }
Benjamin Kramera21d8132011-08-08 18:32:12 +0000301 continue;
Benjamin Kramerc13464f2011-08-08 18:41:34 +0000302 }
303
304 if (fi->second.contains(&fi->second))
305 outs() << "# Loop begin:\n";
Benjamin Kramera21d8132011-08-08 18:32:12 +0000306
307 for (unsigned ii = 0, ie = fi->second.getInsts().size(); ii != ie;
308 ++ii) {
309 uint64_t addr;
310 if (error(i->getAddress(addr))) break;
311 const MCDecodedInst &Inst = fi->second.getInsts()[ii];
312 outs() << format("%8x:\t", addr + Inst.Address);
313 DumpBytes(StringRef(Bytes.data() + Inst.Address, Inst.Size));
Benjamin Kramerc13464f2011-08-08 18:41:34 +0000314 // Simple loops.
315 if (fi->second.contains(&fi->second))
316 outs() << '\t';
Benjamin Kramera21d8132011-08-08 18:32:12 +0000317 IP->printInst(&Inst.Inst, outs());
318 outs() << '\n';
319 }
320 }
321
Benjamin Kramer685a2502011-07-20 19:37:35 +0000322 // Start a new dot file.
323 std::string Error;
324 raw_fd_ostream Out((f.getName().str() + ".dot").c_str(), Error);
Benjamin Kramera503ede2011-07-22 18:35:11 +0000325 if (!Error.empty()) {
326 errs() << ToolName << ": warning: " << Error << '\n';
327 continue;
328 }
Benjamin Kramer685a2502011-07-20 19:37:35 +0000329
330 Out << "digraph " << f.getName() << " {\n";
331 Out << "graph [ rankdir = \"LR\" ];\n";
332 for (MCFunction::iterator i = f.begin(), e = f.end(); i != e; ++i) {
Benjamin Kramer853b0fd2011-07-25 23:04:36 +0000333 bool hasPreds = false;
334 // Only print blocks that have predecessors.
335 // FIXME: Slow.
336 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
337 ++pi)
Benjamin Kramerdbc46d72011-07-25 23:10:23 +0000338 if (pi->second.contains(&i->second)) {
Benjamin Kramer853b0fd2011-07-25 23:04:36 +0000339 hasPreds = true;
340 break;
341 }
342
343 if (!hasPreds && i != f.begin())
344 continue;
345
Benjamin Kramer685a2502011-07-20 19:37:35 +0000346 Out << '"' << (uintptr_t)&i->second << "\" [ label=\"<a>";
347 // Print instructions.
348 for (unsigned ii = 0, ie = i->second.getInsts().size(); ii != ie;
349 ++ii) {
Benjamin Kramer853b0fd2011-07-25 23:04:36 +0000350 // Escape special chars and print the instruction in mnemonic form.
351 std::string Str;
352 raw_string_ostream OS(Str);
353 IP->printInst(&i->second.getInsts()[ii].Inst, OS);
354 Out << DOT::EscapeString(OS.str()) << '|';
Benjamin Kramer685a2502011-07-20 19:37:35 +0000355 }
356 Out << "<o>\" shape=\"record\" ];\n";
357
358 // Add edges.
359 for (MCBasicBlock::succ_iterator si = i->second.succ_begin(),
360 se = i->second.succ_end(); si != se; ++si)
361 Out << (uintptr_t)&i->second << ":o -> " << (uintptr_t)*si <<":a\n";
362 }
363 Out << "}\n";
364 }
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000365 }
366 }
367}
368
369int main(int argc, char **argv) {
370 // Print a stack trace if we signal out.
371 sys::PrintStackTraceOnErrorSignal();
372 PrettyStackTraceProgram X(argc, argv);
373 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
374
375 // Initialize targets and assembly printers/parsers.
376 llvm::InitializeAllTargetInfos();
Evan Chenge78085a2011-07-22 21:58:54 +0000377 llvm::InitializeAllTargetMCs();
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000378 llvm::InitializeAllAsmParsers();
379 llvm::InitializeAllDisassemblers();
380
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000381 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
382 TripleName = Triple::normalize(TripleName);
383
384 ToolName = argv[0];
385
386 // Defaults to a.out if no filenames specified.
387 if (InputFilenames.size() == 0)
388 InputFilenames.push_back("a.out");
389
390 // -d is the only flag that is currently implemented, so just print help if
391 // it is not set.
392 if (!Disassemble) {
393 cl::PrintHelpMessage();
394 return 2;
395 }
396
397 std::for_each(InputFilenames.begin(), InputFilenames.end(),
398 DisassembleInput);
399
400 return 0;
401}