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;
182 typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
184 class SectionFilterIterator {
186 SectionFilterIterator(FilterPredicate P,
187 llvm::object::section_iterator const &I,
188 llvm::object::section_iterator const &E)
189 : Predicate(P), Iterator(I), End(E) {
192 const llvm::object::SectionRef &operator*() const { return *Iterator; }
193 SectionFilterIterator &operator++() {
198 bool operator!=(SectionFilterIterator const &Other) const {
199 return Iterator != Other.Iterator;
203 void ScanPredicate() {
204 while (Iterator != End && !Predicate(*Iterator)) {
208 FilterPredicate Predicate;
209 llvm::object::section_iterator Iterator;
210 llvm::object::section_iterator End;
213 class SectionFilter {
215 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
216 : Predicate(P), Object(O) {}
217 SectionFilterIterator begin() {
218 return SectionFilterIterator(Predicate, Object.section_begin(),
219 Object.section_end());
221 SectionFilterIterator end() {
222 return SectionFilterIterator(Predicate, Object.section_end(),
223 Object.section_end());
227 FilterPredicate Predicate;
228 llvm::object::ObjectFile const &Object;
230 SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
231 return SectionFilter([](llvm::object::SectionRef const &S) {
232 if(FilterSections.empty())
234 llvm::StringRef String;
235 std::error_code error = S.getName(String);
238 return std::find(FilterSections.begin(),
239 FilterSections.end(),
240 String) != FilterSections.end();
246 void llvm::error(std::error_code EC) {
250 errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
255 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
256 std::error_code EC) {
258 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
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 report_fatal_error("can't find target: " + Error);
289 // Update the triple name and return the found target.
290 TripleName = TheTriple.getTriple();
294 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
295 return a.getOffset() < b.getOffset();
299 class PrettyPrinter {
301 virtual ~PrettyPrinter(){}
302 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
303 ArrayRef<uint8_t> Bytes, uint64_t Address,
304 raw_ostream &OS, StringRef Annot,
305 MCSubtargetInfo const &STI) {
306 outs() << format("%8" PRIx64 ":", Address);
307 if (!NoShowRawInsn) {
309 dumpBytes(Bytes, outs());
311 IP.printInst(MI, outs(), "", STI);
314 PrettyPrinter PrettyPrinterInst;
315 class HexagonPrettyPrinter : public PrettyPrinter {
317 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
320 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
321 OS << format("%8" PRIx64 ":", Address);
322 if (!NoShowRawInsn) {
324 dumpBytes(Bytes.slice(0, 4), OS);
325 OS << format("%08" PRIx32, opcode);
328 void printInst(MCInstPrinter &IP, const MCInst *MI,
329 ArrayRef<uint8_t> Bytes, uint64_t Address,
330 raw_ostream &OS, StringRef Annot,
331 MCSubtargetInfo const &STI) override {
334 raw_string_ostream TempStream(Buffer);
335 IP.printInst(MI, TempStream, "", STI);
337 StringRef Contents(Buffer);
338 // Split off bundle attributes
339 auto PacketBundle = Contents.rsplit('\n');
340 // Split off first instruction from the rest
341 auto HeadTail = PacketBundle.first.split('\n');
342 auto Preamble = " { ";
344 while(!HeadTail.first.empty()) {
347 printLead(Bytes, Address, OS);
351 auto Duplex = HeadTail.first.split('\v');
352 if(!Duplex.second.empty()){
355 Inst = Duplex.second;
358 Inst = HeadTail.first;
360 Bytes = Bytes.slice(4);
362 HeadTail = HeadTail.second.split('\n');
364 OS << " } " << PacketBundle.second;
367 HexagonPrettyPrinter HexagonPrettyPrinterInst;
368 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
369 switch(Triple.getArch()) {
371 return PrettyPrinterInst;
372 case Triple::hexagon:
373 return HexagonPrettyPrinterInst;
378 template <class ELFT>
379 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
380 const RelocationRef &RelRef,
381 SmallVectorImpl<char> &Result) {
382 DataRefImpl Rel = RelRef.getRawDataRefImpl();
384 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
385 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
386 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
388 const ELFFile<ELFT> &EF = *Obj->getELFFile();
390 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
391 if (std::error_code EC = SecOrErr.getError())
393 const Elf_Shdr *Sec = *SecOrErr;
394 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
395 if (std::error_code EC = SymTabOrErr.getError())
397 const Elf_Shdr *SymTab = *SymTabOrErr;
398 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
399 SymTab->sh_type == ELF::SHT_DYNSYM);
400 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
401 if (std::error_code EC = StrTabSec.getError())
403 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
404 if (std::error_code EC = StrTabOrErr.getError())
406 StringRef StrTab = *StrTabOrErr;
407 uint8_t type = RelRef.getType();
410 switch (Sec->sh_type) {
412 return object_error::parse_failed;
414 // TODO: Read implicit addend from section data.
417 case ELF::SHT_RELA: {
418 const Elf_Rela *ERela = Obj->getRela(Rel);
419 addend = ERela->r_addend;
423 symbol_iterator SI = RelRef.getSymbol();
424 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
426 if (symb->getType() == ELF::STT_SECTION) {
427 ErrorOr<section_iterator> SymSI = SI->getSection();
428 if (std::error_code EC = SymSI.getError())
430 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
431 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
432 if (std::error_code EC = SecName.getError())
436 ErrorOr<StringRef> SymName = symb->getName(StrTab);
438 return SymName.getError();
441 switch (EF.getHeader()->e_machine) {
444 case ELF::R_X86_64_PC8:
445 case ELF::R_X86_64_PC16:
446 case ELF::R_X86_64_PC32: {
448 raw_string_ostream fmt(fmtbuf);
449 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
451 Result.append(fmtbuf.begin(), fmtbuf.end());
453 case ELF::R_X86_64_8:
454 case ELF::R_X86_64_16:
455 case ELF::R_X86_64_32:
456 case ELF::R_X86_64_32S:
457 case ELF::R_X86_64_64: {
459 raw_string_ostream fmt(fmtbuf);
460 fmt << Target << (addend < 0 ? "" : "+") << addend;
462 Result.append(fmtbuf.begin(), fmtbuf.end());
468 case ELF::EM_AARCH64: {
470 raw_string_ostream fmt(fmtbuf);
473 fmt << (addend < 0 ? "" : "+") << addend;
475 Result.append(fmtbuf.begin(), fmtbuf.end());
481 case ELF::EM_HEXAGON:
489 Result.append(res.begin(), res.end());
490 return std::error_code();
493 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
494 const RelocationRef &Rel,
495 SmallVectorImpl<char> &Result) {
496 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
497 return getRelocationValueString(ELF32LE, Rel, Result);
498 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
499 return getRelocationValueString(ELF64LE, Rel, Result);
500 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
501 return getRelocationValueString(ELF32BE, Rel, Result);
502 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
503 return getRelocationValueString(ELF64BE, Rel, Result);
506 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
507 const RelocationRef &Rel,
508 SmallVectorImpl<char> &Result) {
509 symbol_iterator SymI = Rel.getSymbol();
510 ErrorOr<StringRef> SymNameOrErr = SymI->getName();
511 if (std::error_code EC = SymNameOrErr.getError())
513 StringRef SymName = *SymNameOrErr;
514 Result.append(SymName.begin(), SymName.end());
515 return std::error_code();
518 static void printRelocationTargetName(const MachOObjectFile *O,
519 const MachO::any_relocation_info &RE,
520 raw_string_ostream &fmt) {
521 bool IsScattered = O->isRelocationScattered(RE);
523 // Target of a scattered relocation is an address. In the interest of
524 // generating pretty output, scan through the symbol table looking for a
525 // symbol that aligns with that address. If we find one, print it.
526 // Otherwise, we just print the hex address of the target.
528 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
530 for (const SymbolRef &Symbol : O->symbols()) {
532 ErrorOr<uint64_t> Addr = Symbol.getAddress();
533 if ((ec = Addr.getError()))
534 report_fatal_error(ec.message());
537 ErrorOr<StringRef> Name = Symbol.getName();
538 if (std::error_code EC = Name.getError())
539 report_fatal_error(EC.message());
544 // If we couldn't find a symbol that this relocation refers to, try
545 // to find a section beginning instead.
546 for (const SectionRef &Section : ToolSectionFilter(*O)) {
550 uint64_t Addr = Section.getAddress();
553 if ((ec = Section.getName(Name)))
554 report_fatal_error(ec.message());
559 fmt << format("0x%x", Val);
564 bool isExtern = O->getPlainRelocationExternal(RE);
565 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
568 symbol_iterator SI = O->symbol_begin();
570 ErrorOr<StringRef> SOrErr = SI->getName();
571 error(SOrErr.getError());
574 section_iterator SI = O->section_begin();
575 // Adjust for the fact that sections are 1-indexed.
576 advance(SI, Val - 1);
583 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
584 const RelocationRef &RelRef,
585 SmallVectorImpl<char> &Result) {
586 DataRefImpl Rel = RelRef.getRawDataRefImpl();
587 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
589 unsigned Arch = Obj->getArch();
592 raw_string_ostream fmt(fmtbuf);
593 unsigned Type = Obj->getAnyRelocationType(RE);
594 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
596 // Determine any addends that should be displayed with the relocation.
597 // These require decoding the relocation type, which is triple-specific.
599 // X86_64 has entirely custom relocation types.
600 if (Arch == Triple::x86_64) {
601 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
604 case MachO::X86_64_RELOC_GOT_LOAD:
605 case MachO::X86_64_RELOC_GOT: {
606 printRelocationTargetName(Obj, RE, fmt);
612 case MachO::X86_64_RELOC_SUBTRACTOR: {
613 DataRefImpl RelNext = Rel;
614 Obj->moveRelocationNext(RelNext);
615 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
617 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
618 // X86_64_RELOC_UNSIGNED.
619 // NOTE: Scattered relocations don't exist on x86_64.
620 unsigned RType = Obj->getAnyRelocationType(RENext);
621 if (RType != MachO::X86_64_RELOC_UNSIGNED)
622 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
623 "X86_64_RELOC_SUBTRACTOR.");
625 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
626 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
627 printRelocationTargetName(Obj, RENext, fmt);
629 printRelocationTargetName(Obj, RE, fmt);
632 case MachO::X86_64_RELOC_TLV:
633 printRelocationTargetName(Obj, RE, fmt);
638 case MachO::X86_64_RELOC_SIGNED_1:
639 printRelocationTargetName(Obj, RE, fmt);
642 case MachO::X86_64_RELOC_SIGNED_2:
643 printRelocationTargetName(Obj, RE, fmt);
646 case MachO::X86_64_RELOC_SIGNED_4:
647 printRelocationTargetName(Obj, RE, fmt);
651 printRelocationTargetName(Obj, RE, fmt);
654 // X86 and ARM share some relocation types in common.
655 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
656 Arch == Triple::ppc) {
657 // Generic relocation types...
659 case MachO::GENERIC_RELOC_PAIR: // prints no info
660 return std::error_code();
661 case MachO::GENERIC_RELOC_SECTDIFF: {
662 DataRefImpl RelNext = Rel;
663 Obj->moveRelocationNext(RelNext);
664 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
666 // X86 sect diff's must be followed by a relocation of type
667 // GENERIC_RELOC_PAIR.
668 unsigned RType = Obj->getAnyRelocationType(RENext);
670 if (RType != MachO::GENERIC_RELOC_PAIR)
671 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
672 "GENERIC_RELOC_SECTDIFF.");
674 printRelocationTargetName(Obj, RE, fmt);
676 printRelocationTargetName(Obj, RENext, fmt);
681 if (Arch == Triple::x86 || Arch == Triple::ppc) {
683 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
684 DataRefImpl RelNext = Rel;
685 Obj->moveRelocationNext(RelNext);
686 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
688 // X86 sect diff's must be followed by a relocation of type
689 // GENERIC_RELOC_PAIR.
690 unsigned RType = Obj->getAnyRelocationType(RENext);
691 if (RType != MachO::GENERIC_RELOC_PAIR)
692 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
693 "GENERIC_RELOC_LOCAL_SECTDIFF.");
695 printRelocationTargetName(Obj, RE, fmt);
697 printRelocationTargetName(Obj, RENext, fmt);
700 case MachO::GENERIC_RELOC_TLV: {
701 printRelocationTargetName(Obj, RE, fmt);
708 printRelocationTargetName(Obj, RE, fmt);
710 } else { // ARM-specific relocations
712 case MachO::ARM_RELOC_HALF:
713 case MachO::ARM_RELOC_HALF_SECTDIFF: {
714 // Half relocations steal a bit from the length field to encode
715 // whether this is an upper16 or a lower16 relocation.
716 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
722 printRelocationTargetName(Obj, RE, fmt);
724 DataRefImpl RelNext = Rel;
725 Obj->moveRelocationNext(RelNext);
726 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
728 // ARM half relocs must be followed by a relocation of type
730 unsigned RType = Obj->getAnyRelocationType(RENext);
731 if (RType != MachO::ARM_RELOC_PAIR)
732 report_fatal_error("Expected ARM_RELOC_PAIR after "
735 // NOTE: The half of the target virtual address is stashed in the
736 // address field of the secondary relocation, but we can't reverse
737 // engineer the constant offset from it without decoding the movw/movt
738 // instruction to find the other half in its immediate field.
740 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
741 // symbol/section pointer of the follow-on relocation.
742 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
744 printRelocationTargetName(Obj, RENext, fmt);
750 default: { printRelocationTargetName(Obj, RE, fmt); }
754 printRelocationTargetName(Obj, RE, fmt);
757 Result.append(fmtbuf.begin(), fmtbuf.end());
758 return std::error_code();
761 static std::error_code getRelocationValueString(const RelocationRef &Rel,
762 SmallVectorImpl<char> &Result) {
763 const ObjectFile *Obj = Rel.getObject();
764 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
765 return getRelocationValueString(ELF, Rel, Result);
766 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
767 return getRelocationValueString(COFF, Rel, Result);
768 auto *MachO = cast<MachOObjectFile>(Obj);
769 return getRelocationValueString(MachO, Rel, Result);
772 /// @brief Indicates whether this relocation should hidden when listing
773 /// relocations, usually because it is the trailing part of a multipart
774 /// relocation that will be printed as part of the leading relocation.
775 static bool getHidden(RelocationRef RelRef) {
776 const ObjectFile *Obj = RelRef.getObject();
777 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
781 unsigned Arch = MachO->getArch();
782 DataRefImpl Rel = RelRef.getRawDataRefImpl();
783 uint64_t Type = MachO->getRelocationType(Rel);
785 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
787 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
788 if (Type == MachO::GENERIC_RELOC_PAIR)
790 } else if (Arch == Triple::x86_64) {
791 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
792 // an X86_64_RELOC_SUBTRACTOR.
793 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
794 DataRefImpl RelPrev = Rel;
796 uint64_t PrevType = MachO->getRelocationType(RelPrev);
797 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
805 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
806 const Target *TheTarget = getTarget(Obj);
808 // Package up features to be passed to target/subtarget
809 std::string FeaturesStr;
811 SubtargetFeatures Features;
812 for (unsigned i = 0; i != MAttrs.size(); ++i)
813 Features.AddFeature(MAttrs[i]);
814 FeaturesStr = Features.getString();
817 std::unique_ptr<const MCRegisterInfo> MRI(
818 TheTarget->createMCRegInfo(TripleName));
820 report_fatal_error("error: no register info for target " + TripleName);
822 // Set up disassembler.
823 std::unique_ptr<const MCAsmInfo> AsmInfo(
824 TheTarget->createMCAsmInfo(*MRI, TripleName));
826 report_fatal_error("error: no assembly info for target " + TripleName);
827 std::unique_ptr<const MCSubtargetInfo> STI(
828 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
830 report_fatal_error("error: no subtarget info for target " + TripleName);
831 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
833 report_fatal_error("error: no instruction info for target " + TripleName);
834 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
835 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
837 std::unique_ptr<MCDisassembler> DisAsm(
838 TheTarget->createMCDisassembler(*STI, Ctx));
840 report_fatal_error("error: no disassembler for target " + TripleName);
842 std::unique_ptr<const MCInstrAnalysis> MIA(
843 TheTarget->createMCInstrAnalysis(MII.get()));
845 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
846 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
847 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
849 report_fatal_error("error: no instruction printer for target " +
851 IP->setPrintImmHex(PrintImmHex);
852 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
854 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
855 "\t\t\t%08" PRIx64 ": ";
857 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
858 // in RelocSecs contain the relocations for section S.
860 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
861 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
862 section_iterator Sec2 = Section.getRelocatedSection();
863 if (Sec2 != Obj->section_end())
864 SectionRelocMap[*Sec2].push_back(Section);
867 // Create a mapping from virtual address to symbol name. This is used to
868 // pretty print the symbols while disassembling.
869 typedef std::vector<std::pair<uint64_t, StringRef>> SectionSymbolsTy;
870 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
871 for (const SymbolRef &Symbol : Obj->symbols()) {
872 ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
873 error(AddressOrErr.getError());
874 uint64_t Address = *AddressOrErr;
876 ErrorOr<StringRef> Name = Symbol.getName();
877 error(Name.getError());
881 ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
882 error(SectionOrErr.getError());
883 section_iterator SecI = *SectionOrErr;
884 if (SecI == Obj->section_end())
887 AllSymbols[*SecI].emplace_back(Address, *Name);
890 // Create a mapping from virtual address to section.
891 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
892 for (SectionRef Sec : Obj->sections())
893 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
894 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
896 // Linked executables (.exe and .dll files) typically don't include a real
897 // symbol table but they might contain an export table.
898 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
899 for (const auto &ExportEntry : COFFObj->export_directories()) {
901 error(ExportEntry.getSymbolName(Name));
905 error(ExportEntry.getExportRVA(RVA));
907 uint64_t VA = COFFObj->getImageBase() + RVA;
908 auto Sec = std::upper_bound(
909 SectionAddresses.begin(), SectionAddresses.end(), VA,
910 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
911 return LHS < RHS.first;
913 if (Sec != SectionAddresses.begin())
916 Sec = SectionAddresses.end();
918 if (Sec != SectionAddresses.end())
919 AllSymbols[Sec->second].emplace_back(VA, Name);
923 // Sort all the symbols, this allows us to use a simple binary search to find
924 // a symbol near an address.
925 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
926 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
928 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
929 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
932 uint64_t SectionAddr = Section.getAddress();
933 uint64_t SectSize = Section.getSize();
937 // Get the list of all the symbols in this section.
938 SectionSymbolsTy &Symbols = AllSymbols[Section];
939 std::vector<uint64_t> DataMappingSymsAddr;
940 std::vector<uint64_t> TextMappingSymsAddr;
941 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
942 for (const auto &Symb : Symbols) {
943 uint64_t Address = Symb.first;
944 StringRef Name = Symb.second;
945 if (Name.startswith("$d"))
946 DataMappingSymsAddr.push_back(Address - SectionAddr);
947 if (Name.startswith("$x"))
948 TextMappingSymsAddr.push_back(Address - SectionAddr);
952 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
953 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
955 // Make a list of all the relocations for this section.
956 std::vector<RelocationRef> Rels;
958 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
959 for (const RelocationRef &Reloc : RelocSec.relocations()) {
960 Rels.push_back(Reloc);
965 // Sort relocations by address.
966 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
968 StringRef SegmentName = "";
969 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
970 DataRefImpl DR = Section.getRawDataRefImpl();
971 SegmentName = MachO->getSectionFinalSegmentName(DR);
974 error(Section.getName(name));
975 outs() << "Disassembly of section ";
976 if (!SegmentName.empty())
977 outs() << SegmentName << ",";
978 outs() << name << ':';
980 // If the section has no symbol at the start, just insert a dummy one.
981 if (Symbols.empty() || Symbols[0].first != 0)
982 Symbols.insert(Symbols.begin(), std::make_pair(SectionAddr, name));
984 SmallString<40> Comments;
985 raw_svector_ostream CommentStream(Comments);
988 error(Section.getContents(BytesStr));
989 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
995 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
996 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
997 // Disassemble symbol by symbol.
998 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
1000 uint64_t Start = Symbols[si].first - SectionAddr;
1001 // The end is either the section end or the beginning of the next
1004 (si == se - 1) ? SectSize : Symbols[si + 1].first - SectionAddr;
1005 // Don't try to disassemble beyond the end of section contents.
1008 // If this symbol has the same address as the next symbol, then skip it.
1012 outs() << '\n' << Symbols[si].second << ":\n";
1015 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1017 raw_ostream &DebugOut = nulls();
1020 for (Index = Start; Index < End; Index += Size) {
1023 // AArch64 ELF binaries can interleave data and text in the
1024 // same section. We rely on the markers introduced to
1025 // understand what we need to dump.
1026 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1027 uint64_t Stride = 0;
1029 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1030 DataMappingSymsAddr.end(), Index);
1031 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1033 while (Index < End) {
1034 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1036 if (Index + 4 <= End) {
1038 dumpBytes(Bytes.slice(Index, 4), outs());
1039 outs() << "\t.word";
1040 } else if (Index + 2 <= End) {
1042 dumpBytes(Bytes.slice(Index, 2), outs());
1043 outs() << "\t.short";
1046 dumpBytes(Bytes.slice(Index, 1), outs());
1047 outs() << "\t.byte";
1051 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1052 TextMappingSymsAddr.end(), Index);
1053 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1062 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1063 SectionAddr + Index, DebugOut,
1065 PIP.printInst(*IP, &Inst,
1066 Bytes.slice(Index, Size),
1067 SectionAddr + Index, outs(), "", *STI);
1068 outs() << CommentStream.str();
1071 // Try to resolve the target of a call, tail call, etc. to a specific
1073 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1074 MIA->isConditionalBranch(Inst))) {
1076 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1077 // In a relocatable object, the target's section must reside in
1078 // the same section as the call instruction or it is accessed
1079 // through a relocation.
1081 // In a non-relocatable object, the target may be in any section.
1083 // N.B. We don't walk the relocations in the relocatable case yet.
1084 auto *TargetSectionSymbols = &Symbols;
1085 if (!Obj->isRelocatableObject()) {
1086 auto SectionAddress = std::upper_bound(
1087 SectionAddresses.begin(), SectionAddresses.end(), Target,
1089 const std::pair<uint64_t, SectionRef> &RHS) {
1090 return LHS < RHS.first;
1092 if (SectionAddress != SectionAddresses.begin()) {
1094 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1096 TargetSectionSymbols = nullptr;
1100 // Find the first symbol in the section whose offset is less than
1101 // or equal to the target.
1102 if (TargetSectionSymbols) {
1103 auto TargetSym = std::upper_bound(
1104 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1105 Target, [](uint64_t LHS,
1106 const std::pair<uint64_t, StringRef> &RHS) {
1107 return LHS < RHS.first;
1109 if (TargetSym != TargetSectionSymbols->begin()) {
1111 uint64_t TargetAddress = std::get<0>(*TargetSym);
1112 StringRef TargetName = std::get<1>(*TargetSym);
1113 outs() << " <" << TargetName;
1114 uint64_t Disp = Target - TargetAddress;
1116 outs() << '+' << utohexstr(Disp);
1124 errs() << ToolName << ": warning: invalid instruction encoding\n";
1126 Size = 1; // skip illegible bytes
1129 // Print relocation for instruction.
1130 while (rel_cur != rel_end) {
1131 bool hidden = getHidden(*rel_cur);
1132 uint64_t addr = rel_cur->getOffset();
1133 SmallString<16> name;
1134 SmallString<32> val;
1136 // If this relocation is hidden, skip it.
1137 if (hidden) goto skip_print_rel;
1139 // Stop when rel_cur's address is past the current instruction.
1140 if (addr >= Index + Size) break;
1141 rel_cur->getTypeName(name);
1142 error(getRelocationValueString(*rel_cur, val));
1143 outs() << format(Fmt.data(), SectionAddr + addr) << name
1144 << "\t" << val << "\n";
1154 void llvm::PrintRelocations(const ObjectFile *Obj) {
1155 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1157 // Regular objdump doesn't print relocations in non-relocatable object
1159 if (!Obj->isRelocatableObject())
1162 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1163 if (Section.relocation_begin() == Section.relocation_end())
1166 error(Section.getName(secname));
1167 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
1168 for (const RelocationRef &Reloc : Section.relocations()) {
1169 bool hidden = getHidden(Reloc);
1170 uint64_t address = Reloc.getOffset();
1171 SmallString<32> relocname;
1172 SmallString<32> valuestr;
1175 Reloc.getTypeName(relocname);
1176 error(getRelocationValueString(Reloc, valuestr));
1177 outs() << format(Fmt.data(), address) << " " << relocname << " "
1178 << valuestr << "\n";
1184 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
1185 outs() << "Sections:\n"
1186 "Idx Name Size Address Type\n";
1188 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1190 error(Section.getName(Name));
1191 uint64_t Address = Section.getAddress();
1192 uint64_t Size = Section.getSize();
1193 bool Text = Section.isText();
1194 bool Data = Section.isData();
1195 bool BSS = Section.isBSS();
1196 std::string Type = (std::string(Text ? "TEXT " : "") +
1197 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1198 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1199 Name.str().c_str(), Size, Address, Type.c_str());
1204 void llvm::PrintSectionContents(const ObjectFile *Obj) {
1206 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1209 error(Section.getName(Name));
1210 uint64_t BaseAddr = Section.getAddress();
1211 uint64_t Size = Section.getSize();
1215 outs() << "Contents of section " << Name << ":\n";
1216 if (Section.isBSS()) {
1217 outs() << format("<skipping contents of bss section at [%04" PRIx64
1218 ", %04" PRIx64 ")>\n",
1219 BaseAddr, BaseAddr + Size);
1223 error(Section.getContents(Contents));
1225 // Dump out the content as hex and printable ascii characters.
1226 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1227 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1228 // Dump line of hex.
1229 for (std::size_t i = 0; i < 16; ++i) {
1230 if (i != 0 && i % 4 == 0)
1233 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1234 << hexdigit(Contents[addr + i] & 0xF, true);
1240 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1241 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1242 outs() << Contents[addr + i];
1251 void llvm::PrintSymbolTable(const ObjectFile *o) {
1252 outs() << "SYMBOL TABLE:\n";
1254 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1255 printCOFFSymbolTable(coff);
1258 for (const SymbolRef &Symbol : o->symbols()) {
1259 ErrorOr<uint64_t> AddressOrError = Symbol.getAddress();
1260 error(AddressOrError.getError());
1261 uint64_t Address = *AddressOrError;
1262 SymbolRef::Type Type = Symbol.getType();
1263 uint32_t Flags = Symbol.getFlags();
1264 ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
1265 error(SectionOrErr.getError());
1266 section_iterator Section = *SectionOrErr;
1268 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1269 Section->getName(Name);
1271 ErrorOr<StringRef> NameOrErr = Symbol.getName();
1272 error(NameOrErr.getError());
1276 bool Global = Flags & SymbolRef::SF_Global;
1277 bool Weak = Flags & SymbolRef::SF_Weak;
1278 bool Absolute = Flags & SymbolRef::SF_Absolute;
1279 bool Common = Flags & SymbolRef::SF_Common;
1280 bool Hidden = Flags & SymbolRef::SF_Hidden;
1283 if (Type != SymbolRef::ST_Unknown)
1284 GlobLoc = Global ? 'g' : 'l';
1285 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1287 char FileFunc = ' ';
1288 if (Type == SymbolRef::ST_File)
1290 else if (Type == SymbolRef::ST_Function)
1293 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1296 outs() << format(Fmt, Address) << " "
1297 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1298 << (Weak ? 'w' : ' ') // Weak?
1299 << ' ' // Constructor. Not supported yet.
1300 << ' ' // Warning. Not supported yet.
1301 << ' ' // Indirect reference to another symbol.
1302 << Debug // Debugging (d) or dynamic (D) symbol.
1303 << FileFunc // Name of function (F), file (f) or object (O).
1307 } else if (Common) {
1309 } else if (Section == o->section_end()) {
1312 if (const MachOObjectFile *MachO =
1313 dyn_cast<const MachOObjectFile>(o)) {
1314 DataRefImpl DR = Section->getRawDataRefImpl();
1315 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1316 outs() << SegmentName << ",";
1318 StringRef SectionName;
1319 error(Section->getName(SectionName));
1320 outs() << SectionName;
1324 if (Common || isa<ELFObjectFileBase>(o)) {
1326 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1327 outs() << format("\t %08" PRIx64 " ", Val);
1331 outs() << ".hidden ";
1338 static void PrintUnwindInfo(const ObjectFile *o) {
1339 outs() << "Unwind info:\n\n";
1341 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1342 printCOFFUnwindInfo(coff);
1343 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1344 printMachOUnwindInfo(MachO);
1346 // TODO: Extract DWARF dump tool to objdump.
1347 errs() << "This operation is only currently supported "
1348 "for COFF and MachO object files.\n";
1353 void llvm::printExportsTrie(const ObjectFile *o) {
1354 outs() << "Exports trie:\n";
1355 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1356 printMachOExportsTrie(MachO);
1358 errs() << "This operation is only currently supported "
1359 "for Mach-O executable files.\n";
1364 void llvm::printRebaseTable(const ObjectFile *o) {
1365 outs() << "Rebase table:\n";
1366 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1367 printMachORebaseTable(MachO);
1369 errs() << "This operation is only currently supported "
1370 "for Mach-O executable files.\n";
1375 void llvm::printBindTable(const ObjectFile *o) {
1376 outs() << "Bind table:\n";
1377 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1378 printMachOBindTable(MachO);
1380 errs() << "This operation is only currently supported "
1381 "for Mach-O executable files.\n";
1386 void llvm::printLazyBindTable(const ObjectFile *o) {
1387 outs() << "Lazy bind table:\n";
1388 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1389 printMachOLazyBindTable(MachO);
1391 errs() << "This operation is only currently supported "
1392 "for Mach-O executable files.\n";
1397 void llvm::printWeakBindTable(const ObjectFile *o) {
1398 outs() << "Weak bind table:\n";
1399 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1400 printMachOWeakBindTable(MachO);
1402 errs() << "This operation is only currently supported "
1403 "for Mach-O executable files.\n";
1408 /// Dump the raw contents of the __clangast section so the output can be piped
1409 /// into llvm-bcanalyzer.
1410 void llvm::printRawClangAST(const ObjectFile *Obj) {
1411 if (outs().is_displayed()) {
1412 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1413 "the clang ast section.\n"
1414 "Please redirect the output to a file or another program such as "
1415 "llvm-bcanalyzer.\n";
1419 StringRef ClangASTSectionName("__clangast");
1420 if (isa<COFFObjectFile>(Obj)) {
1421 ClangASTSectionName = "clangast";
1424 Optional<object::SectionRef> ClangASTSection;
1425 for (auto Sec : ToolSectionFilter(*Obj)) {
1428 if (Name == ClangASTSectionName) {
1429 ClangASTSection = Sec;
1433 if (!ClangASTSection)
1436 StringRef ClangASTContents;
1437 error(ClangASTSection.getValue().getContents(ClangASTContents));
1438 outs().write(ClangASTContents.data(), ClangASTContents.size());
1441 static void printFaultMaps(const ObjectFile *Obj) {
1442 const char *FaultMapSectionName = nullptr;
1444 if (isa<ELFObjectFileBase>(Obj)) {
1445 FaultMapSectionName = ".llvm_faultmaps";
1446 } else if (isa<MachOObjectFile>(Obj)) {
1447 FaultMapSectionName = "__llvm_faultmaps";
1449 errs() << "This operation is only currently supported "
1450 "for ELF and Mach-O executable files.\n";
1454 Optional<object::SectionRef> FaultMapSection;
1456 for (auto Sec : ToolSectionFilter(*Obj)) {
1459 if (Name == FaultMapSectionName) {
1460 FaultMapSection = Sec;
1465 outs() << "FaultMap table:\n";
1467 if (!FaultMapSection.hasValue()) {
1468 outs() << "<not found>\n";
1472 StringRef FaultMapContents;
1473 error(FaultMapSection.getValue().getContents(FaultMapContents));
1475 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1476 FaultMapContents.bytes_end());
1481 static void printPrivateFileHeader(const ObjectFile *o) {
1483 printELFFileHeader(o);
1484 else if (o->isCOFF())
1485 printCOFFFileHeader(o);
1486 else if (o->isMachO())
1487 printMachOFileHeader(o);
1489 report_fatal_error("Invalid/Unsupported object file format");
1492 static void DumpObject(const ObjectFile *o) {
1493 // Avoid other output when using a raw option.
1496 outs() << o->getFileName()
1497 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1501 DisassembleObject(o, Relocations);
1502 if (Relocations && !Disassemble)
1503 PrintRelocations(o);
1505 PrintSectionHeaders(o);
1506 if (SectionContents)
1507 PrintSectionContents(o);
1509 PrintSymbolTable(o);
1513 printPrivateFileHeader(o);
1515 printExportsTrie(o);
1517 printRebaseTable(o);
1521 printLazyBindTable(o);
1523 printWeakBindTable(o);
1525 printRawClangAST(o);
1530 /// @brief Dump each object file in \a a;
1531 static void DumpArchive(const Archive *a) {
1532 for (auto &ErrorOrChild : a->children()) {
1533 if (std::error_code EC = ErrorOrChild.getError())
1534 report_error(a->getFileName(), EC);
1535 const Archive::Child &C = *ErrorOrChild;
1536 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1537 if (std::error_code EC = ChildOrErr.getError())
1538 if (EC != object_error::invalid_file_type)
1539 report_error(a->getFileName(), EC);
1540 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
1543 report_error(a->getFileName(), object_error::invalid_file_type);
1547 /// @brief Open file and figure out how to dump it.
1548 static void DumpInput(StringRef file) {
1550 // If we are using the Mach-O specific object file parser, then let it parse
1551 // the file and process the command line options. So the -arch flags can
1552 // be used to select specific slices, etc.
1554 ParseInputMachO(file);
1558 // Attempt to open the binary.
1559 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1560 if (std::error_code EC = BinaryOrErr.getError())
1561 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::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 && !(FilterSections.size() != 0 && MachOOpt)
1620 && !PrintFaultMaps) {
1621 cl::PrintHelpMessage();
1625 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1628 return EXIT_SUCCESS;