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 // The flags and output of this program should be near identical to those of
17 //===----------------------------------------------------------------------===//
19 #include "llvm-objdump.h"
20 #include "MCFunction.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCDisassembler.h"
28 #include "llvm/MC/MCInst.h"
29 #include "llvm/MC/MCInstPrinter.h"
30 #include "llvm/MC/MCInstrInfo.h"
31 #include "llvm/MC/MCObjectFileInfo.h"
32 #include "llvm/MC/MCObjectSymbolizer.h"
33 #include "llvm/MC/MCRegisterInfo.h"
34 #include "llvm/MC/MCSubtargetInfo.h"
35 #include "llvm/MC/MCRelocationInfo.h"
36 #include "llvm/Object/Archive.h"
37 #include "llvm/Object/COFF.h"
38 #include "llvm/Object/MachO.h"
39 #include "llvm/Object/ObjectFile.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/Format.h"
45 #include "llvm/Support/GraphWriter.h"
46 #include "llvm/Support/Host.h"
47 #include "llvm/Support/ManagedStatic.h"
48 #include "llvm/Support/MemoryBuffer.h"
49 #include "llvm/Support/MemoryObject.h"
50 #include "llvm/Support/PrettyStackTrace.h"
51 #include "llvm/Support/Signals.h"
52 #include "llvm/Support/SourceMgr.h"
53 #include "llvm/Support/TargetRegistry.h"
54 #include "llvm/Support/TargetSelect.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Support/system_error.h"
61 using namespace object;
63 static cl::list<std::string>
64 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
67 Disassemble("disassemble",
68 cl::desc("Display assembler mnemonics for the machine instructions"));
70 Disassembled("d", cl::desc("Alias for --disassemble"),
71 cl::aliasopt(Disassemble));
74 Relocations("r", cl::desc("Display the relocation entries in the file"));
77 SectionContents("s", cl::desc("Display the content of each section"));
80 SymbolTable("t", cl::desc("Display the symbol table"));
83 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
85 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
88 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
89 "see -version for available targets"));
92 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
93 "see -version for available targets"));
96 SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
97 "for each section."));
99 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
100 cl::aliasopt(SectionHeaders));
102 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
103 cl::aliasopt(SectionHeaders));
105 static cl::list<std::string>
108 cl::desc("Target specific attributes"),
109 cl::value_desc("a1,+a2,-a3,..."));
112 NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, "
113 "do not print the instruction bytes."));
116 UnwindInfo("unwind-info", cl::desc("Display unwind information"));
119 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
120 cl::aliasopt(UnwindInfo));
123 PrivateHeaders("private-headers",
124 cl::desc("Display format specific file headers"));
127 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
128 cl::aliasopt(PrivateHeaders));
131 Symbolize("symbolize", cl::desc("When disassembling instructions, "
132 "try to symbolize operands."));
134 static StringRef ToolName;
136 bool llvm::error(error_code ec) {
137 if (!ec) return false;
139 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
144 static const Target *getTarget(const ObjectFile *Obj = NULL) {
145 // Figure out the target triple.
146 llvm::Triple TheTriple("unknown-unknown-unknown");
147 if (TripleName.empty()) {
149 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
150 // TheTriple defaults to ELF, and COFF doesn't have an environment:
151 // the best we can do here is indicate that it is mach-o.
153 TheTriple.setEnvironment(Triple::MachO);
156 TheTriple.setTriple(Triple::normalize(TripleName));
158 // Get the target specific parser.
160 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
163 errs() << ToolName << ": " << Error;
167 // Update the triple name and return the found target.
168 TripleName = TheTriple.getTriple();
172 void llvm::StringRefMemoryObject::anchor() { }
174 void llvm::DumpBytes(StringRef bytes) {
175 static const char hex_rep[] = "0123456789abcdef";
176 // FIXME: The real way to do this is to figure out the longest instruction
177 // and align to that size before printing. I'll fix this when I get
178 // around to outputting relocations.
179 // 15 is the longest x86 instruction
180 // 3 is for the hex rep of a byte + a space.
181 // 1 is for the null terminator.
182 enum { OutputSize = (15 * 3) + 1 };
183 char output[OutputSize];
185 assert(bytes.size() <= 15
186 && "DumpBytes only supports instructions of up to 15 bytes");
187 memset(output, ' ', sizeof(output));
189 for (StringRef::iterator i = bytes.begin(),
190 e = bytes.end(); i != e; ++i) {
191 output[index] = hex_rep[(*i & 0xF0) >> 4];
192 output[index + 1] = hex_rep[*i & 0xF];
196 output[sizeof(output) - 1] = 0;
200 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
201 uint64_t a_addr, b_addr;
202 if (error(a.getOffset(a_addr))) return false;
203 if (error(b.getOffset(b_addr))) return false;
204 return a_addr < b_addr;
207 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
208 const Target *TheTarget = getTarget(Obj);
209 // getTarget() will have already issued a diagnostic if necessary, so
210 // just bail here if it failed.
214 // Package up features to be passed to target/subtarget
215 std::string FeaturesStr;
217 SubtargetFeatures Features;
218 for (unsigned i = 0; i != MAttrs.size(); ++i)
219 Features.AddFeature(MAttrs[i]);
220 FeaturesStr = Features.getString();
223 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
225 errs() << "error: no register info for target " << TripleName << "\n";
229 // Set up disassembler.
230 OwningPtr<const MCAsmInfo> AsmInfo(
231 TheTarget->createMCAsmInfo(*MRI, TripleName));
233 errs() << "error: no assembly info for target " << TripleName << "\n";
237 OwningPtr<const MCSubtargetInfo> STI(
238 TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
240 errs() << "error: no subtarget info for target " << TripleName << "\n";
244 OwningPtr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
246 errs() << "error: no instruction info for target " << TripleName << "\n";
250 OwningPtr<MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI));
252 errs() << "error: no disassembler for target " << TripleName << "\n";
256 OwningPtr<const MCObjectFileInfo> MOFI;
257 OwningPtr<MCContext> Ctx;
260 MOFI.reset(new MCObjectFileInfo);
261 Ctx.reset(new MCContext(*AsmInfo.get(), *MRI.get(), MOFI.get()));
262 OwningPtr<MCRelocationInfo> RelInfo(
263 TheTarget->createMCRelocationInfo(TripleName, *Ctx.get()));
265 OwningPtr<MCSymbolizer> Symzer(
266 MCObjectSymbolizer::createObjectSymbolizer(*Ctx.get(), RelInfo, Obj));
268 DisAsm->setSymbolizer(Symzer);
272 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
273 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
274 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
276 errs() << "error: no instruction printer for target " << TripleName
282 for (section_iterator i = Obj->begin_sections(),
283 e = Obj->end_sections();
284 i != e; i.increment(ec)) {
285 if (error(ec)) break;
287 if (error(i->isText(text))) break;
290 uint64_t SectionAddr;
291 if (error(i->getAddress(SectionAddr))) break;
293 // Make a list of all the symbols in this section.
294 std::vector<std::pair<uint64_t, StringRef> > Symbols;
295 for (symbol_iterator si = Obj->begin_symbols(),
296 se = Obj->end_symbols();
297 si != se; si.increment(ec)) {
299 if (!error(i->containsSymbol(*si, contains)) && contains) {
301 if (error(si->getAddress(Address))) break;
302 if (Address == UnknownAddressOrSize) continue;
303 Address -= SectionAddr;
306 if (error(si->getName(Name))) break;
307 Symbols.push_back(std::make_pair(Address, Name));
311 // Sort the symbols by address, just in case they didn't come in that way.
312 array_pod_sort(Symbols.begin(), Symbols.end());
314 // Make a list of all the relocations for this section.
315 std::vector<RelocationRef> Rels;
317 for (relocation_iterator ri = i->begin_relocations(),
318 re = i->end_relocations();
319 ri != re; ri.increment(ec)) {
320 if (error(ec)) break;
325 // Sort relocations by address.
326 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
328 StringRef SegmentName = "";
329 if (const MachOObjectFile *MachO =
330 dyn_cast<const MachOObjectFile>(Obj)) {
331 DataRefImpl DR = i->getRawDataRefImpl();
332 SegmentName = MachO->getSectionFinalSegmentName(DR);
335 if (error(i->getName(name))) break;
336 outs() << "Disassembly of section ";
337 if (!SegmentName.empty())
338 outs() << SegmentName << ",";
339 outs() << name << ':';
341 // If the section has no symbols just insert a dummy one and disassemble
342 // the whole section.
344 Symbols.push_back(std::make_pair(0, name));
347 SmallString<40> Comments;
348 raw_svector_ostream CommentStream(Comments);
351 if (error(i->getContents(Bytes))) break;
352 StringRefMemoryObject memoryObject(Bytes, SectionAddr);
356 if (error(i->getSize(SectSize))) break;
358 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
359 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
360 // Disassemble symbol by symbol.
361 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
362 uint64_t Start = Symbols[si].first;
364 // The end is either the size of the section or the beginning of the next
368 // Make sure this symbol takes up space.
369 else if (Symbols[si + 1].first != Start)
370 End = Symbols[si + 1].first - 1;
372 // This symbol has the same address as the next symbol. Skip it.
375 outs() << '\n' << Symbols[si].second << ":\n";
378 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
380 raw_ostream &DebugOut = nulls();
383 for (Index = Start; Index < End; Index += Size) {
386 if (DisAsm->getInstruction(Inst, Size, memoryObject,
388 DebugOut, CommentStream)) {
389 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
390 if (!NoShowRawInsn) {
392 DumpBytes(StringRef(Bytes.data() + Index, Size));
394 IP->printInst(&Inst, outs(), "");
395 outs() << CommentStream.str();
399 errs() << ToolName << ": warning: invalid instruction encoding\n";
401 Size = 1; // skip illegible bytes
404 // Print relocation for instruction.
405 while (rel_cur != rel_end) {
408 SmallString<16> name;
411 // If this relocation is hidden, skip it.
412 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
413 if (hidden) goto skip_print_rel;
415 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
416 // Stop when rel_cur's address is past the current instruction.
417 if (addr >= Index + Size) break;
418 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
419 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
421 outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
422 << "\t" << val << "\n";
432 static void PrintRelocations(const ObjectFile *o) {
434 for (section_iterator si = o->begin_sections(), se = o->end_sections();
435 si != se; si.increment(ec)){
436 if (error(ec)) return;
437 if (si->begin_relocations() == si->end_relocations())
440 if (error(si->getName(secname))) continue;
441 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
442 for (relocation_iterator ri = si->begin_relocations(),
443 re = si->end_relocations();
444 ri != re; ri.increment(ec)) {
445 if (error(ec)) return;
449 SmallString<32> relocname;
450 SmallString<32> valuestr;
451 if (error(ri->getHidden(hidden))) continue;
452 if (hidden) continue;
453 if (error(ri->getTypeName(relocname))) continue;
454 if (error(ri->getOffset(address))) continue;
455 if (error(ri->getValueString(valuestr))) continue;
456 outs() << address << " " << relocname << " " << valuestr << "\n";
462 static void PrintSectionHeaders(const ObjectFile *o) {
463 outs() << "Sections:\n"
464 "Idx Name Size Address Type\n";
467 for (section_iterator si = o->begin_sections(), se = o->end_sections();
468 si != se; si.increment(ec)) {
469 if (error(ec)) return;
471 if (error(si->getName(Name))) return;
473 if (error(si->getAddress(Address))) return;
475 if (error(si->getSize(Size))) return;
476 bool Text, Data, BSS;
477 if (error(si->isText(Text))) return;
478 if (error(si->isData(Data))) return;
479 if (error(si->isBSS(BSS))) return;
480 std::string Type = (std::string(Text ? "TEXT " : "") +
481 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
482 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
483 i, Name.str().c_str(), Size, Address, Type.c_str());
488 static void PrintSectionContents(const ObjectFile *o) {
490 for (section_iterator si = o->begin_sections(),
491 se = o->end_sections();
492 si != se; si.increment(ec)) {
493 if (error(ec)) return;
498 if (error(si->getName(Name))) continue;
499 if (error(si->getContents(Contents))) continue;
500 if (error(si->getAddress(BaseAddr))) continue;
501 if (error(si->isBSS(BSS))) continue;
503 outs() << "Contents of section " << Name << ":\n";
505 outs() << format("<skipping contents of bss section at [%04" PRIx64
506 ", %04" PRIx64 ")>\n", BaseAddr,
507 BaseAddr + Contents.size());
511 // Dump out the content as hex and printable ascii characters.
512 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
513 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
515 for (std::size_t i = 0; i < 16; ++i) {
516 if (i != 0 && i % 4 == 0)
519 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
520 << hexdigit(Contents[addr + i] & 0xF, true);
526 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
527 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
528 outs() << Contents[addr + i];
537 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
538 const coff_file_header *header;
539 if (error(coff->getHeader(header))) return;
541 const coff_symbol *symbol = 0;
542 for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
544 // Figure out which type of aux this is.
545 if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
546 && symbol->Value == 0) { // Section definition.
547 const coff_aux_section_definition *asd;
548 if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
551 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
552 , unsigned(asd->Length)
553 , unsigned(asd->NumberOfRelocations)
554 , unsigned(asd->NumberOfLinenumbers)
555 , unsigned(asd->CheckSum))
556 << format("assoc %d comdat %d\n"
557 , unsigned(asd->Number)
558 , unsigned(asd->Selection));
560 outs() << "AUX Unknown\n";
563 if (error(coff->getSymbol(i, symbol))) return;
564 if (error(coff->getSymbolName(symbol, name))) return;
565 outs() << "[" << format("%2d", i) << "]"
566 << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
567 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
568 << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
569 << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
570 << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
571 << "0x" << format("%08x", unsigned(symbol->Value)) << " "
573 aux_count = symbol->NumberOfAuxSymbols;
578 static void PrintSymbolTable(const ObjectFile *o) {
579 outs() << "SYMBOL TABLE:\n";
581 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
582 PrintCOFFSymbolTable(coff);
585 for (symbol_iterator si = o->begin_symbols(),
586 se = o->end_symbols(); si != se; si.increment(ec)) {
587 if (error(ec)) return;
590 SymbolRef::Type Type;
593 section_iterator Section = o->end_sections();
594 if (error(si->getName(Name))) continue;
595 if (error(si->getAddress(Address))) continue;
596 if (error(si->getFlags(Flags))) continue;
597 if (error(si->getType(Type))) continue;
598 if (error(si->getSize(Size))) continue;
599 if (error(si->getSection(Section))) continue;
601 bool Global = Flags & SymbolRef::SF_Global;
602 bool Weak = Flags & SymbolRef::SF_Weak;
603 bool Absolute = Flags & SymbolRef::SF_Absolute;
605 if (Address == UnknownAddressOrSize)
607 if (Size == UnknownAddressOrSize)
610 if (Type != SymbolRef::ST_Unknown)
611 GlobLoc = Global ? 'g' : 'l';
612 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
615 if (Type == SymbolRef::ST_File)
617 else if (Type == SymbolRef::ST_Function)
620 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
623 outs() << format(Fmt, Address) << " "
624 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
625 << (Weak ? 'w' : ' ') // Weak?
626 << ' ' // Constructor. Not supported yet.
627 << ' ' // Warning. Not supported yet.
628 << ' ' // Indirect reference to another symbol.
629 << Debug // Debugging (d) or dynamic (D) symbol.
630 << FileFunc // Name of function (F), file (f) or object (O).
634 else if (Section == o->end_sections())
637 if (const MachOObjectFile *MachO =
638 dyn_cast<const MachOObjectFile>(o)) {
639 DataRefImpl DR = Section->getRawDataRefImpl();
640 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
641 outs() << SegmentName << ",";
643 StringRef SectionName;
644 if (error(Section->getName(SectionName)))
646 outs() << SectionName;
649 << format("%08" PRIx64 " ", Size)
656 static void PrintUnwindInfo(const ObjectFile *o) {
657 outs() << "Unwind info:\n\n";
659 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
660 printCOFFUnwindInfo(coff);
662 // TODO: Extract DWARF dump tool to objdump.
663 errs() << "This operation is only currently supported "
664 "for COFF object files.\n";
669 static void DumpObject(const ObjectFile *o) {
671 outs() << o->getFileName()
672 << ":\tfile format " << o->getFileFormatName() << "\n\n";
675 DisassembleObject(o, Relocations);
676 if (Relocations && !Disassemble)
679 PrintSectionHeaders(o);
681 PrintSectionContents(o);
686 if (PrivateHeaders && o->isELF())
687 printELFFileHeader(o);
690 /// @brief Dump each object file in \a a;
691 static void DumpArchive(const Archive *a) {
692 for (Archive::child_iterator i = a->begin_children(),
693 e = a->end_children(); i != e; ++i) {
694 OwningPtr<Binary> child;
695 if (error_code ec = i->getAsBinary(child)) {
696 // Ignore non-object files.
697 if (ec != object_error::invalid_file_type)
698 errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
702 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
705 errs() << ToolName << ": '" << a->getFileName() << "': "
706 << "Unrecognized file type.\n";
710 /// @brief Open file and figure out how to dump it.
711 static void DumpInput(StringRef file) {
712 // If file isn't stdin, check that it exists.
713 if (file != "-" && !sys::fs::exists(file)) {
714 errs() << ToolName << ": '" << file << "': " << "No such file\n";
718 if (MachOOpt && Disassemble) {
719 DisassembleInputMachO(file);
723 // Attempt to open the binary.
724 OwningPtr<Binary> binary;
725 if (error_code ec = createBinary(file, binary)) {
726 errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
730 if (Archive *a = dyn_cast<Archive>(binary.get()))
732 else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
735 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
738 int main(int argc, char **argv) {
739 // Print a stack trace if we signal out.
740 sys::PrintStackTraceOnErrorSignal();
741 PrettyStackTraceProgram X(argc, argv);
742 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
744 // Initialize targets and assembly printers/parsers.
745 llvm::InitializeAllTargetInfos();
746 llvm::InitializeAllTargetMCs();
747 llvm::InitializeAllAsmParsers();
748 llvm::InitializeAllDisassemblers();
750 // Register the target printer for --version.
751 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
753 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
754 TripleName = Triple::normalize(TripleName);
758 // Defaults to a.out if no filenames specified.
759 if (InputFilenames.size() == 0)
760 InputFilenames.push_back("a.out");
768 && !PrivateHeaders) {
769 cl::PrintHelpMessage();
773 std::for_each(InputFilenames.begin(), InputFilenames.end(),