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/ADT/OwningPtr.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCDisassembler.h"
24 #include "llvm/MC/MCInst.h"
25 #include "llvm/MC/MCInstPrinter.h"
26 #include "llvm/MC/MCInstrInfo.h"
27 #include "llvm/MC/MCRegisterInfo.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/Object/Archive.h"
30 #include "llvm/Object/COFF.h"
31 #include "llvm/Object/ObjectFile.h"
32 #include "llvm/Support/Casting.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/FileSystem.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/GraphWriter.h"
38 #include "llvm/Support/Host.h"
39 #include "llvm/Support/ManagedStatic.h"
40 #include "llvm/Support/MemoryBuffer.h"
41 #include "llvm/Support/MemoryObject.h"
42 #include "llvm/Support/PrettyStackTrace.h"
43 #include "llvm/Support/Signals.h"
44 #include "llvm/Support/SourceMgr.h"
45 #include "llvm/Support/TargetRegistry.h"
46 #include "llvm/Support/TargetSelect.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Support/system_error.h"
53 using namespace object;
55 static cl::list<std::string>
56 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
59 Disassemble("disassemble",
60 cl::desc("Display assembler mnemonics for the machine instructions"));
62 Disassembled("d", cl::desc("Alias for --disassemble"),
63 cl::aliasopt(Disassemble));
66 Relocations("r", cl::desc("Display the relocation entries in the file"));
69 SectionContents("s", cl::desc("Display the content of each section"));
72 SymbolTable("t", cl::desc("Display the symbol table"));
75 MachO("macho", cl::desc("Use MachO specific object file parser"));
77 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachO));
80 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
81 "see -version for available targets"));
84 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
85 "see -version for available targets"));
88 SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
89 "for each section."));
91 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
92 cl::aliasopt(SectionHeaders));
94 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
95 cl::aliasopt(SectionHeaders));
97 static cl::list<std::string>
100 cl::desc("Target specific attributes"),
101 cl::value_desc("a1,+a2,-a3,..."));
104 NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, "
105 "do not print the instruction bytes."));
108 UnwindInfo("unwind-info", cl::desc("Display unwind information"));
111 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
112 cl::aliasopt(UnwindInfo));
114 static StringRef ToolName;
116 bool llvm::error(error_code ec) {
117 if (!ec) return false;
119 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
124 static const Target *getTarget(const ObjectFile *Obj = NULL) {
125 // Figure out the target triple.
126 llvm::Triple TheTriple("unknown-unknown-unknown");
127 if (TripleName.empty()) {
129 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
131 TheTriple.setTriple(Triple::normalize(TripleName));
133 // Get the target specific parser.
135 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
138 errs() << ToolName << ": " << Error;
142 // Update the triple name and return the found target.
143 TripleName = TheTriple.getTriple();
147 void llvm::StringRefMemoryObject::anchor() { }
149 void llvm::DumpBytes(StringRef bytes) {
150 static const char hex_rep[] = "0123456789abcdef";
151 // FIXME: The real way to do this is to figure out the longest instruction
152 // and align to that size before printing. I'll fix this when I get
153 // around to outputting relocations.
154 // 15 is the longest x86 instruction
155 // 3 is for the hex rep of a byte + a space.
156 // 1 is for the null terminator.
157 enum { OutputSize = (15 * 3) + 1 };
158 char output[OutputSize];
160 assert(bytes.size() <= 15
161 && "DumpBytes only supports instructions of up to 15 bytes");
162 memset(output, ' ', sizeof(output));
164 for (StringRef::iterator i = bytes.begin(),
165 e = bytes.end(); i != e; ++i) {
166 output[index] = hex_rep[(*i & 0xF0) >> 4];
167 output[index + 1] = hex_rep[*i & 0xF];
171 output[sizeof(output) - 1] = 0;
175 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
176 uint64_t a_addr, b_addr;
177 if (error(a.getAddress(a_addr))) return false;
178 if (error(b.getAddress(b_addr))) return false;
179 return a_addr < b_addr;
182 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
183 const Target *TheTarget = getTarget(Obj);
184 // getTarget() will have already issued a diagnostic if necessary, so
185 // just bail here if it failed.
189 // Package up features to be passed to target/subtarget
190 std::string FeaturesStr;
192 SubtargetFeatures Features;
193 for (unsigned i = 0; i != MAttrs.size(); ++i)
194 Features.AddFeature(MAttrs[i]);
195 FeaturesStr = Features.getString();
199 for (section_iterator i = Obj->begin_sections(),
200 e = Obj->end_sections();
201 i != e; i.increment(ec)) {
202 if (error(ec)) break;
204 if (error(i->isText(text))) break;
207 uint64_t SectionAddr;
208 if (error(i->getAddress(SectionAddr))) break;
210 // Make a list of all the symbols in this section.
211 std::vector<std::pair<uint64_t, StringRef> > Symbols;
212 for (symbol_iterator si = Obj->begin_symbols(),
213 se = Obj->end_symbols();
214 si != se; si.increment(ec)) {
216 if (!error(i->containsSymbol(*si, contains)) && contains) {
218 if (error(si->getAddress(Address))) break;
219 Address -= SectionAddr;
222 if (error(si->getName(Name))) break;
223 Symbols.push_back(std::make_pair(Address, Name));
227 // Sort the symbols by address, just in case they didn't come in that way.
228 array_pod_sort(Symbols.begin(), Symbols.end());
230 // Make a list of all the relocations for this section.
231 std::vector<RelocationRef> Rels;
233 for (relocation_iterator ri = i->begin_relocations(),
234 re = i->end_relocations();
235 ri != re; ri.increment(ec)) {
236 if (error(ec)) break;
241 // Sort relocations by address.
242 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
245 if (error(i->getName(name))) break;
246 outs() << "Disassembly of section " << name << ':';
248 // If the section has no symbols just insert a dummy one and disassemble
249 // the whole section.
251 Symbols.push_back(std::make_pair(0, name));
253 // Set up disassembler.
254 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
257 errs() << "error: no assembly info for target " << TripleName << "\n";
261 OwningPtr<const MCSubtargetInfo> STI(
262 TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
265 errs() << "error: no subtarget info for target " << TripleName << "\n";
269 OwningPtr<const MCDisassembler> DisAsm(
270 TheTarget->createMCDisassembler(*STI));
272 errs() << "error: no disassembler for target " << TripleName << "\n";
276 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
278 errs() << "error: no register info for target " << TripleName << "\n";
282 OwningPtr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
284 errs() << "error: no instruction info for target " << TripleName << "\n";
288 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
289 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
290 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
292 errs() << "error: no instruction printer for target " << TripleName
298 if (error(i->getContents(Bytes))) break;
299 StringRefMemoryObject memoryObject(Bytes);
303 if (error(i->getSize(SectSize))) break;
305 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
306 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
307 // Disassemble symbol by symbol.
308 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
309 uint64_t Start = Symbols[si].first;
311 // The end is either the size of the section or the beginning of the next
315 // Make sure this symbol takes up space.
316 else if (Symbols[si + 1].first != Start)
317 End = Symbols[si + 1].first - 1;
319 // This symbol has the same address as the next symbol. Skip it.
322 outs() << '\n' << Symbols[si].second << ":\n";
325 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
327 raw_ostream &DebugOut = nulls();
330 for (Index = Start; Index < End; Index += Size) {
333 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
334 DebugOut, nulls())) {
335 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
336 if (!NoShowRawInsn) {
338 DumpBytes(StringRef(Bytes.data() + Index, Size));
340 IP->printInst(&Inst, outs(), "");
343 errs() << ToolName << ": warning: invalid instruction encoding\n";
345 Size = 1; // skip illegible bytes
348 // Print relocation for instruction.
349 while (rel_cur != rel_end) {
352 SmallString<16> name;
355 // If this relocation is hidden, skip it.
356 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
357 if (hidden) goto skip_print_rel;
359 if (error(rel_cur->getAddress(addr))) goto skip_print_rel;
360 // Stop when rel_cur's address is past the current instruction.
361 if (addr >= Index + Size) break;
362 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
363 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
365 outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
366 << "\t" << val << "\n";
376 static void PrintRelocations(const ObjectFile *o) {
378 for (section_iterator si = o->begin_sections(), se = o->end_sections();
379 si != se; si.increment(ec)){
380 if (error(ec)) return;
381 if (si->begin_relocations() == si->end_relocations())
384 if (error(si->getName(secname))) continue;
385 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
386 for (relocation_iterator ri = si->begin_relocations(),
387 re = si->end_relocations();
388 ri != re; ri.increment(ec)) {
389 if (error(ec)) return;
393 SmallString<32> relocname;
394 SmallString<32> valuestr;
395 if (error(ri->getHidden(hidden))) continue;
396 if (hidden) continue;
397 if (error(ri->getTypeName(relocname))) continue;
398 if (error(ri->getAddress(address))) continue;
399 if (error(ri->getValueString(valuestr))) continue;
400 outs() << address << " " << relocname << " " << valuestr << "\n";
406 static void PrintSectionHeaders(const ObjectFile *o) {
407 outs() << "Sections:\n"
408 "Idx Name Size Address Type\n";
411 for (section_iterator si = o->begin_sections(), se = o->end_sections();
412 si != se; si.increment(ec)) {
413 if (error(ec)) return;
415 if (error(si->getName(Name))) return;
417 if (error(si->getAddress(Address))) return;
419 if (error(si->getSize(Size))) return;
420 bool Text, Data, BSS;
421 if (error(si->isText(Text))) return;
422 if (error(si->isData(Data))) return;
423 if (error(si->isBSS(BSS))) return;
424 std::string Type = (std::string(Text ? "TEXT " : "") +
425 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
426 outs() << format("%3d %-13s %09" PRIx64 " %017" PRIx64 " %s\n",
427 i, Name.str().c_str(), Size, Address, Type.c_str());
432 static void PrintSectionContents(const ObjectFile *o) {
434 for (section_iterator si = o->begin_sections(),
435 se = o->end_sections();
436 si != se; si.increment(ec)) {
437 if (error(ec)) return;
441 if (error(si->getName(Name))) continue;
442 if (error(si->getContents(Contents))) continue;
443 if (error(si->getAddress(BaseAddr))) continue;
445 outs() << "Contents of section " << Name << ":\n";
447 // Dump out the content as hex and printable ascii characters.
448 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
449 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
451 for (std::size_t i = 0; i < 16; ++i) {
452 if (i != 0 && i % 4 == 0)
455 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
456 << hexdigit(Contents[addr + i] & 0xF, true);
462 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
463 if (std::isprint(Contents[addr + i] & 0xFF))
464 outs() << Contents[addr + i];
473 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
474 const coff_file_header *header;
475 if (error(coff->getHeader(header))) return;
477 const coff_symbol *symbol = 0;
478 for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
480 // Figure out which type of aux this is.
481 if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
482 && symbol->Value == 0) { // Section definition.
483 const coff_aux_section_definition *asd;
484 if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
487 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
488 , unsigned(asd->Length)
489 , unsigned(asd->NumberOfRelocations)
490 , unsigned(asd->NumberOfLinenumbers)
491 , unsigned(asd->CheckSum))
492 << format("assoc %d comdat %d\n"
493 , unsigned(asd->Number)
494 , unsigned(asd->Selection));
496 outs() << "AUX Unknown\n";
499 if (error(coff->getSymbol(i, symbol))) return;
500 if (error(coff->getSymbolName(symbol, name))) return;
501 outs() << "[" << format("%2d", i) << "]"
502 << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
503 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
504 << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
505 << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
506 << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
507 << "0x" << format("%08x", unsigned(symbol->Value)) << " "
509 aux_count = symbol->NumberOfAuxSymbols;
514 static void PrintSymbolTable(const ObjectFile *o) {
515 outs() << "SYMBOL TABLE:\n";
517 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
518 PrintCOFFSymbolTable(coff);
521 for (symbol_iterator si = o->begin_symbols(),
522 se = o->end_symbols(); si != se; si.increment(ec)) {
523 if (error(ec)) return;
526 SymbolRef::Type Type;
529 section_iterator Section = o->end_sections();
530 if (error(si->getName(Name))) continue;
531 if (error(si->getAddress(Address))) continue;
532 if (error(si->getFlags(Flags))) continue;
533 if (error(si->getType(Type))) continue;
534 if (error(si->getSize(Size))) continue;
535 if (error(si->getSection(Section))) continue;
537 bool Global = Flags & SymbolRef::SF_Global;
538 bool Weak = Flags & SymbolRef::SF_Weak;
539 bool Absolute = Flags & SymbolRef::SF_Absolute;
541 if (Address == UnknownAddressOrSize)
543 if (Size == UnknownAddressOrSize)
546 if (Type != SymbolRef::ST_Unknown)
547 GlobLoc = Global ? 'g' : 'l';
548 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
551 if (Type == SymbolRef::ST_File)
553 else if (Type == SymbolRef::ST_Function)
556 outs() << format("%08" PRIx64, Address) << " "
557 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
558 << (Weak ? 'w' : ' ') // Weak?
559 << ' ' // Constructor. Not supported yet.
560 << ' ' // Warning. Not supported yet.
561 << ' ' // Indirect reference to another symbol.
562 << Debug // Debugging (d) or dynamic (D) symbol.
563 << FileFunc // Name of function (F), file (f) or object (O).
567 else if (Section == o->end_sections())
570 StringRef SectionName;
571 if (error(Section->getName(SectionName)))
573 outs() << SectionName;
576 << format("%08" PRIx64 " ", Size)
583 static void PrintUnwindInfo(const ObjectFile *o) {
584 outs() << "Unwind info:\n\n";
586 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
587 printCOFFUnwindInfo(coff);
589 // TODO: Extract DWARF dump tool to objdump.
590 errs() << "This operation is only currently supported "
591 "for COFF object files.\n";
596 static void DumpObject(const ObjectFile *o) {
598 outs() << o->getFileName()
599 << ":\tfile format " << o->getFileFormatName() << "\n\n";
602 DisassembleObject(o, Relocations);
603 if (Relocations && !Disassemble)
606 PrintSectionHeaders(o);
608 PrintSectionContents(o);
615 /// @brief Dump each object file in \a a;
616 static void DumpArchive(const Archive *a) {
617 for (Archive::child_iterator i = a->begin_children(),
618 e = a->end_children(); i != e; ++i) {
619 OwningPtr<Binary> child;
620 if (error_code ec = i->getAsBinary(child)) {
621 // Ignore non-object files.
622 if (ec != object_error::invalid_file_type)
623 errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
627 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
630 errs() << ToolName << ": '" << a->getFileName() << "': "
631 << "Unrecognized file type.\n";
635 /// @brief Open file and figure out how to dump it.
636 static void DumpInput(StringRef file) {
637 // If file isn't stdin, check that it exists.
638 if (file != "-" && !sys::fs::exists(file)) {
639 errs() << ToolName << ": '" << file << "': " << "No such file\n";
643 if (MachO && Disassemble) {
644 DisassembleInputMachO(file);
648 // Attempt to open the binary.
649 OwningPtr<Binary> binary;
650 if (error_code ec = createBinary(file, binary)) {
651 errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
655 if (Archive *a = dyn_cast<Archive>(binary.get()))
657 else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
660 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
663 int main(int argc, char **argv) {
664 // Print a stack trace if we signal out.
665 sys::PrintStackTraceOnErrorSignal();
666 PrettyStackTraceProgram X(argc, argv);
667 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
669 // Initialize targets and assembly printers/parsers.
670 llvm::InitializeAllTargetInfos();
671 llvm::InitializeAllTargetMCs();
672 llvm::InitializeAllAsmParsers();
673 llvm::InitializeAllDisassemblers();
675 // Register the target printer for --version.
676 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
678 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
679 TripleName = Triple::normalize(TripleName);
683 // Defaults to a.out if no filenames specified.
684 if (InputFilenames.size() == 0)
685 InputFilenames.push_back("a.out");
693 cl::PrintHelpMessage();
697 std::for_each(InputFilenames.begin(), InputFilenames.end(),