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 "llvm-objdump.h"
17 #include "MCFunction.h"
18 #include "llvm/Object/Archive.h"
19 #include "llvm/Object/COFF.h"
20 #include "llvm/Object/ObjectFile.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCDisassembler.h"
27 #include "llvm/MC/MCInst.h"
28 #include "llvm/MC/MCInstPrinter.h"
29 #include "llvm/MC/MCSubtargetInfo.h"
30 #include "llvm/Support/Casting.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/Format.h"
35 #include "llvm/Support/GraphWriter.h"
36 #include "llvm/Support/Host.h"
37 #include "llvm/Support/ManagedStatic.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/MemoryObject.h"
40 #include "llvm/Support/PrettyStackTrace.h"
41 #include "llvm/Support/Signals.h"
42 #include "llvm/Support/SourceMgr.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/TargetSelect.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/Support/system_error.h"
50 using namespace object;
52 static cl::list<std::string>
53 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
56 Disassemble("disassemble",
57 cl::desc("Display assembler mnemonics for the machine instructions"));
59 Disassembled("d", cl::desc("Alias for --disassemble"),
60 cl::aliasopt(Disassemble));
63 Relocations("r", cl::desc("Display the relocation entries in the file"));
66 SectionContents("s", cl::desc("Display the content of each section"));
69 SymbolTable("t", cl::desc("Display the symbol table"));
72 MachO("macho", cl::desc("Use MachO specific object file parser"));
74 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachO));
77 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
78 "see -version for available targets"));
81 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
82 "see -version for available targets"));
85 SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
86 "for each section."));
88 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
89 cl::aliasopt(SectionHeaders));
91 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
92 cl::aliasopt(SectionHeaders));
94 static StringRef ToolName;
96 static bool error(error_code ec) {
97 if (!ec) return false;
99 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
104 static const Target *GetTarget(const ObjectFile *Obj = NULL) {
105 // Figure out the target triple.
106 llvm::Triple TT("unknown-unknown-unknown");
107 if (TripleName.empty()) {
109 TT.setArch(Triple::ArchType(Obj->getArch()));
111 TT.setTriple(Triple::normalize(TripleName));
113 if (!ArchName.empty())
114 TT.setArchName(ArchName);
116 TripleName = TT.str();
118 // Get the target specific parser.
120 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
124 errs() << ToolName << ": error: unable to get target for '" << TripleName
125 << "', see --version and --triple.\n";
129 void llvm::StringRefMemoryObject::anchor() { }
131 void llvm::DumpBytes(StringRef bytes) {
132 static const char hex_rep[] = "0123456789abcdef";
133 // FIXME: The real way to do this is to figure out the longest instruction
134 // and align to that size before printing. I'll fix this when I get
135 // around to outputting relocations.
136 // 15 is the longest x86 instruction
137 // 3 is for the hex rep of a byte + a space.
138 // 1 is for the null terminator.
139 enum { OutputSize = (15 * 3) + 1 };
140 char output[OutputSize];
142 assert(bytes.size() <= 15
143 && "DumpBytes only supports instructions of up to 15 bytes");
144 memset(output, ' ', sizeof(output));
146 for (StringRef::iterator i = bytes.begin(),
147 e = bytes.end(); i != e; ++i) {
148 output[index] = hex_rep[(*i & 0xF0) >> 4];
149 output[index + 1] = hex_rep[*i & 0xF];
153 output[sizeof(output) - 1] = 0;
157 static bool RelocAddressLess(RelocationRef a, RelocationRef b) {
158 uint64_t a_addr, b_addr;
159 if (error(a.getAddress(a_addr))) return false;
160 if (error(b.getAddress(b_addr))) return false;
161 return a_addr < b_addr;
164 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
165 const Target *TheTarget = GetTarget(Obj);
167 // GetTarget prints out stuff.
172 for (section_iterator i = Obj->begin_sections(),
173 e = Obj->end_sections();
174 i != e; i.increment(ec)) {
175 if (error(ec)) break;
177 if (error(i->isText(text))) break;
180 uint64_t SectionAddr;
181 if (error(i->getAddress(SectionAddr))) break;
183 // Make a list of all the symbols in this section.
184 std::vector<std::pair<uint64_t, StringRef> > Symbols;
185 for (symbol_iterator si = Obj->begin_symbols(),
186 se = Obj->end_symbols();
187 si != se; si.increment(ec)) {
189 if (!error(i->containsSymbol(*si, contains)) && contains) {
191 if (error(si->getAddress(Address))) break;
192 Address -= SectionAddr;
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());
203 // Make a list of all the relocations for this section.
204 std::vector<RelocationRef> Rels;
206 for (relocation_iterator ri = i->begin_relocations(),
207 re = i->end_relocations();
208 ri != re; ri.increment(ec)) {
209 if (error(ec)) break;
214 // Sort relocations by address.
215 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
218 if (error(i->getName(name))) break;
219 outs() << "Disassembly of section " << name << ':';
221 // If the section has no symbols just insert a dummy one and disassemble
222 // the whole section.
224 Symbols.push_back(std::make_pair(0, name));
226 // Set up disassembler.
227 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
230 errs() << "error: no assembly info for target " << TripleName << "\n";
234 OwningPtr<const MCSubtargetInfo> STI(
235 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
238 errs() << "error: no subtarget info for target " << TripleName << "\n";
242 OwningPtr<const MCDisassembler> DisAsm(
243 TheTarget->createMCDisassembler(*STI));
245 errs() << "error: no disassembler for target " << TripleName << "\n";
249 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
250 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
251 AsmPrinterVariant, *AsmInfo, *STI));
253 errs() << "error: no instruction printer for target " << TripleName
259 if (error(i->getContents(Bytes))) break;
260 StringRefMemoryObject memoryObject(Bytes);
264 if (error(i->getSize(SectSize))) break;
266 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
267 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
268 // Disassemble symbol by symbol.
269 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
270 uint64_t Start = Symbols[si].first;
272 // The end is either the size of the section or the beginning of the next
276 // Make sure this symbol takes up space.
277 else if (Symbols[si + 1].first != Start)
278 End = Symbols[si + 1].first - 1;
280 // This symbol has the same address as the next symbol. Skip it.
283 outs() << '\n' << Symbols[si].second << ":\n";
286 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
288 raw_ostream &DebugOut = nulls();
291 for (Index = Start; Index < End; Index += Size) {
294 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
295 DebugOut, nulls())) {
296 outs() << format("%8"PRIx64":\t", SectionAddr + Index);
297 DumpBytes(StringRef(Bytes.data() + Index, Size));
298 IP->printInst(&Inst, outs(), "");
301 errs() << ToolName << ": warning: invalid instruction encoding\n";
303 Size = 1; // skip illegible bytes
306 // Print relocation for instruction.
307 while (rel_cur != rel_end) {
310 SmallString<16> name;
313 // If this relocation is hidden, skip it.
314 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
315 if (hidden) goto skip_print_rel;
317 if (error(rel_cur->getAddress(addr))) goto skip_print_rel;
318 // Stop when rel_cur's address is past the current instruction.
319 if (addr >= Index + Size) break;
320 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
321 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
323 outs() << format("\t\t\t%8"PRIx64": ", SectionAddr + addr) << name << "\t"
334 static void PrintRelocations(const ObjectFile *o) {
336 for (section_iterator si = o->begin_sections(), se = o->end_sections();
337 si != se; si.increment(ec)){
338 if (error(ec)) return;
339 if (si->begin_relocations() == si->end_relocations())
342 if (error(si->getName(secname))) continue;
343 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
344 for (relocation_iterator ri = si->begin_relocations(),
345 re = si->end_relocations();
346 ri != re; ri.increment(ec)) {
347 if (error(ec)) return;
351 SmallString<32> relocname;
352 SmallString<32> valuestr;
353 if (error(ri->getHidden(hidden))) continue;
354 if (hidden) continue;
355 if (error(ri->getTypeName(relocname))) continue;
356 if (error(ri->getAddress(address))) continue;
357 if (error(ri->getValueString(valuestr))) continue;
358 outs() << address << " " << relocname << " " << valuestr << "\n";
364 static void PrintSectionHeaders(const ObjectFile *o) {
365 outs() << "Sections:\n"
366 "Idx Name Size Address Type\n";
369 for (section_iterator si = o->begin_sections(), se = o->end_sections();
370 si != se; si.increment(ec)) {
371 if (error(ec)) return;
373 if (error(si->getName(Name))) return;
375 if (error(si->getAddress(Address))) return;
377 if (error(si->getSize(Size))) return;
378 bool Text, Data, BSS;
379 if (error(si->isText(Text))) return;
380 if (error(si->isData(Data))) return;
381 if (error(si->isBSS(BSS))) return;
382 std::string Type = (std::string(Text ? "TEXT " : "") +
383 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
384 outs() << format("%3d %-13s %09"PRIx64" %017"PRIx64" %s\n", i, Name.str().c_str(), Size,
385 Address, Type.c_str());
390 static void PrintSectionContents(const ObjectFile *o) {
392 for (section_iterator si = o->begin_sections(),
393 se = o->end_sections();
394 si != se; si.increment(ec)) {
395 if (error(ec)) return;
399 if (error(si->getName(Name))) continue;
400 if (error(si->getContents(Contents))) continue;
401 if (error(si->getAddress(BaseAddr))) continue;
403 outs() << "Contents of section " << Name << ":\n";
405 // Dump out the content as hex and printable ascii characters.
406 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
407 outs() << format(" %04"PRIx64" ", BaseAddr + addr);
409 for (std::size_t i = 0; i < 16; ++i) {
410 if (i != 0 && i % 4 == 0)
413 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
414 << hexdigit(Contents[addr + i] & 0xF, true);
420 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
421 if (std::isprint(Contents[addr + i] & 0xFF))
422 outs() << Contents[addr + i];
431 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
432 const coff_file_header *header;
433 if (error(coff->getHeader(header))) return;
435 const coff_symbol *symbol = 0;
436 for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
438 // Figure out which type of aux this is.
439 if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
440 && symbol->Value == 0) { // Section definition.
441 const coff_aux_section_definition *asd;
442 if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
445 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
446 , unsigned(asd->Length)
447 , unsigned(asd->NumberOfRelocations)
448 , unsigned(asd->NumberOfLinenumbers)
449 , unsigned(asd->CheckSum))
450 << format("assoc %d comdat %d\n"
451 , unsigned(asd->Number)
452 , unsigned(asd->Selection));
454 outs() << "AUX Unknown\n";
458 if (error(coff->getSymbol(i, symbol))) return;
459 if (error(coff->getSymbolName(symbol, name))) return;
460 outs() << "[" << format("%2d", i) << "]"
461 << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
462 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
463 << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
464 << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
465 << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
466 << "0x" << format("%08x", unsigned(symbol->Value)) << " "
468 aux_count = symbol->NumberOfAuxSymbols;
473 static void PrintSymbolTable(const ObjectFile *o) {
474 outs() << "SYMBOL TABLE:\n";
476 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
477 PrintCOFFSymbolTable(coff);
480 for (symbol_iterator si = o->begin_symbols(),
481 se = o->end_symbols(); si != se; si.increment(ec)) {
482 if (error(ec)) return;
486 SymbolRef::Type Type;
490 section_iterator Section = o->end_sections();
491 if (error(si->getName(Name))) continue;
492 if (error(si->getAddress(Address))) continue;
493 if (error(si->isGlobal(Global))) continue;
494 if (error(si->getType(Type))) continue;
495 if (error(si->isWeak(Weak))) continue;
496 if (error(si->isAbsolute(Absolute))) continue;
497 if (error(si->getSize(Size))) continue;
498 if (error(si->getSection(Section))) continue;
500 if (Address == UnknownAddressOrSize)
502 if (Size == UnknownAddressOrSize)
505 if (Type != SymbolRef::ST_External)
506 GlobLoc = Global ? 'g' : 'l';
507 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
510 if (Type == SymbolRef::ST_File)
512 else if (Type == SymbolRef::ST_Function)
515 outs() << format("%08"PRIx64, Address) << " "
516 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
517 << (Weak ? 'w' : ' ') // Weak?
518 << ' ' // Constructor. Not supported yet.
519 << ' ' // Warning. Not supported yet.
520 << ' ' // Indirect reference to another symbol.
521 << Debug // Debugging (d) or dynamic (D) symbol.
522 << FileFunc // Name of function (F), file (f) or object (O).
526 else if (Section == o->end_sections())
529 StringRef SectionName;
530 if (error(Section->getName(SectionName)))
532 outs() << SectionName;
535 << format("%08"PRIx64" ", Size)
542 static void DumpObject(const ObjectFile *o) {
544 outs() << o->getFileName()
545 << ":\tfile format " << o->getFileFormatName() << "\n\n";
548 DisassembleObject(o, Relocations);
549 if (Relocations && !Disassemble)
552 PrintSectionHeaders(o);
554 PrintSectionContents(o);
559 /// @brief Dump each object file in \a a;
560 static void DumpArchive(const Archive *a) {
561 for (Archive::child_iterator i = a->begin_children(),
562 e = a->end_children(); i != e; ++i) {
563 OwningPtr<Binary> child;
564 if (error_code ec = i->getAsBinary(child)) {
565 // Ignore non-object files.
566 if (ec != object_error::invalid_file_type)
567 errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
571 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
574 errs() << ToolName << ": '" << a->getFileName() << "': "
575 << "Unrecognized file type.\n";
579 /// @brief Open file and figure out how to dump it.
580 static void DumpInput(StringRef file) {
581 // If file isn't stdin, check that it exists.
582 if (file != "-" && !sys::fs::exists(file)) {
583 errs() << ToolName << ": '" << file << "': " << "No such file\n";
587 if (MachO && Disassemble) {
588 DisassembleInputMachO(file);
592 // Attempt to open the binary.
593 OwningPtr<Binary> binary;
594 if (error_code ec = createBinary(file, binary)) {
595 errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
599 if (Archive *a = dyn_cast<Archive>(binary.get())) {
601 } else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get())) {
604 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
608 int main(int argc, char **argv) {
609 // Print a stack trace if we signal out.
610 sys::PrintStackTraceOnErrorSignal();
611 PrettyStackTraceProgram X(argc, argv);
612 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
614 // Initialize targets and assembly printers/parsers.
615 llvm::InitializeAllTargetInfos();
616 llvm::InitializeAllTargetMCs();
617 llvm::InitializeAllAsmParsers();
618 llvm::InitializeAllDisassemblers();
620 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
621 TripleName = Triple::normalize(TripleName);
625 // Defaults to a.out if no filenames specified.
626 if (InputFilenames.size() == 0)
627 InputFilenames.push_back("a.out");
634 cl::PrintHelpMessage();
638 std::for_each(InputFilenames.begin(), InputFilenames.end(),