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 llvm::FirstPrivateHeader("private-header",
170 cl::desc("Display only the first format specific file "
174 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
175 cl::aliasopt(PrivateHeaders));
178 llvm::PrintImmHex("print-imm-hex",
179 cl::desc("Use hex format for immediate values"));
181 cl::opt<bool> PrintFaultMaps("fault-map-section",
182 cl::desc("Display contents of faultmap section"));
184 static StringRef ToolName;
187 typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
189 class SectionFilterIterator {
191 SectionFilterIterator(FilterPredicate P,
192 llvm::object::section_iterator const &I,
193 llvm::object::section_iterator const &E)
194 : Predicate(P), Iterator(I), End(E) {
197 const llvm::object::SectionRef &operator*() const { return *Iterator; }
198 SectionFilterIterator &operator++() {
203 bool operator!=(SectionFilterIterator const &Other) const {
204 return Iterator != Other.Iterator;
208 void ScanPredicate() {
209 while (Iterator != End && !Predicate(*Iterator)) {
213 FilterPredicate Predicate;
214 llvm::object::section_iterator Iterator;
215 llvm::object::section_iterator End;
218 class SectionFilter {
220 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
221 : Predicate(P), Object(O) {}
222 SectionFilterIterator begin() {
223 return SectionFilterIterator(Predicate, Object.section_begin(),
224 Object.section_end());
226 SectionFilterIterator end() {
227 return SectionFilterIterator(Predicate, Object.section_end(),
228 Object.section_end());
232 FilterPredicate Predicate;
233 llvm::object::ObjectFile const &Object;
235 SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
236 return SectionFilter([](llvm::object::SectionRef const &S) {
237 if(FilterSections.empty())
239 llvm::StringRef String;
240 std::error_code error = S.getName(String);
243 return std::find(FilterSections.begin(),
244 FilterSections.end(),
245 String) != FilterSections.end();
251 void llvm::error(std::error_code EC) {
255 errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
260 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
261 std::error_code EC) {
263 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
267 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
268 // Figure out the target triple.
269 llvm::Triple TheTriple("unknown-unknown-unknown");
270 if (TripleName.empty()) {
272 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
273 // TheTriple defaults to ELF, and COFF doesn't have an environment:
274 // the best we can do here is indicate that it is mach-o.
276 TheTriple.setObjectFormat(Triple::MachO);
279 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
280 if (COFFObj->getArch() == Triple::thumb)
281 TheTriple.setTriple("thumbv7-windows");
285 TheTriple.setTriple(Triple::normalize(TripleName));
287 // Get the target specific parser.
289 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
292 report_fatal_error("can't find target: " + Error);
294 // Update the triple name and return the found target.
295 TripleName = TheTriple.getTriple();
299 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
300 return a.getOffset() < b.getOffset();
304 class PrettyPrinter {
306 virtual ~PrettyPrinter(){}
307 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
308 ArrayRef<uint8_t> Bytes, uint64_t Address,
309 raw_ostream &OS, StringRef Annot,
310 MCSubtargetInfo const &STI) {
311 outs() << format("%8" PRIx64 ":", Address);
312 if (!NoShowRawInsn) {
314 dumpBytes(Bytes, outs());
316 IP.printInst(MI, outs(), "", STI);
319 PrettyPrinter PrettyPrinterInst;
320 class HexagonPrettyPrinter : public PrettyPrinter {
322 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
325 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
326 OS << format("%8" PRIx64 ":", Address);
327 if (!NoShowRawInsn) {
329 dumpBytes(Bytes.slice(0, 4), OS);
330 OS << format("%08" PRIx32, opcode);
333 void printInst(MCInstPrinter &IP, const MCInst *MI,
334 ArrayRef<uint8_t> Bytes, uint64_t Address,
335 raw_ostream &OS, StringRef Annot,
336 MCSubtargetInfo const &STI) override {
339 raw_string_ostream TempStream(Buffer);
340 IP.printInst(MI, TempStream, "", STI);
342 StringRef Contents(Buffer);
343 // Split off bundle attributes
344 auto PacketBundle = Contents.rsplit('\n');
345 // Split off first instruction from the rest
346 auto HeadTail = PacketBundle.first.split('\n');
347 auto Preamble = " { ";
349 while(!HeadTail.first.empty()) {
352 printLead(Bytes, Address, OS);
356 auto Duplex = HeadTail.first.split('\v');
357 if(!Duplex.second.empty()){
360 Inst = Duplex.second;
363 Inst = HeadTail.first;
365 Bytes = Bytes.slice(4);
367 HeadTail = HeadTail.second.split('\n');
369 OS << " } " << PacketBundle.second;
372 HexagonPrettyPrinter HexagonPrettyPrinterInst;
373 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
374 switch(Triple.getArch()) {
376 return PrettyPrinterInst;
377 case Triple::hexagon:
378 return HexagonPrettyPrinterInst;
383 template <class ELFT>
384 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
385 const RelocationRef &RelRef,
386 SmallVectorImpl<char> &Result) {
387 DataRefImpl Rel = RelRef.getRawDataRefImpl();
389 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
390 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
391 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
393 const ELFFile<ELFT> &EF = *Obj->getELFFile();
395 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
396 if (std::error_code EC = SecOrErr.getError())
398 const Elf_Shdr *Sec = *SecOrErr;
399 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
400 if (std::error_code EC = SymTabOrErr.getError())
402 const Elf_Shdr *SymTab = *SymTabOrErr;
403 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
404 SymTab->sh_type == ELF::SHT_DYNSYM);
405 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
406 if (std::error_code EC = StrTabSec.getError())
408 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
409 if (std::error_code EC = StrTabOrErr.getError())
411 StringRef StrTab = *StrTabOrErr;
412 uint8_t type = RelRef.getType();
415 switch (Sec->sh_type) {
417 return object_error::parse_failed;
419 // TODO: Read implicit addend from section data.
422 case ELF::SHT_RELA: {
423 const Elf_Rela *ERela = Obj->getRela(Rel);
424 addend = ERela->r_addend;
428 symbol_iterator SI = RelRef.getSymbol();
429 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
431 if (symb->getType() == ELF::STT_SECTION) {
432 ErrorOr<section_iterator> SymSI = SI->getSection();
433 if (std::error_code EC = SymSI.getError())
435 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
436 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
437 if (std::error_code EC = SecName.getError())
441 ErrorOr<StringRef> SymName = symb->getName(StrTab);
443 return SymName.getError();
446 switch (EF.getHeader()->e_machine) {
449 case ELF::R_X86_64_PC8:
450 case ELF::R_X86_64_PC16:
451 case ELF::R_X86_64_PC32: {
453 raw_string_ostream fmt(fmtbuf);
454 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
456 Result.append(fmtbuf.begin(), fmtbuf.end());
458 case ELF::R_X86_64_8:
459 case ELF::R_X86_64_16:
460 case ELF::R_X86_64_32:
461 case ELF::R_X86_64_32S:
462 case ELF::R_X86_64_64: {
464 raw_string_ostream fmt(fmtbuf);
465 fmt << Target << (addend < 0 ? "" : "+") << addend;
467 Result.append(fmtbuf.begin(), fmtbuf.end());
473 case ELF::EM_AARCH64: {
475 raw_string_ostream fmt(fmtbuf);
478 fmt << (addend < 0 ? "" : "+") << addend;
480 Result.append(fmtbuf.begin(), fmtbuf.end());
486 case ELF::EM_HEXAGON:
490 case ELF::EM_WEBASSEMBLY:
492 case ELF::R_WEBASSEMBLY_DATA: {
494 raw_string_ostream fmt(fmtbuf);
495 fmt << Target << (addend < 0 ? "" : "+") << addend;
497 Result.append(fmtbuf.begin(), fmtbuf.end());
500 case ELF::R_WEBASSEMBLY_FUNCTION:
511 Result.append(res.begin(), res.end());
512 return std::error_code();
515 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
516 const RelocationRef &Rel,
517 SmallVectorImpl<char> &Result) {
518 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
519 return getRelocationValueString(ELF32LE, Rel, Result);
520 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
521 return getRelocationValueString(ELF64LE, Rel, Result);
522 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
523 return getRelocationValueString(ELF32BE, Rel, Result);
524 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
525 return getRelocationValueString(ELF64BE, Rel, Result);
528 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
529 const RelocationRef &Rel,
530 SmallVectorImpl<char> &Result) {
531 symbol_iterator SymI = Rel.getSymbol();
532 ErrorOr<StringRef> SymNameOrErr = SymI->getName();
533 if (std::error_code EC = SymNameOrErr.getError())
535 StringRef SymName = *SymNameOrErr;
536 Result.append(SymName.begin(), SymName.end());
537 return std::error_code();
540 static void printRelocationTargetName(const MachOObjectFile *O,
541 const MachO::any_relocation_info &RE,
542 raw_string_ostream &fmt) {
543 bool IsScattered = O->isRelocationScattered(RE);
545 // Target of a scattered relocation is an address. In the interest of
546 // generating pretty output, scan through the symbol table looking for a
547 // symbol that aligns with that address. If we find one, print it.
548 // Otherwise, we just print the hex address of the target.
550 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
552 for (const SymbolRef &Symbol : O->symbols()) {
554 ErrorOr<uint64_t> Addr = Symbol.getAddress();
555 if ((ec = Addr.getError()))
556 report_fatal_error(ec.message());
559 ErrorOr<StringRef> Name = Symbol.getName();
560 if (std::error_code EC = Name.getError())
561 report_fatal_error(EC.message());
566 // If we couldn't find a symbol that this relocation refers to, try
567 // to find a section beginning instead.
568 for (const SectionRef &Section : ToolSectionFilter(*O)) {
572 uint64_t Addr = Section.getAddress();
575 if ((ec = Section.getName(Name)))
576 report_fatal_error(ec.message());
581 fmt << format("0x%x", Val);
586 bool isExtern = O->getPlainRelocationExternal(RE);
587 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
590 symbol_iterator SI = O->symbol_begin();
592 ErrorOr<StringRef> SOrErr = SI->getName();
593 error(SOrErr.getError());
596 section_iterator SI = O->section_begin();
597 // Adjust for the fact that sections are 1-indexed.
598 advance(SI, Val - 1);
605 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
606 const RelocationRef &RelRef,
607 SmallVectorImpl<char> &Result) {
608 DataRefImpl Rel = RelRef.getRawDataRefImpl();
609 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
611 unsigned Arch = Obj->getArch();
614 raw_string_ostream fmt(fmtbuf);
615 unsigned Type = Obj->getAnyRelocationType(RE);
616 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
618 // Determine any addends that should be displayed with the relocation.
619 // These require decoding the relocation type, which is triple-specific.
621 // X86_64 has entirely custom relocation types.
622 if (Arch == Triple::x86_64) {
623 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
626 case MachO::X86_64_RELOC_GOT_LOAD:
627 case MachO::X86_64_RELOC_GOT: {
628 printRelocationTargetName(Obj, RE, fmt);
634 case MachO::X86_64_RELOC_SUBTRACTOR: {
635 DataRefImpl RelNext = Rel;
636 Obj->moveRelocationNext(RelNext);
637 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
639 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
640 // X86_64_RELOC_UNSIGNED.
641 // NOTE: Scattered relocations don't exist on x86_64.
642 unsigned RType = Obj->getAnyRelocationType(RENext);
643 if (RType != MachO::X86_64_RELOC_UNSIGNED)
644 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
645 "X86_64_RELOC_SUBTRACTOR.");
647 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
648 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
649 printRelocationTargetName(Obj, RENext, fmt);
651 printRelocationTargetName(Obj, RE, fmt);
654 case MachO::X86_64_RELOC_TLV:
655 printRelocationTargetName(Obj, RE, fmt);
660 case MachO::X86_64_RELOC_SIGNED_1:
661 printRelocationTargetName(Obj, RE, fmt);
664 case MachO::X86_64_RELOC_SIGNED_2:
665 printRelocationTargetName(Obj, RE, fmt);
668 case MachO::X86_64_RELOC_SIGNED_4:
669 printRelocationTargetName(Obj, RE, fmt);
673 printRelocationTargetName(Obj, RE, fmt);
676 // X86 and ARM share some relocation types in common.
677 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
678 Arch == Triple::ppc) {
679 // Generic relocation types...
681 case MachO::GENERIC_RELOC_PAIR: // prints no info
682 return std::error_code();
683 case MachO::GENERIC_RELOC_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);
692 if (RType != MachO::GENERIC_RELOC_PAIR)
693 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
694 "GENERIC_RELOC_SECTDIFF.");
696 printRelocationTargetName(Obj, RE, fmt);
698 printRelocationTargetName(Obj, RENext, fmt);
703 if (Arch == Triple::x86 || Arch == Triple::ppc) {
705 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
706 DataRefImpl RelNext = Rel;
707 Obj->moveRelocationNext(RelNext);
708 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
710 // X86 sect diff's must be followed by a relocation of type
711 // GENERIC_RELOC_PAIR.
712 unsigned RType = Obj->getAnyRelocationType(RENext);
713 if (RType != MachO::GENERIC_RELOC_PAIR)
714 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
715 "GENERIC_RELOC_LOCAL_SECTDIFF.");
717 printRelocationTargetName(Obj, RE, fmt);
719 printRelocationTargetName(Obj, RENext, fmt);
722 case MachO::GENERIC_RELOC_TLV: {
723 printRelocationTargetName(Obj, RE, fmt);
730 printRelocationTargetName(Obj, RE, fmt);
732 } else { // ARM-specific relocations
734 case MachO::ARM_RELOC_HALF:
735 case MachO::ARM_RELOC_HALF_SECTDIFF: {
736 // Half relocations steal a bit from the length field to encode
737 // whether this is an upper16 or a lower16 relocation.
738 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
744 printRelocationTargetName(Obj, RE, fmt);
746 DataRefImpl RelNext = Rel;
747 Obj->moveRelocationNext(RelNext);
748 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
750 // ARM half relocs must be followed by a relocation of type
752 unsigned RType = Obj->getAnyRelocationType(RENext);
753 if (RType != MachO::ARM_RELOC_PAIR)
754 report_fatal_error("Expected ARM_RELOC_PAIR after "
757 // NOTE: The half of the target virtual address is stashed in the
758 // address field of the secondary relocation, but we can't reverse
759 // engineer the constant offset from it without decoding the movw/movt
760 // instruction to find the other half in its immediate field.
762 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
763 // symbol/section pointer of the follow-on relocation.
764 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
766 printRelocationTargetName(Obj, RENext, fmt);
772 default: { printRelocationTargetName(Obj, RE, fmt); }
776 printRelocationTargetName(Obj, RE, fmt);
779 Result.append(fmtbuf.begin(), fmtbuf.end());
780 return std::error_code();
783 static std::error_code getRelocationValueString(const RelocationRef &Rel,
784 SmallVectorImpl<char> &Result) {
785 const ObjectFile *Obj = Rel.getObject();
786 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
787 return getRelocationValueString(ELF, Rel, Result);
788 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
789 return getRelocationValueString(COFF, Rel, Result);
790 auto *MachO = cast<MachOObjectFile>(Obj);
791 return getRelocationValueString(MachO, Rel, Result);
794 /// @brief Indicates whether this relocation should hidden when listing
795 /// relocations, usually because it is the trailing part of a multipart
796 /// relocation that will be printed as part of the leading relocation.
797 static bool getHidden(RelocationRef RelRef) {
798 const ObjectFile *Obj = RelRef.getObject();
799 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
803 unsigned Arch = MachO->getArch();
804 DataRefImpl Rel = RelRef.getRawDataRefImpl();
805 uint64_t Type = MachO->getRelocationType(Rel);
807 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
809 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
810 if (Type == MachO::GENERIC_RELOC_PAIR)
812 } else if (Arch == Triple::x86_64) {
813 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
814 // an X86_64_RELOC_SUBTRACTOR.
815 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
816 DataRefImpl RelPrev = Rel;
818 uint64_t PrevType = MachO->getRelocationType(RelPrev);
819 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
827 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
828 const Target *TheTarget = getTarget(Obj);
830 // Package up features to be passed to target/subtarget
831 std::string FeaturesStr;
833 SubtargetFeatures Features;
834 for (unsigned i = 0; i != MAttrs.size(); ++i)
835 Features.AddFeature(MAttrs[i]);
836 FeaturesStr = Features.getString();
839 std::unique_ptr<const MCRegisterInfo> MRI(
840 TheTarget->createMCRegInfo(TripleName));
842 report_fatal_error("error: no register info for target " + TripleName);
844 // Set up disassembler.
845 std::unique_ptr<const MCAsmInfo> AsmInfo(
846 TheTarget->createMCAsmInfo(*MRI, TripleName));
848 report_fatal_error("error: no assembly info for target " + TripleName);
849 std::unique_ptr<const MCSubtargetInfo> STI(
850 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
852 report_fatal_error("error: no subtarget info for target " + TripleName);
853 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
855 report_fatal_error("error: no instruction info for target " + TripleName);
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));
862 report_fatal_error("error: no disassembler for target " + TripleName);
864 std::unique_ptr<const MCInstrAnalysis> MIA(
865 TheTarget->createMCInstrAnalysis(MII.get()));
867 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
868 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
869 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
871 report_fatal_error("error: no instruction printer for target " +
873 IP->setPrintImmHex(PrintImmHex);
874 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
876 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
877 "\t\t\t%08" PRIx64 ": ";
879 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
880 // in RelocSecs contain the relocations for section S.
882 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
883 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
884 section_iterator Sec2 = Section.getRelocatedSection();
885 if (Sec2 != Obj->section_end())
886 SectionRelocMap[*Sec2].push_back(Section);
889 // Create a mapping from virtual address to symbol name. This is used to
890 // pretty print the symbols while disassembling.
891 typedef std::vector<std::pair<uint64_t, StringRef>> SectionSymbolsTy;
892 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
893 for (const SymbolRef &Symbol : Obj->symbols()) {
894 ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
895 error(AddressOrErr.getError());
896 uint64_t Address = *AddressOrErr;
898 ErrorOr<StringRef> Name = Symbol.getName();
899 error(Name.getError());
903 ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
904 error(SectionOrErr.getError());
905 section_iterator SecI = *SectionOrErr;
906 if (SecI == Obj->section_end())
909 AllSymbols[*SecI].emplace_back(Address, *Name);
912 // Create a mapping from virtual address to section.
913 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
914 for (SectionRef Sec : Obj->sections())
915 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
916 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
918 // Linked executables (.exe and .dll files) typically don't include a real
919 // symbol table but they might contain an export table.
920 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
921 for (const auto &ExportEntry : COFFObj->export_directories()) {
923 error(ExportEntry.getSymbolName(Name));
927 error(ExportEntry.getExportRVA(RVA));
929 uint64_t VA = COFFObj->getImageBase() + RVA;
930 auto Sec = std::upper_bound(
931 SectionAddresses.begin(), SectionAddresses.end(), VA,
932 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
933 return LHS < RHS.first;
935 if (Sec != SectionAddresses.begin())
938 Sec = SectionAddresses.end();
940 if (Sec != SectionAddresses.end())
941 AllSymbols[Sec->second].emplace_back(VA, Name);
945 // Sort all the symbols, this allows us to use a simple binary search to find
946 // a symbol near an address.
947 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
948 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
950 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
951 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
954 uint64_t SectionAddr = Section.getAddress();
955 uint64_t SectSize = Section.getSize();
959 // Get the list of all the symbols in this section.
960 SectionSymbolsTy &Symbols = AllSymbols[Section];
961 std::vector<uint64_t> DataMappingSymsAddr;
962 std::vector<uint64_t> TextMappingSymsAddr;
963 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
964 for (const auto &Symb : Symbols) {
965 uint64_t Address = Symb.first;
966 StringRef Name = Symb.second;
967 if (Name.startswith("$d"))
968 DataMappingSymsAddr.push_back(Address - SectionAddr);
969 if (Name.startswith("$x"))
970 TextMappingSymsAddr.push_back(Address - SectionAddr);
974 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
975 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
977 // Make a list of all the relocations for this section.
978 std::vector<RelocationRef> Rels;
980 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
981 for (const RelocationRef &Reloc : RelocSec.relocations()) {
982 Rels.push_back(Reloc);
987 // Sort relocations by address.
988 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
990 StringRef SegmentName = "";
991 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
992 DataRefImpl DR = Section.getRawDataRefImpl();
993 SegmentName = MachO->getSectionFinalSegmentName(DR);
996 error(Section.getName(name));
997 outs() << "Disassembly of section ";
998 if (!SegmentName.empty())
999 outs() << SegmentName << ",";
1000 outs() << name << ':';
1002 // If the section has no symbol at the start, just insert a dummy one.
1003 if (Symbols.empty() || Symbols[0].first != 0)
1004 Symbols.insert(Symbols.begin(), std::make_pair(SectionAddr, name));
1006 SmallString<40> Comments;
1007 raw_svector_ostream CommentStream(Comments);
1010 error(Section.getContents(BytesStr));
1011 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1017 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1018 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
1019 // Disassemble symbol by symbol.
1020 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
1022 uint64_t Start = Symbols[si].first - SectionAddr;
1023 // The end is either the section end or the beginning of the next
1026 (si == se - 1) ? SectSize : Symbols[si + 1].first - SectionAddr;
1027 // Don't try to disassemble beyond the end of section contents.
1030 // If this symbol has the same address as the next symbol, then skip it.
1034 outs() << '\n' << Symbols[si].second << ":\n";
1037 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1039 raw_ostream &DebugOut = nulls();
1042 for (Index = Start; Index < End; Index += Size) {
1045 // AArch64 ELF binaries can interleave data and text in the
1046 // same section. We rely on the markers introduced to
1047 // understand what we need to dump.
1048 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1049 uint64_t Stride = 0;
1051 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1052 DataMappingSymsAddr.end(), Index);
1053 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1055 while (Index < End) {
1056 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1058 if (Index + 4 <= End) {
1060 dumpBytes(Bytes.slice(Index, 4), outs());
1061 outs() << "\t.word";
1062 } else if (Index + 2 <= End) {
1064 dumpBytes(Bytes.slice(Index, 2), outs());
1065 outs() << "\t.short";
1068 dumpBytes(Bytes.slice(Index, 1), outs());
1069 outs() << "\t.byte";
1073 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1074 TextMappingSymsAddr.end(), Index);
1075 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1084 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1085 SectionAddr + Index, DebugOut,
1087 PIP.printInst(*IP, &Inst,
1088 Bytes.slice(Index, Size),
1089 SectionAddr + Index, outs(), "", *STI);
1090 outs() << CommentStream.str();
1093 // Try to resolve the target of a call, tail call, etc. to a specific
1095 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1096 MIA->isConditionalBranch(Inst))) {
1098 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1099 // In a relocatable object, the target's section must reside in
1100 // the same section as the call instruction or it is accessed
1101 // through a relocation.
1103 // In a non-relocatable object, the target may be in any section.
1105 // N.B. We don't walk the relocations in the relocatable case yet.
1106 auto *TargetSectionSymbols = &Symbols;
1107 if (!Obj->isRelocatableObject()) {
1108 auto SectionAddress = std::upper_bound(
1109 SectionAddresses.begin(), SectionAddresses.end(), Target,
1111 const std::pair<uint64_t, SectionRef> &RHS) {
1112 return LHS < RHS.first;
1114 if (SectionAddress != SectionAddresses.begin()) {
1116 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1118 TargetSectionSymbols = nullptr;
1122 // Find the first symbol in the section whose offset is less than
1123 // or equal to the target.
1124 if (TargetSectionSymbols) {
1125 auto TargetSym = std::upper_bound(
1126 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1127 Target, [](uint64_t LHS,
1128 const std::pair<uint64_t, StringRef> &RHS) {
1129 return LHS < RHS.first;
1131 if (TargetSym != TargetSectionSymbols->begin()) {
1133 uint64_t TargetAddress = std::get<0>(*TargetSym);
1134 StringRef TargetName = std::get<1>(*TargetSym);
1135 outs() << " <" << TargetName;
1136 uint64_t Disp = Target - TargetAddress;
1138 outs() << '+' << utohexstr(Disp);
1146 errs() << ToolName << ": warning: invalid instruction encoding\n";
1148 Size = 1; // skip illegible bytes
1151 // Print relocation for instruction.
1152 while (rel_cur != rel_end) {
1153 bool hidden = getHidden(*rel_cur);
1154 uint64_t addr = rel_cur->getOffset();
1155 SmallString<16> name;
1156 SmallString<32> val;
1158 // If this relocation is hidden, skip it.
1159 if (hidden) goto skip_print_rel;
1161 // Stop when rel_cur's address is past the current instruction.
1162 if (addr >= Index + Size) break;
1163 rel_cur->getTypeName(name);
1164 error(getRelocationValueString(*rel_cur, val));
1165 outs() << format(Fmt.data(), SectionAddr + addr) << name
1166 << "\t" << val << "\n";
1176 void llvm::PrintRelocations(const ObjectFile *Obj) {
1177 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1179 // Regular objdump doesn't print relocations in non-relocatable object
1181 if (!Obj->isRelocatableObject())
1184 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1185 if (Section.relocation_begin() == Section.relocation_end())
1188 error(Section.getName(secname));
1189 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
1190 for (const RelocationRef &Reloc : Section.relocations()) {
1191 bool hidden = getHidden(Reloc);
1192 uint64_t address = Reloc.getOffset();
1193 SmallString<32> relocname;
1194 SmallString<32> valuestr;
1197 Reloc.getTypeName(relocname);
1198 error(getRelocationValueString(Reloc, valuestr));
1199 outs() << format(Fmt.data(), address) << " " << relocname << " "
1200 << valuestr << "\n";
1206 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
1207 outs() << "Sections:\n"
1208 "Idx Name Size Address Type\n";
1210 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1212 error(Section.getName(Name));
1213 uint64_t Address = Section.getAddress();
1214 uint64_t Size = Section.getSize();
1215 bool Text = Section.isText();
1216 bool Data = Section.isData();
1217 bool BSS = Section.isBSS();
1218 std::string Type = (std::string(Text ? "TEXT " : "") +
1219 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1220 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1221 Name.str().c_str(), Size, Address, Type.c_str());
1226 void llvm::PrintSectionContents(const ObjectFile *Obj) {
1228 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1231 error(Section.getName(Name));
1232 uint64_t BaseAddr = Section.getAddress();
1233 uint64_t Size = Section.getSize();
1237 outs() << "Contents of section " << Name << ":\n";
1238 if (Section.isBSS()) {
1239 outs() << format("<skipping contents of bss section at [%04" PRIx64
1240 ", %04" PRIx64 ")>\n",
1241 BaseAddr, BaseAddr + Size);
1245 error(Section.getContents(Contents));
1247 // Dump out the content as hex and printable ascii characters.
1248 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1249 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1250 // Dump line of hex.
1251 for (std::size_t i = 0; i < 16; ++i) {
1252 if (i != 0 && i % 4 == 0)
1255 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1256 << hexdigit(Contents[addr + i] & 0xF, true);
1262 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1263 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1264 outs() << Contents[addr + i];
1273 void llvm::PrintSymbolTable(const ObjectFile *o) {
1274 outs() << "SYMBOL TABLE:\n";
1276 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1277 printCOFFSymbolTable(coff);
1280 for (const SymbolRef &Symbol : o->symbols()) {
1281 ErrorOr<uint64_t> AddressOrError = Symbol.getAddress();
1282 error(AddressOrError.getError());
1283 uint64_t Address = *AddressOrError;
1284 SymbolRef::Type Type = Symbol.getType();
1285 uint32_t Flags = Symbol.getFlags();
1286 ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
1287 error(SectionOrErr.getError());
1288 section_iterator Section = *SectionOrErr;
1290 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1291 Section->getName(Name);
1293 ErrorOr<StringRef> NameOrErr = Symbol.getName();
1294 error(NameOrErr.getError());
1298 bool Global = Flags & SymbolRef::SF_Global;
1299 bool Weak = Flags & SymbolRef::SF_Weak;
1300 bool Absolute = Flags & SymbolRef::SF_Absolute;
1301 bool Common = Flags & SymbolRef::SF_Common;
1302 bool Hidden = Flags & SymbolRef::SF_Hidden;
1305 if (Type != SymbolRef::ST_Unknown)
1306 GlobLoc = Global ? 'g' : 'l';
1307 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1309 char FileFunc = ' ';
1310 if (Type == SymbolRef::ST_File)
1312 else if (Type == SymbolRef::ST_Function)
1315 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1318 outs() << format(Fmt, Address) << " "
1319 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1320 << (Weak ? 'w' : ' ') // Weak?
1321 << ' ' // Constructor. Not supported yet.
1322 << ' ' // Warning. Not supported yet.
1323 << ' ' // Indirect reference to another symbol.
1324 << Debug // Debugging (d) or dynamic (D) symbol.
1325 << FileFunc // Name of function (F), file (f) or object (O).
1329 } else if (Common) {
1331 } else if (Section == o->section_end()) {
1334 if (const MachOObjectFile *MachO =
1335 dyn_cast<const MachOObjectFile>(o)) {
1336 DataRefImpl DR = Section->getRawDataRefImpl();
1337 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1338 outs() << SegmentName << ",";
1340 StringRef SectionName;
1341 error(Section->getName(SectionName));
1342 outs() << SectionName;
1346 if (Common || isa<ELFObjectFileBase>(o)) {
1348 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1349 outs() << format("\t %08" PRIx64 " ", Val);
1353 outs() << ".hidden ";
1360 static void PrintUnwindInfo(const ObjectFile *o) {
1361 outs() << "Unwind info:\n\n";
1363 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1364 printCOFFUnwindInfo(coff);
1365 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1366 printMachOUnwindInfo(MachO);
1368 // TODO: Extract DWARF dump tool to objdump.
1369 errs() << "This operation is only currently supported "
1370 "for COFF and MachO object files.\n";
1375 void llvm::printExportsTrie(const ObjectFile *o) {
1376 outs() << "Exports trie:\n";
1377 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1378 printMachOExportsTrie(MachO);
1380 errs() << "This operation is only currently supported "
1381 "for Mach-O executable files.\n";
1386 void llvm::printRebaseTable(const ObjectFile *o) {
1387 outs() << "Rebase table:\n";
1388 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1389 printMachORebaseTable(MachO);
1391 errs() << "This operation is only currently supported "
1392 "for Mach-O executable files.\n";
1397 void llvm::printBindTable(const ObjectFile *o) {
1398 outs() << "Bind table:\n";
1399 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1400 printMachOBindTable(MachO);
1402 errs() << "This operation is only currently supported "
1403 "for Mach-O executable files.\n";
1408 void llvm::printLazyBindTable(const ObjectFile *o) {
1409 outs() << "Lazy bind table:\n";
1410 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1411 printMachOLazyBindTable(MachO);
1413 errs() << "This operation is only currently supported "
1414 "for Mach-O executable files.\n";
1419 void llvm::printWeakBindTable(const ObjectFile *o) {
1420 outs() << "Weak bind table:\n";
1421 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1422 printMachOWeakBindTable(MachO);
1424 errs() << "This operation is only currently supported "
1425 "for Mach-O executable files.\n";
1430 /// Dump the raw contents of the __clangast section so the output can be piped
1431 /// into llvm-bcanalyzer.
1432 void llvm::printRawClangAST(const ObjectFile *Obj) {
1433 if (outs().is_displayed()) {
1434 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1435 "the clang ast section.\n"
1436 "Please redirect the output to a file or another program such as "
1437 "llvm-bcanalyzer.\n";
1441 StringRef ClangASTSectionName("__clangast");
1442 if (isa<COFFObjectFile>(Obj)) {
1443 ClangASTSectionName = "clangast";
1446 Optional<object::SectionRef> ClangASTSection;
1447 for (auto Sec : ToolSectionFilter(*Obj)) {
1450 if (Name == ClangASTSectionName) {
1451 ClangASTSection = Sec;
1455 if (!ClangASTSection)
1458 StringRef ClangASTContents;
1459 error(ClangASTSection.getValue().getContents(ClangASTContents));
1460 outs().write(ClangASTContents.data(), ClangASTContents.size());
1463 static void printFaultMaps(const ObjectFile *Obj) {
1464 const char *FaultMapSectionName = nullptr;
1466 if (isa<ELFObjectFileBase>(Obj)) {
1467 FaultMapSectionName = ".llvm_faultmaps";
1468 } else if (isa<MachOObjectFile>(Obj)) {
1469 FaultMapSectionName = "__llvm_faultmaps";
1471 errs() << "This operation is only currently supported "
1472 "for ELF and Mach-O executable files.\n";
1476 Optional<object::SectionRef> FaultMapSection;
1478 for (auto Sec : ToolSectionFilter(*Obj)) {
1481 if (Name == FaultMapSectionName) {
1482 FaultMapSection = Sec;
1487 outs() << "FaultMap table:\n";
1489 if (!FaultMapSection.hasValue()) {
1490 outs() << "<not found>\n";
1494 StringRef FaultMapContents;
1495 error(FaultMapSection.getValue().getContents(FaultMapContents));
1497 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1498 FaultMapContents.bytes_end());
1503 static void printPrivateFileHeaders(const ObjectFile *o) {
1505 printELFFileHeader(o);
1506 else if (o->isCOFF())
1507 printCOFFFileHeader(o);
1508 else if (o->isMachO()) {
1509 printMachOFileHeader(o);
1510 printMachOLoadCommands(o);
1512 report_fatal_error("Invalid/Unsupported object file format");
1515 static void printFirstPrivateFileHeader(const ObjectFile *o) {
1517 printELFFileHeader(o);
1518 else if (o->isCOFF())
1519 printCOFFFileHeader(o);
1520 else if (o->isMachO())
1521 printMachOFileHeader(o);
1523 report_fatal_error("Invalid/Unsupported object file format");
1526 static void DumpObject(const ObjectFile *o) {
1527 // Avoid other output when using a raw option.
1530 outs() << o->getFileName()
1531 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1535 DisassembleObject(o, Relocations);
1536 if (Relocations && !Disassemble)
1537 PrintRelocations(o);
1539 PrintSectionHeaders(o);
1540 if (SectionContents)
1541 PrintSectionContents(o);
1543 PrintSymbolTable(o);
1547 printPrivateFileHeaders(o);
1548 if (FirstPrivateHeader)
1549 printFirstPrivateFileHeader(o);
1551 printExportsTrie(o);
1553 printRebaseTable(o);
1557 printLazyBindTable(o);
1559 printWeakBindTable(o);
1561 printRawClangAST(o);
1566 /// @brief Dump each object file in \a a;
1567 static void DumpArchive(const Archive *a) {
1568 for (auto &ErrorOrChild : a->children()) {
1569 if (std::error_code EC = ErrorOrChild.getError())
1570 report_error(a->getFileName(), EC);
1571 const Archive::Child &C = *ErrorOrChild;
1572 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1573 if (std::error_code EC = ChildOrErr.getError())
1574 if (EC != object_error::invalid_file_type)
1575 report_error(a->getFileName(), EC);
1576 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
1579 report_error(a->getFileName(), object_error::invalid_file_type);
1583 /// @brief Open file and figure out how to dump it.
1584 static void DumpInput(StringRef file) {
1586 // If we are using the Mach-O specific object file parser, then let it parse
1587 // the file and process the command line options. So the -arch flags can
1588 // be used to select specific slices, etc.
1590 ParseInputMachO(file);
1594 // Attempt to open the binary.
1595 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1596 if (std::error_code EC = BinaryOrErr.getError())
1597 report_error(file, EC);
1598 Binary &Binary = *BinaryOrErr.get().getBinary();
1600 if (Archive *a = dyn_cast<Archive>(&Binary))
1602 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
1605 report_error(file, object_error::invalid_file_type);
1608 int main(int argc, char **argv) {
1609 // Print a stack trace if we signal out.
1610 sys::PrintStackTraceOnErrorSignal();
1611 PrettyStackTraceProgram X(argc, argv);
1612 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1614 // Initialize targets and assembly printers/parsers.
1615 llvm::InitializeAllTargetInfos();
1616 llvm::InitializeAllTargetMCs();
1617 llvm::InitializeAllDisassemblers();
1619 // Register the target printer for --version.
1620 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1622 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1623 TripleName = Triple::normalize(TripleName);
1627 // Defaults to a.out if no filenames specified.
1628 if (InputFilenames.size() == 0)
1629 InputFilenames.push_back("a.out");
1640 && !FirstPrivateHeader
1647 && !(UniversalHeaders && MachOOpt)
1648 && !(ArchiveHeaders && MachOOpt)
1649 && !(IndirectSymbols && MachOOpt)
1650 && !(DataInCode && MachOOpt)
1651 && !(LinkOptHints && MachOOpt)
1652 && !(InfoPlist && MachOOpt)
1653 && !(DylibsUsed && MachOOpt)
1654 && !(DylibId && MachOOpt)
1655 && !(ObjcMetaData && MachOOpt)
1656 && !(FilterSections.size() != 0 && MachOOpt)
1657 && !PrintFaultMaps) {
1658 cl::PrintHelpMessage();
1662 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1665 return EXIT_SUCCESS;