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 "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCDisassembler.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCInstPrinter.h"
28 #include "llvm/MC/MCInstrAnalysis.h"
29 #include "llvm/MC/MCInstrInfo.h"
30 #include "llvm/MC/MCObjectFileInfo.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/MC/MCRelocationInfo.h"
33 #include "llvm/MC/MCSubtargetInfo.h"
34 #include "llvm/Object/Archive.h"
35 #include "llvm/Object/COFF.h"
36 #include "llvm/Object/MachO.h"
37 #include "llvm/Object/ObjectFile.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/FileSystem.h"
42 #include "llvm/Support/Format.h"
43 #include "llvm/Support/GraphWriter.h"
44 #include "llvm/Support/Host.h"
45 #include "llvm/Support/ManagedStatic.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/PrettyStackTrace.h"
48 #include "llvm/Support/Signals.h"
49 #include "llvm/Support/SourceMgr.h"
50 #include "llvm/Support/TargetRegistry.h"
51 #include "llvm/Support/TargetSelect.h"
52 #include "llvm/Support/raw_ostream.h"
56 #include <system_error>
59 using namespace object;
61 static cl::list<std::string>
62 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
65 llvm::Disassemble("disassemble",
66 cl::desc("Display assembler mnemonics for the machine instructions"));
68 Disassembled("d", cl::desc("Alias for --disassemble"),
69 cl::aliasopt(Disassemble));
72 llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
75 llvm::SectionContents("s", cl::desc("Display the content of each section"));
78 llvm::SymbolTable("t", cl::desc("Display the symbol table"));
81 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
84 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
87 llvm::Bind("bind", cl::desc("Display mach-o binding info"));
90 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
93 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
96 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
98 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
101 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
102 "see -version for available targets"));
106 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
107 cl::value_desc("cpu-name"),
111 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
112 "see -version for available targets"));
115 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
116 "headers for each section."));
118 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
119 cl::aliasopt(SectionHeaders));
121 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
122 cl::aliasopt(SectionHeaders));
124 cl::list<std::string>
125 llvm::MAttrs("mattr",
127 cl::desc("Target specific attributes"),
128 cl::value_desc("a1,+a2,-a3,..."));
131 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
132 "instructions, do not print "
133 "the instruction bytes."));
136 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
139 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
140 cl::aliasopt(UnwindInfo));
143 llvm::PrivateHeaders("private-headers",
144 cl::desc("Display format specific file headers"));
147 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
148 cl::aliasopt(PrivateHeaders));
150 static StringRef ToolName;
151 static int ReturnValue = EXIT_SUCCESS;
153 bool llvm::error(std::error_code EC) {
157 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
159 ReturnValue = EXIT_FAILURE;
163 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
164 // Figure out the target triple.
165 llvm::Triple TheTriple("unknown-unknown-unknown");
166 if (TripleName.empty()) {
168 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
169 // TheTriple defaults to ELF, and COFF doesn't have an environment:
170 // the best we can do here is indicate that it is mach-o.
172 TheTriple.setObjectFormat(Triple::MachO);
175 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
176 if (COFFObj->getArch() == Triple::thumb)
177 TheTriple.setTriple("thumbv7-windows");
181 TheTriple.setTriple(Triple::normalize(TripleName));
183 // Get the target specific parser.
185 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
188 errs() << ToolName << ": " << Error;
192 // Update the triple name and return the found target.
193 TripleName = TheTriple.getTriple();
197 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
198 uint64_t a_addr, b_addr;
199 if (error(a.getOffset(a_addr))) return false;
200 if (error(b.getOffset(b_addr))) return false;
201 return a_addr < b_addr;
205 class PrettyPrinter {
207 virtual ~PrettyPrinter(){}
208 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
209 ArrayRef<uint8_t> Bytes, uint64_t Address,
210 raw_ostream &OS, StringRef Annot,
211 MCSubtargetInfo const &STI) {
212 outs() << format("%8" PRIx64 ":", Address);
213 if (!NoShowRawInsn) {
215 dumpBytes(Bytes, outs());
217 IP.printInst(MI, outs(), "", STI);
220 PrettyPrinter PrettyPrinterInst;
221 class HexagonPrettyPrinter : public PrettyPrinter {
223 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
226 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
227 OS << format("%8" PRIx64 ":", Address);
228 if (!NoShowRawInsn) {
230 dumpBytes(Bytes.slice(0, 4), OS);
231 OS << format("%08" PRIx32, opcode);
234 void printInst(MCInstPrinter &IP, const MCInst *MI,
235 ArrayRef<uint8_t> Bytes, uint64_t Address,
236 raw_ostream &OS, StringRef Annot,
237 MCSubtargetInfo const &STI) override {
240 raw_string_ostream TempStream(Buffer);
241 IP.printInst(MI, TempStream, "", STI);
243 StringRef Contents(Buffer);
244 // Split off bundle attributes
245 auto PacketBundle = Contents.rsplit('\n');
246 // Split off first instruction from the rest
247 auto HeadTail = PacketBundle.first.split('\n');
248 auto Preamble = " { ";
250 while(!HeadTail.first.empty()) {
253 printLead(Bytes, Address, OS);
257 auto Duplex = HeadTail.first.split('\v');
258 if(!Duplex.second.empty()){
261 Inst = Duplex.second;
264 Inst = HeadTail.first;
266 Bytes = Bytes.slice(4);
268 HeadTail = HeadTail.second.split('\n');
270 OS << " } " << PacketBundle.second;
273 HexagonPrettyPrinter HexagonPrettyPrinterInst;
274 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
275 switch(Triple.getArch()) {
277 return PrettyPrinterInst;
278 case Triple::hexagon:
279 return HexagonPrettyPrinterInst;
284 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
285 const Target *TheTarget = getTarget(Obj);
286 // getTarget() will have already issued a diagnostic if necessary, so
287 // just bail here if it failed.
291 // Package up features to be passed to target/subtarget
292 std::string FeaturesStr;
294 SubtargetFeatures Features;
295 for (unsigned i = 0; i != MAttrs.size(); ++i)
296 Features.AddFeature(MAttrs[i]);
297 FeaturesStr = Features.getString();
300 std::unique_ptr<const MCRegisterInfo> MRI(
301 TheTarget->createMCRegInfo(TripleName));
303 errs() << "error: no register info for target " << TripleName << "\n";
307 // Set up disassembler.
308 std::unique_ptr<const MCAsmInfo> AsmInfo(
309 TheTarget->createMCAsmInfo(*MRI, TripleName));
311 errs() << "error: no assembly info for target " << TripleName << "\n";
315 std::unique_ptr<const MCSubtargetInfo> STI(
316 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
318 errs() << "error: no subtarget info for target " << TripleName << "\n";
322 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
324 errs() << "error: no instruction info for target " << TripleName << "\n";
328 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
329 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
331 std::unique_ptr<MCDisassembler> DisAsm(
332 TheTarget->createMCDisassembler(*STI, Ctx));
335 errs() << "error: no disassembler for target " << TripleName << "\n";
339 std::unique_ptr<const MCInstrAnalysis> MIA(
340 TheTarget->createMCInstrAnalysis(MII.get()));
342 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
343 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
344 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
346 errs() << "error: no instruction printer for target " << TripleName
350 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
352 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
353 "\t\t\t%08" PRIx64 ": ";
355 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
356 // in RelocSecs contain the relocations for section S.
358 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
359 for (const SectionRef &Section : Obj->sections()) {
360 section_iterator Sec2 = Section.getRelocatedSection();
361 if (Sec2 != Obj->section_end())
362 SectionRelocMap[*Sec2].push_back(Section);
365 for (const SectionRef &Section : Obj->sections()) {
366 if (!Section.isText() || Section.isVirtual())
369 uint64_t SectionAddr = Section.getAddress();
370 uint64_t SectSize = Section.getSize();
374 // Make a list of all the symbols in this section.
375 std::vector<std::pair<uint64_t, StringRef>> Symbols;
376 for (const SymbolRef &Symbol : Obj->symbols()) {
377 if (Section.containsSymbol(Symbol)) {
379 if (error(Symbol.getAddress(Address)))
381 if (Address == UnknownAddressOrSize)
383 Address -= SectionAddr;
384 if (Address >= SectSize)
388 if (error(Symbol.getName(Name)))
390 Symbols.push_back(std::make_pair(Address, Name));
394 // Sort the symbols by address, just in case they didn't come in that way.
395 array_pod_sort(Symbols.begin(), Symbols.end());
397 // Make a list of all the relocations for this section.
398 std::vector<RelocationRef> Rels;
400 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
401 for (const RelocationRef &Reloc : RelocSec.relocations()) {
402 Rels.push_back(Reloc);
407 // Sort relocations by address.
408 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
410 StringRef SegmentName = "";
411 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
412 DataRefImpl DR = Section.getRawDataRefImpl();
413 SegmentName = MachO->getSectionFinalSegmentName(DR);
416 if (error(Section.getName(name)))
418 outs() << "Disassembly of section ";
419 if (!SegmentName.empty())
420 outs() << SegmentName << ",";
421 outs() << name << ':';
423 // If the section has no symbols just insert a dummy one and disassemble
424 // the whole section.
426 Symbols.push_back(std::make_pair(0, name));
429 SmallString<40> Comments;
430 raw_svector_ostream CommentStream(Comments);
433 if (error(Section.getContents(BytesStr)))
435 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
441 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
442 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
443 // Disassemble symbol by symbol.
444 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
446 uint64_t Start = Symbols[si].first;
447 // The end is either the section end or the beginning of the next symbol.
448 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
449 // If this symbol has the same address as the next symbol, then skip it.
453 outs() << '\n' << Symbols[si].second << ":\n";
456 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
458 raw_ostream &DebugOut = nulls();
461 for (Index = Start; Index < End; Index += Size) {
464 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
465 SectionAddr + Index, DebugOut,
467 PIP.printInst(*IP, &Inst,
468 Bytes.slice(Index, Size),
469 SectionAddr + Index, outs(), "", *STI);
470 outs() << CommentStream.str();
474 errs() << ToolName << ": warning: invalid instruction encoding\n";
476 Size = 1; // skip illegible bytes
479 // Print relocation for instruction.
480 while (rel_cur != rel_end) {
483 SmallString<16> name;
486 // If this relocation is hidden, skip it.
487 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
488 if (hidden) goto skip_print_rel;
490 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
491 // Stop when rel_cur's address is past the current instruction.
492 if (addr >= Index + Size) break;
493 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
494 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
496 outs() << format(Fmt.data(), SectionAddr + addr) << name
497 << "\t" << val << "\n";
507 void llvm::PrintRelocations(const ObjectFile *Obj) {
508 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
510 // Regular objdump doesn't print relocations in non-relocatable object
512 if (!Obj->isRelocatableObject())
515 for (const SectionRef &Section : Obj->sections()) {
516 if (Section.relocation_begin() == Section.relocation_end())
519 if (error(Section.getName(secname)))
521 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
522 for (const RelocationRef &Reloc : Section.relocations()) {
525 SmallString<32> relocname;
526 SmallString<32> valuestr;
527 if (error(Reloc.getHidden(hidden)))
531 if (error(Reloc.getTypeName(relocname)))
533 if (error(Reloc.getOffset(address)))
535 if (error(Reloc.getValueString(valuestr)))
537 outs() << format(Fmt.data(), address) << " " << relocname << " "
544 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
545 outs() << "Sections:\n"
546 "Idx Name Size Address Type\n";
548 for (const SectionRef &Section : Obj->sections()) {
550 if (error(Section.getName(Name)))
552 uint64_t Address = Section.getAddress();
553 uint64_t Size = Section.getSize();
554 bool Text = Section.isText();
555 bool Data = Section.isData();
556 bool BSS = Section.isBSS();
557 std::string Type = (std::string(Text ? "TEXT " : "") +
558 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
559 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
560 Name.str().c_str(), Size, Address, Type.c_str());
565 void llvm::PrintSectionContents(const ObjectFile *Obj) {
567 for (const SectionRef &Section : Obj->sections()) {
570 if (error(Section.getName(Name)))
572 uint64_t BaseAddr = Section.getAddress();
573 uint64_t Size = Section.getSize();
577 outs() << "Contents of section " << Name << ":\n";
578 if (Section.isBSS()) {
579 outs() << format("<skipping contents of bss section at [%04" PRIx64
580 ", %04" PRIx64 ")>\n",
581 BaseAddr, BaseAddr + Size);
585 if (error(Section.getContents(Contents)))
588 // Dump out the content as hex and printable ascii characters.
589 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
590 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
592 for (std::size_t i = 0; i < 16; ++i) {
593 if (i != 0 && i % 4 == 0)
596 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
597 << hexdigit(Contents[addr + i] & 0xF, true);
603 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
604 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
605 outs() << Contents[addr + i];
614 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
615 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
616 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
618 if (error(Symbol.getError()))
621 if (error(coff->getSymbolName(*Symbol, Name)))
624 outs() << "[" << format("%2d", SI) << "]"
625 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
626 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
627 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
628 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
629 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
630 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
633 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
634 if (Symbol->isSectionDefinition()) {
635 const coff_aux_section_definition *asd;
636 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
639 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
642 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
643 , unsigned(asd->Length)
644 , unsigned(asd->NumberOfRelocations)
645 , unsigned(asd->NumberOfLinenumbers)
646 , unsigned(asd->CheckSum))
647 << format("assoc %d comdat %d\n"
648 , unsigned(AuxNumber)
649 , unsigned(asd->Selection));
650 } else if (Symbol->isFileRecord()) {
651 const char *FileName;
652 if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
655 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
656 coff->getSymbolTableEntrySize());
657 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
659 SI = SI + Symbol->getNumberOfAuxSymbols();
662 outs() << "AUX Unknown\n";
668 void llvm::PrintSymbolTable(const ObjectFile *o) {
669 outs() << "SYMBOL TABLE:\n";
671 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
672 PrintCOFFSymbolTable(coff);
675 for (const SymbolRef &Symbol : o->symbols()) {
678 SymbolRef::Type Type;
680 uint32_t Flags = Symbol.getFlags();
681 section_iterator Section = o->section_end();
682 if (error(Symbol.getName(Name)))
684 if (error(Symbol.getAddress(Address)))
686 if (error(Symbol.getType(Type)))
688 if (error(Symbol.getSize(Size)))
690 if (error(Symbol.getSection(Section)))
693 bool Global = Flags & SymbolRef::SF_Global;
694 bool Weak = Flags & SymbolRef::SF_Weak;
695 bool Absolute = Flags & SymbolRef::SF_Absolute;
696 bool Common = Flags & SymbolRef::SF_Common;
697 bool Hidden = Flags & SymbolRef::SF_Hidden;
700 uint32_t Alignment = Symbol.getAlignment();
704 if (Address == UnknownAddressOrSize)
706 if (Size == UnknownAddressOrSize)
709 if (Type != SymbolRef::ST_Unknown)
710 GlobLoc = Global ? 'g' : 'l';
711 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
714 if (Type == SymbolRef::ST_File)
716 else if (Type == SymbolRef::ST_Function)
719 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
722 outs() << format(Fmt, Address) << " "
723 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
724 << (Weak ? 'w' : ' ') // Weak?
725 << ' ' // Constructor. Not supported yet.
726 << ' ' // Warning. Not supported yet.
727 << ' ' // Indirect reference to another symbol.
728 << Debug // Debugging (d) or dynamic (D) symbol.
729 << FileFunc // Name of function (F), file (f) or object (O).
735 } else if (Section == o->section_end()) {
738 if (const MachOObjectFile *MachO =
739 dyn_cast<const MachOObjectFile>(o)) {
740 DataRefImpl DR = Section->getRawDataRefImpl();
741 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
742 outs() << SegmentName << ",";
744 StringRef SectionName;
745 if (error(Section->getName(SectionName)))
747 outs() << SectionName;
750 << format("%08" PRIx64 " ", Size);
752 outs() << ".hidden ";
759 static void PrintUnwindInfo(const ObjectFile *o) {
760 outs() << "Unwind info:\n\n";
762 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
763 printCOFFUnwindInfo(coff);
764 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
765 printMachOUnwindInfo(MachO);
767 // TODO: Extract DWARF dump tool to objdump.
768 errs() << "This operation is only currently supported "
769 "for COFF and MachO object files.\n";
774 void llvm::printExportsTrie(const ObjectFile *o) {
775 outs() << "Exports trie:\n";
776 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
777 printMachOExportsTrie(MachO);
779 errs() << "This operation is only currently supported "
780 "for Mach-O executable files.\n";
785 void llvm::printRebaseTable(const ObjectFile *o) {
786 outs() << "Rebase table:\n";
787 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
788 printMachORebaseTable(MachO);
790 errs() << "This operation is only currently supported "
791 "for Mach-O executable files.\n";
796 void llvm::printBindTable(const ObjectFile *o) {
797 outs() << "Bind table:\n";
798 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
799 printMachOBindTable(MachO);
801 errs() << "This operation is only currently supported "
802 "for Mach-O executable files.\n";
807 void llvm::printLazyBindTable(const ObjectFile *o) {
808 outs() << "Lazy bind table:\n";
809 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
810 printMachOLazyBindTable(MachO);
812 errs() << "This operation is only currently supported "
813 "for Mach-O executable files.\n";
818 void llvm::printWeakBindTable(const ObjectFile *o) {
819 outs() << "Weak bind table:\n";
820 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
821 printMachOWeakBindTable(MachO);
823 errs() << "This operation is only currently supported "
824 "for Mach-O executable files.\n";
829 static void printPrivateFileHeader(const ObjectFile *o) {
831 printELFFileHeader(o);
832 } else if (o->isCOFF()) {
833 printCOFFFileHeader(o);
834 } else if (o->isMachO()) {
835 printMachOFileHeader(o);
839 static void DumpObject(const ObjectFile *o) {
841 outs() << o->getFileName()
842 << ":\tfile format " << o->getFileFormatName() << "\n\n";
845 DisassembleObject(o, Relocations);
846 if (Relocations && !Disassemble)
849 PrintSectionHeaders(o);
851 PrintSectionContents(o);
857 printPrivateFileHeader(o);
865 printLazyBindTable(o);
867 printWeakBindTable(o);
870 /// @brief Dump each object file in \a a;
871 static void DumpArchive(const Archive *a) {
872 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
874 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
875 if (std::error_code EC = ChildOrErr.getError()) {
876 // Ignore non-object files.
877 if (EC != object_error::invalid_file_type)
878 errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
882 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
885 errs() << ToolName << ": '" << a->getFileName() << "': "
886 << "Unrecognized file type.\n";
890 /// @brief Open file and figure out how to dump it.
891 static void DumpInput(StringRef file) {
892 // If file isn't stdin, check that it exists.
893 if (file != "-" && !sys::fs::exists(file)) {
894 errs() << ToolName << ": '" << file << "': " << "No such file\n";
898 // If we are using the Mach-O specific object file parser, then let it parse
899 // the file and process the command line options. So the -arch flags can
900 // be used to select specific slices, etc.
902 ParseInputMachO(file);
906 // Attempt to open the binary.
907 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
908 if (std::error_code EC = BinaryOrErr.getError()) {
909 errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
912 Binary &Binary = *BinaryOrErr.get().getBinary();
914 if (Archive *a = dyn_cast<Archive>(&Binary))
916 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
919 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
922 int main(int argc, char **argv) {
923 // Print a stack trace if we signal out.
924 sys::PrintStackTraceOnErrorSignal();
925 PrettyStackTraceProgram X(argc, argv);
926 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
928 // Initialize targets and assembly printers/parsers.
929 llvm::InitializeAllTargetInfos();
930 llvm::InitializeAllTargetMCs();
931 llvm::InitializeAllAsmParsers();
932 llvm::InitializeAllDisassemblers();
934 // Register the target printer for --version.
935 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
937 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
938 TripleName = Triple::normalize(TripleName);
942 // Defaults to a.out if no filenames specified.
943 if (InputFilenames.size() == 0)
944 InputFilenames.push_back("a.out");
958 && !(UniversalHeaders && MachOOpt)
959 && !(ArchiveHeaders && MachOOpt)
960 && !(IndirectSymbols && MachOOpt)
961 && !(DataInCode && MachOOpt)
962 && !(LinkOptHints && MachOOpt)
963 && !(InfoPlist && MachOOpt)
964 && !(DylibsUsed && MachOOpt)
965 && !(DylibId && MachOOpt)
966 && !(ObjcMetaData && MachOOpt)
967 && !(DumpSections.size() != 0 && MachOOpt)) {
968 cl::PrintHelpMessage();
972 std::for_each(InputFilenames.begin(), InputFilenames.end(),