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/DebugInfo/DWARF/DWARFContext.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCDisassembler.h"
29 #include "llvm/MC/MCInst.h"
30 #include "llvm/MC/MCInstPrinter.h"
31 #include "llvm/MC/MCInstrAnalysis.h"
32 #include "llvm/MC/MCInstrInfo.h"
33 #include "llvm/MC/MCObjectFileInfo.h"
34 #include "llvm/MC/MCRegisterInfo.h"
35 #include "llvm/MC/MCRelocationInfo.h"
36 #include "llvm/MC/MCSubtargetInfo.h"
37 #include "llvm/Object/Archive.h"
38 #include "llvm/Object/ELFObjectFile.h"
39 #include "llvm/Object/COFF.h"
40 #include "llvm/Object/MachO.h"
41 #include "llvm/Object/ObjectFile.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/Errc.h"
46 #include "llvm/Support/FileSystem.h"
47 #include "llvm/Support/Format.h"
48 #include "llvm/Support/GraphWriter.h"
49 #include "llvm/Support/Host.h"
50 #include "llvm/Support/ManagedStatic.h"
51 #include "llvm/Support/MemoryBuffer.h"
52 #include "llvm/Support/PrettyStackTrace.h"
53 #include "llvm/Support/Signals.h"
54 #include "llvm/Support/SourceMgr.h"
55 #include "llvm/Support/TargetRegistry.h"
56 #include "llvm/Support/TargetSelect.h"
57 #include "llvm/Support/raw_ostream.h"
61 #include <system_error>
64 using namespace object;
66 static cl::list<std::string>
67 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
70 llvm::Disassemble("disassemble",
71 cl::desc("Display assembler mnemonics for the machine instructions"));
73 Disassembled("d", cl::desc("Alias for --disassemble"),
74 cl::aliasopt(Disassemble));
77 llvm::DisassembleAll("disassemble-all",
78 cl::desc("Display assembler mnemonics for the machine instructions"));
80 DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
81 cl::aliasopt(DisassembleAll));
84 llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
87 llvm::SectionContents("s", cl::desc("Display the content of each section"));
90 llvm::SymbolTable("t", cl::desc("Display the symbol table"));
93 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
96 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
99 llvm::Bind("bind", cl::desc("Display mach-o binding info"));
102 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
105 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
108 llvm::RawClangAST("raw-clang-ast",
109 cl::desc("Dump the raw binary contents of the clang AST section"));
112 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
114 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
117 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
118 "see -version for available targets"));
122 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
123 cl::value_desc("cpu-name"),
127 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
128 "see -version for available targets"));
131 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
132 "headers for each section."));
134 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
135 cl::aliasopt(SectionHeaders));
137 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
138 cl::aliasopt(SectionHeaders));
140 cl::list<std::string>
141 llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
142 "With -macho dump segment,section"));
144 static FilterSectionsj("j", cl::desc("Alias for --section"),
145 cl::aliasopt(llvm::FilterSections));
147 cl::list<std::string>
148 llvm::MAttrs("mattr",
150 cl::desc("Target specific attributes"),
151 cl::value_desc("a1,+a2,-a3,..."));
154 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
155 "instructions, do not print "
156 "the instruction bytes."));
159 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
162 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
163 cl::aliasopt(UnwindInfo));
166 llvm::PrivateHeaders("private-headers",
167 cl::desc("Display format specific file headers"));
170 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
171 cl::aliasopt(PrivateHeaders));
174 llvm::PrintImmHex("print-imm-hex",
175 cl::desc("Use hex format for immediate values"));
177 cl::opt<bool> PrintFaultMaps("fault-map-section",
178 cl::desc("Display contents of faultmap section"));
180 cl::opt<DIDumpType> llvm::DwarfDumpType(
181 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
182 cl::values(clEnumValN(DIDT_Frames, "frames", ".debug_frame"),
185 static StringRef ToolName;
188 typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
190 class SectionFilterIterator {
192 SectionFilterIterator(FilterPredicate P,
193 llvm::object::section_iterator const &I,
194 llvm::object::section_iterator const &E)
195 : Predicate(P), Iterator(I), End(E) {
198 const llvm::object::SectionRef &operator*() const { return *Iterator; }
199 SectionFilterIterator &operator++() {
204 bool operator!=(SectionFilterIterator const &Other) const {
205 return Iterator != Other.Iterator;
209 void ScanPredicate() {
210 while (Iterator != End && !Predicate(*Iterator)) {
214 FilterPredicate Predicate;
215 llvm::object::section_iterator Iterator;
216 llvm::object::section_iterator End;
219 class SectionFilter {
221 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
222 : Predicate(P), Object(O) {}
223 SectionFilterIterator begin() {
224 return SectionFilterIterator(Predicate, Object.section_begin(),
225 Object.section_end());
227 SectionFilterIterator end() {
228 return SectionFilterIterator(Predicate, Object.section_end(),
229 Object.section_end());
233 FilterPredicate Predicate;
234 llvm::object::ObjectFile const &Object;
236 SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
237 return SectionFilter([](llvm::object::SectionRef const &S) {
238 if(FilterSections.empty())
240 llvm::StringRef String;
241 std::error_code error = S.getName(String);
244 return std::find(FilterSections.begin(),
245 FilterSections.end(),
246 String) != FilterSections.end();
252 void llvm::error(std::error_code EC) {
256 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
261 void llvm::report_error(StringRef File, 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:
494 Result.append(res.begin(), res.end());
495 return std::error_code();
498 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
499 const RelocationRef &Rel,
500 SmallVectorImpl<char> &Result) {
501 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
502 return getRelocationValueString(ELF32LE, Rel, Result);
503 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
504 return getRelocationValueString(ELF64LE, Rel, Result);
505 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
506 return getRelocationValueString(ELF32BE, Rel, Result);
507 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
508 return getRelocationValueString(ELF64BE, Rel, Result);
511 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
512 const RelocationRef &Rel,
513 SmallVectorImpl<char> &Result) {
514 symbol_iterator SymI = Rel.getSymbol();
515 ErrorOr<StringRef> SymNameOrErr = SymI->getName();
516 if (std::error_code EC = SymNameOrErr.getError())
518 StringRef SymName = *SymNameOrErr;
519 Result.append(SymName.begin(), SymName.end());
520 return std::error_code();
523 static void printRelocationTargetName(const MachOObjectFile *O,
524 const MachO::any_relocation_info &RE,
525 raw_string_ostream &fmt) {
526 bool IsScattered = O->isRelocationScattered(RE);
528 // Target of a scattered relocation is an address. In the interest of
529 // generating pretty output, scan through the symbol table looking for a
530 // symbol that aligns with that address. If we find one, print it.
531 // Otherwise, we just print the hex address of the target.
533 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
535 for (const SymbolRef &Symbol : O->symbols()) {
537 ErrorOr<uint64_t> Addr = Symbol.getAddress();
538 if ((ec = Addr.getError()))
539 report_fatal_error(ec.message());
542 ErrorOr<StringRef> Name = Symbol.getName();
543 if (std::error_code EC = Name.getError())
544 report_fatal_error(EC.message());
549 // If we couldn't find a symbol that this relocation refers to, try
550 // to find a section beginning instead.
551 for (const SectionRef &Section : ToolSectionFilter(*O)) {
555 uint64_t Addr = Section.getAddress();
558 if ((ec = Section.getName(Name)))
559 report_fatal_error(ec.message());
564 fmt << format("0x%x", Val);
569 bool isExtern = O->getPlainRelocationExternal(RE);
570 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
573 symbol_iterator SI = O->symbol_begin();
575 ErrorOr<StringRef> SOrErr = SI->getName();
576 error(SOrErr.getError());
579 section_iterator SI = O->section_begin();
580 // Adjust for the fact that sections are 1-indexed.
581 advance(SI, Val - 1);
588 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
589 const RelocationRef &RelRef,
590 SmallVectorImpl<char> &Result) {
591 DataRefImpl Rel = RelRef.getRawDataRefImpl();
592 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
594 unsigned Arch = Obj->getArch();
597 raw_string_ostream fmt(fmtbuf);
598 unsigned Type = Obj->getAnyRelocationType(RE);
599 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
601 // Determine any addends that should be displayed with the relocation.
602 // These require decoding the relocation type, which is triple-specific.
604 // X86_64 has entirely custom relocation types.
605 if (Arch == Triple::x86_64) {
606 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
609 case MachO::X86_64_RELOC_GOT_LOAD:
610 case MachO::X86_64_RELOC_GOT: {
611 printRelocationTargetName(Obj, RE, fmt);
617 case MachO::X86_64_RELOC_SUBTRACTOR: {
618 DataRefImpl RelNext = Rel;
619 Obj->moveRelocationNext(RelNext);
620 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
622 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
623 // X86_64_RELOC_UNSIGNED.
624 // NOTE: Scattered relocations don't exist on x86_64.
625 unsigned RType = Obj->getAnyRelocationType(RENext);
626 if (RType != MachO::X86_64_RELOC_UNSIGNED)
627 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
628 "X86_64_RELOC_SUBTRACTOR.");
630 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
631 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
632 printRelocationTargetName(Obj, RENext, fmt);
634 printRelocationTargetName(Obj, RE, fmt);
637 case MachO::X86_64_RELOC_TLV:
638 printRelocationTargetName(Obj, RE, fmt);
643 case MachO::X86_64_RELOC_SIGNED_1:
644 printRelocationTargetName(Obj, RE, fmt);
647 case MachO::X86_64_RELOC_SIGNED_2:
648 printRelocationTargetName(Obj, RE, fmt);
651 case MachO::X86_64_RELOC_SIGNED_4:
652 printRelocationTargetName(Obj, RE, fmt);
656 printRelocationTargetName(Obj, RE, fmt);
659 // X86 and ARM share some relocation types in common.
660 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
661 Arch == Triple::ppc) {
662 // Generic relocation types...
664 case MachO::GENERIC_RELOC_PAIR: // prints no info
665 return std::error_code();
666 case MachO::GENERIC_RELOC_SECTDIFF: {
667 DataRefImpl RelNext = Rel;
668 Obj->moveRelocationNext(RelNext);
669 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
671 // X86 sect diff's must be followed by a relocation of type
672 // GENERIC_RELOC_PAIR.
673 unsigned RType = Obj->getAnyRelocationType(RENext);
675 if (RType != MachO::GENERIC_RELOC_PAIR)
676 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
677 "GENERIC_RELOC_SECTDIFF.");
679 printRelocationTargetName(Obj, RE, fmt);
681 printRelocationTargetName(Obj, RENext, fmt);
686 if (Arch == Triple::x86 || Arch == Triple::ppc) {
688 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
689 DataRefImpl RelNext = Rel;
690 Obj->moveRelocationNext(RelNext);
691 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
693 // X86 sect diff's must be followed by a relocation of type
694 // GENERIC_RELOC_PAIR.
695 unsigned RType = Obj->getAnyRelocationType(RENext);
696 if (RType != MachO::GENERIC_RELOC_PAIR)
697 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
698 "GENERIC_RELOC_LOCAL_SECTDIFF.");
700 printRelocationTargetName(Obj, RE, fmt);
702 printRelocationTargetName(Obj, RENext, fmt);
705 case MachO::GENERIC_RELOC_TLV: {
706 printRelocationTargetName(Obj, RE, fmt);
713 printRelocationTargetName(Obj, RE, fmt);
715 } else { // ARM-specific relocations
717 case MachO::ARM_RELOC_HALF:
718 case MachO::ARM_RELOC_HALF_SECTDIFF: {
719 // Half relocations steal a bit from the length field to encode
720 // whether this is an upper16 or a lower16 relocation.
721 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
727 printRelocationTargetName(Obj, RE, fmt);
729 DataRefImpl RelNext = Rel;
730 Obj->moveRelocationNext(RelNext);
731 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
733 // ARM half relocs must be followed by a relocation of type
735 unsigned RType = Obj->getAnyRelocationType(RENext);
736 if (RType != MachO::ARM_RELOC_PAIR)
737 report_fatal_error("Expected ARM_RELOC_PAIR after "
740 // NOTE: The half of the target virtual address is stashed in the
741 // address field of the secondary relocation, but we can't reverse
742 // engineer the constant offset from it without decoding the movw/movt
743 // instruction to find the other half in its immediate field.
745 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
746 // symbol/section pointer of the follow-on relocation.
747 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
749 printRelocationTargetName(Obj, RENext, fmt);
755 default: { printRelocationTargetName(Obj, RE, fmt); }
759 printRelocationTargetName(Obj, RE, fmt);
762 Result.append(fmtbuf.begin(), fmtbuf.end());
763 return std::error_code();
766 static std::error_code getRelocationValueString(const RelocationRef &Rel,
767 SmallVectorImpl<char> &Result) {
768 const ObjectFile *Obj = Rel.getObject();
769 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
770 return getRelocationValueString(ELF, Rel, Result);
771 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
772 return getRelocationValueString(COFF, Rel, Result);
773 auto *MachO = cast<MachOObjectFile>(Obj);
774 return getRelocationValueString(MachO, Rel, Result);
777 /// @brief Indicates whether this relocation should hidden when listing
778 /// relocations, usually because it is the trailing part of a multipart
779 /// relocation that will be printed as part of the leading relocation.
780 static bool getHidden(RelocationRef RelRef) {
781 const ObjectFile *Obj = RelRef.getObject();
782 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
786 unsigned Arch = MachO->getArch();
787 DataRefImpl Rel = RelRef.getRawDataRefImpl();
788 uint64_t Type = MachO->getRelocationType(Rel);
790 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
792 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
793 if (Type == MachO::GENERIC_RELOC_PAIR)
795 } else if (Arch == Triple::x86_64) {
796 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
797 // an X86_64_RELOC_SUBTRACTOR.
798 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
799 DataRefImpl RelPrev = Rel;
801 uint64_t PrevType = MachO->getRelocationType(RelPrev);
802 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
810 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
811 const Target *TheTarget = getTarget(Obj);
813 // Package up features to be passed to target/subtarget
814 std::string FeaturesStr;
816 SubtargetFeatures Features;
817 for (unsigned i = 0; i != MAttrs.size(); ++i)
818 Features.AddFeature(MAttrs[i]);
819 FeaturesStr = Features.getString();
822 std::unique_ptr<const MCRegisterInfo> MRI(
823 TheTarget->createMCRegInfo(TripleName));
825 report_fatal_error("error: no register info for target " + TripleName);
827 // Set up disassembler.
828 std::unique_ptr<const MCAsmInfo> AsmInfo(
829 TheTarget->createMCAsmInfo(*MRI, TripleName));
831 report_fatal_error("error: no assembly info for target " + TripleName);
832 std::unique_ptr<const MCSubtargetInfo> STI(
833 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
835 report_fatal_error("error: no subtarget info for target " + TripleName);
836 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
838 report_fatal_error("error: no instruction info for target " + TripleName);
839 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
840 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
842 std::unique_ptr<MCDisassembler> DisAsm(
843 TheTarget->createMCDisassembler(*STI, Ctx));
845 report_fatal_error("error: no disassembler for target " + TripleName);
847 std::unique_ptr<const MCInstrAnalysis> MIA(
848 TheTarget->createMCInstrAnalysis(MII.get()));
850 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
851 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
852 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
854 report_fatal_error("error: no instruction printer for target " +
856 IP->setPrintImmHex(PrintImmHex);
857 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
859 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
860 "\t\t\t%08" PRIx64 ": ";
862 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
863 // in RelocSecs contain the relocations for section S.
865 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
866 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
867 section_iterator Sec2 = Section.getRelocatedSection();
868 if (Sec2 != Obj->section_end())
869 SectionRelocMap[*Sec2].push_back(Section);
872 // Create a mapping from virtual address to symbol name. This is used to
873 // pretty print the symbols while disassembling.
874 typedef std::vector<std::pair<uint64_t, StringRef>> SectionSymbolsTy;
875 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
876 for (const SymbolRef &Symbol : Obj->symbols()) {
877 ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
878 error(AddressOrErr.getError());
879 uint64_t Address = *AddressOrErr;
881 ErrorOr<StringRef> Name = Symbol.getName();
882 error(Name.getError());
886 ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
887 error(SectionOrErr.getError());
888 section_iterator SecI = *SectionOrErr;
889 if (SecI == Obj->section_end())
892 AllSymbols[*SecI].emplace_back(Address, *Name);
895 // Create a mapping from virtual address to section.
896 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
897 for (SectionRef Sec : Obj->sections())
898 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
899 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
901 // Linked executables (.exe and .dll files) typically don't include a real
902 // symbol table but they might contain an export table.
903 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
904 for (const auto &ExportEntry : COFFObj->export_directories()) {
906 error(ExportEntry.getSymbolName(Name));
910 error(ExportEntry.getExportRVA(RVA));
912 uint64_t VA = COFFObj->getImageBase() + RVA;
913 auto Sec = std::upper_bound(
914 SectionAddresses.begin(), SectionAddresses.end(), VA,
915 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
916 return LHS < RHS.first;
918 if (Sec != SectionAddresses.begin())
921 Sec = SectionAddresses.end();
923 if (Sec != SectionAddresses.end())
924 AllSymbols[Sec->second].emplace_back(VA, Name);
928 // Sort all the symbols, this allows us to use a simple binary search to find
929 // a symbol near an address.
930 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
931 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
933 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
934 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
937 uint64_t SectionAddr = Section.getAddress();
938 uint64_t SectSize = Section.getSize();
942 // Get the list of all the symbols in this section.
943 SectionSymbolsTy &Symbols = AllSymbols[Section];
944 std::vector<uint64_t> DataMappingSymsAddr;
945 std::vector<uint64_t> TextMappingSymsAddr;
946 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
947 for (const auto &Symb : Symbols) {
948 uint64_t Address = Symb.first;
949 StringRef Name = Symb.second;
950 if (Name.startswith("$d"))
951 DataMappingSymsAddr.push_back(Address - SectionAddr);
952 if (Name.startswith("$x"))
953 TextMappingSymsAddr.push_back(Address - SectionAddr);
957 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
958 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
960 // Make a list of all the relocations for this section.
961 std::vector<RelocationRef> Rels;
963 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
964 for (const RelocationRef &Reloc : RelocSec.relocations()) {
965 Rels.push_back(Reloc);
970 // Sort relocations by address.
971 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
973 StringRef SegmentName = "";
974 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
975 DataRefImpl DR = Section.getRawDataRefImpl();
976 SegmentName = MachO->getSectionFinalSegmentName(DR);
979 error(Section.getName(name));
980 outs() << "Disassembly of section ";
981 if (!SegmentName.empty())
982 outs() << SegmentName << ",";
983 outs() << name << ':';
985 // If the section has no symbol at the start, just insert a dummy one.
986 if (Symbols.empty() || Symbols[0].first != 0)
987 Symbols.insert(Symbols.begin(), std::make_pair(SectionAddr, name));
989 SmallString<40> Comments;
990 raw_svector_ostream CommentStream(Comments);
993 error(Section.getContents(BytesStr));
994 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1000 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1001 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
1002 // Disassemble symbol by symbol.
1003 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
1005 uint64_t Start = Symbols[si].first - SectionAddr;
1006 // The end is either the section end or the beginning of the next
1009 (si == se - 1) ? SectSize : Symbols[si + 1].first - SectionAddr;
1010 // Don't try to disassemble beyond the end of section contents.
1013 // If this symbol has the same address as the next symbol, then skip it.
1017 outs() << '\n' << Symbols[si].second << ":\n";
1020 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1022 raw_ostream &DebugOut = nulls();
1025 for (Index = Start; Index < End; Index += Size) {
1028 // AArch64 ELF binaries can interleave data and text in the
1029 // same section. We rely on the markers introduced to
1030 // understand what we need to dump.
1031 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1032 uint64_t Stride = 0;
1034 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1035 DataMappingSymsAddr.end(), Index);
1036 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1038 while (Index < End) {
1039 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1041 if (Index + 4 <= End) {
1043 dumpBytes(Bytes.slice(Index, 4), outs());
1044 outs() << "\t.word";
1045 } else if (Index + 2 <= End) {
1047 dumpBytes(Bytes.slice(Index, 2), outs());
1048 outs() << "\t.short";
1051 dumpBytes(Bytes.slice(Index, 1), outs());
1052 outs() << "\t.byte";
1056 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1057 TextMappingSymsAddr.end(), Index);
1058 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1067 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1068 SectionAddr + Index, DebugOut,
1070 PIP.printInst(*IP, &Inst,
1071 Bytes.slice(Index, Size),
1072 SectionAddr + Index, outs(), "", *STI);
1073 outs() << CommentStream.str();
1076 // Try to resolve the target of a call, tail call, etc. to a specific
1078 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1079 MIA->isConditionalBranch(Inst))) {
1081 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1082 // In a relocatable object, the target's section must reside in
1083 // the same section as the call instruction or it is accessed
1084 // through a relocation.
1086 // In a non-relocatable object, the target may be in any section.
1088 // N.B. We don't walk the relocations in the relocatable case yet.
1089 auto *TargetSectionSymbols = &Symbols;
1090 if (!Obj->isRelocatableObject()) {
1091 auto SectionAddress = std::upper_bound(
1092 SectionAddresses.begin(), SectionAddresses.end(), Target,
1094 const std::pair<uint64_t, SectionRef> &RHS) {
1095 return LHS < RHS.first;
1097 if (SectionAddress != SectionAddresses.begin()) {
1099 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1101 TargetSectionSymbols = nullptr;
1105 // Find the first symbol in the section whose offset is less than
1106 // or equal to the target.
1107 if (TargetSectionSymbols) {
1108 auto TargetSym = std::upper_bound(
1109 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1110 Target, [](uint64_t LHS,
1111 const std::pair<uint64_t, StringRef> &RHS) {
1112 return LHS < RHS.first;
1114 if (TargetSym != TargetSectionSymbols->begin()) {
1116 uint64_t TargetAddress = std::get<0>(*TargetSym);
1117 StringRef TargetName = std::get<1>(*TargetSym);
1118 outs() << " <" << TargetName;
1119 uint64_t Disp = Target - TargetAddress;
1121 outs() << '+' << utohexstr(Disp);
1129 errs() << ToolName << ": warning: invalid instruction encoding\n";
1131 Size = 1; // skip illegible bytes
1134 // Print relocation for instruction.
1135 while (rel_cur != rel_end) {
1136 bool hidden = getHidden(*rel_cur);
1137 uint64_t addr = rel_cur->getOffset();
1138 SmallString<16> name;
1139 SmallString<32> val;
1141 // If this relocation is hidden, skip it.
1142 if (hidden) goto skip_print_rel;
1144 // Stop when rel_cur's address is past the current instruction.
1145 if (addr >= Index + Size) break;
1146 rel_cur->getTypeName(name);
1147 error(getRelocationValueString(*rel_cur, val));
1148 outs() << format(Fmt.data(), SectionAddr + addr) << name
1149 << "\t" << val << "\n";
1159 void llvm::PrintRelocations(const ObjectFile *Obj) {
1160 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1162 // Regular objdump doesn't print relocations in non-relocatable object
1164 if (!Obj->isRelocatableObject())
1167 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1168 if (Section.relocation_begin() == Section.relocation_end())
1171 error(Section.getName(secname));
1172 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
1173 for (const RelocationRef &Reloc : Section.relocations()) {
1174 bool hidden = getHidden(Reloc);
1175 uint64_t address = Reloc.getOffset();
1176 SmallString<32> relocname;
1177 SmallString<32> valuestr;
1180 Reloc.getTypeName(relocname);
1181 error(getRelocationValueString(Reloc, valuestr));
1182 outs() << format(Fmt.data(), address) << " " << relocname << " "
1183 << valuestr << "\n";
1189 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
1190 outs() << "Sections:\n"
1191 "Idx Name Size Address Type\n";
1193 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1195 error(Section.getName(Name));
1196 uint64_t Address = Section.getAddress();
1197 uint64_t Size = Section.getSize();
1198 bool Text = Section.isText();
1199 bool Data = Section.isData();
1200 bool BSS = Section.isBSS();
1201 std::string Type = (std::string(Text ? "TEXT " : "") +
1202 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1203 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1204 Name.str().c_str(), Size, Address, Type.c_str());
1209 void llvm::PrintSectionContents(const ObjectFile *Obj) {
1211 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1214 error(Section.getName(Name));
1215 uint64_t BaseAddr = Section.getAddress();
1216 uint64_t Size = Section.getSize();
1220 outs() << "Contents of section " << Name << ":\n";
1221 if (Section.isBSS()) {
1222 outs() << format("<skipping contents of bss section at [%04" PRIx64
1223 ", %04" PRIx64 ")>\n",
1224 BaseAddr, BaseAddr + Size);
1228 error(Section.getContents(Contents));
1230 // Dump out the content as hex and printable ascii characters.
1231 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1232 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1233 // Dump line of hex.
1234 for (std::size_t i = 0; i < 16; ++i) {
1235 if (i != 0 && i % 4 == 0)
1238 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1239 << hexdigit(Contents[addr + i] & 0xF, true);
1245 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1246 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1247 outs() << Contents[addr + i];
1256 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
1257 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1258 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
1260 error(Symbol.getError());
1261 error(coff->getSymbolName(*Symbol, Name));
1263 outs() << "[" << format("%2d", SI) << "]"
1264 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
1265 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
1266 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1267 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1268 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1269 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
1272 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
1273 if (Symbol->isSectionDefinition()) {
1274 const coff_aux_section_definition *asd;
1275 error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd));
1277 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1280 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1281 , unsigned(asd->Length)
1282 , unsigned(asd->NumberOfRelocations)
1283 , unsigned(asd->NumberOfLinenumbers)
1284 , unsigned(asd->CheckSum))
1285 << format("assoc %d comdat %d\n"
1286 , unsigned(AuxNumber)
1287 , unsigned(asd->Selection));
1288 } else if (Symbol->isFileRecord()) {
1289 const char *FileName;
1290 error(coff->getAuxSymbol<char>(SI + 1, FileName));
1292 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1293 coff->getSymbolTableEntrySize());
1294 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
1296 SI = SI + Symbol->getNumberOfAuxSymbols();
1299 outs() << "AUX Unknown\n";
1305 void llvm::PrintSymbolTable(const ObjectFile *o) {
1306 outs() << "SYMBOL TABLE:\n";
1308 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1309 PrintCOFFSymbolTable(coff);
1312 for (const SymbolRef &Symbol : o->symbols()) {
1313 ErrorOr<uint64_t> AddressOrError = Symbol.getAddress();
1314 error(AddressOrError.getError());
1315 uint64_t Address = *AddressOrError;
1316 SymbolRef::Type Type = Symbol.getType();
1317 uint32_t Flags = Symbol.getFlags();
1318 ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
1319 error(SectionOrErr.getError());
1320 section_iterator Section = *SectionOrErr;
1322 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1323 Section->getName(Name);
1325 ErrorOr<StringRef> NameOrErr = Symbol.getName();
1326 error(NameOrErr.getError());
1330 bool Global = Flags & SymbolRef::SF_Global;
1331 bool Weak = Flags & SymbolRef::SF_Weak;
1332 bool Absolute = Flags & SymbolRef::SF_Absolute;
1333 bool Common = Flags & SymbolRef::SF_Common;
1334 bool Hidden = Flags & SymbolRef::SF_Hidden;
1337 if (Type != SymbolRef::ST_Unknown)
1338 GlobLoc = Global ? 'g' : 'l';
1339 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1341 char FileFunc = ' ';
1342 if (Type == SymbolRef::ST_File)
1344 else if (Type == SymbolRef::ST_Function)
1347 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1350 outs() << format(Fmt, Address) << " "
1351 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1352 << (Weak ? 'w' : ' ') // Weak?
1353 << ' ' // Constructor. Not supported yet.
1354 << ' ' // Warning. Not supported yet.
1355 << ' ' // Indirect reference to another symbol.
1356 << Debug // Debugging (d) or dynamic (D) symbol.
1357 << FileFunc // Name of function (F), file (f) or object (O).
1361 } else if (Common) {
1363 } else if (Section == o->section_end()) {
1366 if (const MachOObjectFile *MachO =
1367 dyn_cast<const MachOObjectFile>(o)) {
1368 DataRefImpl DR = Section->getRawDataRefImpl();
1369 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1370 outs() << SegmentName << ",";
1372 StringRef SectionName;
1373 error(Section->getName(SectionName));
1374 outs() << SectionName;
1378 if (Common || isa<ELFObjectFileBase>(o)) {
1380 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1381 outs() << format("\t %08" PRIx64 " ", Val);
1385 outs() << ".hidden ";
1392 static void PrintUnwindInfo(const ObjectFile *o) {
1393 outs() << "Unwind info:\n\n";
1395 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1396 printCOFFUnwindInfo(coff);
1397 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1398 printMachOUnwindInfo(MachO);
1400 // TODO: Extract DWARF dump tool to objdump.
1401 errs() << "This operation is only currently supported "
1402 "for COFF and MachO object files.\n";
1407 void llvm::printExportsTrie(const ObjectFile *o) {
1408 outs() << "Exports trie:\n";
1409 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1410 printMachOExportsTrie(MachO);
1412 errs() << "This operation is only currently supported "
1413 "for Mach-O executable files.\n";
1418 void llvm::printRebaseTable(const ObjectFile *o) {
1419 outs() << "Rebase table:\n";
1420 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1421 printMachORebaseTable(MachO);
1423 errs() << "This operation is only currently supported "
1424 "for Mach-O executable files.\n";
1429 void llvm::printBindTable(const ObjectFile *o) {
1430 outs() << "Bind table:\n";
1431 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1432 printMachOBindTable(MachO);
1434 errs() << "This operation is only currently supported "
1435 "for Mach-O executable files.\n";
1440 void llvm::printLazyBindTable(const ObjectFile *o) {
1441 outs() << "Lazy bind table:\n";
1442 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1443 printMachOLazyBindTable(MachO);
1445 errs() << "This operation is only currently supported "
1446 "for Mach-O executable files.\n";
1451 void llvm::printWeakBindTable(const ObjectFile *o) {
1452 outs() << "Weak bind table:\n";
1453 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1454 printMachOWeakBindTable(MachO);
1456 errs() << "This operation is only currently supported "
1457 "for Mach-O executable files.\n";
1462 /// Dump the raw contents of the __clangast section so the output can be piped
1463 /// into llvm-bcanalyzer.
1464 void llvm::printRawClangAST(const ObjectFile *Obj) {
1465 if (outs().is_displayed()) {
1466 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1467 "the clang ast section.\n"
1468 "Please redirect the output to a file or another program such as "
1469 "llvm-bcanalyzer.\n";
1473 StringRef ClangASTSectionName("__clangast");
1474 if (isa<COFFObjectFile>(Obj)) {
1475 ClangASTSectionName = "clangast";
1478 Optional<object::SectionRef> ClangASTSection;
1479 for (auto Sec : ToolSectionFilter(*Obj)) {
1482 if (Name == ClangASTSectionName) {
1483 ClangASTSection = Sec;
1487 if (!ClangASTSection)
1490 StringRef ClangASTContents;
1491 error(ClangASTSection.getValue().getContents(ClangASTContents));
1492 outs().write(ClangASTContents.data(), ClangASTContents.size());
1495 static void printFaultMaps(const ObjectFile *Obj) {
1496 const char *FaultMapSectionName = nullptr;
1498 if (isa<ELFObjectFileBase>(Obj)) {
1499 FaultMapSectionName = ".llvm_faultmaps";
1500 } else if (isa<MachOObjectFile>(Obj)) {
1501 FaultMapSectionName = "__llvm_faultmaps";
1503 errs() << "This operation is only currently supported "
1504 "for ELF and Mach-O executable files.\n";
1508 Optional<object::SectionRef> FaultMapSection;
1510 for (auto Sec : ToolSectionFilter(*Obj)) {
1513 if (Name == FaultMapSectionName) {
1514 FaultMapSection = Sec;
1519 outs() << "FaultMap table:\n";
1521 if (!FaultMapSection.hasValue()) {
1522 outs() << "<not found>\n";
1526 StringRef FaultMapContents;
1527 error(FaultMapSection.getValue().getContents(FaultMapContents));
1529 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1530 FaultMapContents.bytes_end());
1535 static void printPrivateFileHeader(const ObjectFile *o) {
1537 printELFFileHeader(o);
1538 } else if (o->isCOFF()) {
1539 printCOFFFileHeader(o);
1540 } else if (o->isMachO()) {
1541 printMachOFileHeader(o);
1545 static void DumpObject(const ObjectFile *o) {
1546 // Avoid other output when using a raw option.
1549 outs() << o->getFileName()
1550 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1554 DisassembleObject(o, Relocations);
1555 if (Relocations && !Disassemble)
1556 PrintRelocations(o);
1558 PrintSectionHeaders(o);
1559 if (SectionContents)
1560 PrintSectionContents(o);
1562 PrintSymbolTable(o);
1566 printPrivateFileHeader(o);
1568 printExportsTrie(o);
1570 printRebaseTable(o);
1574 printLazyBindTable(o);
1576 printWeakBindTable(o);
1578 printRawClangAST(o);
1581 if (DwarfDumpType != DIDT_Null) {
1582 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o));
1583 // Dump the complete DWARF structure.
1584 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1588 /// @brief Dump each object file in \a a;
1589 static void DumpArchive(const Archive *a) {
1590 for (auto &ErrorOrChild : a->children()) {
1591 if (std::error_code EC = ErrorOrChild.getError())
1592 report_error(a->getFileName(), EC);
1593 const Archive::Child &C = *ErrorOrChild;
1594 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1595 if (std::error_code EC = ChildOrErr.getError())
1596 if (EC != object_error::invalid_file_type)
1597 report_error(a->getFileName(), EC);
1598 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
1601 report_error(a->getFileName(), object_error::invalid_file_type);
1605 /// @brief Open file and figure out how to dump it.
1606 static void DumpInput(StringRef file) {
1608 // If we are using the Mach-O specific object file parser, then let it parse
1609 // the file and process the command line options. So the -arch flags can
1610 // be used to select specific slices, etc.
1612 ParseInputMachO(file);
1616 // Attempt to open the binary.
1617 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1618 if (std::error_code EC = BinaryOrErr.getError())
1619 report_error(file, EC);
1620 Binary &Binary = *BinaryOrErr.get().getBinary();
1622 if (Archive *a = dyn_cast<Archive>(&Binary))
1624 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
1627 report_error(file, object_error::invalid_file_type);
1630 int main(int argc, char **argv) {
1631 // Print a stack trace if we signal out.
1632 sys::PrintStackTraceOnErrorSignal();
1633 PrettyStackTraceProgram X(argc, argv);
1634 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1636 // Initialize targets and assembly printers/parsers.
1637 llvm::InitializeAllTargetInfos();
1638 llvm::InitializeAllTargetMCs();
1639 llvm::InitializeAllDisassemblers();
1641 // Register the target printer for --version.
1642 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1644 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1645 TripleName = Triple::normalize(TripleName);
1649 // Defaults to a.out if no filenames specified.
1650 if (InputFilenames.size() == 0)
1651 InputFilenames.push_back("a.out");
1668 && !(UniversalHeaders && MachOOpt)
1669 && !(ArchiveHeaders && MachOOpt)
1670 && !(IndirectSymbols && MachOOpt)
1671 && !(DataInCode && MachOOpt)
1672 && !(LinkOptHints && MachOOpt)
1673 && !(InfoPlist && MachOOpt)
1674 && !(DylibsUsed && MachOOpt)
1675 && !(DylibId && MachOOpt)
1676 && !(ObjcMetaData && MachOOpt)
1677 && !(FilterSections.size() != 0 && MachOOpt)
1679 && DwarfDumpType == DIDT_Null) {
1680 cl::PrintHelpMessage();
1684 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1687 return EXIT_SUCCESS;