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/MCDisassembler.h"
29 #include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
30 #include "llvm/MC/MCInst.h"
31 #include "llvm/MC/MCInstPrinter.h"
32 #include "llvm/MC/MCInstrAnalysis.h"
33 #include "llvm/MC/MCInstrInfo.h"
34 #include "llvm/MC/MCObjectFileInfo.h"
35 #include "llvm/MC/MCRegisterInfo.h"
36 #include "llvm/MC/MCSubtargetInfo.h"
37 #include "llvm/Object/Archive.h"
38 #include "llvm/Object/COFF.h"
39 #include "llvm/Object/ELFObjectFile.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>
65 using namespace object;
67 static cl::list<std::string>
68 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
71 llvm::Disassemble("disassemble",
72 cl::desc("Display assembler mnemonics for the machine instructions"));
74 Disassembled("d", cl::desc("Alias for --disassemble"),
75 cl::aliasopt(Disassemble));
78 llvm::DisassembleAll("disassemble-all",
79 cl::desc("Display assembler mnemonics for the machine instructions"));
81 DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
82 cl::aliasopt(DisassembleAll));
85 llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
88 llvm::SectionContents("s", cl::desc("Display the content of each section"));
91 llvm::SymbolTable("t", cl::desc("Display the symbol table"));
94 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
97 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
100 llvm::Bind("bind", cl::desc("Display mach-o binding info"));
103 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
106 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
109 llvm::RawClangAST("raw-clang-ast",
110 cl::desc("Dump the raw binary contents of the clang AST section"));
113 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
115 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
118 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
119 "see -version for available targets"));
123 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
124 cl::value_desc("cpu-name"),
128 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
129 "see -version for available targets"));
132 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
133 "headers for each section."));
135 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
136 cl::aliasopt(SectionHeaders));
138 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
139 cl::aliasopt(SectionHeaders));
141 cl::list<std::string>
142 llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
143 "With -macho dump segment,section"));
145 static FilterSectionsj("j", cl::desc("Alias for --section"),
146 cl::aliasopt(llvm::FilterSections));
148 cl::list<std::string>
149 llvm::MAttrs("mattr",
151 cl::desc("Target specific attributes"),
152 cl::value_desc("a1,+a2,-a3,..."));
155 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
156 "instructions, do not print "
157 "the instruction bytes."));
160 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
163 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
164 cl::aliasopt(UnwindInfo));
167 llvm::PrivateHeaders("private-headers",
168 cl::desc("Display format specific file headers"));
171 llvm::FirstPrivateHeader("private-header",
172 cl::desc("Display only the first format specific file "
176 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
177 cl::aliasopt(PrivateHeaders));
180 llvm::PrintImmHex("print-imm-hex",
181 cl::desc("Use hex format for immediate values"));
183 cl::opt<bool> PrintFaultMaps("fault-map-section",
184 cl::desc("Display contents of faultmap section"));
186 cl::opt<DIDumpType> llvm::DwarfDumpType(
187 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
188 cl::values(clEnumValN(DIDT_Frames, "frames", ".debug_frame"),
191 static StringRef ToolName;
194 typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
196 class SectionFilterIterator {
198 SectionFilterIterator(FilterPredicate P,
199 llvm::object::section_iterator const &I,
200 llvm::object::section_iterator const &E)
201 : Predicate(std::move(P)), Iterator(I), End(E) {
204 const llvm::object::SectionRef &operator*() const { return *Iterator; }
205 SectionFilterIterator &operator++() {
210 bool operator!=(SectionFilterIterator const &Other) const {
211 return Iterator != Other.Iterator;
215 void ScanPredicate() {
216 while (Iterator != End && !Predicate(*Iterator)) {
220 FilterPredicate Predicate;
221 llvm::object::section_iterator Iterator;
222 llvm::object::section_iterator End;
225 class SectionFilter {
227 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
228 : Predicate(std::move(P)), Object(O) {}
229 SectionFilterIterator begin() {
230 return SectionFilterIterator(Predicate, Object.section_begin(),
231 Object.section_end());
233 SectionFilterIterator end() {
234 return SectionFilterIterator(Predicate, Object.section_end(),
235 Object.section_end());
239 FilterPredicate Predicate;
240 llvm::object::ObjectFile const &Object;
242 SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
243 return SectionFilter([](llvm::object::SectionRef const &S) {
244 if(FilterSections.empty())
246 llvm::StringRef String;
247 std::error_code error = S.getName(String);
250 return std::find(FilterSections.begin(),
251 FilterSections.end(),
252 String) != FilterSections.end();
258 void llvm::error(std::error_code EC) {
262 errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
267 LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
268 errs() << ToolName << ": " << Message << ".\n";
273 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
274 std::error_code EC) {
276 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
280 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
284 raw_string_ostream OS(Buf);
285 logAllUnhandledErrors(std::move(E), OS, "");
287 errs() << ToolName << ": '" << File << "': " << Buf;
291 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
294 StringRef ArchitectureName) {
296 errs() << ToolName << ": ";
297 if (ArchiveName != "")
298 errs() << ArchiveName << "(" << FileName << ")";
301 if (!ArchitectureName.empty())
302 errs() << " (for architecture " << ArchitectureName << ")";
304 raw_string_ostream OS(Buf);
305 logAllUnhandledErrors(std::move(E), OS, "");
307 errs() << " " << Buf;
311 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
312 const object::Archive::Child &C,
314 StringRef ArchitectureName) {
315 ErrorOr<StringRef> NameOrErr = C.getName();
316 // TODO: if we have a error getting the name then it would be nice to print
317 // the index of which archive member this is and or its offset in the
318 // archive instead of "???" as the name.
319 if (NameOrErr.getError())
320 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
322 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
326 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
327 // Figure out the target triple.
328 llvm::Triple TheTriple("unknown-unknown-unknown");
329 if (TripleName.empty()) {
331 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
332 // TheTriple defaults to ELF, and COFF doesn't have an environment:
333 // the best we can do here is indicate that it is mach-o.
335 TheTriple.setObjectFormat(Triple::MachO);
338 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
339 if (COFFObj->getArch() == Triple::thumb)
340 TheTriple.setTriple("thumbv7-windows");
344 TheTriple.setTriple(Triple::normalize(TripleName));
346 // Get the target specific parser.
348 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
351 report_fatal_error("can't find target: " + Error);
353 // Update the triple name and return the found target.
354 TripleName = TheTriple.getTriple();
358 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
359 return a.getOffset() < b.getOffset();
363 class PrettyPrinter {
365 virtual ~PrettyPrinter(){}
366 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
367 ArrayRef<uint8_t> Bytes, uint64_t Address,
368 raw_ostream &OS, StringRef Annot,
369 MCSubtargetInfo const &STI) {
370 OS << format("%8" PRIx64 ":", Address);
371 if (!NoShowRawInsn) {
373 dumpBytes(Bytes, OS);
376 IP.printInst(MI, OS, "", STI);
381 PrettyPrinter PrettyPrinterInst;
382 class HexagonPrettyPrinter : public PrettyPrinter {
384 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
387 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
388 OS << format("%8" PRIx64 ":", Address);
389 if (!NoShowRawInsn) {
391 dumpBytes(Bytes.slice(0, 4), OS);
392 OS << format("%08" PRIx32, opcode);
395 void printInst(MCInstPrinter &IP, const MCInst *MI,
396 ArrayRef<uint8_t> Bytes, uint64_t Address,
397 raw_ostream &OS, StringRef Annot,
398 MCSubtargetInfo const &STI) override {
400 printLead(Bytes, Address, OS);
406 raw_string_ostream TempStream(Buffer);
407 IP.printInst(MI, TempStream, "", STI);
409 StringRef Contents(Buffer);
410 // Split off bundle attributes
411 auto PacketBundle = Contents.rsplit('\n');
412 // Split off first instruction from the rest
413 auto HeadTail = PacketBundle.first.split('\n');
414 auto Preamble = " { ";
416 while(!HeadTail.first.empty()) {
419 printLead(Bytes, Address, OS);
423 auto Duplex = HeadTail.first.split('\v');
424 if(!Duplex.second.empty()){
427 Inst = Duplex.second;
430 Inst = HeadTail.first;
432 Bytes = Bytes.slice(4);
434 HeadTail = HeadTail.second.split('\n');
436 OS << " } " << PacketBundle.second;
439 HexagonPrettyPrinter HexagonPrettyPrinterInst;
441 class AMDGCNPrettyPrinter : public PrettyPrinter {
443 void printInst(MCInstPrinter &IP,
445 ArrayRef<uint8_t> Bytes,
449 MCSubtargetInfo const &STI) override {
455 SmallString<40> InstStr;
456 raw_svector_ostream IS(InstStr);
458 IP.printInst(MI, IS, "", STI);
460 OS << left_justify(IS.str(), 60) << format("// %012" PRIX64 ": ", Address);
461 typedef support::ulittle32_t U32;
462 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
463 Bytes.size() / sizeof(U32)))
464 // D should be explicitly casted to uint32_t here as it is passed
465 // by format to snprintf as vararg.
466 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
469 OS << "// " << Annot;
472 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
474 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
475 switch(Triple.getArch()) {
477 return PrettyPrinterInst;
478 case Triple::hexagon:
479 return HexagonPrettyPrinterInst;
481 return AMDGCNPrettyPrinterInst;
486 template <class ELFT>
487 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
488 const RelocationRef &RelRef,
489 SmallVectorImpl<char> &Result) {
490 DataRefImpl Rel = RelRef.getRawDataRefImpl();
492 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
493 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
494 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
496 const ELFFile<ELFT> &EF = *Obj->getELFFile();
498 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
499 if (std::error_code EC = SecOrErr.getError())
501 const Elf_Shdr *Sec = *SecOrErr;
502 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
503 if (std::error_code EC = SymTabOrErr.getError())
505 const Elf_Shdr *SymTab = *SymTabOrErr;
506 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
507 SymTab->sh_type == ELF::SHT_DYNSYM);
508 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
509 if (std::error_code EC = StrTabSec.getError())
511 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
512 if (std::error_code EC = StrTabOrErr.getError())
514 StringRef StrTab = *StrTabOrErr;
515 uint8_t type = RelRef.getType();
518 switch (Sec->sh_type) {
520 return object_error::parse_failed;
522 // TODO: Read implicit addend from section data.
525 case ELF::SHT_RELA: {
526 const Elf_Rela *ERela = Obj->getRela(Rel);
527 addend = ERela->r_addend;
531 symbol_iterator SI = RelRef.getSymbol();
532 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
534 if (symb->getType() == ELF::STT_SECTION) {
535 Expected<section_iterator> SymSI = SI->getSection();
537 return errorToErrorCode(SymSI.takeError());
538 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
539 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
540 if (std::error_code EC = SecName.getError())
544 Expected<StringRef> SymName = symb->getName(StrTab);
546 return errorToErrorCode(SymName.takeError());
549 switch (EF.getHeader()->e_machine) {
552 case ELF::R_X86_64_PC8:
553 case ELF::R_X86_64_PC16:
554 case ELF::R_X86_64_PC32: {
556 raw_string_ostream fmt(fmtbuf);
557 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
559 Result.append(fmtbuf.begin(), fmtbuf.end());
561 case ELF::R_X86_64_8:
562 case ELF::R_X86_64_16:
563 case ELF::R_X86_64_32:
564 case ELF::R_X86_64_32S:
565 case ELF::R_X86_64_64: {
567 raw_string_ostream fmt(fmtbuf);
568 fmt << Target << (addend < 0 ? "" : "+") << addend;
570 Result.append(fmtbuf.begin(), fmtbuf.end());
577 case ELF::EM_AARCH64: {
579 raw_string_ostream fmt(fmtbuf);
582 fmt << (addend < 0 ? "" : "+") << addend;
584 Result.append(fmtbuf.begin(), fmtbuf.end());
590 case ELF::EM_HEXAGON:
595 case ELF::EM_WEBASSEMBLY:
597 case ELF::R_WEBASSEMBLY_DATA: {
599 raw_string_ostream fmt(fmtbuf);
600 fmt << Target << (addend < 0 ? "" : "+") << addend;
602 Result.append(fmtbuf.begin(), fmtbuf.end());
605 case ELF::R_WEBASSEMBLY_FUNCTION:
616 Result.append(res.begin(), res.end());
617 return std::error_code();
620 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
621 const RelocationRef &Rel,
622 SmallVectorImpl<char> &Result) {
623 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
624 return getRelocationValueString(ELF32LE, Rel, Result);
625 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
626 return getRelocationValueString(ELF64LE, Rel, Result);
627 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
628 return getRelocationValueString(ELF32BE, Rel, Result);
629 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
630 return getRelocationValueString(ELF64BE, Rel, Result);
633 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
634 const RelocationRef &Rel,
635 SmallVectorImpl<char> &Result) {
636 symbol_iterator SymI = Rel.getSymbol();
637 Expected<StringRef> SymNameOrErr = SymI->getName();
639 return errorToErrorCode(SymNameOrErr.takeError());
640 StringRef SymName = *SymNameOrErr;
641 Result.append(SymName.begin(), SymName.end());
642 return std::error_code();
645 static void printRelocationTargetName(const MachOObjectFile *O,
646 const MachO::any_relocation_info &RE,
647 raw_string_ostream &fmt) {
648 bool IsScattered = O->isRelocationScattered(RE);
650 // Target of a scattered relocation is an address. In the interest of
651 // generating pretty output, scan through the symbol table looking for a
652 // symbol that aligns with that address. If we find one, print it.
653 // Otherwise, we just print the hex address of the target.
655 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
657 for (const SymbolRef &Symbol : O->symbols()) {
659 Expected<uint64_t> Addr = Symbol.getAddress();
662 raw_string_ostream OS(Buf);
663 logAllUnhandledErrors(Addr.takeError(), OS, "");
665 report_fatal_error(Buf);
669 Expected<StringRef> Name = Symbol.getName();
672 raw_string_ostream OS(Buf);
673 logAllUnhandledErrors(Name.takeError(), OS, "");
675 report_fatal_error(Buf);
681 // If we couldn't find a symbol that this relocation refers to, try
682 // to find a section beginning instead.
683 for (const SectionRef &Section : ToolSectionFilter(*O)) {
687 uint64_t Addr = Section.getAddress();
690 if ((ec = Section.getName(Name)))
691 report_fatal_error(ec.message());
696 fmt << format("0x%x", Val);
701 bool isExtern = O->getPlainRelocationExternal(RE);
702 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
705 symbol_iterator SI = O->symbol_begin();
707 Expected<StringRef> SOrErr = SI->getName();
708 error(errorToErrorCode(SOrErr.takeError()));
711 section_iterator SI = O->section_begin();
712 // Adjust for the fact that sections are 1-indexed.
713 advance(SI, Val - 1);
720 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
721 const RelocationRef &RelRef,
722 SmallVectorImpl<char> &Result) {
723 DataRefImpl Rel = RelRef.getRawDataRefImpl();
724 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
726 unsigned Arch = Obj->getArch();
729 raw_string_ostream fmt(fmtbuf);
730 unsigned Type = Obj->getAnyRelocationType(RE);
731 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
733 // Determine any addends that should be displayed with the relocation.
734 // These require decoding the relocation type, which is triple-specific.
736 // X86_64 has entirely custom relocation types.
737 if (Arch == Triple::x86_64) {
738 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
741 case MachO::X86_64_RELOC_GOT_LOAD:
742 case MachO::X86_64_RELOC_GOT: {
743 printRelocationTargetName(Obj, RE, fmt);
749 case MachO::X86_64_RELOC_SUBTRACTOR: {
750 DataRefImpl RelNext = Rel;
751 Obj->moveRelocationNext(RelNext);
752 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
754 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
755 // X86_64_RELOC_UNSIGNED.
756 // NOTE: Scattered relocations don't exist on x86_64.
757 unsigned RType = Obj->getAnyRelocationType(RENext);
758 if (RType != MachO::X86_64_RELOC_UNSIGNED)
759 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
760 "X86_64_RELOC_SUBTRACTOR.");
762 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
763 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
764 printRelocationTargetName(Obj, RENext, fmt);
766 printRelocationTargetName(Obj, RE, fmt);
769 case MachO::X86_64_RELOC_TLV:
770 printRelocationTargetName(Obj, RE, fmt);
775 case MachO::X86_64_RELOC_SIGNED_1:
776 printRelocationTargetName(Obj, RE, fmt);
779 case MachO::X86_64_RELOC_SIGNED_2:
780 printRelocationTargetName(Obj, RE, fmt);
783 case MachO::X86_64_RELOC_SIGNED_4:
784 printRelocationTargetName(Obj, RE, fmt);
788 printRelocationTargetName(Obj, RE, fmt);
791 // X86 and ARM share some relocation types in common.
792 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
793 Arch == Triple::ppc) {
794 // Generic relocation types...
796 case MachO::GENERIC_RELOC_PAIR: // prints no info
797 return std::error_code();
798 case MachO::GENERIC_RELOC_SECTDIFF: {
799 DataRefImpl RelNext = Rel;
800 Obj->moveRelocationNext(RelNext);
801 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
803 // X86 sect diff's must be followed by a relocation of type
804 // GENERIC_RELOC_PAIR.
805 unsigned RType = Obj->getAnyRelocationType(RENext);
807 if (RType != MachO::GENERIC_RELOC_PAIR)
808 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
809 "GENERIC_RELOC_SECTDIFF.");
811 printRelocationTargetName(Obj, RE, fmt);
813 printRelocationTargetName(Obj, RENext, fmt);
818 if (Arch == Triple::x86 || Arch == Triple::ppc) {
820 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
821 DataRefImpl RelNext = Rel;
822 Obj->moveRelocationNext(RelNext);
823 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
825 // X86 sect diff's must be followed by a relocation of type
826 // GENERIC_RELOC_PAIR.
827 unsigned RType = Obj->getAnyRelocationType(RENext);
828 if (RType != MachO::GENERIC_RELOC_PAIR)
829 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
830 "GENERIC_RELOC_LOCAL_SECTDIFF.");
832 printRelocationTargetName(Obj, RE, fmt);
834 printRelocationTargetName(Obj, RENext, fmt);
837 case MachO::GENERIC_RELOC_TLV: {
838 printRelocationTargetName(Obj, RE, fmt);
845 printRelocationTargetName(Obj, RE, fmt);
847 } else { // ARM-specific relocations
849 case MachO::ARM_RELOC_HALF:
850 case MachO::ARM_RELOC_HALF_SECTDIFF: {
851 // Half relocations steal a bit from the length field to encode
852 // whether this is an upper16 or a lower16 relocation.
853 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
859 printRelocationTargetName(Obj, RE, fmt);
861 DataRefImpl RelNext = Rel;
862 Obj->moveRelocationNext(RelNext);
863 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
865 // ARM half relocs must be followed by a relocation of type
867 unsigned RType = Obj->getAnyRelocationType(RENext);
868 if (RType != MachO::ARM_RELOC_PAIR)
869 report_fatal_error("Expected ARM_RELOC_PAIR after "
872 // NOTE: The half of the target virtual address is stashed in the
873 // address field of the secondary relocation, but we can't reverse
874 // engineer the constant offset from it without decoding the movw/movt
875 // instruction to find the other half in its immediate field.
877 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
878 // symbol/section pointer of the follow-on relocation.
879 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
881 printRelocationTargetName(Obj, RENext, fmt);
887 default: { printRelocationTargetName(Obj, RE, fmt); }
891 printRelocationTargetName(Obj, RE, fmt);
894 Result.append(fmtbuf.begin(), fmtbuf.end());
895 return std::error_code();
898 static std::error_code getRelocationValueString(const RelocationRef &Rel,
899 SmallVectorImpl<char> &Result) {
900 const ObjectFile *Obj = Rel.getObject();
901 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
902 return getRelocationValueString(ELF, Rel, Result);
903 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
904 return getRelocationValueString(COFF, Rel, Result);
905 auto *MachO = cast<MachOObjectFile>(Obj);
906 return getRelocationValueString(MachO, Rel, Result);
909 /// @brief Indicates whether this relocation should hidden when listing
910 /// relocations, usually because it is the trailing part of a multipart
911 /// relocation that will be printed as part of the leading relocation.
912 static bool getHidden(RelocationRef RelRef) {
913 const ObjectFile *Obj = RelRef.getObject();
914 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
918 unsigned Arch = MachO->getArch();
919 DataRefImpl Rel = RelRef.getRawDataRefImpl();
920 uint64_t Type = MachO->getRelocationType(Rel);
922 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
924 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
925 if (Type == MachO::GENERIC_RELOC_PAIR)
927 } else if (Arch == Triple::x86_64) {
928 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
929 // an X86_64_RELOC_SUBTRACTOR.
930 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
931 DataRefImpl RelPrev = Rel;
933 uint64_t PrevType = MachO->getRelocationType(RelPrev);
934 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
942 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
943 const Target *TheTarget = getTarget(Obj);
945 // Package up features to be passed to target/subtarget
946 SubtargetFeatures Features = Obj->getFeatures();
948 for (unsigned i = 0; i != MAttrs.size(); ++i)
949 Features.AddFeature(MAttrs[i]);
952 std::unique_ptr<const MCRegisterInfo> MRI(
953 TheTarget->createMCRegInfo(TripleName));
955 report_fatal_error("error: no register info for target " + TripleName);
957 // Set up disassembler.
958 std::unique_ptr<const MCAsmInfo> AsmInfo(
959 TheTarget->createMCAsmInfo(*MRI, TripleName));
961 report_fatal_error("error: no assembly info for target " + TripleName);
962 std::unique_ptr<const MCSubtargetInfo> STI(
963 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
965 report_fatal_error("error: no subtarget info for target " + TripleName);
966 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
968 report_fatal_error("error: no instruction info for target " + TripleName);
969 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
970 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
972 std::unique_ptr<MCDisassembler> DisAsm(
973 TheTarget->createMCDisassembler(*STI, Ctx));
975 report_fatal_error("error: no disassembler for target " + TripleName);
977 std::unique_ptr<const MCInstrAnalysis> MIA(
978 TheTarget->createMCInstrAnalysis(MII.get()));
980 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
981 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
982 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
984 report_fatal_error("error: no instruction printer for target " +
986 IP->setPrintImmHex(PrintImmHex);
987 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
989 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
990 "\t\t\t%08" PRIx64 ": ";
992 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
993 // in RelocSecs contain the relocations for section S.
995 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
996 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
997 section_iterator Sec2 = Section.getRelocatedSection();
998 if (Sec2 != Obj->section_end())
999 SectionRelocMap[*Sec2].push_back(Section);
1002 // Create a mapping from virtual address to symbol name. This is used to
1003 // pretty print the symbols while disassembling.
1004 typedef std::vector<std::pair<uint64_t, StringRef>> SectionSymbolsTy;
1005 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1006 for (const SymbolRef &Symbol : Obj->symbols()) {
1007 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1008 error(errorToErrorCode(AddressOrErr.takeError()));
1009 uint64_t Address = *AddressOrErr;
1011 Expected<StringRef> Name = Symbol.getName();
1012 error(errorToErrorCode(Name.takeError()));
1016 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1017 error(errorToErrorCode(SectionOrErr.takeError()));
1018 section_iterator SecI = *SectionOrErr;
1019 if (SecI == Obj->section_end())
1022 AllSymbols[*SecI].emplace_back(Address, *Name);
1025 // Create a mapping from virtual address to section.
1026 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1027 for (SectionRef Sec : Obj->sections())
1028 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1029 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1031 // Linked executables (.exe and .dll files) typically don't include a real
1032 // symbol table but they might contain an export table.
1033 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1034 for (const auto &ExportEntry : COFFObj->export_directories()) {
1036 error(ExportEntry.getSymbolName(Name));
1040 error(ExportEntry.getExportRVA(RVA));
1042 uint64_t VA = COFFObj->getImageBase() + RVA;
1043 auto Sec = std::upper_bound(
1044 SectionAddresses.begin(), SectionAddresses.end(), VA,
1045 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1046 return LHS < RHS.first;
1048 if (Sec != SectionAddresses.begin())
1051 Sec = SectionAddresses.end();
1053 if (Sec != SectionAddresses.end())
1054 AllSymbols[Sec->second].emplace_back(VA, Name);
1058 // Sort all the symbols, this allows us to use a simple binary search to find
1059 // a symbol near an address.
1060 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1061 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1063 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1064 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
1067 uint64_t SectionAddr = Section.getAddress();
1068 uint64_t SectSize = Section.getSize();
1072 // Get the list of all the symbols in this section.
1073 SectionSymbolsTy &Symbols = AllSymbols[Section];
1074 std::vector<uint64_t> DataMappingSymsAddr;
1075 std::vector<uint64_t> TextMappingSymsAddr;
1076 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1077 for (const auto &Symb : Symbols) {
1078 uint64_t Address = Symb.first;
1079 StringRef Name = Symb.second;
1080 if (Name.startswith("$d"))
1081 DataMappingSymsAddr.push_back(Address - SectionAddr);
1082 if (Name.startswith("$x"))
1083 TextMappingSymsAddr.push_back(Address - SectionAddr);
1087 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1088 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
1090 // Make a list of all the relocations for this section.
1091 std::vector<RelocationRef> Rels;
1093 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1094 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1095 Rels.push_back(Reloc);
1100 // Sort relocations by address.
1101 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
1103 StringRef SegmentName = "";
1104 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
1105 DataRefImpl DR = Section.getRawDataRefImpl();
1106 SegmentName = MachO->getSectionFinalSegmentName(DR);
1109 error(Section.getName(name));
1110 outs() << "Disassembly of section ";
1111 if (!SegmentName.empty())
1112 outs() << SegmentName << ",";
1113 outs() << name << ':';
1115 // If the section has no symbol at the start, just insert a dummy one.
1116 if (Symbols.empty() || Symbols[0].first != 0)
1117 Symbols.insert(Symbols.begin(), std::make_pair(SectionAddr, name));
1119 SmallString<40> Comments;
1120 raw_svector_ostream CommentStream(Comments);
1123 error(Section.getContents(BytesStr));
1124 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1130 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1131 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
1132 // Disassemble symbol by symbol.
1133 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
1135 uint64_t Start = Symbols[si].first - SectionAddr;
1136 // The end is either the section end or the beginning of the next
1139 (si == se - 1) ? SectSize : Symbols[si + 1].first - SectionAddr;
1140 // Don't try to disassemble beyond the end of section contents.
1143 // If this symbol has the same address as the next symbol, then skip it.
1147 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1148 // make size 4 bytes folded
1149 End = Start + ((End - Start) & ~0x3ull);
1150 Start += 256; // add sizeof(amd_kernel_code_t)
1151 // cut trailing zeroes - up to 256 bytes (align)
1152 const uint64_t EndAlign = 256;
1153 const auto Limit = End - (std::min)(EndAlign, End - Start);
1154 while (End > Limit &&
1155 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1159 outs() << '\n' << Symbols[si].second << ":\n";
1162 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1164 raw_ostream &DebugOut = nulls();
1167 for (Index = Start; Index < End; Index += Size) {
1170 // AArch64 ELF binaries can interleave data and text in the
1171 // same section. We rely on the markers introduced to
1172 // understand what we need to dump.
1173 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1174 uint64_t Stride = 0;
1176 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1177 DataMappingSymsAddr.end(), Index);
1178 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1180 while (Index < End) {
1181 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1183 if (Index + 4 <= End) {
1185 dumpBytes(Bytes.slice(Index, 4), outs());
1186 outs() << "\t.word";
1187 } else if (Index + 2 <= End) {
1189 dumpBytes(Bytes.slice(Index, 2), outs());
1190 outs() << "\t.short";
1193 dumpBytes(Bytes.slice(Index, 1), outs());
1194 outs() << "\t.byte";
1198 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1199 TextMappingSymsAddr.end(), Index);
1200 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1209 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1210 SectionAddr + Index, DebugOut,
1214 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
1215 Bytes.slice(Index, Size),
1216 SectionAddr + Index, outs(), "", *STI);
1217 outs() << CommentStream.str();
1220 // Try to resolve the target of a call, tail call, etc. to a specific
1222 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1223 MIA->isConditionalBranch(Inst))) {
1225 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1226 // In a relocatable object, the target's section must reside in
1227 // the same section as the call instruction or it is accessed
1228 // through a relocation.
1230 // In a non-relocatable object, the target may be in any section.
1232 // N.B. We don't walk the relocations in the relocatable case yet.
1233 auto *TargetSectionSymbols = &Symbols;
1234 if (!Obj->isRelocatableObject()) {
1235 auto SectionAddress = std::upper_bound(
1236 SectionAddresses.begin(), SectionAddresses.end(), Target,
1238 const std::pair<uint64_t, SectionRef> &RHS) {
1239 return LHS < RHS.first;
1241 if (SectionAddress != SectionAddresses.begin()) {
1243 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1245 TargetSectionSymbols = nullptr;
1249 // Find the first symbol in the section whose offset is less than
1250 // or equal to the target.
1251 if (TargetSectionSymbols) {
1252 auto TargetSym = std::upper_bound(
1253 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1254 Target, [](uint64_t LHS,
1255 const std::pair<uint64_t, StringRef> &RHS) {
1256 return LHS < RHS.first;
1258 if (TargetSym != TargetSectionSymbols->begin()) {
1260 uint64_t TargetAddress = std::get<0>(*TargetSym);
1261 StringRef TargetName = std::get<1>(*TargetSym);
1262 outs() << " <" << TargetName;
1263 uint64_t Disp = Target - TargetAddress;
1265 outs() << "+0x" << utohexstr(Disp);
1273 // Print relocation for instruction.
1274 while (rel_cur != rel_end) {
1275 bool hidden = getHidden(*rel_cur);
1276 uint64_t addr = rel_cur->getOffset();
1277 SmallString<16> name;
1278 SmallString<32> val;
1280 // If this relocation is hidden, skip it.
1281 if (hidden) goto skip_print_rel;
1283 // Stop when rel_cur's address is past the current instruction.
1284 if (addr >= Index + Size) break;
1285 rel_cur->getTypeName(name);
1286 error(getRelocationValueString(*rel_cur, val));
1287 outs() << format(Fmt.data(), SectionAddr + addr) << name
1288 << "\t" << val << "\n";
1298 void llvm::PrintRelocations(const ObjectFile *Obj) {
1299 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1301 // Regular objdump doesn't print relocations in non-relocatable object
1303 if (!Obj->isRelocatableObject())
1306 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1307 if (Section.relocation_begin() == Section.relocation_end())
1310 error(Section.getName(secname));
1311 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
1312 for (const RelocationRef &Reloc : Section.relocations()) {
1313 bool hidden = getHidden(Reloc);
1314 uint64_t address = Reloc.getOffset();
1315 SmallString<32> relocname;
1316 SmallString<32> valuestr;
1319 Reloc.getTypeName(relocname);
1320 error(getRelocationValueString(Reloc, valuestr));
1321 outs() << format(Fmt.data(), address) << " " << relocname << " "
1322 << valuestr << "\n";
1328 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
1329 outs() << "Sections:\n"
1330 "Idx Name Size Address Type\n";
1332 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1334 error(Section.getName(Name));
1335 uint64_t Address = Section.getAddress();
1336 uint64_t Size = Section.getSize();
1337 bool Text = Section.isText();
1338 bool Data = Section.isData();
1339 bool BSS = Section.isBSS();
1340 std::string Type = (std::string(Text ? "TEXT " : "") +
1341 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1342 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1343 Name.str().c_str(), Size, Address, Type.c_str());
1348 void llvm::PrintSectionContents(const ObjectFile *Obj) {
1350 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1353 error(Section.getName(Name));
1354 uint64_t BaseAddr = Section.getAddress();
1355 uint64_t Size = Section.getSize();
1359 outs() << "Contents of section " << Name << ":\n";
1360 if (Section.isBSS()) {
1361 outs() << format("<skipping contents of bss section at [%04" PRIx64
1362 ", %04" PRIx64 ")>\n",
1363 BaseAddr, BaseAddr + Size);
1367 error(Section.getContents(Contents));
1369 // Dump out the content as hex and printable ascii characters.
1370 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1371 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1372 // Dump line of hex.
1373 for (std::size_t i = 0; i < 16; ++i) {
1374 if (i != 0 && i % 4 == 0)
1377 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1378 << hexdigit(Contents[addr + i] & 0xF, true);
1384 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1385 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1386 outs() << Contents[addr + i];
1395 void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1396 StringRef ArchitectureName) {
1397 outs() << "SYMBOL TABLE:\n";
1399 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1400 printCOFFSymbolTable(coff);
1403 for (const SymbolRef &Symbol : o->symbols()) {
1404 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1405 if (!AddressOrError)
1406 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError());
1407 uint64_t Address = *AddressOrError;
1408 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1410 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError());
1411 SymbolRef::Type Type = *TypeOrError;
1412 uint32_t Flags = Symbol.getFlags();
1413 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1414 error(errorToErrorCode(SectionOrErr.takeError()));
1415 section_iterator Section = *SectionOrErr;
1417 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1418 Section->getName(Name);
1420 Expected<StringRef> NameOrErr = Symbol.getName();
1422 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1427 bool Global = Flags & SymbolRef::SF_Global;
1428 bool Weak = Flags & SymbolRef::SF_Weak;
1429 bool Absolute = Flags & SymbolRef::SF_Absolute;
1430 bool Common = Flags & SymbolRef::SF_Common;
1431 bool Hidden = Flags & SymbolRef::SF_Hidden;
1434 if (Type != SymbolRef::ST_Unknown)
1435 GlobLoc = Global ? 'g' : 'l';
1436 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1438 char FileFunc = ' ';
1439 if (Type == SymbolRef::ST_File)
1441 else if (Type == SymbolRef::ST_Function)
1444 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1447 outs() << format(Fmt, Address) << " "
1448 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1449 << (Weak ? 'w' : ' ') // Weak?
1450 << ' ' // Constructor. Not supported yet.
1451 << ' ' // Warning. Not supported yet.
1452 << ' ' // Indirect reference to another symbol.
1453 << Debug // Debugging (d) or dynamic (D) symbol.
1454 << FileFunc // Name of function (F), file (f) or object (O).
1458 } else if (Common) {
1460 } else if (Section == o->section_end()) {
1463 if (const MachOObjectFile *MachO =
1464 dyn_cast<const MachOObjectFile>(o)) {
1465 DataRefImpl DR = Section->getRawDataRefImpl();
1466 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1467 outs() << SegmentName << ",";
1469 StringRef SectionName;
1470 error(Section->getName(SectionName));
1471 outs() << SectionName;
1475 if (Common || isa<ELFObjectFileBase>(o)) {
1477 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1478 outs() << format("\t %08" PRIx64 " ", Val);
1482 outs() << ".hidden ";
1489 static void PrintUnwindInfo(const ObjectFile *o) {
1490 outs() << "Unwind info:\n\n";
1492 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1493 printCOFFUnwindInfo(coff);
1494 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1495 printMachOUnwindInfo(MachO);
1497 // TODO: Extract DWARF dump tool to objdump.
1498 errs() << "This operation is only currently supported "
1499 "for COFF and MachO object files.\n";
1504 void llvm::printExportsTrie(const ObjectFile *o) {
1505 outs() << "Exports trie:\n";
1506 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1507 printMachOExportsTrie(MachO);
1509 errs() << "This operation is only currently supported "
1510 "for Mach-O executable files.\n";
1515 void llvm::printRebaseTable(const ObjectFile *o) {
1516 outs() << "Rebase table:\n";
1517 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1518 printMachORebaseTable(MachO);
1520 errs() << "This operation is only currently supported "
1521 "for Mach-O executable files.\n";
1526 void llvm::printBindTable(const ObjectFile *o) {
1527 outs() << "Bind table:\n";
1528 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1529 printMachOBindTable(MachO);
1531 errs() << "This operation is only currently supported "
1532 "for Mach-O executable files.\n";
1537 void llvm::printLazyBindTable(const ObjectFile *o) {
1538 outs() << "Lazy bind table:\n";
1539 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1540 printMachOLazyBindTable(MachO);
1542 errs() << "This operation is only currently supported "
1543 "for Mach-O executable files.\n";
1548 void llvm::printWeakBindTable(const ObjectFile *o) {
1549 outs() << "Weak bind table:\n";
1550 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1551 printMachOWeakBindTable(MachO);
1553 errs() << "This operation is only currently supported "
1554 "for Mach-O executable files.\n";
1559 /// Dump the raw contents of the __clangast section so the output can be piped
1560 /// into llvm-bcanalyzer.
1561 void llvm::printRawClangAST(const ObjectFile *Obj) {
1562 if (outs().is_displayed()) {
1563 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1564 "the clang ast section.\n"
1565 "Please redirect the output to a file or another program such as "
1566 "llvm-bcanalyzer.\n";
1570 StringRef ClangASTSectionName("__clangast");
1571 if (isa<COFFObjectFile>(Obj)) {
1572 ClangASTSectionName = "clangast";
1575 Optional<object::SectionRef> ClangASTSection;
1576 for (auto Sec : ToolSectionFilter(*Obj)) {
1579 if (Name == ClangASTSectionName) {
1580 ClangASTSection = Sec;
1584 if (!ClangASTSection)
1587 StringRef ClangASTContents;
1588 error(ClangASTSection.getValue().getContents(ClangASTContents));
1589 outs().write(ClangASTContents.data(), ClangASTContents.size());
1592 static void printFaultMaps(const ObjectFile *Obj) {
1593 const char *FaultMapSectionName = nullptr;
1595 if (isa<ELFObjectFileBase>(Obj)) {
1596 FaultMapSectionName = ".llvm_faultmaps";
1597 } else if (isa<MachOObjectFile>(Obj)) {
1598 FaultMapSectionName = "__llvm_faultmaps";
1600 errs() << "This operation is only currently supported "
1601 "for ELF and Mach-O executable files.\n";
1605 Optional<object::SectionRef> FaultMapSection;
1607 for (auto Sec : ToolSectionFilter(*Obj)) {
1610 if (Name == FaultMapSectionName) {
1611 FaultMapSection = Sec;
1616 outs() << "FaultMap table:\n";
1618 if (!FaultMapSection.hasValue()) {
1619 outs() << "<not found>\n";
1623 StringRef FaultMapContents;
1624 error(FaultMapSection.getValue().getContents(FaultMapContents));
1626 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1627 FaultMapContents.bytes_end());
1632 static void printPrivateFileHeaders(const ObjectFile *o) {
1634 printELFFileHeader(o);
1635 else if (o->isCOFF())
1636 printCOFFFileHeader(o);
1637 else if (o->isMachO()) {
1638 printMachOFileHeader(o);
1639 printMachOLoadCommands(o);
1641 report_fatal_error("Invalid/Unsupported object file format");
1644 static void printFirstPrivateFileHeader(const ObjectFile *o) {
1646 printELFFileHeader(o);
1647 else if (o->isCOFF())
1648 printCOFFFileHeader(o);
1649 else if (o->isMachO())
1650 printMachOFileHeader(o);
1652 report_fatal_error("Invalid/Unsupported object file format");
1655 static void DumpObject(const ObjectFile *o, const Archive *a = nullptr) {
1656 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
1657 // Avoid other output when using a raw option.
1661 outs() << a->getFileName() << "(" << o->getFileName() << ")";
1663 outs() << o->getFileName();
1664 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
1668 DisassembleObject(o, Relocations);
1669 if (Relocations && !Disassemble)
1670 PrintRelocations(o);
1672 PrintSectionHeaders(o);
1673 if (SectionContents)
1674 PrintSectionContents(o);
1676 PrintSymbolTable(o, ArchiveName);
1680 printPrivateFileHeaders(o);
1681 if (FirstPrivateHeader)
1682 printFirstPrivateFileHeader(o);
1684 printExportsTrie(o);
1686 printRebaseTable(o);
1690 printLazyBindTable(o);
1692 printWeakBindTable(o);
1694 printRawClangAST(o);
1697 if (DwarfDumpType != DIDT_Null) {
1698 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o));
1699 // Dump the complete DWARF structure.
1700 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1704 /// @brief Dump each object file in \a a;
1705 static void DumpArchive(const Archive *a) {
1707 for (auto &C : a->children(Err)) {
1708 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1710 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1711 report_error(a->getFileName(), C, std::move(E));
1714 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
1717 report_error(a->getFileName(), object_error::invalid_file_type);
1720 report_error(a->getFileName(), std::move(Err));
1723 /// @brief Open file and figure out how to dump it.
1724 static void DumpInput(StringRef file) {
1726 // If we are using the Mach-O specific object file parser, then let it parse
1727 // the file and process the command line options. So the -arch flags can
1728 // be used to select specific slices, etc.
1730 ParseInputMachO(file);
1734 // Attempt to open the binary.
1735 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1737 report_error(file, BinaryOrErr.takeError());
1738 Binary &Binary = *BinaryOrErr.get().getBinary();
1740 if (Archive *a = dyn_cast<Archive>(&Binary))
1742 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
1745 report_error(file, object_error::invalid_file_type);
1748 int main(int argc, char **argv) {
1749 // Print a stack trace if we signal out.
1750 sys::PrintStackTraceOnErrorSignal(argv[0]);
1751 PrettyStackTraceProgram X(argc, argv);
1752 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1754 // Initialize targets and assembly printers/parsers.
1755 llvm::InitializeAllTargetInfos();
1756 llvm::InitializeAllTargetMCs();
1757 llvm::InitializeAllDisassemblers();
1759 // Register the target printer for --version.
1760 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1762 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1763 TripleName = Triple::normalize(TripleName);
1767 // Defaults to a.out if no filenames specified.
1768 if (InputFilenames.size() == 0)
1769 InputFilenames.push_back("a.out");
1780 && !FirstPrivateHeader
1787 && !(UniversalHeaders && MachOOpt)
1788 && !(ArchiveHeaders && MachOOpt)
1789 && !(IndirectSymbols && MachOOpt)
1790 && !(DataInCode && MachOOpt)
1791 && !(LinkOptHints && MachOOpt)
1792 && !(InfoPlist && MachOOpt)
1793 && !(DylibsUsed && MachOOpt)
1794 && !(DylibId && MachOOpt)
1795 && !(ObjcMetaData && MachOOpt)
1796 && !(FilterSections.size() != 0 && MachOOpt)
1798 && DwarfDumpType == DIDT_Null) {
1799 cl::PrintHelpMessage();
1803 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1806 return EXIT_SUCCESS;