1 //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
14 //===----------------------------------------------------------------------===//
16 #include "MCFunction.h"
17 #include "llvm/Object/ObjectFile.h"
18 #include "llvm/ADT/OwningPtr.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCDisassembler.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCInstPrinter.h"
25 #include "llvm/MC/MCInstrAnalysis.h"
26 #include "llvm/MC/MCInstrDesc.h"
27 #include "llvm/MC/MCInstrInfo.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/Format.h"
31 #include "llvm/Support/GraphWriter.h"
32 #include "llvm/Support/Host.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/MemoryObject.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/Signals.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Support/system_error.h"
41 #include "llvm/Target/TargetRegistry.h"
42 #include "llvm/Target/TargetSelect.h"
46 using namespace object;
50 InputFilenames(cl::Positional, cl::desc("<input object files>"),
54 Disassemble("disassemble",
55 cl::desc("Display assembler mnemonics for the machine instructions"));
57 Disassembled("d", cl::desc("Alias for --disassemble"),
58 cl::aliasopt(Disassemble));
61 CFG("cfg", cl::desc("Create a CFG for every symbol in the object file and"
62 "write it to a graphviz file"));
65 TripleName("triple", cl::desc("Target triple to disassemble for, "
66 "see -version for available targets"));
69 ArchName("arch", cl::desc("Target arch to disassemble for, "
70 "see -version for available targets"));
74 bool error(error_code ec) {
75 if (!ec) return false;
77 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
83 static const Target *GetTarget(const ObjectFile *Obj = NULL) {
84 // Figure out the target triple.
85 llvm::Triple TT("unknown-unknown-unknown");
86 if (TripleName.empty()) {
88 TT.setArch(Triple::ArchType(Obj->getArch()));
90 TT.setTriple(Triple::normalize(TripleName));
92 if (!ArchName.empty())
93 TT.setArchName(ArchName);
95 TripleName = TT.str();
97 // Get the target specific parser.
99 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
103 errs() << ToolName << ": error: unable to get target for '" << TripleName
104 << "', see --version and --triple.\n";
109 class StringRefMemoryObject : public MemoryObject {
113 StringRefMemoryObject(StringRef bytes) : Bytes(bytes) {}
115 uint64_t getBase() const { return 0; }
116 uint64_t getExtent() const { return Bytes.size(); }
118 int readByte(uint64_t Addr, uint8_t *Byte) const {
119 if (Addr >= getExtent())
127 static void DumpBytes(StringRef bytes) {
128 static char hex_rep[] = "0123456789abcdef";
129 // FIXME: The real way to do this is to figure out the longest instruction
130 // and align to that size before printing. I'll fix this when I get
131 // around to outputting relocations.
132 // 15 is the longest x86 instruction
133 // 3 is for the hex rep of a byte + a space.
134 // 1 is for the null terminator.
135 enum { OutputSize = (15 * 3) + 1 };
136 char output[OutputSize];
138 assert(bytes.size() <= 15
139 && "DumpBytes only supports instructions of up to 15 bytes");
140 memset(output, ' ', sizeof(output));
142 for (StringRef::iterator i = bytes.begin(),
143 e = bytes.end(); i != e; ++i) {
144 output[index] = hex_rep[(*i & 0xF0) >> 4];
145 output[index + 1] = hex_rep[*i & 0xF];
149 output[sizeof(output) - 1] = 0;
153 static void DisassembleInput(const StringRef &Filename) {
154 OwningPtr<MemoryBuffer> Buff;
156 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
157 errs() << ToolName << ": " << Filename << ": " << ec.message() << "\n";
161 OwningPtr<ObjectFile> Obj(ObjectFile::createObjectFile(Buff.take()));
163 const Target *TheTarget = GetTarget(Obj.get());
165 // GetTarget prints out stuff.
168 const MCInstrInfo *InstrInfo = TheTarget->createMCInstrInfo();
169 OwningPtr<MCInstrAnalysis>
170 InstrAnalysis(TheTarget->createMCInstrAnalysis(InstrInfo));
174 << ":\tfile format " << Obj->getFileFormatName() << "\n\n";
177 for (ObjectFile::section_iterator i = Obj->begin_sections(),
178 e = Obj->end_sections();
179 i != e; i.increment(ec)) {
180 if (error(ec)) break;
182 if (error(i->isText(text))) break;
185 // Make a list of all the symbols in this section.
186 std::vector<std::pair<uint64_t, StringRef> > Symbols;
187 for (ObjectFile::symbol_iterator si = Obj->begin_symbols(),
188 se = Obj->end_symbols();
189 si != se; si.increment(ec)) {
191 if (!error(i->containsSymbol(*si, contains)) && contains) {
193 if (error(si->getAddress(Address))) break;
195 if (error(si->getName(Name))) break;
196 Symbols.push_back(std::make_pair(Address, Name));
200 // Sort the symbols by address, just in case they didn't come in that way.
201 array_pod_sort(Symbols.begin(), Symbols.end());
204 if (error(i->getName(name))) break;
205 outs() << "Disassembly of section " << name << ':';
207 // If the section has no symbols just insert a dummy one and disassemble
208 // the whole section.
210 Symbols.push_back(std::make_pair(0, name));
212 // Set up disassembler.
213 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
216 errs() << "error: no assembly info for target " << TripleName << "\n";
220 OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler());
222 errs() << "error: no disassembler for target " << TripleName << "\n";
226 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
227 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
228 AsmPrinterVariant, *AsmInfo));
230 errs() << "error: no instruction printer for target " << TripleName << '\n';
235 if (error(i->getContents(Bytes))) break;
236 StringRefMemoryObject memoryObject(Bytes);
240 if (error(i->getSize(SectSize))) break;
242 // Disassemble symbol by symbol.
243 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
244 uint64_t Start = Symbols[si].first;
245 uint64_t End = si == se-1 ? SectSize : Symbols[si + 1].first - 1;
246 outs() << '\n' << Symbols[si].second << ":\n";
249 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
251 raw_ostream &DebugOut = nulls();
255 for (Index = Start; Index < End; Index += Size) {
257 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
260 if (error(i->getAddress(addr))) break;
261 outs() << format("%8x:\t", addr + Index);
262 DumpBytes(StringRef(Bytes.data() + Index, Size));
263 IP->printInst(&Inst, outs());
266 errs() << ToolName << ": warning: invalid instruction encoding\n";
268 Size = 1; // skip illegible bytes
273 // Create CFG and use it for disassembly.
275 MCFunction::createFunctionFromMC(Symbols[si].second, DisAsm.get(),
276 memoryObject, Start, End,
277 InstrAnalysis.get(), DebugOut);
279 for (MCFunction::iterator fi = f.begin(), fe = f.end(); fi != fe; ++fi){
280 bool hasPreds = false;
281 // Only print blocks that have predecessors.
283 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
285 if (pi->second.contains(&fi->second)) {
291 if (!hasPreds && fi != f.begin()) {
292 uint64_t End = llvm::next(fi) == fe ? SectSize :
293 llvm::next(fi)->first;
295 if (error(i->getAddress(addr))) break;
296 outs() << "# " << End-fi->first << " bytes of data:\n";
297 for (unsigned pos = fi->first; pos != End; ++pos) {
298 outs() << format("%8x:\t", addr + pos);
299 DumpBytes(StringRef(Bytes.data() + pos, 1));
300 outs() << format("\t.byte 0x%02x\n", (uint8_t)Bytes[pos]);
305 if (fi->second.contains(&fi->second))
306 outs() << "# Loop begin:\n";
308 for (unsigned ii = 0, ie = fi->second.getInsts().size(); ii != ie;
311 if (error(i->getAddress(addr))) break;
312 const MCDecodedInst &Inst = fi->second.getInsts()[ii];
313 outs() << format("%8x:\t", addr + Inst.Address);
314 DumpBytes(StringRef(Bytes.data() + Inst.Address, Inst.Size));
316 if (fi->second.contains(&fi->second))
318 IP->printInst(&Inst.Inst, outs());
323 // Start a new dot file.
325 raw_fd_ostream Out((f.getName().str() + ".dot").c_str(), Error);
326 if (!Error.empty()) {
327 errs() << ToolName << ": warning: " << Error << '\n';
331 Out << "digraph " << f.getName() << " {\n";
332 Out << "graph [ rankdir = \"LR\" ];\n";
333 for (MCFunction::iterator i = f.begin(), e = f.end(); i != e; ++i) {
334 bool hasPreds = false;
335 // Only print blocks that have predecessors.
337 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
339 if (pi->second.contains(&i->second)) {
344 if (!hasPreds && i != f.begin())
347 Out << '"' << (uintptr_t)&i->second << "\" [ label=\"<a>";
348 // Print instructions.
349 for (unsigned ii = 0, ie = i->second.getInsts().size(); ii != ie;
351 // Escape special chars and print the instruction in mnemonic form.
353 raw_string_ostream OS(Str);
354 IP->printInst(&i->second.getInsts()[ii].Inst, OS);
355 Out << DOT::EscapeString(OS.str()) << '|';
357 Out << "<o>\" shape=\"record\" ];\n";
360 for (MCBasicBlock::succ_iterator si = i->second.succ_begin(),
361 se = i->second.succ_end(); si != se; ++si)
362 Out << (uintptr_t)&i->second << ":o -> " << (uintptr_t)*si <<":a\n";
370 int main(int argc, char **argv) {
371 // Print a stack trace if we signal out.
372 sys::PrintStackTraceOnErrorSignal();
373 PrettyStackTraceProgram X(argc, argv);
374 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
376 // Initialize targets and assembly printers/parsers.
377 llvm::InitializeAllTargetInfos();
378 llvm::InitializeAllTargetMCs();
379 llvm::InitializeAllAsmParsers();
380 llvm::InitializeAllDisassemblers();
382 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
383 TripleName = Triple::normalize(TripleName);
387 // Defaults to a.out if no filenames specified.
388 if (InputFilenames.size() == 0)
389 InputFilenames.push_back("a.out");
391 // -d is the only flag that is currently implemented, so just print help if
394 cl::PrintHelpMessage();
398 std::for_each(InputFilenames.begin(), InputFilenames.end(),