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/MemoryObject.h"
48 #include "llvm/Support/PrettyStackTrace.h"
49 #include "llvm/Support/Signals.h"
50 #include "llvm/Support/SourceMgr.h"
51 #include "llvm/Support/TargetRegistry.h"
52 #include "llvm/Support/TargetSelect.h"
53 #include "llvm/Support/raw_ostream.h"
57 #include <system_error>
60 using namespace object;
62 static cl::list<std::string>
63 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
66 Disassemble("disassemble",
67 cl::desc("Display assembler mnemonics for the machine instructions"));
69 Disassembled("d", cl::desc("Alias for --disassemble"),
70 cl::aliasopt(Disassemble));
73 Relocations("r", cl::desc("Display the relocation entries in the file"));
76 SectionContents("s", cl::desc("Display the content of each section"));
79 SymbolTable("t", cl::desc("Display the symbol table"));
82 ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
85 Rebase("rebase", cl::desc("Display mach-o rebasing info"));
88 Bind("bind", cl::desc("Display mach-o binding info"));
91 LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
94 WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
97 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
99 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
102 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
103 "see -version for available targets"));
107 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
108 cl::value_desc("cpu-name"),
112 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
113 "see -version for available targets"));
116 SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
117 "for each section."));
119 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
120 cl::aliasopt(SectionHeaders));
122 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
123 cl::aliasopt(SectionHeaders));
125 cl::list<std::string>
126 llvm::MAttrs("mattr",
128 cl::desc("Target specific attributes"),
129 cl::value_desc("a1,+a2,-a3,..."));
132 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
133 "instructions, do not print "
134 "the instruction bytes."));
137 UnwindInfo("unwind-info", cl::desc("Display unwind information"));
140 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
141 cl::aliasopt(UnwindInfo));
144 PrivateHeaders("private-headers",
145 cl::desc("Display format specific file headers"));
148 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
149 cl::aliasopt(PrivateHeaders));
151 static StringRef ToolName;
153 bool llvm::error(std::error_code EC) {
157 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
162 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
163 // Figure out the target triple.
164 llvm::Triple TheTriple("unknown-unknown-unknown");
165 if (TripleName.empty()) {
167 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
168 // TheTriple defaults to ELF, and COFF doesn't have an environment:
169 // the best we can do here is indicate that it is mach-o.
171 TheTriple.setObjectFormat(Triple::MachO);
174 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
175 if (COFFObj->getArch() == Triple::thumb)
176 TheTriple.setTriple("thumbv7-windows");
180 TheTriple.setTriple(Triple::normalize(TripleName));
182 // Get the target specific parser.
184 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
187 errs() << ToolName << ": " << Error;
191 // Update the triple name and return the found target.
192 TripleName = TheTriple.getTriple();
196 void llvm::DumpBytes(StringRef bytes) {
197 static const char hex_rep[] = "0123456789abcdef";
198 // FIXME: The real way to do this is to figure out the longest instruction
199 // and align to that size before printing. I'll fix this when I get
200 // around to outputting relocations.
201 // 15 is the longest x86 instruction
202 // 3 is for the hex rep of a byte + a space.
203 // 1 is for the null terminator.
204 enum { OutputSize = (15 * 3) + 1 };
205 char output[OutputSize];
207 assert(bytes.size() <= 15
208 && "DumpBytes only supports instructions of up to 15 bytes");
209 memset(output, ' ', sizeof(output));
211 for (StringRef::iterator i = bytes.begin(),
212 e = bytes.end(); i != e; ++i) {
213 output[index] = hex_rep[(*i & 0xF0) >> 4];
214 output[index + 1] = hex_rep[*i & 0xF];
218 output[sizeof(output) - 1] = 0;
222 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
223 uint64_t a_addr, b_addr;
224 if (error(a.getOffset(a_addr))) return false;
225 if (error(b.getOffset(b_addr))) return false;
226 return a_addr < b_addr;
229 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
230 const Target *TheTarget = getTarget(Obj);
231 // getTarget() will have already issued a diagnostic if necessary, so
232 // just bail here if it failed.
236 // Package up features to be passed to target/subtarget
237 std::string FeaturesStr;
239 SubtargetFeatures Features;
240 for (unsigned i = 0; i != MAttrs.size(); ++i)
241 Features.AddFeature(MAttrs[i]);
242 FeaturesStr = Features.getString();
245 std::unique_ptr<const MCRegisterInfo> MRI(
246 TheTarget->createMCRegInfo(TripleName));
248 errs() << "error: no register info for target " << TripleName << "\n";
252 // Set up disassembler.
253 std::unique_ptr<const MCAsmInfo> AsmInfo(
254 TheTarget->createMCAsmInfo(*MRI, TripleName));
256 errs() << "error: no assembly info for target " << TripleName << "\n";
260 std::unique_ptr<const MCSubtargetInfo> STI(
261 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
263 errs() << "error: no subtarget info for target " << TripleName << "\n";
267 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
269 errs() << "error: no instruction info for target " << TripleName << "\n";
273 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
274 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
276 std::unique_ptr<MCDisassembler> DisAsm(
277 TheTarget->createMCDisassembler(*STI, Ctx));
280 errs() << "error: no disassembler for target " << TripleName << "\n";
284 std::unique_ptr<const MCInstrAnalysis> MIA(
285 TheTarget->createMCInstrAnalysis(MII.get()));
287 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
288 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
289 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
291 errs() << "error: no instruction printer for target " << TripleName
296 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
297 "\t\t\t%08" PRIx64 ": ";
299 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
300 // in RelocSecs contain the relocations for section S.
302 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
303 for (const SectionRef &Section : Obj->sections()) {
304 section_iterator Sec2 = Section.getRelocatedSection();
305 if (Sec2 != Obj->section_end())
306 SectionRelocMap[*Sec2].push_back(Section);
309 for (const SectionRef &Section : Obj->sections()) {
311 if (error(Section.isText(Text)))
316 uint64_t SectionAddr;
317 if (error(Section.getAddress(SectionAddr)))
321 if (error(Section.getSize(SectSize)))
324 // Make a list of all the symbols in this section.
325 std::vector<std::pair<uint64_t, StringRef>> Symbols;
326 for (const SymbolRef &Symbol : Obj->symbols()) {
328 if (!error(Section.containsSymbol(Symbol, contains)) && contains) {
330 if (error(Symbol.getAddress(Address)))
332 if (Address == UnknownAddressOrSize)
334 Address -= SectionAddr;
335 if (Address >= SectSize)
339 if (error(Symbol.getName(Name)))
341 Symbols.push_back(std::make_pair(Address, Name));
345 // Sort the symbols by address, just in case they didn't come in that way.
346 array_pod_sort(Symbols.begin(), Symbols.end());
348 // Make a list of all the relocations for this section.
349 std::vector<RelocationRef> Rels;
351 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
352 for (const RelocationRef &Reloc : RelocSec.relocations()) {
353 Rels.push_back(Reloc);
358 // Sort relocations by address.
359 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
361 StringRef SegmentName = "";
362 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
363 DataRefImpl DR = Section.getRawDataRefImpl();
364 SegmentName = MachO->getSectionFinalSegmentName(DR);
367 if (error(Section.getName(name)))
369 outs() << "Disassembly of section ";
370 if (!SegmentName.empty())
371 outs() << SegmentName << ",";
372 outs() << name << ':';
374 // If the section has no symbols just insert a dummy one and disassemble
375 // the whole section.
377 Symbols.push_back(std::make_pair(0, name));
380 SmallString<40> Comments;
381 raw_svector_ostream CommentStream(Comments);
384 if (error(Section.getContents(Bytes)))
386 StringRefMemoryObject memoryObject(Bytes, SectionAddr);
390 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
391 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
392 // Disassemble symbol by symbol.
393 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
395 uint64_t Start = Symbols[si].first;
396 // The end is either the section end or the beginning of the next symbol.
397 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
398 // If this symbol has the same address as the next symbol, then skip it.
402 outs() << '\n' << Symbols[si].second << ":\n";
405 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
407 raw_ostream &DebugOut = nulls();
410 for (Index = Start; Index < End; Index += Size) {
413 if (DisAsm->getInstruction(Inst, Size, memoryObject,
415 DebugOut, CommentStream)) {
416 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
417 if (!NoShowRawInsn) {
419 DumpBytes(StringRef(Bytes.data() + Index, Size));
421 IP->printInst(&Inst, outs(), "");
422 outs() << CommentStream.str();
426 errs() << ToolName << ": warning: invalid instruction encoding\n";
428 Size = 1; // skip illegible bytes
431 // Print relocation for instruction.
432 while (rel_cur != rel_end) {
435 SmallString<16> name;
438 // If this relocation is hidden, skip it.
439 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
440 if (hidden) goto skip_print_rel;
442 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
443 // Stop when rel_cur's address is past the current instruction.
444 if (addr >= Index + Size) break;
445 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
446 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
448 outs() << format(Fmt.data(), SectionAddr + addr) << name
449 << "\t" << val << "\n";
459 static void PrintRelocations(const ObjectFile *Obj) {
460 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
462 // Regular objdump doesn't print relocations in non-relocatable object
464 if (!Obj->isRelocatableObject())
467 for (const SectionRef &Section : Obj->sections()) {
468 if (Section.relocation_begin() == Section.relocation_end())
471 if (error(Section.getName(secname)))
473 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
474 for (const RelocationRef &Reloc : Section.relocations()) {
477 SmallString<32> relocname;
478 SmallString<32> valuestr;
479 if (error(Reloc.getHidden(hidden)))
483 if (error(Reloc.getTypeName(relocname)))
485 if (error(Reloc.getOffset(address)))
487 if (error(Reloc.getValueString(valuestr)))
489 outs() << format(Fmt.data(), address) << " " << relocname << " "
496 static void PrintSectionHeaders(const ObjectFile *Obj) {
497 outs() << "Sections:\n"
498 "Idx Name Size Address Type\n";
500 for (const SectionRef &Section : Obj->sections()) {
502 if (error(Section.getName(Name)))
505 if (error(Section.getAddress(Address)))
508 if (error(Section.getSize(Size)))
510 bool Text, Data, BSS;
511 if (error(Section.isText(Text)))
513 if (error(Section.isData(Data)))
515 if (error(Section.isBSS(BSS)))
517 std::string Type = (std::string(Text ? "TEXT " : "") +
518 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
519 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
520 Name.str().c_str(), Size, Address, Type.c_str());
525 static void PrintSectionContents(const ObjectFile *Obj) {
527 for (const SectionRef &Section : Obj->sections()) {
532 if (error(Section.getName(Name)))
534 if (error(Section.getAddress(BaseAddr)))
536 if (error(Section.isBSS(BSS)))
539 outs() << "Contents of section " << Name << ":\n";
542 if (error(Section.getSize(Size)))
544 outs() << format("<skipping contents of bss section at [%04" PRIx64
545 ", %04" PRIx64 ")>\n",
546 BaseAddr, BaseAddr + Size);
550 if (error(Section.getContents(Contents)))
553 // Dump out the content as hex and printable ascii characters.
554 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
555 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
557 for (std::size_t i = 0; i < 16; ++i) {
558 if (i != 0 && i % 4 == 0)
561 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
562 << hexdigit(Contents[addr + i] & 0xF, true);
568 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
569 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
570 outs() << Contents[addr + i];
579 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
580 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
581 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
583 if (error(Symbol.getError()))
586 if (error(coff->getSymbolName(*Symbol, Name)))
589 outs() << "[" << format("%2d", SI) << "]"
590 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
591 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
592 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
593 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
594 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
595 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
598 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
599 if (Symbol->isSectionDefinition()) {
600 const coff_aux_section_definition *asd;
601 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
604 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
607 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
608 , unsigned(asd->Length)
609 , unsigned(asd->NumberOfRelocations)
610 , unsigned(asd->NumberOfLinenumbers)
611 , unsigned(asd->CheckSum))
612 << format("assoc %d comdat %d\n"
613 , unsigned(AuxNumber)
614 , unsigned(asd->Selection));
615 } else if (Symbol->isFileRecord()) {
616 const char *FileName;
617 if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
620 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
621 coff->getSymbolTableEntrySize());
622 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
624 SI = SI + Symbol->getNumberOfAuxSymbols();
627 outs() << "AUX Unknown\n";
633 static void PrintSymbolTable(const ObjectFile *o) {
634 outs() << "SYMBOL TABLE:\n";
636 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
637 PrintCOFFSymbolTable(coff);
640 for (const SymbolRef &Symbol : o->symbols()) {
643 SymbolRef::Type Type;
645 uint32_t Flags = Symbol.getFlags();
646 section_iterator Section = o->section_end();
647 if (error(Symbol.getName(Name)))
649 if (error(Symbol.getAddress(Address)))
651 if (error(Symbol.getType(Type)))
653 if (error(Symbol.getSize(Size)))
655 if (error(Symbol.getSection(Section)))
658 bool Global = Flags & SymbolRef::SF_Global;
659 bool Weak = Flags & SymbolRef::SF_Weak;
660 bool Absolute = Flags & SymbolRef::SF_Absolute;
662 if (Address == UnknownAddressOrSize)
664 if (Size == UnknownAddressOrSize)
667 if (Type != SymbolRef::ST_Unknown)
668 GlobLoc = Global ? 'g' : 'l';
669 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
672 if (Type == SymbolRef::ST_File)
674 else if (Type == SymbolRef::ST_Function)
677 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
680 outs() << format(Fmt, Address) << " "
681 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
682 << (Weak ? 'w' : ' ') // Weak?
683 << ' ' // Constructor. Not supported yet.
684 << ' ' // Warning. Not supported yet.
685 << ' ' // Indirect reference to another symbol.
686 << Debug // Debugging (d) or dynamic (D) symbol.
687 << FileFunc // Name of function (F), file (f) or object (O).
691 } else if (Section == o->section_end()) {
694 if (const MachOObjectFile *MachO =
695 dyn_cast<const MachOObjectFile>(o)) {
696 DataRefImpl DR = Section->getRawDataRefImpl();
697 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
698 outs() << SegmentName << ",";
700 StringRef SectionName;
701 if (error(Section->getName(SectionName)))
703 outs() << SectionName;
706 << format("%08" PRIx64 " ", Size)
712 static void PrintUnwindInfo(const ObjectFile *o) {
713 outs() << "Unwind info:\n\n";
715 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
716 printCOFFUnwindInfo(coff);
717 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
718 printMachOUnwindInfo(MachO);
720 // TODO: Extract DWARF dump tool to objdump.
721 errs() << "This operation is only currently supported "
722 "for COFF and MachO object files.\n";
727 static void printExportsTrie(const ObjectFile *o) {
728 outs() << "Exports trie:\n";
729 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
730 printMachOExportsTrie(MachO);
732 errs() << "This operation is only currently supported "
733 "for Mach-O executable files.\n";
738 static void printRebaseTable(const ObjectFile *o) {
739 outs() << "Rebase table:\n";
740 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
741 printMachORebaseTable(MachO);
743 errs() << "This operation is only currently supported "
744 "for Mach-O executable files.\n";
749 static void printBindTable(const ObjectFile *o) {
750 outs() << "Bind table:\n";
751 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
752 printMachOBindTable(MachO);
754 errs() << "This operation is only currently supported "
755 "for Mach-O executable files.\n";
760 static void printLazyBindTable(const ObjectFile *o) {
761 outs() << "Lazy bind table:\n";
762 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
763 printMachOLazyBindTable(MachO);
765 errs() << "This operation is only currently supported "
766 "for Mach-O executable files.\n";
771 static void printWeakBindTable(const ObjectFile *o) {
772 outs() << "Weak bind table:\n";
773 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
774 printMachOWeakBindTable(MachO);
776 errs() << "This operation is only currently supported "
777 "for Mach-O executable files.\n";
782 static void printPrivateFileHeader(const ObjectFile *o) {
784 printELFFileHeader(o);
785 } else if (o->isCOFF()) {
786 printCOFFFileHeader(o);
787 } else if (o->isMachO()) {
788 printMachOFileHeader(o);
792 static void DumpObject(const ObjectFile *o) {
794 outs() << o->getFileName()
795 << ":\tfile format " << o->getFileFormatName() << "\n\n";
798 DisassembleObject(o, Relocations);
799 if (Relocations && !Disassemble)
802 PrintSectionHeaders(o);
804 PrintSectionContents(o);
810 printPrivateFileHeader(o);
818 printLazyBindTable(o);
820 printWeakBindTable(o);
823 /// @brief Dump each object file in \a a;
824 static void DumpArchive(const Archive *a) {
825 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
827 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
828 if (std::error_code EC = ChildOrErr.getError()) {
829 // Ignore non-object files.
830 if (EC != object_error::invalid_file_type)
831 errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
835 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
838 errs() << ToolName << ": '" << a->getFileName() << "': "
839 << "Unrecognized file type.\n";
843 /// @brief Open file and figure out how to dump it.
844 static void DumpInput(StringRef file) {
845 // If file isn't stdin, check that it exists.
846 if (file != "-" && !sys::fs::exists(file)) {
847 errs() << ToolName << ": '" << file << "': " << "No such file\n";
851 if (MachOOpt && Disassemble) {
852 DisassembleInputMachO(file);
856 // Attempt to open the binary.
857 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
858 if (std::error_code EC = BinaryOrErr.getError()) {
859 errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
862 Binary &Binary = *BinaryOrErr.get().getBinary();
864 if (Archive *a = dyn_cast<Archive>(&Binary))
866 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
869 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
872 int main(int argc, char **argv) {
873 // Print a stack trace if we signal out.
874 sys::PrintStackTraceOnErrorSignal();
875 PrettyStackTraceProgram X(argc, argv);
876 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
878 // Initialize targets and assembly printers/parsers.
879 llvm::InitializeAllTargetInfos();
880 llvm::InitializeAllTargetMCs();
881 llvm::InitializeAllAsmParsers();
882 llvm::InitializeAllDisassemblers();
884 // Register the target printer for --version.
885 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
887 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
888 TripleName = Triple::normalize(TripleName);
892 // Defaults to a.out if no filenames specified.
893 if (InputFilenames.size() == 0)
894 InputFilenames.push_back("a.out");
908 cl::PrintHelpMessage();
912 std::for_each(InputFilenames.begin(), InputFilenames.end(),