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/Optional.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/FaultMaps.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/MCInstrAnalysis.h"
31 #include "llvm/MC/MCInstrInfo.h"
32 #include "llvm/MC/MCObjectFileInfo.h"
33 #include "llvm/MC/MCRegisterInfo.h"
34 #include "llvm/MC/MCRelocationInfo.h"
35 #include "llvm/MC/MCSubtargetInfo.h"
36 #include "llvm/Object/Archive.h"
37 #include "llvm/Object/ELFObjectFile.h"
38 #include "llvm/Object/COFF.h"
39 #include "llvm/Object/MachO.h"
40 #include "llvm/Object/ObjectFile.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/Errc.h"
45 #include "llvm/Support/FileSystem.h"
46 #include "llvm/Support/Format.h"
47 #include "llvm/Support/GraphWriter.h"
48 #include "llvm/Support/Host.h"
49 #include "llvm/Support/ManagedStatic.h"
50 #include "llvm/Support/MemoryBuffer.h"
51 #include "llvm/Support/PrettyStackTrace.h"
52 #include "llvm/Support/Signals.h"
53 #include "llvm/Support/SourceMgr.h"
54 #include "llvm/Support/TargetRegistry.h"
55 #include "llvm/Support/TargetSelect.h"
56 #include "llvm/Support/raw_ostream.h"
60 #include <system_error>
63 using namespace object;
65 static cl::list<std::string>
66 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
69 llvm::Disassemble("disassemble",
70 cl::desc("Display assembler mnemonics for the machine instructions"));
72 Disassembled("d", cl::desc("Alias for --disassemble"),
73 cl::aliasopt(Disassemble));
76 llvm::DisassembleAll("disassemble-all",
77 cl::desc("Display assembler mnemonics for the machine instructions"));
79 DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
80 cl::aliasopt(DisassembleAll));
83 llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
86 llvm::SectionContents("s", cl::desc("Display the content of each section"));
89 llvm::SymbolTable("t", cl::desc("Display the symbol table"));
92 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
95 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
98 llvm::Bind("bind", cl::desc("Display mach-o binding info"));
101 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
104 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
107 llvm::RawClangAST("raw-clang-ast",
108 cl::desc("Dump the raw binary contents of the clang AST section"));
111 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
113 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
116 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
117 "see -version for available targets"));
121 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
122 cl::value_desc("cpu-name"),
126 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
127 "see -version for available targets"));
130 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
131 "headers for each section."));
133 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
134 cl::aliasopt(SectionHeaders));
136 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
137 cl::aliasopt(SectionHeaders));
138 cl::list<std::string>
139 llvm::Sections("j", cl::desc("Operate on the specified sections only"));
141 cl::list<std::string>
142 llvm::MAttrs("mattr",
144 cl::desc("Target specific attributes"),
145 cl::value_desc("a1,+a2,-a3,..."));
148 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
149 "instructions, do not print "
150 "the instruction bytes."));
153 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
156 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
157 cl::aliasopt(UnwindInfo));
160 llvm::PrivateHeaders("private-headers",
161 cl::desc("Display format specific file headers"));
164 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
165 cl::aliasopt(PrivateHeaders));
168 llvm::PrintImmHex("print-imm-hex",
169 cl::desc("Use hex format for immediate values"));
171 cl::opt<bool> PrintFaultMaps("fault-map-section",
172 cl::desc("Display contents of faultmap section"));
174 static StringRef ToolName;
175 static int ReturnValue = EXIT_SUCCESS;
178 typedef std::function<int(llvm::object::SectionRef const &)> FilterPredicate;
180 class SectionFilterIterator {
182 SectionFilterIterator(FilterPredicate P,
183 llvm::object::section_iterator const &I,
184 llvm::object::section_iterator const &E)
185 : Predicate(P), Iterator(I), End(E) {
188 llvm::object::SectionRef operator*() const { return *Iterator; }
189 SectionFilterIterator &operator++() {
194 bool operator!=(SectionFilterIterator const &Other) const {
195 return Iterator != Other.Iterator;
199 void ScanPredicate() {
200 while (Iterator != End && Predicate(*Iterator)) {
204 FilterPredicate Predicate;
205 llvm::object::section_iterator Iterator;
206 llvm::object::section_iterator End;
209 class SectionFilter {
211 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
212 : Predicate(P), Object(O) {}
213 SectionFilterIterator begin() {
214 return SectionFilterIterator(Predicate, Object.section_begin(),
215 Object.section_end());
217 SectionFilterIterator end() {
218 return SectionFilterIterator(Predicate, Object.section_end(),
219 Object.section_end());
223 FilterPredicate Predicate;
224 llvm::object::ObjectFile const &Object;
226 SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
227 if (Sections.empty()) {
228 return SectionFilter([](llvm::object::SectionRef const &) { return 0; }, O);
230 return SectionFilter([](llvm::object::SectionRef const &S) {
231 llvm::StringRef String;
232 std::error_code error = S.getName(String);
234 return error.value();
236 if (std::find(Sections.begin(), Sections.end(),
237 String) != Sections.end()) {
246 bool llvm::error(std::error_code EC) {
250 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
252 ReturnValue = EXIT_FAILURE;
256 static void report_error(StringRef File, std::error_code EC) {
258 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
259 ReturnValue = EXIT_FAILURE;
262 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
263 // Figure out the target triple.
264 llvm::Triple TheTriple("unknown-unknown-unknown");
265 if (TripleName.empty()) {
267 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
268 // TheTriple defaults to ELF, and COFF doesn't have an environment:
269 // the best we can do here is indicate that it is mach-o.
271 TheTriple.setObjectFormat(Triple::MachO);
274 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
275 if (COFFObj->getArch() == Triple::thumb)
276 TheTriple.setTriple("thumbv7-windows");
280 TheTriple.setTriple(Triple::normalize(TripleName));
282 // Get the target specific parser.
284 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
287 errs() << ToolName << ": " << Error;
291 // Update the triple name and return the found target.
292 TripleName = TheTriple.getTriple();
296 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
297 return a.getOffset() < b.getOffset();
301 class PrettyPrinter {
303 virtual ~PrettyPrinter(){}
304 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
305 ArrayRef<uint8_t> Bytes, uint64_t Address,
306 raw_ostream &OS, StringRef Annot,
307 MCSubtargetInfo const &STI) {
308 outs() << format("%8" PRIx64 ":", Address);
309 if (!NoShowRawInsn) {
311 dumpBytes(Bytes, outs());
313 IP.printInst(MI, outs(), "", STI);
316 PrettyPrinter PrettyPrinterInst;
317 class HexagonPrettyPrinter : public PrettyPrinter {
319 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
322 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
323 OS << format("%8" PRIx64 ":", Address);
324 if (!NoShowRawInsn) {
326 dumpBytes(Bytes.slice(0, 4), OS);
327 OS << format("%08" PRIx32, opcode);
330 void printInst(MCInstPrinter &IP, const MCInst *MI,
331 ArrayRef<uint8_t> Bytes, uint64_t Address,
332 raw_ostream &OS, StringRef Annot,
333 MCSubtargetInfo const &STI) override {
336 raw_string_ostream TempStream(Buffer);
337 IP.printInst(MI, TempStream, "", STI);
339 StringRef Contents(Buffer);
340 // Split off bundle attributes
341 auto PacketBundle = Contents.rsplit('\n');
342 // Split off first instruction from the rest
343 auto HeadTail = PacketBundle.first.split('\n');
344 auto Preamble = " { ";
346 while(!HeadTail.first.empty()) {
349 printLead(Bytes, Address, OS);
353 auto Duplex = HeadTail.first.split('\v');
354 if(!Duplex.second.empty()){
357 Inst = Duplex.second;
360 Inst = HeadTail.first;
362 Bytes = Bytes.slice(4);
364 HeadTail = HeadTail.second.split('\n');
366 OS << " } " << PacketBundle.second;
369 HexagonPrettyPrinter HexagonPrettyPrinterInst;
370 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
371 switch(Triple.getArch()) {
373 return PrettyPrinterInst;
374 case Triple::hexagon:
375 return HexagonPrettyPrinterInst;
380 template <class ELFT>
381 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
383 SmallVectorImpl<char> &Result) {
384 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
385 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
386 typedef typename ELFObjectFile<ELFT>::Elf_Rel Elf_Rel;
387 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
389 const ELFFile<ELFT> &EF = *Obj->getELFFile();
391 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
392 if (std::error_code EC = SecOrErr.getError())
394 const Elf_Shdr *Sec = *SecOrErr;
395 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
396 if (std::error_code EC = SymTabOrErr.getError())
398 const Elf_Shdr *SymTab = *SymTabOrErr;
399 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
400 SymTab->sh_type == ELF::SHT_DYNSYM);
401 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
402 if (std::error_code EC = StrTabSec.getError())
404 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
405 if (std::error_code EC = StrTabOrErr.getError())
407 StringRef StrTab = *StrTabOrErr;
411 uint16_t symbol_index = 0;
412 switch (Sec->sh_type) {
414 return object_error::parse_failed;
416 const Elf_Rel *ERel = Obj->getRel(Rel);
417 type = ERel->getType(EF.isMips64EL());
418 symbol_index = ERel->getSymbol(EF.isMips64EL());
419 // TODO: Read implicit addend from section data.
422 case ELF::SHT_RELA: {
423 const Elf_Rela *ERela = Obj->getRela(Rel);
424 type = ERela->getType(EF.isMips64EL());
425 symbol_index = ERela->getSymbol(EF.isMips64EL());
426 addend = ERela->r_addend;
430 const Elf_Sym *symb =
431 EF.template getEntry<Elf_Sym>(Sec->sh_link, symbol_index);
433 ErrorOr<const Elf_Shdr *> SymSec = EF.getSection(symb);
434 if (std::error_code EC = SymSec.getError())
436 if (symb->getType() == ELF::STT_SECTION) {
437 ErrorOr<StringRef> SecName = EF.getSectionName(*SymSec);
438 if (std::error_code EC = SecName.getError())
442 ErrorOr<StringRef> SymName = symb->getName(StrTab);
444 return SymName.getError();
447 switch (EF.getHeader()->e_machine) {
450 case ELF::R_X86_64_PC8:
451 case ELF::R_X86_64_PC16:
452 case ELF::R_X86_64_PC32: {
454 raw_string_ostream fmt(fmtbuf);
455 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
457 Result.append(fmtbuf.begin(), fmtbuf.end());
459 case ELF::R_X86_64_8:
460 case ELF::R_X86_64_16:
461 case ELF::R_X86_64_32:
462 case ELF::R_X86_64_32S:
463 case ELF::R_X86_64_64: {
465 raw_string_ostream fmt(fmtbuf);
466 fmt << Target << (addend < 0 ? "" : "+") << addend;
468 Result.append(fmtbuf.begin(), fmtbuf.end());
474 case ELF::EM_AARCH64: {
476 raw_string_ostream fmt(fmtbuf);
479 fmt << (addend < 0 ? "" : "+") << addend;
481 Result.append(fmtbuf.begin(), fmtbuf.end());
486 case ELF::EM_HEXAGON:
494 Result.append(res.begin(), res.end());
495 return std::error_code();
498 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
499 const RelocationRef &RelRef,
500 SmallVectorImpl<char> &Result) {
501 DataRefImpl Rel = RelRef.getRawDataRefImpl();
502 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
503 return getRelocationValueString(ELF32LE, Rel, Result);
504 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
505 return getRelocationValueString(ELF64LE, Rel, Result);
506 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
507 return getRelocationValueString(ELF32BE, Rel, Result);
508 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
509 return getRelocationValueString(ELF64BE, Rel, Result);
512 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
513 const RelocationRef &Rel,
514 SmallVectorImpl<char> &Result) {
515 symbol_iterator SymI = Rel.getSymbol();
516 ErrorOr<StringRef> SymNameOrErr = SymI->getName();
517 if (std::error_code EC = SymNameOrErr.getError())
519 StringRef SymName = *SymNameOrErr;
520 Result.append(SymName.begin(), SymName.end());
521 return std::error_code();
524 static void printRelocationTargetName(const MachOObjectFile *O,
525 const MachO::any_relocation_info &RE,
526 raw_string_ostream &fmt) {
527 bool IsScattered = O->isRelocationScattered(RE);
529 // Target of a scattered relocation is an address. In the interest of
530 // generating pretty output, scan through the symbol table looking for a
531 // symbol that aligns with that address. If we find one, print it.
532 // Otherwise, we just print the hex address of the target.
534 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
536 for (const SymbolRef &Symbol : O->symbols()) {
538 ErrorOr<uint64_t> Addr = Symbol.getAddress();
539 if ((ec = Addr.getError()))
540 report_fatal_error(ec.message());
543 ErrorOr<StringRef> Name = Symbol.getName();
544 if (std::error_code EC = Name.getError())
545 report_fatal_error(EC.message());
550 // If we couldn't find a symbol that this relocation refers to, try
551 // to find a section beginning instead.
552 for (const SectionRef &Section : ToolSectionFilter(*O)) {
556 uint64_t Addr = Section.getAddress();
559 if ((ec = Section.getName(Name)))
560 report_fatal_error(ec.message());
565 fmt << format("0x%x", Val);
570 bool isExtern = O->getPlainRelocationExternal(RE);
571 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
574 symbol_iterator SI = O->symbol_begin();
576 ErrorOr<StringRef> SOrErr = SI->getName();
577 if (!error(SOrErr.getError()))
580 section_iterator SI = O->section_begin();
581 // Adjust for the fact that sections are 1-indexed.
582 advance(SI, Val - 1);
589 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
590 const RelocationRef &RelRef,
591 SmallVectorImpl<char> &Result) {
592 DataRefImpl Rel = RelRef.getRawDataRefImpl();
593 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
595 unsigned Arch = Obj->getArch();
598 raw_string_ostream fmt(fmtbuf);
599 unsigned Type = Obj->getAnyRelocationType(RE);
600 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
602 // Determine any addends that should be displayed with the relocation.
603 // These require decoding the relocation type, which is triple-specific.
605 // X86_64 has entirely custom relocation types.
606 if (Arch == Triple::x86_64) {
607 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
610 case MachO::X86_64_RELOC_GOT_LOAD:
611 case MachO::X86_64_RELOC_GOT: {
612 printRelocationTargetName(Obj, RE, fmt);
618 case MachO::X86_64_RELOC_SUBTRACTOR: {
619 DataRefImpl RelNext = Rel;
620 Obj->moveRelocationNext(RelNext);
621 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
623 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
624 // X86_64_RELOC_UNSIGNED.
625 // NOTE: Scattered relocations don't exist on x86_64.
626 unsigned RType = Obj->getAnyRelocationType(RENext);
627 if (RType != MachO::X86_64_RELOC_UNSIGNED)
628 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
629 "X86_64_RELOC_SUBTRACTOR.");
631 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
632 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
633 printRelocationTargetName(Obj, RENext, fmt);
635 printRelocationTargetName(Obj, RE, fmt);
638 case MachO::X86_64_RELOC_TLV:
639 printRelocationTargetName(Obj, RE, fmt);
644 case MachO::X86_64_RELOC_SIGNED_1:
645 printRelocationTargetName(Obj, RE, fmt);
648 case MachO::X86_64_RELOC_SIGNED_2:
649 printRelocationTargetName(Obj, RE, fmt);
652 case MachO::X86_64_RELOC_SIGNED_4:
653 printRelocationTargetName(Obj, RE, fmt);
657 printRelocationTargetName(Obj, RE, fmt);
660 // X86 and ARM share some relocation types in common.
661 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
662 Arch == Triple::ppc) {
663 // Generic relocation types...
665 case MachO::GENERIC_RELOC_PAIR: // prints no info
666 return std::error_code();
667 case MachO::GENERIC_RELOC_SECTDIFF: {
668 DataRefImpl RelNext = Rel;
669 Obj->moveRelocationNext(RelNext);
670 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
672 // X86 sect diff's must be followed by a relocation of type
673 // GENERIC_RELOC_PAIR.
674 unsigned RType = Obj->getAnyRelocationType(RENext);
676 if (RType != MachO::GENERIC_RELOC_PAIR)
677 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
678 "GENERIC_RELOC_SECTDIFF.");
680 printRelocationTargetName(Obj, RE, fmt);
682 printRelocationTargetName(Obj, RENext, fmt);
687 if (Arch == Triple::x86 || Arch == Triple::ppc) {
689 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
690 DataRefImpl RelNext = Rel;
691 Obj->moveRelocationNext(RelNext);
692 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
694 // X86 sect diff's must be followed by a relocation of type
695 // GENERIC_RELOC_PAIR.
696 unsigned RType = Obj->getAnyRelocationType(RENext);
697 if (RType != MachO::GENERIC_RELOC_PAIR)
698 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
699 "GENERIC_RELOC_LOCAL_SECTDIFF.");
701 printRelocationTargetName(Obj, RE, fmt);
703 printRelocationTargetName(Obj, RENext, fmt);
706 case MachO::GENERIC_RELOC_TLV: {
707 printRelocationTargetName(Obj, RE, fmt);
714 printRelocationTargetName(Obj, RE, fmt);
716 } else { // ARM-specific relocations
718 case MachO::ARM_RELOC_HALF:
719 case MachO::ARM_RELOC_HALF_SECTDIFF: {
720 // Half relocations steal a bit from the length field to encode
721 // whether this is an upper16 or a lower16 relocation.
722 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
728 printRelocationTargetName(Obj, RE, fmt);
730 DataRefImpl RelNext = Rel;
731 Obj->moveRelocationNext(RelNext);
732 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
734 // ARM half relocs must be followed by a relocation of type
736 unsigned RType = Obj->getAnyRelocationType(RENext);
737 if (RType != MachO::ARM_RELOC_PAIR)
738 report_fatal_error("Expected ARM_RELOC_PAIR after "
741 // NOTE: The half of the target virtual address is stashed in the
742 // address field of the secondary relocation, but we can't reverse
743 // engineer the constant offset from it without decoding the movw/movt
744 // instruction to find the other half in its immediate field.
746 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
747 // symbol/section pointer of the follow-on relocation.
748 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
750 printRelocationTargetName(Obj, RENext, fmt);
756 default: { printRelocationTargetName(Obj, RE, fmt); }
760 printRelocationTargetName(Obj, RE, fmt);
763 Result.append(fmtbuf.begin(), fmtbuf.end());
764 return std::error_code();
767 static std::error_code getRelocationValueString(const RelocationRef &Rel,
768 SmallVectorImpl<char> &Result) {
769 const ObjectFile *Obj = Rel.getObject();
770 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
771 return getRelocationValueString(ELF, Rel, Result);
772 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
773 return getRelocationValueString(COFF, Rel, Result);
774 auto *MachO = cast<MachOObjectFile>(Obj);
775 return getRelocationValueString(MachO, Rel, Result);
778 /// @brief Indicates whether this relocation should hidden when listing
779 /// relocations, usually because it is the trailing part of a multipart
780 /// relocation that will be printed as part of the leading relocation.
781 static bool getHidden(RelocationRef RelRef) {
782 const ObjectFile *Obj = RelRef.getObject();
783 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
787 unsigned Arch = MachO->getArch();
788 DataRefImpl Rel = RelRef.getRawDataRefImpl();
789 uint64_t Type = MachO->getRelocationType(Rel);
791 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
793 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
794 if (Type == MachO::GENERIC_RELOC_PAIR)
796 } else if (Arch == Triple::x86_64) {
797 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
798 // an X86_64_RELOC_SUBTRACTOR.
799 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
800 DataRefImpl RelPrev = Rel;
802 uint64_t PrevType = MachO->getRelocationType(RelPrev);
803 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
811 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
812 const Target *TheTarget = getTarget(Obj);
813 // getTarget() will have already issued a diagnostic if necessary, so
814 // just bail here if it failed.
818 // Package up features to be passed to target/subtarget
819 std::string FeaturesStr;
821 SubtargetFeatures Features;
822 for (unsigned i = 0; i != MAttrs.size(); ++i)
823 Features.AddFeature(MAttrs[i]);
824 FeaturesStr = Features.getString();
827 std::unique_ptr<const MCRegisterInfo> MRI(
828 TheTarget->createMCRegInfo(TripleName));
830 errs() << "error: no register info for target " << TripleName << "\n";
834 // Set up disassembler.
835 std::unique_ptr<const MCAsmInfo> AsmInfo(
836 TheTarget->createMCAsmInfo(*MRI, TripleName));
838 errs() << "error: no assembly info for target " << TripleName << "\n";
842 std::unique_ptr<const MCSubtargetInfo> STI(
843 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
845 errs() << "error: no subtarget info for target " << TripleName << "\n";
849 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
851 errs() << "error: no instruction info for target " << TripleName << "\n";
855 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
856 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
858 std::unique_ptr<MCDisassembler> DisAsm(
859 TheTarget->createMCDisassembler(*STI, Ctx));
862 errs() << "error: no disassembler for target " << TripleName << "\n";
866 std::unique_ptr<const MCInstrAnalysis> MIA(
867 TheTarget->createMCInstrAnalysis(MII.get()));
869 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
870 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
871 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
873 errs() << "error: no instruction printer for target " << TripleName
877 IP->setPrintImmHex(PrintImmHex);
878 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
880 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
881 "\t\t\t%08" PRIx64 ": ";
883 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
884 // in RelocSecs contain the relocations for section S.
886 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
887 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
888 section_iterator Sec2 = Section.getRelocatedSection();
889 if (Sec2 != Obj->section_end())
890 SectionRelocMap[*Sec2].push_back(Section);
893 // Create a mapping from virtual address to symbol name. This is used to
894 // pretty print the target of a call.
895 std::vector<std::pair<uint64_t, StringRef>> AllSymbols;
897 for (const SymbolRef &Symbol : Obj->symbols()) {
898 if (Symbol.getType() != SymbolRef::ST_Function)
901 ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
902 if (error(AddressOrErr.getError()))
904 uint64_t Address = *AddressOrErr;
906 ErrorOr<StringRef> Name = Symbol.getName();
907 if (error(Name.getError()))
911 AllSymbols.push_back(std::make_pair(Address, *Name));
914 array_pod_sort(AllSymbols.begin(), AllSymbols.end());
917 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
918 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
921 uint64_t SectionAddr = Section.getAddress();
922 uint64_t SectSize = Section.getSize();
926 // Make a list of all the symbols in this section.
927 std::vector<std::pair<uint64_t, StringRef>> Symbols;
928 for (const SymbolRef &Symbol : Obj->symbols()) {
929 if (Section.containsSymbol(Symbol)) {
930 ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
931 if (error(AddressOrErr.getError()))
933 uint64_t Address = *AddressOrErr;
934 Address -= SectionAddr;
935 if (Address >= SectSize)
938 ErrorOr<StringRef> Name = Symbol.getName();
939 if (error(Name.getError()))
941 Symbols.push_back(std::make_pair(Address, *Name));
945 // Sort the symbols by address, just in case they didn't come in that way.
946 array_pod_sort(Symbols.begin(), Symbols.end());
948 // Make a list of all the relocations for this section.
949 std::vector<RelocationRef> Rels;
951 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
952 for (const RelocationRef &Reloc : RelocSec.relocations()) {
953 Rels.push_back(Reloc);
958 // Sort relocations by address.
959 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
961 StringRef SegmentName = "";
962 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
963 DataRefImpl DR = Section.getRawDataRefImpl();
964 SegmentName = MachO->getSectionFinalSegmentName(DR);
967 if (error(Section.getName(name)))
969 outs() << "Disassembly of section ";
970 if (!SegmentName.empty())
971 outs() << SegmentName << ",";
972 outs() << name << ':';
974 // If the section has no symbol at the start, just insert a dummy one.
975 if (Symbols.empty() || Symbols[0].first != 0)
976 Symbols.insert(Symbols.begin(), std::make_pair(0, name));
978 SmallString<40> Comments;
979 raw_svector_ostream CommentStream(Comments);
982 if (error(Section.getContents(BytesStr)))
984 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
990 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
991 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
992 // Disassemble symbol by symbol.
993 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
995 uint64_t Start = Symbols[si].first;
996 // The end is either the section end or the beginning of the next symbol.
997 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
998 // If this symbol has the same address as the next symbol, then skip it.
1002 outs() << '\n' << Symbols[si].second << ":\n";
1005 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1007 raw_ostream &DebugOut = nulls();
1010 for (Index = Start; Index < End; Index += Size) {
1013 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1014 SectionAddr + Index, DebugOut,
1016 PIP.printInst(*IP, &Inst,
1017 Bytes.slice(Index, Size),
1018 SectionAddr + Index, outs(), "", *STI);
1019 outs() << CommentStream.str();
1021 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1022 MIA->isConditionalBranch(Inst))) {
1024 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1025 auto TargetSym = std::upper_bound(
1026 AllSymbols.begin(), AllSymbols.end(), Target,
1027 [](uint64_t LHS, const std::pair<uint64_t, StringRef> &RHS) {
1028 return LHS < RHS.first;
1030 if (TargetSym != AllSymbols.begin())
1033 TargetSym = AllSymbols.end();
1035 if (TargetSym != AllSymbols.end()) {
1036 outs() << " <" << TargetSym->second;
1037 uint64_t Disp = Target - TargetSym->first;
1039 outs() << '+' << utohexstr(Disp);
1046 errs() << ToolName << ": warning: invalid instruction encoding\n";
1048 Size = 1; // skip illegible bytes
1051 // Print relocation for instruction.
1052 while (rel_cur != rel_end) {
1053 bool hidden = getHidden(*rel_cur);
1054 uint64_t addr = rel_cur->getOffset();
1055 SmallString<16> name;
1056 SmallString<32> val;
1058 // If this relocation is hidden, skip it.
1059 if (hidden) goto skip_print_rel;
1061 // Stop when rel_cur's address is past the current instruction.
1062 if (addr >= Index + Size) break;
1063 rel_cur->getTypeName(name);
1064 if (error(getRelocationValueString(*rel_cur, val)))
1065 goto skip_print_rel;
1066 outs() << format(Fmt.data(), SectionAddr + addr) << name
1067 << "\t" << val << "\n";
1077 void llvm::PrintRelocations(const ObjectFile *Obj) {
1078 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1080 // Regular objdump doesn't print relocations in non-relocatable object
1082 if (!Obj->isRelocatableObject())
1085 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1086 if (Section.relocation_begin() == Section.relocation_end())
1089 if (error(Section.getName(secname)))
1091 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
1092 for (const RelocationRef &Reloc : Section.relocations()) {
1093 bool hidden = getHidden(Reloc);
1094 uint64_t address = Reloc.getOffset();
1095 SmallString<32> relocname;
1096 SmallString<32> valuestr;
1099 Reloc.getTypeName(relocname);
1100 if (error(getRelocationValueString(Reloc, valuestr)))
1102 outs() << format(Fmt.data(), address) << " " << relocname << " "
1103 << valuestr << "\n";
1109 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
1110 outs() << "Sections:\n"
1111 "Idx Name Size Address Type\n";
1113 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1115 if (error(Section.getName(Name)))
1117 uint64_t Address = Section.getAddress();
1118 uint64_t Size = Section.getSize();
1119 bool Text = Section.isText();
1120 bool Data = Section.isData();
1121 bool BSS = Section.isBSS();
1122 std::string Type = (std::string(Text ? "TEXT " : "") +
1123 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1124 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1125 Name.str().c_str(), Size, Address, Type.c_str());
1130 void llvm::PrintSectionContents(const ObjectFile *Obj) {
1132 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1135 if (error(Section.getName(Name)))
1137 uint64_t BaseAddr = Section.getAddress();
1138 uint64_t Size = Section.getSize();
1142 outs() << "Contents of section " << Name << ":\n";
1143 if (Section.isBSS()) {
1144 outs() << format("<skipping contents of bss section at [%04" PRIx64
1145 ", %04" PRIx64 ")>\n",
1146 BaseAddr, BaseAddr + Size);
1150 if (error(Section.getContents(Contents)))
1153 // Dump out the content as hex and printable ascii characters.
1154 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1155 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1156 // Dump line of hex.
1157 for (std::size_t i = 0; i < 16; ++i) {
1158 if (i != 0 && i % 4 == 0)
1161 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1162 << hexdigit(Contents[addr + i] & 0xF, true);
1168 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1169 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1170 outs() << Contents[addr + i];
1179 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
1180 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1181 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
1183 if (error(Symbol.getError()))
1186 if (error(coff->getSymbolName(*Symbol, Name)))
1189 outs() << "[" << format("%2d", SI) << "]"
1190 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
1191 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
1192 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1193 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1194 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1195 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
1198 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
1199 if (Symbol->isSectionDefinition()) {
1200 const coff_aux_section_definition *asd;
1201 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
1204 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1207 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1208 , unsigned(asd->Length)
1209 , unsigned(asd->NumberOfRelocations)
1210 , unsigned(asd->NumberOfLinenumbers)
1211 , unsigned(asd->CheckSum))
1212 << format("assoc %d comdat %d\n"
1213 , unsigned(AuxNumber)
1214 , unsigned(asd->Selection));
1215 } else if (Symbol->isFileRecord()) {
1216 const char *FileName;
1217 if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
1220 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1221 coff->getSymbolTableEntrySize());
1222 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
1224 SI = SI + Symbol->getNumberOfAuxSymbols();
1227 outs() << "AUX Unknown\n";
1233 void llvm::PrintSymbolTable(const ObjectFile *o) {
1234 outs() << "SYMBOL TABLE:\n";
1236 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1237 PrintCOFFSymbolTable(coff);
1240 for (const SymbolRef &Symbol : o->symbols()) {
1241 ErrorOr<uint64_t> AddressOrError = Symbol.getAddress();
1242 if (error(AddressOrError.getError()))
1244 uint64_t Address = *AddressOrError;
1245 SymbolRef::Type Type = Symbol.getType();
1246 uint32_t Flags = Symbol.getFlags();
1247 section_iterator Section = o->section_end();
1248 if (error(Symbol.getSection(Section)))
1251 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1252 Section->getName(Name);
1254 ErrorOr<StringRef> NameOrErr = Symbol.getName();
1255 if (error(NameOrErr.getError()))
1260 bool Global = Flags & SymbolRef::SF_Global;
1261 bool Weak = Flags & SymbolRef::SF_Weak;
1262 bool Absolute = Flags & SymbolRef::SF_Absolute;
1263 bool Common = Flags & SymbolRef::SF_Common;
1264 bool Hidden = Flags & SymbolRef::SF_Hidden;
1267 if (Type != SymbolRef::ST_Unknown)
1268 GlobLoc = Global ? 'g' : 'l';
1269 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1271 char FileFunc = ' ';
1272 if (Type == SymbolRef::ST_File)
1274 else if (Type == SymbolRef::ST_Function)
1277 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1280 outs() << format(Fmt, Address) << " "
1281 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1282 << (Weak ? 'w' : ' ') // Weak?
1283 << ' ' // Constructor. Not supported yet.
1284 << ' ' // Warning. Not supported yet.
1285 << ' ' // Indirect reference to another symbol.
1286 << Debug // Debugging (d) or dynamic (D) symbol.
1287 << FileFunc // Name of function (F), file (f) or object (O).
1291 } else if (Common) {
1293 } else if (Section == o->section_end()) {
1296 if (const MachOObjectFile *MachO =
1297 dyn_cast<const MachOObjectFile>(o)) {
1298 DataRefImpl DR = Section->getRawDataRefImpl();
1299 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1300 outs() << SegmentName << ",";
1302 StringRef SectionName;
1303 if (error(Section->getName(SectionName)))
1305 outs() << SectionName;
1309 if (Common || isa<ELFObjectFileBase>(o)) {
1311 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1312 outs() << format("\t %08" PRIx64 " ", Val);
1316 outs() << ".hidden ";
1323 static void PrintUnwindInfo(const ObjectFile *o) {
1324 outs() << "Unwind info:\n\n";
1326 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1327 printCOFFUnwindInfo(coff);
1328 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1329 printMachOUnwindInfo(MachO);
1331 // TODO: Extract DWARF dump tool to objdump.
1332 errs() << "This operation is only currently supported "
1333 "for COFF and MachO object files.\n";
1338 void llvm::printExportsTrie(const ObjectFile *o) {
1339 outs() << "Exports trie:\n";
1340 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1341 printMachOExportsTrie(MachO);
1343 errs() << "This operation is only currently supported "
1344 "for Mach-O executable files.\n";
1349 void llvm::printRebaseTable(const ObjectFile *o) {
1350 outs() << "Rebase table:\n";
1351 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1352 printMachORebaseTable(MachO);
1354 errs() << "This operation is only currently supported "
1355 "for Mach-O executable files.\n";
1360 void llvm::printBindTable(const ObjectFile *o) {
1361 outs() << "Bind table:\n";
1362 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1363 printMachOBindTable(MachO);
1365 errs() << "This operation is only currently supported "
1366 "for Mach-O executable files.\n";
1371 void llvm::printLazyBindTable(const ObjectFile *o) {
1372 outs() << "Lazy bind table:\n";
1373 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1374 printMachOLazyBindTable(MachO);
1376 errs() << "This operation is only currently supported "
1377 "for Mach-O executable files.\n";
1382 void llvm::printWeakBindTable(const ObjectFile *o) {
1383 outs() << "Weak bind table:\n";
1384 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1385 printMachOWeakBindTable(MachO);
1387 errs() << "This operation is only currently supported "
1388 "for Mach-O executable files.\n";
1393 /// Dump the raw contents of the __clangast section so the output can be piped
1394 /// into llvm-bcanalyzer.
1395 void llvm::printRawClangAST(const ObjectFile *Obj) {
1396 if (outs().is_displayed()) {
1397 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1398 "the clang ast section.\n"
1399 "Please redirect the output to a file or another program such as "
1400 "llvm-bcanalyzer.\n";
1404 StringRef ClangASTSectionName("__clangast");
1405 if (isa<COFFObjectFile>(Obj)) {
1406 ClangASTSectionName = "clangast";
1409 Optional<object::SectionRef> ClangASTSection;
1410 for (auto Sec : ToolSectionFilter(*Obj)) {
1413 if (Name == ClangASTSectionName) {
1414 ClangASTSection = Sec;
1418 if (!ClangASTSection)
1421 StringRef ClangASTContents;
1422 if (error(ClangASTSection.getValue().getContents(ClangASTContents))) {
1423 errs() << "Could not read the " << ClangASTSectionName << " section!\n";
1427 outs().write(ClangASTContents.data(), ClangASTContents.size());
1430 static void printFaultMaps(const ObjectFile *Obj) {
1431 const char *FaultMapSectionName = nullptr;
1433 if (isa<ELFObjectFileBase>(Obj)) {
1434 FaultMapSectionName = ".llvm_faultmaps";
1435 } else if (isa<MachOObjectFile>(Obj)) {
1436 FaultMapSectionName = "__llvm_faultmaps";
1438 errs() << "This operation is only currently supported "
1439 "for ELF and Mach-O executable files.\n";
1443 Optional<object::SectionRef> FaultMapSection;
1445 for (auto Sec : ToolSectionFilter(*Obj)) {
1448 if (Name == FaultMapSectionName) {
1449 FaultMapSection = Sec;
1454 outs() << "FaultMap table:\n";
1456 if (!FaultMapSection.hasValue()) {
1457 outs() << "<not found>\n";
1461 StringRef FaultMapContents;
1462 if (error(FaultMapSection.getValue().getContents(FaultMapContents))) {
1463 errs() << "Could not read the " << FaultMapContents << " section!\n";
1467 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1468 FaultMapContents.bytes_end());
1473 static void printPrivateFileHeader(const ObjectFile *o) {
1475 printELFFileHeader(o);
1476 } else if (o->isCOFF()) {
1477 printCOFFFileHeader(o);
1478 } else if (o->isMachO()) {
1479 printMachOFileHeader(o);
1483 static void DumpObject(const ObjectFile *o) {
1484 // Avoid other output when using a raw option.
1487 outs() << o->getFileName()
1488 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1492 DisassembleObject(o, Relocations);
1493 if (Relocations && !Disassemble)
1494 PrintRelocations(o);
1496 PrintSectionHeaders(o);
1497 if (SectionContents)
1498 PrintSectionContents(o);
1500 PrintSymbolTable(o);
1504 printPrivateFileHeader(o);
1506 printExportsTrie(o);
1508 printRebaseTable(o);
1512 printLazyBindTable(o);
1514 printWeakBindTable(o);
1516 printRawClangAST(o);
1521 /// @brief Dump each object file in \a a;
1522 static void DumpArchive(const Archive *a) {
1523 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
1525 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
1526 if (std::error_code EC = ChildOrErr.getError()) {
1527 // Ignore non-object files.
1528 if (EC != object_error::invalid_file_type)
1529 report_error(a->getFileName(), EC);
1532 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
1535 report_error(a->getFileName(), object_error::invalid_file_type);
1539 /// @brief Open file and figure out how to dump it.
1540 static void DumpInput(StringRef file) {
1541 // If file isn't stdin, check that it exists.
1542 if (file != "-" && !sys::fs::exists(file)) {
1543 report_error(file, errc::no_such_file_or_directory);
1547 // If we are using the Mach-O specific object file parser, then let it parse
1548 // the file and process the command line options. So the -arch flags can
1549 // be used to select specific slices, etc.
1551 ParseInputMachO(file);
1555 // Attempt to open the binary.
1556 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1557 if (std::error_code EC = BinaryOrErr.getError()) {
1558 report_error(file, EC);
1561 Binary &Binary = *BinaryOrErr.get().getBinary();
1563 if (Archive *a = dyn_cast<Archive>(&Binary))
1565 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
1568 report_error(file, object_error::invalid_file_type);
1571 int main(int argc, char **argv) {
1572 // Print a stack trace if we signal out.
1573 sys::PrintStackTraceOnErrorSignal();
1574 PrettyStackTraceProgram X(argc, argv);
1575 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1577 // Initialize targets and assembly printers/parsers.
1578 llvm::InitializeAllTargetInfos();
1579 llvm::InitializeAllTargetMCs();
1580 llvm::InitializeAllAsmParsers();
1581 llvm::InitializeAllDisassemblers();
1583 // Register the target printer for --version.
1584 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1586 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1587 TripleName = Triple::normalize(TripleName);
1591 // Defaults to a.out if no filenames specified.
1592 if (InputFilenames.size() == 0)
1593 InputFilenames.push_back("a.out");
1610 && !(UniversalHeaders && MachOOpt)
1611 && !(ArchiveHeaders && MachOOpt)
1612 && !(IndirectSymbols && MachOOpt)
1613 && !(DataInCode && MachOOpt)
1614 && !(LinkOptHints && MachOOpt)
1615 && !(InfoPlist && MachOOpt)
1616 && !(DylibsUsed && MachOOpt)
1617 && !(DylibId && MachOOpt)
1618 && !(ObjcMetaData && MachOOpt)
1619 && !(DumpSections.size() != 0 && MachOOpt)
1620 && !PrintFaultMaps) {
1621 cl::PrintHelpMessage();
1625 std::for_each(InputFilenames.begin(), InputFilenames.end(),