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));
139 cl::list<std::string>
140 llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
141 "With -macho dump segment,section"));
143 static FilterSectionsj("j", cl::desc("Alias for --section"),
144 cl::aliasopt(llvm::FilterSections));
146 cl::list<std::string>
147 llvm::MAttrs("mattr",
149 cl::desc("Target specific attributes"),
150 cl::value_desc("a1,+a2,-a3,..."));
153 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
154 "instructions, do not print "
155 "the instruction bytes."));
158 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
161 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
162 cl::aliasopt(UnwindInfo));
165 llvm::PrivateHeaders("private-headers",
166 cl::desc("Display format specific file headers"));
169 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
170 cl::aliasopt(PrivateHeaders));
173 llvm::PrintImmHex("print-imm-hex",
174 cl::desc("Use hex format for immediate values"));
176 cl::opt<bool> PrintFaultMaps("fault-map-section",
177 cl::desc("Display contents of faultmap section"));
179 static StringRef ToolName;
180 static int ReturnValue = EXIT_SUCCESS;
183 typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
185 class SectionFilterIterator {
187 SectionFilterIterator(FilterPredicate P,
188 llvm::object::section_iterator const &I,
189 llvm::object::section_iterator const &E)
190 : Predicate(P), Iterator(I), End(E) {
193 llvm::object::SectionRef operator*() const { return *Iterator; }
194 SectionFilterIterator &operator++() {
199 bool operator!=(SectionFilterIterator const &Other) const {
200 return Iterator != Other.Iterator;
204 void ScanPredicate() {
205 while (Iterator != End && !Predicate(*Iterator)) {
209 FilterPredicate Predicate;
210 llvm::object::section_iterator Iterator;
211 llvm::object::section_iterator End;
214 class SectionFilter {
216 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
217 : Predicate(P), Object(O) {}
218 SectionFilterIterator begin() {
219 return SectionFilterIterator(Predicate, Object.section_begin(),
220 Object.section_end());
222 SectionFilterIterator end() {
223 return SectionFilterIterator(Predicate, Object.section_end(),
224 Object.section_end());
228 FilterPredicate Predicate;
229 llvm::object::ObjectFile const &Object;
231 SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
232 return SectionFilter([](llvm::object::SectionRef const &S) {
233 if(FilterSections.empty())
235 llvm::StringRef String;
236 std::error_code error = S.getName(String);
239 return std::find(FilterSections.begin(),
240 FilterSections.end(),
241 String) != FilterSections.end();
247 bool llvm::error(std::error_code EC) {
251 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
253 ReturnValue = EXIT_FAILURE;
257 static void report_error(StringRef File, std::error_code EC) {
259 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
260 ReturnValue = EXIT_FAILURE;
263 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
264 // Figure out the target triple.
265 llvm::Triple TheTriple("unknown-unknown-unknown");
266 if (TripleName.empty()) {
268 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
269 // TheTriple defaults to ELF, and COFF doesn't have an environment:
270 // the best we can do here is indicate that it is mach-o.
272 TheTriple.setObjectFormat(Triple::MachO);
275 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
276 if (COFFObj->getArch() == Triple::thumb)
277 TheTriple.setTriple("thumbv7-windows");
281 TheTriple.setTriple(Triple::normalize(TripleName));
283 // Get the target specific parser.
285 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
288 errs() << ToolName << ": " << Error;
292 // Update the triple name and return the found target.
293 TripleName = TheTriple.getTriple();
297 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
298 return a.getOffset() < b.getOffset();
302 class PrettyPrinter {
304 virtual ~PrettyPrinter(){}
305 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
306 ArrayRef<uint8_t> Bytes, uint64_t Address,
307 raw_ostream &OS, StringRef Annot,
308 MCSubtargetInfo const &STI) {
309 outs() << format("%8" PRIx64 ":", Address);
310 if (!NoShowRawInsn) {
312 dumpBytes(Bytes, outs());
314 IP.printInst(MI, outs(), "", STI);
317 PrettyPrinter PrettyPrinterInst;
318 class HexagonPrettyPrinter : public PrettyPrinter {
320 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
323 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
324 OS << format("%8" PRIx64 ":", Address);
325 if (!NoShowRawInsn) {
327 dumpBytes(Bytes.slice(0, 4), OS);
328 OS << format("%08" PRIx32, opcode);
331 void printInst(MCInstPrinter &IP, const MCInst *MI,
332 ArrayRef<uint8_t> Bytes, uint64_t Address,
333 raw_ostream &OS, StringRef Annot,
334 MCSubtargetInfo const &STI) override {
337 raw_string_ostream TempStream(Buffer);
338 IP.printInst(MI, TempStream, "", STI);
340 StringRef Contents(Buffer);
341 // Split off bundle attributes
342 auto PacketBundle = Contents.rsplit('\n');
343 // Split off first instruction from the rest
344 auto HeadTail = PacketBundle.first.split('\n');
345 auto Preamble = " { ";
347 while(!HeadTail.first.empty()) {
350 printLead(Bytes, Address, OS);
354 auto Duplex = HeadTail.first.split('\v');
355 if(!Duplex.second.empty()){
358 Inst = Duplex.second;
361 Inst = HeadTail.first;
363 Bytes = Bytes.slice(4);
365 HeadTail = HeadTail.second.split('\n');
367 OS << " } " << PacketBundle.second;
370 HexagonPrettyPrinter HexagonPrettyPrinterInst;
371 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
372 switch(Triple.getArch()) {
374 return PrettyPrinterInst;
375 case Triple::hexagon:
376 return HexagonPrettyPrinterInst;
381 template <class ELFT>
382 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
384 SmallVectorImpl<char> &Result) {
385 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
386 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
387 typedef typename ELFObjectFile<ELFT>::Elf_Rel Elf_Rel;
388 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
390 const ELFFile<ELFT> &EF = *Obj->getELFFile();
392 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
393 if (std::error_code EC = SecOrErr.getError())
395 const Elf_Shdr *Sec = *SecOrErr;
396 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
397 if (std::error_code EC = SymTabOrErr.getError())
399 const Elf_Shdr *SymTab = *SymTabOrErr;
400 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
401 SymTab->sh_type == ELF::SHT_DYNSYM);
402 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
403 if (std::error_code EC = StrTabSec.getError())
405 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
406 if (std::error_code EC = StrTabOrErr.getError())
408 StringRef StrTab = *StrTabOrErr;
412 uint16_t symbol_index = 0;
413 switch (Sec->sh_type) {
415 return object_error::parse_failed;
417 const Elf_Rel *ERel = Obj->getRel(Rel);
418 type = ERel->getType(EF.isMips64EL());
419 symbol_index = ERel->getSymbol(EF.isMips64EL());
420 // TODO: Read implicit addend from section data.
423 case ELF::SHT_RELA: {
424 const Elf_Rela *ERela = Obj->getRela(Rel);
425 type = ERela->getType(EF.isMips64EL());
426 symbol_index = ERela->getSymbol(EF.isMips64EL());
427 addend = ERela->r_addend;
431 const Elf_Sym *symb =
432 EF.template getEntry<Elf_Sym>(Sec->sh_link, symbol_index);
434 ErrorOr<const Elf_Shdr *> SymSec = EF.getSection(symb);
435 if (std::error_code EC = SymSec.getError())
437 if (symb->getType() == ELF::STT_SECTION) {
438 ErrorOr<StringRef> SecName = EF.getSectionName(*SymSec);
439 if (std::error_code EC = SecName.getError())
443 ErrorOr<StringRef> SymName = symb->getName(StrTab);
445 return SymName.getError();
448 switch (EF.getHeader()->e_machine) {
451 case ELF::R_X86_64_PC8:
452 case ELF::R_X86_64_PC16:
453 case ELF::R_X86_64_PC32: {
455 raw_string_ostream fmt(fmtbuf);
456 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
458 Result.append(fmtbuf.begin(), fmtbuf.end());
460 case ELF::R_X86_64_8:
461 case ELF::R_X86_64_16:
462 case ELF::R_X86_64_32:
463 case ELF::R_X86_64_32S:
464 case ELF::R_X86_64_64: {
466 raw_string_ostream fmt(fmtbuf);
467 fmt << Target << (addend < 0 ? "" : "+") << addend;
469 Result.append(fmtbuf.begin(), fmtbuf.end());
475 case ELF::EM_AARCH64: {
477 raw_string_ostream fmt(fmtbuf);
480 fmt << (addend < 0 ? "" : "+") << addend;
482 Result.append(fmtbuf.begin(), fmtbuf.end());
487 case ELF::EM_HEXAGON:
495 Result.append(res.begin(), res.end());
496 return std::error_code();
499 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
500 const RelocationRef &RelRef,
501 SmallVectorImpl<char> &Result) {
502 DataRefImpl Rel = RelRef.getRawDataRefImpl();
503 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
504 return getRelocationValueString(ELF32LE, Rel, Result);
505 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
506 return getRelocationValueString(ELF64LE, Rel, Result);
507 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
508 return getRelocationValueString(ELF32BE, Rel, Result);
509 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
510 return getRelocationValueString(ELF64BE, Rel, Result);
513 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
514 const RelocationRef &Rel,
515 SmallVectorImpl<char> &Result) {
516 symbol_iterator SymI = Rel.getSymbol();
517 ErrorOr<StringRef> SymNameOrErr = SymI->getName();
518 if (std::error_code EC = SymNameOrErr.getError())
520 StringRef SymName = *SymNameOrErr;
521 Result.append(SymName.begin(), SymName.end());
522 return std::error_code();
525 static void printRelocationTargetName(const MachOObjectFile *O,
526 const MachO::any_relocation_info &RE,
527 raw_string_ostream &fmt) {
528 bool IsScattered = O->isRelocationScattered(RE);
530 // Target of a scattered relocation is an address. In the interest of
531 // generating pretty output, scan through the symbol table looking for a
532 // symbol that aligns with that address. If we find one, print it.
533 // Otherwise, we just print the hex address of the target.
535 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
537 for (const SymbolRef &Symbol : O->symbols()) {
539 ErrorOr<uint64_t> Addr = Symbol.getAddress();
540 if ((ec = Addr.getError()))
541 report_fatal_error(ec.message());
544 ErrorOr<StringRef> Name = Symbol.getName();
545 if (std::error_code EC = Name.getError())
546 report_fatal_error(EC.message());
551 // If we couldn't find a symbol that this relocation refers to, try
552 // to find a section beginning instead.
553 for (const SectionRef &Section : ToolSectionFilter(*O)) {
557 uint64_t Addr = Section.getAddress();
560 if ((ec = Section.getName(Name)))
561 report_fatal_error(ec.message());
566 fmt << format("0x%x", Val);
571 bool isExtern = O->getPlainRelocationExternal(RE);
572 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
575 symbol_iterator SI = O->symbol_begin();
577 ErrorOr<StringRef> SOrErr = SI->getName();
578 if (!error(SOrErr.getError()))
581 section_iterator SI = O->section_begin();
582 // Adjust for the fact that sections are 1-indexed.
583 advance(SI, Val - 1);
590 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
591 const RelocationRef &RelRef,
592 SmallVectorImpl<char> &Result) {
593 DataRefImpl Rel = RelRef.getRawDataRefImpl();
594 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
596 unsigned Arch = Obj->getArch();
599 raw_string_ostream fmt(fmtbuf);
600 unsigned Type = Obj->getAnyRelocationType(RE);
601 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
603 // Determine any addends that should be displayed with the relocation.
604 // These require decoding the relocation type, which is triple-specific.
606 // X86_64 has entirely custom relocation types.
607 if (Arch == Triple::x86_64) {
608 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
611 case MachO::X86_64_RELOC_GOT_LOAD:
612 case MachO::X86_64_RELOC_GOT: {
613 printRelocationTargetName(Obj, RE, fmt);
619 case MachO::X86_64_RELOC_SUBTRACTOR: {
620 DataRefImpl RelNext = Rel;
621 Obj->moveRelocationNext(RelNext);
622 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
624 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
625 // X86_64_RELOC_UNSIGNED.
626 // NOTE: Scattered relocations don't exist on x86_64.
627 unsigned RType = Obj->getAnyRelocationType(RENext);
628 if (RType != MachO::X86_64_RELOC_UNSIGNED)
629 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
630 "X86_64_RELOC_SUBTRACTOR.");
632 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
633 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
634 printRelocationTargetName(Obj, RENext, fmt);
636 printRelocationTargetName(Obj, RE, fmt);
639 case MachO::X86_64_RELOC_TLV:
640 printRelocationTargetName(Obj, RE, fmt);
645 case MachO::X86_64_RELOC_SIGNED_1:
646 printRelocationTargetName(Obj, RE, fmt);
649 case MachO::X86_64_RELOC_SIGNED_2:
650 printRelocationTargetName(Obj, RE, fmt);
653 case MachO::X86_64_RELOC_SIGNED_4:
654 printRelocationTargetName(Obj, RE, fmt);
658 printRelocationTargetName(Obj, RE, fmt);
661 // X86 and ARM share some relocation types in common.
662 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
663 Arch == Triple::ppc) {
664 // Generic relocation types...
666 case MachO::GENERIC_RELOC_PAIR: // prints no info
667 return std::error_code();
668 case MachO::GENERIC_RELOC_SECTDIFF: {
669 DataRefImpl RelNext = Rel;
670 Obj->moveRelocationNext(RelNext);
671 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
673 // X86 sect diff's must be followed by a relocation of type
674 // GENERIC_RELOC_PAIR.
675 unsigned RType = Obj->getAnyRelocationType(RENext);
677 if (RType != MachO::GENERIC_RELOC_PAIR)
678 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
679 "GENERIC_RELOC_SECTDIFF.");
681 printRelocationTargetName(Obj, RE, fmt);
683 printRelocationTargetName(Obj, RENext, fmt);
688 if (Arch == Triple::x86 || Arch == Triple::ppc) {
690 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
691 DataRefImpl RelNext = Rel;
692 Obj->moveRelocationNext(RelNext);
693 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
695 // X86 sect diff's must be followed by a relocation of type
696 // GENERIC_RELOC_PAIR.
697 unsigned RType = Obj->getAnyRelocationType(RENext);
698 if (RType != MachO::GENERIC_RELOC_PAIR)
699 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
700 "GENERIC_RELOC_LOCAL_SECTDIFF.");
702 printRelocationTargetName(Obj, RE, fmt);
704 printRelocationTargetName(Obj, RENext, fmt);
707 case MachO::GENERIC_RELOC_TLV: {
708 printRelocationTargetName(Obj, RE, fmt);
715 printRelocationTargetName(Obj, RE, fmt);
717 } else { // ARM-specific relocations
719 case MachO::ARM_RELOC_HALF:
720 case MachO::ARM_RELOC_HALF_SECTDIFF: {
721 // Half relocations steal a bit from the length field to encode
722 // whether this is an upper16 or a lower16 relocation.
723 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
729 printRelocationTargetName(Obj, RE, fmt);
731 DataRefImpl RelNext = Rel;
732 Obj->moveRelocationNext(RelNext);
733 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
735 // ARM half relocs must be followed by a relocation of type
737 unsigned RType = Obj->getAnyRelocationType(RENext);
738 if (RType != MachO::ARM_RELOC_PAIR)
739 report_fatal_error("Expected ARM_RELOC_PAIR after "
742 // NOTE: The half of the target virtual address is stashed in the
743 // address field of the secondary relocation, but we can't reverse
744 // engineer the constant offset from it without decoding the movw/movt
745 // instruction to find the other half in its immediate field.
747 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
748 // symbol/section pointer of the follow-on relocation.
749 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
751 printRelocationTargetName(Obj, RENext, fmt);
757 default: { printRelocationTargetName(Obj, RE, fmt); }
761 printRelocationTargetName(Obj, RE, fmt);
764 Result.append(fmtbuf.begin(), fmtbuf.end());
765 return std::error_code();
768 static std::error_code getRelocationValueString(const RelocationRef &Rel,
769 SmallVectorImpl<char> &Result) {
770 const ObjectFile *Obj = Rel.getObject();
771 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
772 return getRelocationValueString(ELF, Rel, Result);
773 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
774 return getRelocationValueString(COFF, Rel, Result);
775 auto *MachO = cast<MachOObjectFile>(Obj);
776 return getRelocationValueString(MachO, Rel, Result);
779 /// @brief Indicates whether this relocation should hidden when listing
780 /// relocations, usually because it is the trailing part of a multipart
781 /// relocation that will be printed as part of the leading relocation.
782 static bool getHidden(RelocationRef RelRef) {
783 const ObjectFile *Obj = RelRef.getObject();
784 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
788 unsigned Arch = MachO->getArch();
789 DataRefImpl Rel = RelRef.getRawDataRefImpl();
790 uint64_t Type = MachO->getRelocationType(Rel);
792 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
794 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
795 if (Type == MachO::GENERIC_RELOC_PAIR)
797 } else if (Arch == Triple::x86_64) {
798 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
799 // an X86_64_RELOC_SUBTRACTOR.
800 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
801 DataRefImpl RelPrev = Rel;
803 uint64_t PrevType = MachO->getRelocationType(RelPrev);
804 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
812 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
813 const Target *TheTarget = getTarget(Obj);
814 // getTarget() will have already issued a diagnostic if necessary, so
815 // just bail here if it failed.
819 // Package up features to be passed to target/subtarget
820 std::string FeaturesStr;
822 SubtargetFeatures Features;
823 for (unsigned i = 0; i != MAttrs.size(); ++i)
824 Features.AddFeature(MAttrs[i]);
825 FeaturesStr = Features.getString();
828 std::unique_ptr<const MCRegisterInfo> MRI(
829 TheTarget->createMCRegInfo(TripleName));
831 errs() << "error: no register info for target " << TripleName << "\n";
835 // Set up disassembler.
836 std::unique_ptr<const MCAsmInfo> AsmInfo(
837 TheTarget->createMCAsmInfo(*MRI, TripleName));
839 errs() << "error: no assembly info for target " << TripleName << "\n";
843 std::unique_ptr<const MCSubtargetInfo> STI(
844 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
846 errs() << "error: no subtarget info for target " << TripleName << "\n";
850 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
852 errs() << "error: no instruction info for target " << TripleName << "\n";
856 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
857 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
859 std::unique_ptr<MCDisassembler> DisAsm(
860 TheTarget->createMCDisassembler(*STI, Ctx));
863 errs() << "error: no disassembler for target " << TripleName << "\n";
867 std::unique_ptr<const MCInstrAnalysis> MIA(
868 TheTarget->createMCInstrAnalysis(MII.get()));
870 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
871 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
872 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
874 errs() << "error: no instruction printer for target " << TripleName
878 IP->setPrintImmHex(PrintImmHex);
879 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
881 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
882 "\t\t\t%08" PRIx64 ": ";
884 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
885 // in RelocSecs contain the relocations for section S.
887 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
888 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
889 section_iterator Sec2 = Section.getRelocatedSection();
890 if (Sec2 != Obj->section_end())
891 SectionRelocMap[*Sec2].push_back(Section);
894 // Create a mapping from virtual address to symbol name. This is used to
895 // pretty print the target of a call.
896 std::vector<std::pair<uint64_t, StringRef>> AllSymbols;
898 for (const SymbolRef &Symbol : Obj->symbols()) {
899 if (Symbol.getType() != SymbolRef::ST_Function)
902 ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
903 if (error(AddressOrErr.getError()))
905 uint64_t Address = *AddressOrErr;
907 ErrorOr<StringRef> Name = Symbol.getName();
908 if (error(Name.getError()))
912 AllSymbols.push_back(std::make_pair(Address, *Name));
915 array_pod_sort(AllSymbols.begin(), AllSymbols.end());
918 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
919 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
922 uint64_t SectionAddr = Section.getAddress();
923 uint64_t SectSize = Section.getSize();
927 // Make a list of all the symbols in this section.
928 std::vector<std::pair<uint64_t, StringRef>> Symbols;
929 for (const SymbolRef &Symbol : Obj->symbols()) {
930 if (Section.containsSymbol(Symbol)) {
931 ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
932 if (error(AddressOrErr.getError()))
934 uint64_t Address = *AddressOrErr;
935 Address -= SectionAddr;
936 if (Address >= SectSize)
939 ErrorOr<StringRef> Name = Symbol.getName();
940 if (error(Name.getError()))
942 Symbols.push_back(std::make_pair(Address, *Name));
946 // Sort the symbols by address, just in case they didn't come in that way.
947 array_pod_sort(Symbols.begin(), Symbols.end());
949 // Make a list of all the relocations for this section.
950 std::vector<RelocationRef> Rels;
952 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
953 for (const RelocationRef &Reloc : RelocSec.relocations()) {
954 Rels.push_back(Reloc);
959 // Sort relocations by address.
960 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
962 StringRef SegmentName = "";
963 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
964 DataRefImpl DR = Section.getRawDataRefImpl();
965 SegmentName = MachO->getSectionFinalSegmentName(DR);
968 if (error(Section.getName(name)))
970 outs() << "Disassembly of section ";
971 if (!SegmentName.empty())
972 outs() << SegmentName << ",";
973 outs() << name << ':';
975 // If the section has no symbol at the start, just insert a dummy one.
976 if (Symbols.empty() || Symbols[0].first != 0)
977 Symbols.insert(Symbols.begin(), std::make_pair(0, name));
979 SmallString<40> Comments;
980 raw_svector_ostream CommentStream(Comments);
983 if (error(Section.getContents(BytesStr)))
985 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
991 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
992 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
993 // Disassemble symbol by symbol.
994 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
996 uint64_t Start = Symbols[si].first;
997 // The end is either the section end or the beginning of the next symbol.
998 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
999 // If this symbol has the same address as the next symbol, then skip it.
1003 outs() << '\n' << Symbols[si].second << ":\n";
1006 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1008 raw_ostream &DebugOut = nulls();
1011 for (Index = Start; Index < End; Index += Size) {
1014 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1015 SectionAddr + Index, DebugOut,
1017 PIP.printInst(*IP, &Inst,
1018 Bytes.slice(Index, Size),
1019 SectionAddr + Index, outs(), "", *STI);
1020 outs() << CommentStream.str();
1022 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1023 MIA->isConditionalBranch(Inst))) {
1025 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1026 auto TargetSym = std::upper_bound(
1027 AllSymbols.begin(), AllSymbols.end(), Target,
1028 [](uint64_t LHS, const std::pair<uint64_t, StringRef> &RHS) {
1029 return LHS < RHS.first;
1031 if (TargetSym != AllSymbols.begin())
1034 TargetSym = AllSymbols.end();
1036 if (TargetSym != AllSymbols.end()) {
1037 outs() << " <" << TargetSym->second;
1038 uint64_t Disp = Target - TargetSym->first;
1040 outs() << '+' << utohexstr(Disp);
1047 errs() << ToolName << ": warning: invalid instruction encoding\n";
1049 Size = 1; // skip illegible bytes
1052 // Print relocation for instruction.
1053 while (rel_cur != rel_end) {
1054 bool hidden = getHidden(*rel_cur);
1055 uint64_t addr = rel_cur->getOffset();
1056 SmallString<16> name;
1057 SmallString<32> val;
1059 // If this relocation is hidden, skip it.
1060 if (hidden) goto skip_print_rel;
1062 // Stop when rel_cur's address is past the current instruction.
1063 if (addr >= Index + Size) break;
1064 rel_cur->getTypeName(name);
1065 if (error(getRelocationValueString(*rel_cur, val)))
1066 goto skip_print_rel;
1067 outs() << format(Fmt.data(), SectionAddr + addr) << name
1068 << "\t" << val << "\n";
1078 void llvm::PrintRelocations(const ObjectFile *Obj) {
1079 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1081 // Regular objdump doesn't print relocations in non-relocatable object
1083 if (!Obj->isRelocatableObject())
1086 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1087 if (Section.relocation_begin() == Section.relocation_end())
1090 if (error(Section.getName(secname)))
1092 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
1093 for (const RelocationRef &Reloc : Section.relocations()) {
1094 bool hidden = getHidden(Reloc);
1095 uint64_t address = Reloc.getOffset();
1096 SmallString<32> relocname;
1097 SmallString<32> valuestr;
1100 Reloc.getTypeName(relocname);
1101 if (error(getRelocationValueString(Reloc, valuestr)))
1103 outs() << format(Fmt.data(), address) << " " << relocname << " "
1104 << valuestr << "\n";
1110 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
1111 outs() << "Sections:\n"
1112 "Idx Name Size Address Type\n";
1114 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1116 if (error(Section.getName(Name)))
1118 uint64_t Address = Section.getAddress();
1119 uint64_t Size = Section.getSize();
1120 bool Text = Section.isText();
1121 bool Data = Section.isData();
1122 bool BSS = Section.isBSS();
1123 std::string Type = (std::string(Text ? "TEXT " : "") +
1124 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1125 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1126 Name.str().c_str(), Size, Address, Type.c_str());
1131 void llvm::PrintSectionContents(const ObjectFile *Obj) {
1133 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1136 if (error(Section.getName(Name)))
1138 uint64_t BaseAddr = Section.getAddress();
1139 uint64_t Size = Section.getSize();
1143 outs() << "Contents of section " << Name << ":\n";
1144 if (Section.isBSS()) {
1145 outs() << format("<skipping contents of bss section at [%04" PRIx64
1146 ", %04" PRIx64 ")>\n",
1147 BaseAddr, BaseAddr + Size);
1151 if (error(Section.getContents(Contents)))
1154 // Dump out the content as hex and printable ascii characters.
1155 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1156 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1157 // Dump line of hex.
1158 for (std::size_t i = 0; i < 16; ++i) {
1159 if (i != 0 && i % 4 == 0)
1162 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1163 << hexdigit(Contents[addr + i] & 0xF, true);
1169 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1170 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1171 outs() << Contents[addr + i];
1180 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
1181 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1182 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
1184 if (error(Symbol.getError()))
1187 if (error(coff->getSymbolName(*Symbol, Name)))
1190 outs() << "[" << format("%2d", SI) << "]"
1191 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
1192 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
1193 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1194 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1195 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1196 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
1199 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
1200 if (Symbol->isSectionDefinition()) {
1201 const coff_aux_section_definition *asd;
1202 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
1205 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1208 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1209 , unsigned(asd->Length)
1210 , unsigned(asd->NumberOfRelocations)
1211 , unsigned(asd->NumberOfLinenumbers)
1212 , unsigned(asd->CheckSum))
1213 << format("assoc %d comdat %d\n"
1214 , unsigned(AuxNumber)
1215 , unsigned(asd->Selection));
1216 } else if (Symbol->isFileRecord()) {
1217 const char *FileName;
1218 if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
1221 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1222 coff->getSymbolTableEntrySize());
1223 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
1225 SI = SI + Symbol->getNumberOfAuxSymbols();
1228 outs() << "AUX Unknown\n";
1234 void llvm::PrintSymbolTable(const ObjectFile *o) {
1235 outs() << "SYMBOL TABLE:\n";
1237 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1238 PrintCOFFSymbolTable(coff);
1241 for (const SymbolRef &Symbol : o->symbols()) {
1242 ErrorOr<uint64_t> AddressOrError = Symbol.getAddress();
1243 if (error(AddressOrError.getError()))
1245 uint64_t Address = *AddressOrError;
1246 SymbolRef::Type Type = Symbol.getType();
1247 uint32_t Flags = Symbol.getFlags();
1248 section_iterator Section = o->section_end();
1249 if (error(Symbol.getSection(Section)))
1252 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1253 Section->getName(Name);
1255 ErrorOr<StringRef> NameOrErr = Symbol.getName();
1256 if (error(NameOrErr.getError()))
1261 bool Global = Flags & SymbolRef::SF_Global;
1262 bool Weak = Flags & SymbolRef::SF_Weak;
1263 bool Absolute = Flags & SymbolRef::SF_Absolute;
1264 bool Common = Flags & SymbolRef::SF_Common;
1265 bool Hidden = Flags & SymbolRef::SF_Hidden;
1268 if (Type != SymbolRef::ST_Unknown)
1269 GlobLoc = Global ? 'g' : 'l';
1270 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1272 char FileFunc = ' ';
1273 if (Type == SymbolRef::ST_File)
1275 else if (Type == SymbolRef::ST_Function)
1278 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1281 outs() << format(Fmt, Address) << " "
1282 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1283 << (Weak ? 'w' : ' ') // Weak?
1284 << ' ' // Constructor. Not supported yet.
1285 << ' ' // Warning. Not supported yet.
1286 << ' ' // Indirect reference to another symbol.
1287 << Debug // Debugging (d) or dynamic (D) symbol.
1288 << FileFunc // Name of function (F), file (f) or object (O).
1292 } else if (Common) {
1294 } else if (Section == o->section_end()) {
1297 if (const MachOObjectFile *MachO =
1298 dyn_cast<const MachOObjectFile>(o)) {
1299 DataRefImpl DR = Section->getRawDataRefImpl();
1300 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1301 outs() << SegmentName << ",";
1303 StringRef SectionName;
1304 if (error(Section->getName(SectionName)))
1306 outs() << SectionName;
1310 if (Common || isa<ELFObjectFileBase>(o)) {
1312 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1313 outs() << format("\t %08" PRIx64 " ", Val);
1317 outs() << ".hidden ";
1324 static void PrintUnwindInfo(const ObjectFile *o) {
1325 outs() << "Unwind info:\n\n";
1327 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1328 printCOFFUnwindInfo(coff);
1329 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1330 printMachOUnwindInfo(MachO);
1332 // TODO: Extract DWARF dump tool to objdump.
1333 errs() << "This operation is only currently supported "
1334 "for COFF and MachO object files.\n";
1339 void llvm::printExportsTrie(const ObjectFile *o) {
1340 outs() << "Exports trie:\n";
1341 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1342 printMachOExportsTrie(MachO);
1344 errs() << "This operation is only currently supported "
1345 "for Mach-O executable files.\n";
1350 void llvm::printRebaseTable(const ObjectFile *o) {
1351 outs() << "Rebase table:\n";
1352 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1353 printMachORebaseTable(MachO);
1355 errs() << "This operation is only currently supported "
1356 "for Mach-O executable files.\n";
1361 void llvm::printBindTable(const ObjectFile *o) {
1362 outs() << "Bind table:\n";
1363 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1364 printMachOBindTable(MachO);
1366 errs() << "This operation is only currently supported "
1367 "for Mach-O executable files.\n";
1372 void llvm::printLazyBindTable(const ObjectFile *o) {
1373 outs() << "Lazy bind table:\n";
1374 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1375 printMachOLazyBindTable(MachO);
1377 errs() << "This operation is only currently supported "
1378 "for Mach-O executable files.\n";
1383 void llvm::printWeakBindTable(const ObjectFile *o) {
1384 outs() << "Weak bind table:\n";
1385 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1386 printMachOWeakBindTable(MachO);
1388 errs() << "This operation is only currently supported "
1389 "for Mach-O executable files.\n";
1394 /// Dump the raw contents of the __clangast section so the output can be piped
1395 /// into llvm-bcanalyzer.
1396 void llvm::printRawClangAST(const ObjectFile *Obj) {
1397 if (outs().is_displayed()) {
1398 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1399 "the clang ast section.\n"
1400 "Please redirect the output to a file or another program such as "
1401 "llvm-bcanalyzer.\n";
1405 StringRef ClangASTSectionName("__clangast");
1406 if (isa<COFFObjectFile>(Obj)) {
1407 ClangASTSectionName = "clangast";
1410 Optional<object::SectionRef> ClangASTSection;
1411 for (auto Sec : ToolSectionFilter(*Obj)) {
1414 if (Name == ClangASTSectionName) {
1415 ClangASTSection = Sec;
1419 if (!ClangASTSection)
1422 StringRef ClangASTContents;
1423 if (error(ClangASTSection.getValue().getContents(ClangASTContents))) {
1424 errs() << "Could not read the " << ClangASTSectionName << " section!\n";
1428 outs().write(ClangASTContents.data(), ClangASTContents.size());
1431 static void printFaultMaps(const ObjectFile *Obj) {
1432 const char *FaultMapSectionName = nullptr;
1434 if (isa<ELFObjectFileBase>(Obj)) {
1435 FaultMapSectionName = ".llvm_faultmaps";
1436 } else if (isa<MachOObjectFile>(Obj)) {
1437 FaultMapSectionName = "__llvm_faultmaps";
1439 errs() << "This operation is only currently supported "
1440 "for ELF and Mach-O executable files.\n";
1444 Optional<object::SectionRef> FaultMapSection;
1446 for (auto Sec : ToolSectionFilter(*Obj)) {
1449 if (Name == FaultMapSectionName) {
1450 FaultMapSection = Sec;
1455 outs() << "FaultMap table:\n";
1457 if (!FaultMapSection.hasValue()) {
1458 outs() << "<not found>\n";
1462 StringRef FaultMapContents;
1463 if (error(FaultMapSection.getValue().getContents(FaultMapContents))) {
1464 errs() << "Could not read the " << FaultMapContents << " section!\n";
1468 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1469 FaultMapContents.bytes_end());
1474 static void printPrivateFileHeader(const ObjectFile *o) {
1476 printELFFileHeader(o);
1477 } else if (o->isCOFF()) {
1478 printCOFFFileHeader(o);
1479 } else if (o->isMachO()) {
1480 printMachOFileHeader(o);
1484 static void DumpObject(const ObjectFile *o) {
1485 // Avoid other output when using a raw option.
1488 outs() << o->getFileName()
1489 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1493 DisassembleObject(o, Relocations);
1494 if (Relocations && !Disassemble)
1495 PrintRelocations(o);
1497 PrintSectionHeaders(o);
1498 if (SectionContents)
1499 PrintSectionContents(o);
1501 PrintSymbolTable(o);
1505 printPrivateFileHeader(o);
1507 printExportsTrie(o);
1509 printRebaseTable(o);
1513 printLazyBindTable(o);
1515 printWeakBindTable(o);
1517 printRawClangAST(o);
1522 /// @brief Dump each object file in \a a;
1523 static void DumpArchive(const Archive *a) {
1524 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
1526 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
1527 if (std::error_code EC = ChildOrErr.getError()) {
1528 // Ignore non-object files.
1529 if (EC != object_error::invalid_file_type)
1530 report_error(a->getFileName(), EC);
1533 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
1536 report_error(a->getFileName(), object_error::invalid_file_type);
1540 /// @brief Open file and figure out how to dump it.
1541 static void DumpInput(StringRef file) {
1542 // If file isn't stdin, check that it exists.
1543 if (file != "-" && !sys::fs::exists(file)) {
1544 report_error(file, errc::no_such_file_or_directory);
1548 // If we are using the Mach-O specific object file parser, then let it parse
1549 // the file and process the command line options. So the -arch flags can
1550 // be used to select specific slices, etc.
1552 ParseInputMachO(file);
1556 // Attempt to open the binary.
1557 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1558 if (std::error_code EC = BinaryOrErr.getError()) {
1559 report_error(file, EC);
1562 Binary &Binary = *BinaryOrErr.get().getBinary();
1564 if (Archive *a = dyn_cast<Archive>(&Binary))
1566 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
1569 report_error(file, object_error::invalid_file_type);
1572 int main(int argc, char **argv) {
1573 // Print a stack trace if we signal out.
1574 sys::PrintStackTraceOnErrorSignal();
1575 PrettyStackTraceProgram X(argc, argv);
1576 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1578 // Initialize targets and assembly printers/parsers.
1579 llvm::InitializeAllTargetInfos();
1580 llvm::InitializeAllTargetMCs();
1581 llvm::InitializeAllAsmParsers();
1582 llvm::InitializeAllDisassemblers();
1584 // Register the target printer for --version.
1585 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1587 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1588 TripleName = Triple::normalize(TripleName);
1592 // Defaults to a.out if no filenames specified.
1593 if (InputFilenames.size() == 0)
1594 InputFilenames.push_back("a.out");
1611 && !(UniversalHeaders && MachOOpt)
1612 && !(ArchiveHeaders && MachOOpt)
1613 && !(IndirectSymbols && MachOOpt)
1614 && !(DataInCode && MachOOpt)
1615 && !(LinkOptHints && MachOOpt)
1616 && !(InfoPlist && MachOOpt)
1617 && !(DylibsUsed && MachOOpt)
1618 && !(DylibId && MachOOpt)
1619 && !(ObjcMetaData && MachOOpt)
1620 && !(FilterSections.size() != 0 && MachOOpt)
1621 && !PrintFaultMaps) {
1622 cl::PrintHelpMessage();
1626 std::for_each(InputFilenames.begin(), InputFilenames.end(),