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/StringSet.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/CodeGen/FaultMaps.h"
26 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
27 #include "llvm/DebugInfo/Symbolize/Symbolize.h"
28 #include "llvm/Demangle/Demangle.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/MC/MCContext.h"
31 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
32 #include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
33 #include "llvm/MC/MCInst.h"
34 #include "llvm/MC/MCInstPrinter.h"
35 #include "llvm/MC/MCInstrAnalysis.h"
36 #include "llvm/MC/MCInstrInfo.h"
37 #include "llvm/MC/MCObjectFileInfo.h"
38 #include "llvm/MC/MCRegisterInfo.h"
39 #include "llvm/MC/MCSubtargetInfo.h"
40 #include "llvm/Object/Archive.h"
41 #include "llvm/Object/COFF.h"
42 #include "llvm/Object/COFFImportFile.h"
43 #include "llvm/Object/ELFObjectFile.h"
44 #include "llvm/Object/MachO.h"
45 #include "llvm/Object/MachOUniversal.h"
46 #include "llvm/Object/ObjectFile.h"
47 #include "llvm/Object/Wasm.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/Errc.h"
52 #include "llvm/Support/FileSystem.h"
53 #include "llvm/Support/Format.h"
54 #include "llvm/Support/GraphWriter.h"
55 #include "llvm/Support/Host.h"
56 #include "llvm/Support/InitLLVM.h"
57 #include "llvm/Support/MemoryBuffer.h"
58 #include "llvm/Support/SourceMgr.h"
59 #include "llvm/Support/StringSaver.h"
60 #include "llvm/Support/TargetRegistry.h"
61 #include "llvm/Support/TargetSelect.h"
62 #include "llvm/Support/WithColor.h"
63 #include "llvm/Support/raw_ostream.h"
67 #include <system_error>
68 #include <unordered_map>
72 using namespace object;
75 llvm::AllHeaders("all-headers",
76 cl::desc("Display all available header information"));
77 static cl::alias AllHeadersShort("x", cl::desc("Alias for --all-headers"),
78 cl::aliasopt(AllHeaders));
80 static cl::list<std::string>
81 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
84 llvm::Disassemble("disassemble",
85 cl::desc("Display assembler mnemonics for the machine instructions"));
87 Disassembled("d", cl::desc("Alias for --disassemble"),
88 cl::aliasopt(Disassemble));
91 llvm::DisassembleAll("disassemble-all",
92 cl::desc("Display assembler mnemonics for the machine instructions"));
94 DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
95 cl::aliasopt(DisassembleAll));
97 cl::opt<bool> llvm::Demangle("demangle", cl::desc("Demangle symbols names"),
100 static cl::alias DemangleShort("C", cl::desc("Alias for --demangle"),
101 cl::aliasopt(llvm::Demangle));
103 static cl::list<std::string>
104 DisassembleFunctions("df",
106 cl::desc("List of functions to disassemble"));
107 static StringSet<> DisasmFuncsSet;
110 llvm::Relocations("reloc",
111 cl::desc("Display the relocation entries in the file"));
112 static cl::alias RelocationsShort("r", cl::desc("Alias for --reloc"),
114 cl::aliasopt(llvm::Relocations));
117 llvm::DynamicRelocations("dynamic-reloc",
118 cl::desc("Display the dynamic relocation entries in the file"));
120 DynamicRelocationsd("R", cl::desc("Alias for --dynamic-reloc"),
121 cl::aliasopt(DynamicRelocations));
124 llvm::SectionContents("full-contents",
125 cl::desc("Display the content of each section"));
126 static cl::alias SectionContentsShort("s",
127 cl::desc("Alias for --full-contents"),
128 cl::aliasopt(SectionContents));
130 cl::opt<bool> llvm::SymbolTable("syms", cl::desc("Display the symbol table"));
131 static cl::alias SymbolTableShort("t", cl::desc("Alias for --syms"),
133 cl::aliasopt(llvm::SymbolTable));
136 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
139 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
142 llvm::Bind("bind", cl::desc("Display mach-o binding info"));
145 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
148 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
151 llvm::RawClangAST("raw-clang-ast",
152 cl::desc("Dump the raw binary contents of the clang AST section"));
155 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
157 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
160 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
161 "see -version for available targets"));
165 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
166 cl::value_desc("cpu-name"),
170 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
171 "see -version for available targets"));
174 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
175 "headers for each section."));
177 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
178 cl::aliasopt(SectionHeaders));
180 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
181 cl::aliasopt(SectionHeaders));
183 cl::list<std::string>
184 llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
185 "With -macho dump segment,section"));
187 static FilterSectionsj("j", cl::desc("Alias for --section"),
188 cl::aliasopt(llvm::FilterSections));
190 cl::list<std::string>
191 llvm::MAttrs("mattr",
193 cl::desc("Target specific attributes"),
194 cl::value_desc("a1,+a2,-a3,..."));
197 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
198 "instructions, do not print "
199 "the instruction bytes."));
201 llvm::NoLeadingAddr("no-leading-addr", cl::desc("Print no leading address"));
204 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
207 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
208 cl::aliasopt(UnwindInfo));
211 llvm::PrivateHeaders("private-headers",
212 cl::desc("Display format specific file headers"));
215 llvm::FirstPrivateHeader("private-header",
216 cl::desc("Display only the first format specific file "
220 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
221 cl::aliasopt(PrivateHeaders));
223 cl::opt<bool> llvm::FileHeaders(
225 cl::desc("Display the contents of the overall file header"));
227 static cl::alias FileHeadersShort("f", cl::desc("Alias for --file-headers"),
228 cl::aliasopt(FileHeaders));
231 llvm::ArchiveHeaders("archive-headers",
232 cl::desc("Display archive header information"));
235 ArchiveHeadersShort("a", cl::desc("Alias for --archive-headers"),
236 cl::aliasopt(ArchiveHeaders));
239 llvm::PrintImmHex("print-imm-hex",
240 cl::desc("Use hex format for immediate values"));
242 cl::opt<bool> PrintFaultMaps("fault-map-section",
243 cl::desc("Display contents of faultmap section"));
245 cl::opt<DIDumpType> llvm::DwarfDumpType(
246 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
247 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")));
249 cl::opt<bool> PrintSource(
252 "Display source inlined with disassembly. Implies disassemble object"));
254 cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
255 cl::aliasopt(PrintSource));
257 cl::opt<bool> PrintLines("line-numbers",
258 cl::desc("Display source line numbers with "
259 "disassembly. Implies disassemble object"));
261 cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"),
262 cl::aliasopt(PrintLines));
264 cl::opt<unsigned long long>
265 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
266 cl::value_desc("address"), cl::init(0));
267 cl::opt<unsigned long long>
268 StopAddress("stop-address",
269 cl::desc("Stop disassembly at address"),
270 cl::value_desc("address"), cl::init(UINT64_MAX));
272 cl::opt<bool> DisassembleZeroes(
273 "disassemble-zeroes",
274 cl::desc("Do not skip blocks of zeroes when disassembling"));
275 cl::alias DisassembleZeroesShort("z",
276 cl::desc("Alias for --disassemble-zeroes"),
277 cl::aliasopt(DisassembleZeroes));
279 static StringRef ToolName;
281 typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
284 typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
286 class SectionFilterIterator {
288 SectionFilterIterator(FilterPredicate P,
289 llvm::object::section_iterator const &I,
290 llvm::object::section_iterator const &E)
291 : Predicate(std::move(P)), Iterator(I), End(E) {
294 const llvm::object::SectionRef &operator*() const { return *Iterator; }
295 SectionFilterIterator &operator++() {
300 bool operator!=(SectionFilterIterator const &Other) const {
301 return Iterator != Other.Iterator;
305 void ScanPredicate() {
306 while (Iterator != End && !Predicate(*Iterator)) {
310 FilterPredicate Predicate;
311 llvm::object::section_iterator Iterator;
312 llvm::object::section_iterator End;
315 class SectionFilter {
317 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
318 : Predicate(std::move(P)), Object(O) {}
319 SectionFilterIterator begin() {
320 return SectionFilterIterator(Predicate, Object.section_begin(),
321 Object.section_end());
323 SectionFilterIterator end() {
324 return SectionFilterIterator(Predicate, Object.section_end(),
325 Object.section_end());
329 FilterPredicate Predicate;
330 llvm::object::ObjectFile const &Object;
332 SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
333 return SectionFilter(
334 [](llvm::object::SectionRef const &S) {
335 if (FilterSections.empty())
337 llvm::StringRef String;
338 std::error_code error = S.getName(String);
341 return is_contained(FilterSections, String);
347 void llvm::error(std::error_code EC) {
350 WithColor::error(errs(), ToolName)
351 << "reading file: " << EC.message() << ".\n";
356 LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
357 WithColor::error(errs(), ToolName) << Message << ".\n";
362 void llvm::warn(StringRef Message) {
363 WithColor::warning(errs(), ToolName) << Message << ".\n";
367 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
369 WithColor::error(errs(), ToolName)
370 << "'" << File << "': " << Message << ".\n";
374 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
375 std::error_code EC) {
377 WithColor::error(errs(), ToolName)
378 << "'" << File << "': " << EC.message() << ".\n";
382 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
386 raw_string_ostream OS(Buf);
387 logAllUnhandledErrors(std::move(E), OS);
389 WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf;
393 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
396 StringRef ArchitectureName) {
398 WithColor::error(errs(), ToolName);
399 if (ArchiveName != "")
400 errs() << ArchiveName << "(" << FileName << ")";
402 errs() << "'" << FileName << "'";
403 if (!ArchitectureName.empty())
404 errs() << " (for architecture " << ArchitectureName << ")";
406 raw_string_ostream OS(Buf);
407 logAllUnhandledErrors(std::move(E), OS);
409 errs() << ": " << Buf;
413 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
414 const object::Archive::Child &C,
416 StringRef ArchitectureName) {
417 Expected<StringRef> NameOrErr = C.getName();
418 // TODO: if we have a error getting the name then it would be nice to print
419 // the index of which archive member this is and or its offset in the
420 // archive instead of "???" as the name.
422 consumeError(NameOrErr.takeError());
423 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
425 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
429 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
430 // Figure out the target triple.
431 llvm::Triple TheTriple("unknown-unknown-unknown");
432 if (TripleName.empty()) {
434 TheTriple = Obj->makeTriple();
436 TheTriple.setTriple(Triple::normalize(TripleName));
438 // Use the triple, but also try to combine with ARM build attributes.
440 auto Arch = Obj->getArch();
441 if (Arch == Triple::arm || Arch == Triple::armeb)
442 Obj->setARMSubArch(TheTriple);
446 // Get the target specific parser.
448 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
452 report_error(Obj->getFileName(), "can't find target: " + Error);
454 error("can't find target: " + Error);
457 // Update the triple name and return the found target.
458 TripleName = TheTriple.getTriple();
462 bool llvm::isRelocAddressLess(RelocationRef A, RelocationRef B) {
463 return A.getOffset() < B.getOffset();
466 static std::string demangle(StringRef Name) {
467 char *Demangled = nullptr;
468 if (Name.startswith("_Z"))
469 Demangled = itaniumDemangle(Name.data(), Demangled, nullptr, nullptr);
470 else if (Name.startswith("?"))
471 Demangled = microsoftDemangle(Name.data(), Demangled, nullptr, nullptr);
476 std::string Ret = Demangled;
481 template <class ELFT>
482 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
483 const RelocationRef &RelRef,
484 SmallVectorImpl<char> &Result) {
485 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
486 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
487 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
489 const ELFFile<ELFT> &EF = *Obj->getELFFile();
490 DataRefImpl Rel = RelRef.getRawDataRefImpl();
491 auto SecOrErr = EF.getSection(Rel.d.a);
493 return errorToErrorCode(SecOrErr.takeError());
494 const Elf_Shdr *Sec = *SecOrErr;
495 auto SymTabOrErr = EF.getSection(Sec->sh_link);
497 return errorToErrorCode(SymTabOrErr.takeError());
498 const Elf_Shdr *SymTab = *SymTabOrErr;
499 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
500 SymTab->sh_type == ELF::SHT_DYNSYM);
501 auto StrTabSec = EF.getSection(SymTab->sh_link);
503 return errorToErrorCode(StrTabSec.takeError());
504 auto StrTabOrErr = EF.getStringTable(*StrTabSec);
506 return errorToErrorCode(StrTabOrErr.takeError());
507 StringRef StrTab = *StrTabOrErr;
509 // If there is no Symbol associated with the relocation, we set the undef
510 // boolean value to 'true'. This will prevent us from calling functions that
511 // requires the relocation to be associated with a symbol.
513 switch (Sec->sh_type) {
515 return object_error::parse_failed;
517 // TODO: Read implicit addend from section data.
520 case ELF::SHT_RELA: {
521 const Elf_Rela *ERela = Obj->getRela(Rel);
522 Addend = ERela->r_addend;
523 Undef = ERela->getSymbol(false) == 0;
529 symbol_iterator SI = RelRef.getSymbol();
530 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
531 if (symb->getType() == ELF::STT_SECTION) {
532 Expected<section_iterator> SymSI = SI->getSection();
534 return errorToErrorCode(SymSI.takeError());
535 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
536 auto SecName = EF.getSectionName(SymSec);
538 return errorToErrorCode(SecName.takeError());
541 Expected<StringRef> SymName = symb->getName(StrTab);
543 return errorToErrorCode(SymName.takeError());
545 Target = demangle(*SymName);
552 // Default scheme is to print Target, as well as "+ <addend>" for nonzero
553 // addend. Should be acceptable for all normal purposes.
555 raw_string_ostream Fmt(FmtBuf);
558 Fmt << (Addend < 0 ? "" : "+") << Addend;
560 Result.append(FmtBuf.begin(), FmtBuf.end());
561 return std::error_code();
564 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
565 const RelocationRef &Rel,
566 SmallVectorImpl<char> &Result) {
567 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
568 return getRelocationValueString(ELF32LE, Rel, Result);
569 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
570 return getRelocationValueString(ELF64LE, Rel, Result);
571 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
572 return getRelocationValueString(ELF32BE, Rel, Result);
573 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
574 return getRelocationValueString(ELF64BE, Rel, Result);
577 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
578 const RelocationRef &Rel,
579 SmallVectorImpl<char> &Result) {
580 symbol_iterator SymI = Rel.getSymbol();
581 Expected<StringRef> SymNameOrErr = SymI->getName();
583 return errorToErrorCode(SymNameOrErr.takeError());
584 StringRef SymName = *SymNameOrErr;
585 Result.append(SymName.begin(), SymName.end());
586 return std::error_code();
589 static void printRelocationTargetName(const MachOObjectFile *O,
590 const MachO::any_relocation_info &RE,
591 raw_string_ostream &Fmt) {
592 // Target of a scattered relocation is an address. In the interest of
593 // generating pretty output, scan through the symbol table looking for a
594 // symbol that aligns with that address. If we find one, print it.
595 // Otherwise, we just print the hex address of the target.
596 if (O->isRelocationScattered(RE)) {
597 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
599 for (const SymbolRef &Symbol : O->symbols()) {
600 Expected<uint64_t> Addr = Symbol.getAddress();
602 report_error(O->getFileName(), Addr.takeError());
605 Expected<StringRef> Name = Symbol.getName();
607 report_error(O->getFileName(), Name.takeError());
612 // If we couldn't find a symbol that this relocation refers to, try
613 // to find a section beginning instead.
614 for (const SectionRef &Section : ToolSectionFilter(*O)) {
618 uint64_t Addr = Section.getAddress();
621 if ((ec = Section.getName(Name)))
622 report_error(O->getFileName(), ec);
627 Fmt << format("0x%x", Val);
632 bool isExtern = O->getPlainRelocationExternal(RE);
633 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
635 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
636 Fmt << format("0x%0" PRIx64, Val);
641 symbol_iterator SI = O->symbol_begin();
643 Expected<StringRef> SOrErr = SI->getName();
645 report_error(O->getFileName(), SOrErr.takeError());
648 section_iterator SI = O->section_begin();
649 // Adjust for the fact that sections are 1-indexed.
654 uint32_t I = Val - 1;
655 while (I != 0 && SI != O->section_end()) {
659 if (SI == O->section_end())
660 Fmt << Val << " (?,?)";
668 static std::error_code getRelocationValueString(const WasmObjectFile *Obj,
669 const RelocationRef &RelRef,
670 SmallVectorImpl<char> &Result) {
671 const wasm::WasmRelocation& Rel = Obj->getWasmRelocation(RelRef);
672 symbol_iterator SI = RelRef.getSymbol();
674 raw_string_ostream Fmt(FmtBuf);
675 if (SI == Obj->symbol_end()) {
676 // Not all wasm relocations have symbols associated with them.
677 // In particular R_WEBASSEMBLY_TYPE_INDEX_LEB.
680 Expected<StringRef> SymNameOrErr = SI->getName();
682 return errorToErrorCode(SymNameOrErr.takeError());
683 StringRef SymName = *SymNameOrErr;
684 Result.append(SymName.begin(), SymName.end());
686 Fmt << (Rel.Addend < 0 ? "" : "+") << Rel.Addend;
688 Result.append(FmtBuf.begin(), FmtBuf.end());
689 return std::error_code();
692 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
693 const RelocationRef &RelRef,
694 SmallVectorImpl<char> &Result) {
695 DataRefImpl Rel = RelRef.getRawDataRefImpl();
696 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
698 unsigned Arch = Obj->getArch();
701 raw_string_ostream Fmt(FmtBuf);
702 unsigned Type = Obj->getAnyRelocationType(RE);
703 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
705 // Determine any addends that should be displayed with the relocation.
706 // These require decoding the relocation type, which is triple-specific.
708 // X86_64 has entirely custom relocation types.
709 if (Arch == Triple::x86_64) {
711 case MachO::X86_64_RELOC_GOT_LOAD:
712 case MachO::X86_64_RELOC_GOT: {
713 printRelocationTargetName(Obj, RE, Fmt);
719 case MachO::X86_64_RELOC_SUBTRACTOR: {
720 DataRefImpl RelNext = Rel;
721 Obj->moveRelocationNext(RelNext);
722 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
724 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
725 // X86_64_RELOC_UNSIGNED.
726 // NOTE: Scattered relocations don't exist on x86_64.
727 unsigned RType = Obj->getAnyRelocationType(RENext);
728 if (RType != MachO::X86_64_RELOC_UNSIGNED)
729 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
730 "X86_64_RELOC_SUBTRACTOR.");
732 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
733 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
734 printRelocationTargetName(Obj, RENext, Fmt);
736 printRelocationTargetName(Obj, RE, Fmt);
739 case MachO::X86_64_RELOC_TLV:
740 printRelocationTargetName(Obj, RE, Fmt);
745 case MachO::X86_64_RELOC_SIGNED_1:
746 printRelocationTargetName(Obj, RE, Fmt);
749 case MachO::X86_64_RELOC_SIGNED_2:
750 printRelocationTargetName(Obj, RE, Fmt);
753 case MachO::X86_64_RELOC_SIGNED_4:
754 printRelocationTargetName(Obj, RE, Fmt);
758 printRelocationTargetName(Obj, RE, Fmt);
761 // X86 and ARM share some relocation types in common.
762 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
763 Arch == Triple::ppc) {
764 // Generic relocation types...
766 case MachO::GENERIC_RELOC_PAIR: // prints no info
767 return std::error_code();
768 case MachO::GENERIC_RELOC_SECTDIFF: {
769 DataRefImpl RelNext = Rel;
770 Obj->moveRelocationNext(RelNext);
771 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
773 // X86 sect diff's must be followed by a relocation of type
774 // GENERIC_RELOC_PAIR.
775 unsigned RType = Obj->getAnyRelocationType(RENext);
777 if (RType != MachO::GENERIC_RELOC_PAIR)
778 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
779 "GENERIC_RELOC_SECTDIFF.");
781 printRelocationTargetName(Obj, RE, Fmt);
783 printRelocationTargetName(Obj, RENext, Fmt);
788 if (Arch == Triple::x86 || Arch == Triple::ppc) {
790 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
791 DataRefImpl RelNext = Rel;
792 Obj->moveRelocationNext(RelNext);
793 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
795 // X86 sect diff's must be followed by a relocation of type
796 // GENERIC_RELOC_PAIR.
797 unsigned RType = Obj->getAnyRelocationType(RENext);
798 if (RType != MachO::GENERIC_RELOC_PAIR)
799 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
800 "GENERIC_RELOC_LOCAL_SECTDIFF.");
802 printRelocationTargetName(Obj, RE, Fmt);
804 printRelocationTargetName(Obj, RENext, Fmt);
807 case MachO::GENERIC_RELOC_TLV: {
808 printRelocationTargetName(Obj, RE, Fmt);
815 printRelocationTargetName(Obj, RE, Fmt);
817 } else { // ARM-specific relocations
819 case MachO::ARM_RELOC_HALF:
820 case MachO::ARM_RELOC_HALF_SECTDIFF: {
821 // Half relocations steal a bit from the length field to encode
822 // whether this is an upper16 or a lower16 relocation.
823 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
829 printRelocationTargetName(Obj, RE, Fmt);
831 DataRefImpl RelNext = Rel;
832 Obj->moveRelocationNext(RelNext);
833 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
835 // ARM half relocs must be followed by a relocation of type
837 unsigned RType = Obj->getAnyRelocationType(RENext);
838 if (RType != MachO::ARM_RELOC_PAIR)
839 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
842 // NOTE: The half of the target virtual address is stashed in the
843 // address field of the secondary relocation, but we can't reverse
844 // engineer the constant offset from it without decoding the movw/movt
845 // instruction to find the other half in its immediate field.
847 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
848 // symbol/section pointer of the follow-on relocation.
849 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
851 printRelocationTargetName(Obj, RENext, Fmt);
857 default: { printRelocationTargetName(Obj, RE, Fmt); }
861 printRelocationTargetName(Obj, RE, Fmt);
864 Result.append(FmtBuf.begin(), FmtBuf.end());
865 return std::error_code();
868 static std::error_code getRelocationValueString(const RelocationRef &Rel,
869 SmallVectorImpl<char> &Result) {
870 const ObjectFile *Obj = Rel.getObject();
871 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
872 return getRelocationValueString(ELF, Rel, Result);
873 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
874 return getRelocationValueString(COFF, Rel, Result);
875 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
876 return getRelocationValueString(Wasm, Rel, Result);
877 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
878 return getRelocationValueString(MachO, Rel, Result);
879 llvm_unreachable("unknown object file format");
882 /// Indicates whether this relocation should hidden when listing
883 /// relocations, usually because it is the trailing part of a multipart
884 /// relocation that will be printed as part of the leading relocation.
885 static bool getHidden(RelocationRef RelRef) {
886 auto *MachO = dyn_cast<MachOObjectFile>(RelRef.getObject());
890 unsigned Arch = MachO->getArch();
891 DataRefImpl Rel = RelRef.getRawDataRefImpl();
892 uint64_t Type = MachO->getRelocationType(Rel);
894 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
896 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc)
897 return Type == MachO::GENERIC_RELOC_PAIR;
899 if (Arch == Triple::x86_64) {
900 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
901 // an X86_64_RELOC_SUBTRACTOR.
902 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
903 DataRefImpl RelPrev = Rel;
905 uint64_t PrevType = MachO->getRelocationType(RelPrev);
906 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
915 class SourcePrinter {
917 DILineInfo OldLineInfo;
918 const ObjectFile *Obj = nullptr;
919 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
920 // File name to file contents of source
921 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
922 // Mark the line endings of the cached source
923 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
926 bool cacheSource(const DILineInfo& LineInfoFile);
929 SourcePrinter() = default;
930 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
931 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
932 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
934 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
936 virtual ~SourcePrinter() = default;
937 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
938 StringRef Delimiter = "; ");
941 bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
942 std::unique_ptr<MemoryBuffer> Buffer;
943 if (LineInfo.Source) {
944 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);
946 auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName);
949 Buffer = std::move(*BufferOrError);
951 // Chomp the file to get lines
952 size_t BufferSize = Buffer->getBufferSize();
953 const char *BufferStart = Buffer->getBufferStart();
954 for (const char *Start = BufferStart, *End = BufferStart;
955 End < BufferStart + BufferSize; End++)
956 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
957 (*End == '\r' && *(End + 1) == '\n')) {
958 LineCache[LineInfo.FileName].push_back(StringRef(Start, End - Start));
963 SourceCache[LineInfo.FileName] = std::move(Buffer);
967 void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
968 StringRef Delimiter) {
971 DILineInfo LineInfo = DILineInfo();
972 auto ExpectecLineInfo =
973 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
974 if (!ExpectecLineInfo)
975 consumeError(ExpectecLineInfo.takeError());
977 LineInfo = *ExpectecLineInfo;
979 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
984 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
986 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
987 if (!cacheSource(LineInfo))
989 auto FileBuffer = SourceCache.find(LineInfo.FileName);
990 if (FileBuffer != SourceCache.end()) {
991 auto LineBuffer = LineCache.find(LineInfo.FileName);
992 if (LineBuffer != LineCache.end()) {
993 if (LineInfo.Line > LineBuffer->second.size())
995 // Vector begins at 0, line numbers are non-zero
996 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
1001 OldLineInfo = LineInfo;
1004 static bool isArmElf(const ObjectFile *Obj) {
1005 return (Obj->isELF() &&
1006 (Obj->getArch() == Triple::aarch64 ||
1007 Obj->getArch() == Triple::aarch64_be ||
1008 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
1009 Obj->getArch() == Triple::thumb ||
1010 Obj->getArch() == Triple::thumbeb));
1013 class PrettyPrinter {
1015 virtual ~PrettyPrinter() = default;
1016 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
1017 ArrayRef<uint8_t> Bytes, uint64_t Address,
1018 raw_ostream &OS, StringRef Annot,
1019 MCSubtargetInfo const &STI, SourcePrinter *SP,
1020 std::vector<RelocationRef> *Rels = nullptr) {
1021 if (SP && (PrintSource || PrintLines))
1022 SP->printSourceLine(OS, Address);
1024 OS << format("%8" PRIx64 ":", Address);
1025 if (!NoShowRawInsn) {
1027 dumpBytes(Bytes, OS);
1030 IP.printInst(MI, OS, "", STI);
1035 PrettyPrinter PrettyPrinterInst;
1036 class HexagonPrettyPrinter : public PrettyPrinter {
1038 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
1041 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
1043 OS << format("%8" PRIx64 ":", Address);
1044 if (!NoShowRawInsn) {
1046 dumpBytes(Bytes.slice(0, 4), OS);
1047 OS << format("%08" PRIx32, opcode);
1050 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1051 uint64_t Address, raw_ostream &OS, StringRef Annot,
1052 MCSubtargetInfo const &STI, SourcePrinter *SP,
1053 std::vector<RelocationRef> *Rels) override {
1054 if (SP && (PrintSource || PrintLines))
1055 SP->printSourceLine(OS, Address, "");
1057 printLead(Bytes, Address, OS);
1063 raw_string_ostream TempStream(Buffer);
1064 IP.printInst(MI, TempStream, "", STI);
1066 StringRef Contents(Buffer);
1067 // Split off bundle attributes
1068 auto PacketBundle = Contents.rsplit('\n');
1069 // Split off first instruction from the rest
1070 auto HeadTail = PacketBundle.first.split('\n');
1071 auto Preamble = " { ";
1072 auto Separator = "";
1073 StringRef Fmt = "\t\t\t%08" PRIx64 ": ";
1074 std::vector<RelocationRef>::const_iterator RelCur = Rels->begin();
1075 std::vector<RelocationRef>::const_iterator RelEnd = Rels->end();
1077 // Hexagon's packets require relocations to be inline rather than
1078 // clustered at the end of the packet.
1079 auto PrintReloc = [&]() -> void {
1080 while ((RelCur != RelEnd) && (RelCur->getOffset() <= Address)) {
1081 if (RelCur->getOffset() == Address) {
1082 SmallString<16> Name;
1083 SmallString<32> Val;
1084 RelCur->getTypeName(Name);
1085 error(getRelocationValueString(*RelCur, Val));
1086 OS << Separator << format(Fmt.data(), Address) << Name << "\t" << Val
1094 while (!HeadTail.first.empty()) {
1097 if (SP && (PrintSource || PrintLines))
1098 SP->printSourceLine(OS, Address, "");
1099 printLead(Bytes, Address, OS);
1103 auto Duplex = HeadTail.first.split('\v');
1104 if (!Duplex.second.empty()) {
1107 Inst = Duplex.second;
1110 Inst = HeadTail.first;
1112 HeadTail = HeadTail.second.split('\n');
1113 if (HeadTail.first.empty())
1114 OS << " } " << PacketBundle.second;
1116 Bytes = Bytes.slice(4);
1121 HexagonPrettyPrinter HexagonPrettyPrinterInst;
1123 class AMDGCNPrettyPrinter : public PrettyPrinter {
1125 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1126 uint64_t Address, raw_ostream &OS, StringRef Annot,
1127 MCSubtargetInfo const &STI, SourcePrinter *SP,
1128 std::vector<RelocationRef> *Rels) override {
1129 if (SP && (PrintSource || PrintLines))
1130 SP->printSourceLine(OS, Address);
1132 typedef support::ulittle32_t U32;
1135 SmallString<40> InstStr;
1136 raw_svector_ostream IS(InstStr);
1138 IP.printInst(MI, IS, "", STI);
1140 OS << left_justify(IS.str(), 60);
1142 // an unrecognized encoding - this is probably data so represent it
1143 // using the .long directive, or .byte directive if fewer than 4 bytes
1145 if (Bytes.size() >= 4) {
1146 OS << format("\t.long 0x%08" PRIx32 " ",
1147 static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data())));
1150 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
1151 for (unsigned int i = 1; i < Bytes.size(); i++)
1152 OS << format(", 0x%02" PRIx8, Bytes[i]);
1153 OS.indent(55 - (6 * Bytes.size()));
1157 OS << format("// %012" PRIX64 ": ", Address);
1158 if (Bytes.size() >=4) {
1159 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
1160 Bytes.size() / sizeof(U32)))
1161 // D should be explicitly casted to uint32_t here as it is passed
1162 // by format to snprintf as vararg.
1163 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
1165 for (unsigned int i = 0; i < Bytes.size(); i++)
1166 OS << format("%02" PRIX8 " ", Bytes[i]);
1170 OS << "// " << Annot;
1173 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
1175 class BPFPrettyPrinter : public PrettyPrinter {
1177 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1178 uint64_t Address, raw_ostream &OS, StringRef Annot,
1179 MCSubtargetInfo const &STI, SourcePrinter *SP,
1180 std::vector<RelocationRef> *Rels) override {
1181 if (SP && (PrintSource || PrintLines))
1182 SP->printSourceLine(OS, Address);
1184 OS << format("%8" PRId64 ":", Address / 8);
1185 if (!NoShowRawInsn) {
1187 dumpBytes(Bytes, OS);
1190 IP.printInst(MI, OS, "", STI);
1195 BPFPrettyPrinter BPFPrettyPrinterInst;
1197 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
1198 switch(Triple.getArch()) {
1200 return PrettyPrinterInst;
1201 case Triple::hexagon:
1202 return HexagonPrettyPrinterInst;
1203 case Triple::amdgcn:
1204 return AMDGCNPrettyPrinterInst;
1207 return BPFPrettyPrinterInst;
1212 static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1213 assert(Obj->isELF());
1214 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1215 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1216 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1217 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1218 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1219 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1220 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1221 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1222 llvm_unreachable("Unsupported binary format");
1225 template <class ELFT> static void
1226 addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
1227 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1228 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
1229 uint8_t SymbolType = Symbol.getELFType();
1230 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
1233 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1235 report_error(Obj->getFileName(), AddressOrErr.takeError());
1237 Expected<StringRef> Name = Symbol.getName();
1239 report_error(Obj->getFileName(), Name.takeError());
1243 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1245 report_error(Obj->getFileName(), SectionOrErr.takeError());
1246 section_iterator SecI = *SectionOrErr;
1247 if (SecI == Obj->section_end())
1250 AllSymbols[*SecI].emplace_back(*AddressOrErr, *Name, SymbolType);
1255 addDynamicElfSymbols(const ObjectFile *Obj,
1256 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1257 assert(Obj->isELF());
1258 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1259 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
1260 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1261 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
1262 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1263 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
1264 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1265 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
1267 llvm_unreachable("Unsupported binary format");
1270 static void addPltEntries(const ObjectFile *Obj,
1271 std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
1272 StringSaver &Saver) {
1273 Optional<SectionRef> Plt = None;
1274 for (const SectionRef &Section : Obj->sections()) {
1276 if (Section.getName(Name))
1283 if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) {
1284 for (auto PltEntry : ElfObj->getPltAddresses()) {
1285 SymbolRef Symbol(PltEntry.first, ElfObj);
1286 uint8_t SymbolType = getElfSymbolType(Obj, Symbol);
1288 Expected<StringRef> NameOrErr = Symbol.getName();
1290 report_error(Obj->getFileName(), NameOrErr.takeError());
1291 if (NameOrErr->empty())
1293 StringRef Name = Saver.save((*NameOrErr + "@plt").str());
1295 AllSymbols[*Plt].emplace_back(PltEntry.second, Name, SymbolType);
1300 // Normally the disassembly output will skip blocks of zeroes. This function
1301 // returns the number of zero bytes that can be skipped when dumping the
1302 // disassembly of the instructions in Buf.
1303 static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) {
1304 // When -z or --disassemble-zeroes are given we always dissasemble them.
1305 if (DisassembleZeroes)
1308 // Find the number of leading zeroes.
1310 while (N < Buf.size() && !Buf[N])
1313 // We may want to skip blocks of zero bytes, but unless we see
1314 // at least 8 of them in a row.
1318 // We skip zeroes in multiples of 4 because do not want to truncate an
1319 // instruction if it starts with a zero byte.
1323 static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
1324 if (StartAddress > StopAddress)
1325 error("Start address should be less than stop address");
1327 const Target *TheTarget = getTarget(Obj);
1329 // Package up features to be passed to target/subtarget
1330 SubtargetFeatures Features = Obj->getFeatures();
1331 if (!MAttrs.empty())
1332 for (unsigned I = 0; I != MAttrs.size(); ++I)
1333 Features.AddFeature(MAttrs[I]);
1335 std::unique_ptr<const MCRegisterInfo> MRI(
1336 TheTarget->createMCRegInfo(TripleName));
1338 report_error(Obj->getFileName(), "no register info for target " +
1341 // Set up disassembler.
1342 std::unique_ptr<const MCAsmInfo> AsmInfo(
1343 TheTarget->createMCAsmInfo(*MRI, TripleName));
1345 report_error(Obj->getFileName(), "no assembly info for target " +
1347 std::unique_ptr<const MCSubtargetInfo> STI(
1348 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1350 report_error(Obj->getFileName(), "no subtarget info for target " +
1352 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1354 report_error(Obj->getFileName(), "no instruction info for target " +
1356 MCObjectFileInfo MOFI;
1357 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1358 // FIXME: for now initialize MCObjectFileInfo with default values
1359 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
1361 std::unique_ptr<MCDisassembler> DisAsm(
1362 TheTarget->createMCDisassembler(*STI, Ctx));
1364 report_error(Obj->getFileName(), "no disassembler for target " +
1367 std::unique_ptr<const MCInstrAnalysis> MIA(
1368 TheTarget->createMCInstrAnalysis(MII.get()));
1370 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1371 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1372 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
1374 report_error(Obj->getFileName(), "no instruction printer for target " +
1376 IP->setPrintImmHex(PrintImmHex);
1377 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
1379 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
1380 "\t\t\t%08" PRIx64 ": ";
1382 SourcePrinter SP(Obj, TheTarget->getName());
1384 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1385 // in RelocSecs contain the relocations for section S.
1387 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
1388 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1389 section_iterator Sec2 = Section.getRelocatedSection();
1390 if (Sec2 != Obj->section_end())
1391 SectionRelocMap[*Sec2].push_back(Section);
1394 // Create a mapping from virtual address to symbol name. This is used to
1395 // pretty print the symbols while disassembling.
1396 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1397 SectionSymbolsTy AbsoluteSymbols;
1398 for (const SymbolRef &Symbol : Obj->symbols()) {
1399 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1401 report_error(Obj->getFileName(), AddressOrErr.takeError());
1402 uint64_t Address = *AddressOrErr;
1404 Expected<StringRef> Name = Symbol.getName();
1406 report_error(Obj->getFileName(), Name.takeError());
1410 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1412 report_error(Obj->getFileName(), SectionOrErr.takeError());
1414 uint8_t SymbolType = ELF::STT_NOTYPE;
1416 SymbolType = getElfSymbolType(Obj, Symbol);
1418 section_iterator SecI = *SectionOrErr;
1419 if (SecI != Obj->section_end())
1420 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1422 AbsoluteSymbols.emplace_back(Address, *Name, SymbolType);
1426 if (AllSymbols.empty() && Obj->isELF())
1427 addDynamicElfSymbols(Obj, AllSymbols);
1430 StringSaver Saver(A);
1431 addPltEntries(Obj, AllSymbols, Saver);
1433 // Create a mapping from virtual address to section.
1434 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1435 for (SectionRef Sec : Obj->sections())
1436 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1437 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1439 // Linked executables (.exe and .dll files) typically don't include a real
1440 // symbol table but they might contain an export table.
1441 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1442 for (const auto &ExportEntry : COFFObj->export_directories()) {
1444 error(ExportEntry.getSymbolName(Name));
1448 error(ExportEntry.getExportRVA(RVA));
1450 uint64_t VA = COFFObj->getImageBase() + RVA;
1451 auto Sec = std::upper_bound(
1452 SectionAddresses.begin(), SectionAddresses.end(), VA,
1453 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1454 return LHS < RHS.first;
1456 if (Sec != SectionAddresses.begin())
1459 Sec = SectionAddresses.end();
1461 if (Sec != SectionAddresses.end())
1462 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
1464 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
1468 // Sort all the symbols, this allows us to use a simple binary search to find
1469 // a symbol near an address.
1470 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1471 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1472 array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
1474 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1475 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
1478 uint64_t SectionAddr = Section.getAddress();
1479 uint64_t SectSize = Section.getSize();
1483 // Get the list of all the symbols in this section.
1484 SectionSymbolsTy &Symbols = AllSymbols[Section];
1485 std::vector<uint64_t> DataMappingSymsAddr;
1486 std::vector<uint64_t> TextMappingSymsAddr;
1487 if (isArmElf(Obj)) {
1488 for (const auto &Symb : Symbols) {
1489 uint64_t Address = std::get<0>(Symb);
1490 StringRef Name = std::get<1>(Symb);
1491 if (Name.startswith("$d"))
1492 DataMappingSymsAddr.push_back(Address - SectionAddr);
1493 if (Name.startswith("$x"))
1494 TextMappingSymsAddr.push_back(Address - SectionAddr);
1495 if (Name.startswith("$a"))
1496 TextMappingSymsAddr.push_back(Address - SectionAddr);
1497 if (Name.startswith("$t"))
1498 TextMappingSymsAddr.push_back(Address - SectionAddr);
1502 llvm::sort(DataMappingSymsAddr);
1503 llvm::sort(TextMappingSymsAddr);
1505 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1506 // AMDGPU disassembler uses symbolizer for printing labels
1507 std::unique_ptr<MCRelocationInfo> RelInfo(
1508 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1510 std::unique_ptr<MCSymbolizer> Symbolizer(
1511 TheTarget->createMCSymbolizer(
1512 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1513 DisAsm->setSymbolizer(std::move(Symbolizer));
1517 // Make a list of all the relocations for this section.
1518 std::vector<RelocationRef> Rels;
1520 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1521 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1522 Rels.push_back(Reloc);
1527 // Sort relocations by address.
1528 llvm::sort(Rels, isRelocAddressLess);
1530 StringRef SegmentName = "";
1531 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
1532 DataRefImpl DR = Section.getRawDataRefImpl();
1533 SegmentName = MachO->getSectionFinalSegmentName(DR);
1535 StringRef SectionName;
1536 error(Section.getName(SectionName));
1538 // If the section has no symbol at the start, just insert a dummy one.
1539 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
1542 std::make_tuple(SectionAddr, SectionName,
1543 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
1546 SmallString<40> Comments;
1547 raw_svector_ostream CommentStream(Comments);
1550 error(Section.getContents(BytesStr));
1551 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1556 bool PrintedSection = false;
1558 std::vector<RelocationRef>::const_iterator RelCur = Rels.begin();
1559 std::vector<RelocationRef>::const_iterator RelEnd = Rels.end();
1560 // Disassemble symbol by symbol.
1561 for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) {
1562 uint64_t Start = std::get<0>(Symbols[SI]) - SectionAddr;
1563 // The end is either the section end or the beginning of the next
1565 uint64_t End = (SI == SE - 1)
1567 : std::get<0>(Symbols[SI + 1]) - SectionAddr;
1568 // Don't try to disassemble beyond the end of section contents.
1571 // If this symbol has the same address as the next symbol, then skip it.
1575 // Check if we need to skip symbol
1576 // Skip if the symbol's data is not between StartAddress and StopAddress
1577 if (End + SectionAddr < StartAddress ||
1578 Start + SectionAddr > StopAddress) {
1582 /// Skip if user requested specific symbols and this is not in the list
1583 if (!DisasmFuncsSet.empty() &&
1584 !DisasmFuncsSet.count(std::get<1>(Symbols[SI])))
1587 if (!PrintedSection) {
1588 PrintedSection = true;
1589 outs() << "Disassembly of section ";
1590 if (!SegmentName.empty())
1591 outs() << SegmentName << ",";
1592 outs() << SectionName << ':';
1595 // Stop disassembly at the stop address specified
1596 if (End + SectionAddr > StopAddress)
1597 End = StopAddress - SectionAddr;
1599 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1600 if (std::get<2>(Symbols[SI]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1601 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1605 std::get<2>(Symbols[SI + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1606 // cut trailing zeroes at the end of kernel
1607 // cut up to 256 bytes
1608 const uint64_t EndAlign = 256;
1609 const auto Limit = End - (std::min)(EndAlign, End - Start);
1610 while (End > Limit &&
1611 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1618 outs() << format("%016" PRIx64 " ", SectionAddr + Start);
1620 StringRef SymbolName = std::get<1>(Symbols[SI]);
1622 outs() << demangle(SymbolName) << ":\n";
1624 outs() << SymbolName << ":\n";
1626 // Don't print raw contents of a virtual section. A virtual section
1627 // doesn't have any contents in the file.
1628 if (Section.isVirtual()) {
1634 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1636 raw_ostream &DebugOut = nulls();
1639 for (Index = Start; Index < End; Index += Size) {
1642 if (Index + SectionAddr < StartAddress ||
1643 Index + SectionAddr > StopAddress) {
1644 // skip byte by byte till StartAddress is reached
1648 // AArch64 ELF binaries can interleave data and text in the
1649 // same section. We rely on the markers introduced to
1650 // understand what we need to dump. If the data marker is within a
1651 // function, it is denoted as a word/short etc
1652 if (isArmElf(Obj) && std::get<2>(Symbols[SI]) != ELF::STT_OBJECT &&
1654 uint64_t Stride = 0;
1656 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1657 DataMappingSymsAddr.end(), Index);
1658 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1660 while (Index < End) {
1661 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1663 if (Index + 4 <= End) {
1665 dumpBytes(Bytes.slice(Index, 4), outs());
1666 outs() << "\t.word\t";
1668 if (Obj->isLittleEndian()) {
1670 reinterpret_cast<const support::ulittle32_t *>(
1671 Bytes.data() + Index);
1674 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1675 Bytes.data() + Index);
1678 outs() << "0x" << format("%08" PRIx32, Data);
1679 } else if (Index + 2 <= End) {
1681 dumpBytes(Bytes.slice(Index, 2), outs());
1682 outs() << "\t\t.short\t";
1684 if (Obj->isLittleEndian()) {
1686 reinterpret_cast<const support::ulittle16_t *>(
1687 Bytes.data() + Index);
1691 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1695 outs() << "0x" << format("%04" PRIx16, Data);
1698 dumpBytes(Bytes.slice(Index, 1), outs());
1699 outs() << "\t\t.byte\t";
1700 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
1704 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1705 TextMappingSymsAddr.end(), Index);
1706 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1712 // If there is a data symbol inside an ELF text section and we are only
1713 // disassembling text (applicable all architectures),
1714 // we are in a situation where we must print the data and not
1716 if (Obj->isELF() && std::get<2>(Symbols[SI]) == ELF::STT_OBJECT &&
1717 !DisassembleAll && Section.isText()) {
1718 // print out data up to 8 bytes at a time in hex and ascii
1719 uint8_t AsciiData[9] = {'\0'};
1723 for (Index = Start; Index < End; Index += 1) {
1724 if (((SectionAddr + Index) < StartAddress) ||
1725 ((SectionAddr + Index) > StopAddress))
1727 if (NumBytes == 0) {
1728 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1731 Byte = Bytes.slice(Index)[0];
1732 outs() << format(" %02x", Byte);
1733 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
1735 uint8_t IndentOffset = 0;
1737 if (Index == End - 1 || NumBytes > 8) {
1738 // Indent the space for less than 8 bytes data.
1739 // 2 spaces for byte and one for space between bytes
1740 IndentOffset = 3 * (8 - NumBytes);
1741 for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1742 AsciiData[Excess] = '\0';
1745 if (NumBytes == 8) {
1746 AsciiData[8] = '\0';
1747 outs() << std::string(IndentOffset, ' ') << " ";
1748 outs() << reinterpret_cast<char *>(AsciiData);
1758 countSkippableZeroBytes(Bytes.slice(Index, End - Index))) {
1759 outs() << "\t\t..." << '\n';
1765 // Disassemble a real instruction or a data when disassemble all is
1767 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1768 SectionAddr + Index, DebugOut,
1773 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
1774 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
1776 outs() << CommentStream.str();
1779 // Try to resolve the target of a call, tail call, etc. to a specific
1781 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1782 MIA->isConditionalBranch(Inst))) {
1784 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1785 // In a relocatable object, the target's section must reside in
1786 // the same section as the call instruction or it is accessed
1787 // through a relocation.
1789 // In a non-relocatable object, the target may be in any section.
1791 // N.B. We don't walk the relocations in the relocatable case yet.
1792 auto *TargetSectionSymbols = &Symbols;
1793 if (!Obj->isRelocatableObject()) {
1794 auto SectionAddress = std::upper_bound(
1795 SectionAddresses.begin(), SectionAddresses.end(), Target,
1797 const std::pair<uint64_t, SectionRef> &RHS) {
1798 return LHS < RHS.first;
1800 if (SectionAddress != SectionAddresses.begin()) {
1802 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1804 TargetSectionSymbols = &AbsoluteSymbols;
1808 // Find the first symbol in the section whose offset is less than
1809 // or equal to the target. If there isn't a section that contains
1810 // the target, find the nearest preceding absolute symbol.
1811 auto TargetSym = std::upper_bound(
1812 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1813 Target, [](uint64_t LHS,
1814 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1815 return LHS < std::get<0>(RHS);
1817 if (TargetSym == TargetSectionSymbols->begin()) {
1818 TargetSectionSymbols = &AbsoluteSymbols;
1819 TargetSym = std::upper_bound(
1820 AbsoluteSymbols.begin(), AbsoluteSymbols.end(),
1821 Target, [](uint64_t LHS,
1822 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1823 return LHS < std::get<0>(RHS);
1826 if (TargetSym != TargetSectionSymbols->begin()) {
1828 uint64_t TargetAddress = std::get<0>(*TargetSym);
1829 StringRef TargetName = std::get<1>(*TargetSym);
1830 outs() << " <" << TargetName;
1831 uint64_t Disp = Target - TargetAddress;
1833 outs() << "+0x" << Twine::utohexstr(Disp);
1840 // Hexagon does this in pretty printer
1841 if (Obj->getArch() != Triple::hexagon)
1842 // Print relocation for instruction.
1843 while (RelCur != RelEnd) {
1844 uint64_t Addr = RelCur->getOffset();
1845 SmallString<16> Name;
1846 SmallString<32> Val;
1848 // If this relocation is hidden, skip it.
1849 if (getHidden(*RelCur) || ((SectionAddr + Addr) < StartAddress)) {
1854 // Stop when rel_cur's address is past the current instruction.
1855 if (Addr >= Index + Size)
1857 RelCur->getTypeName(Name);
1858 error(getRelocationValueString(*RelCur, Val));
1859 outs() << format(Fmt.data(), SectionAddr + Addr) << Name << "\t"
1868 void llvm::printRelocations(const ObjectFile *Obj) {
1869 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1871 // Regular objdump doesn't print relocations in non-relocatable object
1873 if (!Obj->isRelocatableObject())
1876 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1877 if (Section.relocation_begin() == Section.relocation_end())
1880 error(Section.getName(SecName));
1881 outs() << "RELOCATION RECORDS FOR [" << SecName << "]:\n";
1882 for (const RelocationRef &Reloc : Section.relocations()) {
1883 uint64_t Address = Reloc.getOffset();
1884 SmallString<32> RelocName;
1885 SmallString<32> ValueStr;
1886 if (Address < StartAddress || Address > StopAddress || getHidden(Reloc))
1888 Reloc.getTypeName(RelocName);
1889 error(getRelocationValueString(Reloc, ValueStr));
1890 outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1891 << ValueStr << "\n";
1897 void llvm::printDynamicRelocations(const ObjectFile *Obj) {
1898 // For the moment, this option is for ELF only
1902 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
1903 if (!Elf || Elf->getEType() != ELF::ET_DYN) {
1904 error("not a dynamic object");
1908 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1909 if (DynRelSec.empty())
1912 outs() << "DYNAMIC RELOCATION RECORDS\n";
1913 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1914 for (const SectionRef &Section : DynRelSec) {
1915 if (Section.relocation_begin() == Section.relocation_end())
1917 for (const RelocationRef &Reloc : Section.relocations()) {
1918 uint64_t Address = Reloc.getOffset();
1919 SmallString<32> RelocName;
1920 SmallString<32> ValueStr;
1921 Reloc.getTypeName(RelocName);
1922 error(getRelocationValueString(Reloc, ValueStr));
1923 outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1924 << ValueStr << "\n";
1929 void llvm::printSectionHeaders(const ObjectFile *Obj) {
1930 outs() << "Sections:\n"
1931 "Idx Name Size Address Type\n";
1932 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1934 error(Section.getName(Name));
1935 uint64_t Address = Section.getAddress();
1936 uint64_t Size = Section.getSize();
1937 bool Text = Section.isText();
1938 bool Data = Section.isData();
1939 bool BSS = Section.isBSS();
1940 std::string Type = (std::string(Text ? "TEXT " : "") +
1941 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1942 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
1943 (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1944 Address, Type.c_str());
1949 void llvm::printSectionContents(const ObjectFile *Obj) {
1951 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1954 error(Section.getName(Name));
1955 uint64_t BaseAddr = Section.getAddress();
1956 uint64_t Size = Section.getSize();
1960 outs() << "Contents of section " << Name << ":\n";
1961 if (Section.isBSS()) {
1962 outs() << format("<skipping contents of bss section at [%04" PRIx64
1963 ", %04" PRIx64 ")>\n",
1964 BaseAddr, BaseAddr + Size);
1968 error(Section.getContents(Contents));
1970 // Dump out the content as hex and printable ascii characters.
1971 for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) {
1972 outs() << format(" %04" PRIx64 " ", BaseAddr + Addr);
1973 // Dump line of hex.
1974 for (std::size_t I = 0; I < 16; ++I) {
1975 if (I != 0 && I % 4 == 0)
1978 outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true)
1979 << hexdigit(Contents[Addr + I] & 0xF, true);
1985 for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) {
1986 if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF))
1987 outs() << Contents[Addr + I];
1996 void llvm::printSymbolTable(const ObjectFile *O, StringRef ArchiveName,
1997 StringRef ArchitectureName) {
1998 outs() << "SYMBOL TABLE:\n";
2000 if (const COFFObjectFile *Coff = dyn_cast<const COFFObjectFile>(O)) {
2001 printCOFFSymbolTable(Coff);
2005 for (auto I = O->symbol_begin(), E = O->symbol_end(); I != E; ++I) {
2006 // Skip printing the special zero symbol when dumping an ELF file.
2007 // This makes the output consistent with the GNU objdump.
2008 if (I == O->symbol_begin() && isa<ELFObjectFileBase>(O))
2011 const SymbolRef &Symbol = *I;
2012 Expected<uint64_t> AddressOrError = Symbol.getAddress();
2013 if (!AddressOrError)
2014 report_error(ArchiveName, O->getFileName(), AddressOrError.takeError(),
2016 uint64_t Address = *AddressOrError;
2017 if ((Address < StartAddress) || (Address > StopAddress))
2019 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
2021 report_error(ArchiveName, O->getFileName(), TypeOrError.takeError(),
2023 SymbolRef::Type Type = *TypeOrError;
2024 uint32_t Flags = Symbol.getFlags();
2025 Expected<section_iterator> SectionOrErr = Symbol.getSection();
2027 report_error(ArchiveName, O->getFileName(), SectionOrErr.takeError(),
2029 section_iterator Section = *SectionOrErr;
2031 if (Type == SymbolRef::ST_Debug && Section != O->section_end()) {
2032 Section->getName(Name);
2034 Expected<StringRef> NameOrErr = Symbol.getName();
2036 report_error(ArchiveName, O->getFileName(), NameOrErr.takeError(),
2041 bool Global = Flags & SymbolRef::SF_Global;
2042 bool Weak = Flags & SymbolRef::SF_Weak;
2043 bool Absolute = Flags & SymbolRef::SF_Absolute;
2044 bool Common = Flags & SymbolRef::SF_Common;
2045 bool Hidden = Flags & SymbolRef::SF_Hidden;
2048 if (Type != SymbolRef::ST_Unknown)
2049 GlobLoc = Global ? 'g' : 'l';
2050 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
2052 char FileFunc = ' ';
2053 if (Type == SymbolRef::ST_File)
2055 else if (Type == SymbolRef::ST_Function)
2057 else if (Type == SymbolRef::ST_Data)
2060 const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 :
2063 outs() << format(Fmt, Address) << " "
2064 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
2065 << (Weak ? 'w' : ' ') // Weak?
2066 << ' ' // Constructor. Not supported yet.
2067 << ' ' // Warning. Not supported yet.
2068 << ' ' // Indirect reference to another symbol.
2069 << Debug // Debugging (d) or dynamic (D) symbol.
2070 << FileFunc // Name of function (F), file (f) or object (O).
2074 } else if (Common) {
2076 } else if (Section == O->section_end()) {
2079 if (const MachOObjectFile *MachO =
2080 dyn_cast<const MachOObjectFile>(O)) {
2081 DataRefImpl DR = Section->getRawDataRefImpl();
2082 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
2083 outs() << SegmentName << ",";
2085 StringRef SectionName;
2086 error(Section->getName(SectionName));
2087 outs() << SectionName;
2091 if (Common || isa<ELFObjectFileBase>(O)) {
2093 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
2094 outs() << format("\t %08" PRIx64 " ", Val);
2098 outs() << ".hidden ";
2101 outs() << demangle(Name) << '\n';
2103 outs() << Name << '\n';
2107 static void printUnwindInfo(const ObjectFile *O) {
2108 outs() << "Unwind info:\n\n";
2110 if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O))
2111 printCOFFUnwindInfo(Coff);
2112 else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O))
2113 printMachOUnwindInfo(MachO);
2115 // TODO: Extract DWARF dump tool to objdump.
2116 WithColor::error(errs(), ToolName)
2117 << "This operation is only currently supported "
2118 "for COFF and MachO object files.\n";
2121 void llvm::printExportsTrie(const ObjectFile *o) {
2122 outs() << "Exports trie:\n";
2123 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2124 printMachOExportsTrie(MachO);
2126 WithColor::error(errs(), ToolName)
2127 << "This operation is only currently supported "
2128 "for Mach-O executable files.\n";
2131 void llvm::printRebaseTable(ObjectFile *o) {
2132 outs() << "Rebase table:\n";
2133 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2134 printMachORebaseTable(MachO);
2136 WithColor::error(errs(), ToolName)
2137 << "This operation is only currently supported "
2138 "for Mach-O executable files.\n";
2141 void llvm::printBindTable(ObjectFile *o) {
2142 outs() << "Bind table:\n";
2143 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2144 printMachOBindTable(MachO);
2146 WithColor::error(errs(), ToolName)
2147 << "This operation is only currently supported "
2148 "for Mach-O executable files.\n";
2151 void llvm::printLazyBindTable(ObjectFile *o) {
2152 outs() << "Lazy bind table:\n";
2153 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2154 printMachOLazyBindTable(MachO);
2156 WithColor::error(errs(), ToolName)
2157 << "This operation is only currently supported "
2158 "for Mach-O executable files.\n";
2161 void llvm::printWeakBindTable(ObjectFile *o) {
2162 outs() << "Weak bind table:\n";
2163 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2164 printMachOWeakBindTable(MachO);
2166 WithColor::error(errs(), ToolName)
2167 << "This operation is only currently supported "
2168 "for Mach-O executable files.\n";
2171 /// Dump the raw contents of the __clangast section so the output can be piped
2172 /// into llvm-bcanalyzer.
2173 void llvm::printRawClangAST(const ObjectFile *Obj) {
2174 if (outs().is_displayed()) {
2175 WithColor::error(errs(), ToolName)
2176 << "The -raw-clang-ast option will dump the raw binary contents of "
2177 "the clang ast section.\n"
2178 "Please redirect the output to a file or another program such as "
2179 "llvm-bcanalyzer.\n";
2183 StringRef ClangASTSectionName("__clangast");
2184 if (isa<COFFObjectFile>(Obj)) {
2185 ClangASTSectionName = "clangast";
2188 Optional<object::SectionRef> ClangASTSection;
2189 for (auto Sec : ToolSectionFilter(*Obj)) {
2192 if (Name == ClangASTSectionName) {
2193 ClangASTSection = Sec;
2197 if (!ClangASTSection)
2200 StringRef ClangASTContents;
2201 error(ClangASTSection.getValue().getContents(ClangASTContents));
2202 outs().write(ClangASTContents.data(), ClangASTContents.size());
2205 static void printFaultMaps(const ObjectFile *Obj) {
2206 StringRef FaultMapSectionName;
2208 if (isa<ELFObjectFileBase>(Obj)) {
2209 FaultMapSectionName = ".llvm_faultmaps";
2210 } else if (isa<MachOObjectFile>(Obj)) {
2211 FaultMapSectionName = "__llvm_faultmaps";
2213 WithColor::error(errs(), ToolName)
2214 << "This operation is only currently supported "
2215 "for ELF and Mach-O executable files.\n";
2219 Optional<object::SectionRef> FaultMapSection;
2221 for (auto Sec : ToolSectionFilter(*Obj)) {
2224 if (Name == FaultMapSectionName) {
2225 FaultMapSection = Sec;
2230 outs() << "FaultMap table:\n";
2232 if (!FaultMapSection.hasValue()) {
2233 outs() << "<not found>\n";
2237 StringRef FaultMapContents;
2238 error(FaultMapSection.getValue().getContents(FaultMapContents));
2240 FaultMapParser FMP(FaultMapContents.bytes_begin(),
2241 FaultMapContents.bytes_end());
2246 static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) {
2248 printELFFileHeader(O);
2249 return printELFDynamicSection(O);
2252 return printCOFFFileHeader(O);
2254 return printWasmFileHeader(O);
2256 printMachOFileHeader(O);
2258 printMachOLoadCommands(O);
2261 report_error(O->getFileName(), "Invalid/Unsupported object file format");
2264 static void printFileHeaders(const ObjectFile *O) {
2265 if (!O->isELF() && !O->isCOFF())
2266 report_error(O->getFileName(), "Invalid/Unsupported object file format");
2268 Triple::ArchType AT = O->getArch();
2269 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
2270 Expected<uint64_t> StartAddrOrErr = O->getStartAddress();
2271 if (!StartAddrOrErr)
2272 report_error(O->getFileName(), StartAddrOrErr.takeError());
2274 StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
2275 uint64_t Address = StartAddrOrErr.get();
2276 outs() << "start address: "
2277 << "0x" << format(Fmt.data(), Address) << "\n\n";
2280 static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
2281 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
2283 WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n";
2284 consumeError(ModeOrErr.takeError());
2287 sys::fs::perms Mode = ModeOrErr.get();
2288 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2289 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2290 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2291 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2292 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2293 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2294 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2295 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2296 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2300 Expected<unsigned> UIDOrErr = C.getUID();
2302 report_error(Filename, UIDOrErr.takeError());
2303 unsigned UID = UIDOrErr.get();
2304 outs() << format("%d/", UID);
2306 Expected<unsigned> GIDOrErr = C.getGID();
2308 report_error(Filename, GIDOrErr.takeError());
2309 unsigned GID = GIDOrErr.get();
2310 outs() << format("%-d ", GID);
2312 Expected<uint64_t> Size = C.getRawSize();
2314 report_error(Filename, Size.takeError());
2315 outs() << format("%6" PRId64, Size.get()) << " ";
2317 StringRef RawLastModified = C.getRawLastModified();
2319 if (RawLastModified.getAsInteger(10, Seconds))
2320 outs() << "(date: \"" << RawLastModified
2321 << "\" contains non-decimal chars) ";
2323 // Since ctime(3) returns a 26 character string of the form:
2324 // "Sun Sep 16 01:03:52 1973\n\0"
2325 // just print 24 characters.
2327 outs() << format("%.24s ", ctime(&t));
2330 StringRef Name = "";
2331 Expected<StringRef> NameOrErr = C.getName();
2333 consumeError(NameOrErr.takeError());
2334 Expected<StringRef> RawNameOrErr = C.getRawName();
2336 report_error(Filename, NameOrErr.takeError());
2337 Name = RawNameOrErr.get();
2339 Name = NameOrErr.get();
2341 outs() << Name << "\n";
2344 static void dumpObject(ObjectFile *O, const Archive *A = nullptr,
2345 const Archive::Child *C = nullptr) {
2346 // Avoid other output when using a raw option.
2350 outs() << A->getFileName() << "(" << O->getFileName() << ")";
2352 outs() << O->getFileName();
2353 outs() << ":\tfile format " << O->getFileFormatName() << "\n\n";
2356 StringRef ArchiveName = A ? A->getFileName() : "";
2358 printFileHeaders(O);
2359 if (ArchiveHeaders && !MachOOpt && C)
2360 printArchiveChild(ArchiveName, *C);
2362 disassembleObject(O, Relocations);
2363 if (Relocations && !Disassemble)
2364 printRelocations(O);
2365 if (DynamicRelocations)
2366 printDynamicRelocations(O);
2368 printSectionHeaders(O);
2369 if (SectionContents)
2370 printSectionContents(O);
2372 printSymbolTable(O, ArchiveName);
2375 if (PrivateHeaders || FirstPrivateHeader)
2376 printPrivateFileHeaders(O, FirstPrivateHeader);
2378 printExportsTrie(O);
2380 printRebaseTable(O);
2384 printLazyBindTable(O);
2386 printWeakBindTable(O);
2388 printRawClangAST(O);
2391 if (DwarfDumpType != DIDT_Null) {
2392 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O);
2393 // Dump the complete DWARF structure.
2394 DIDumpOptions DumpOpts;
2395 DumpOpts.DumpType = DwarfDumpType;
2396 DICtx->dump(outs(), DumpOpts);
2400 static void dumpObject(const COFFImportFile *I, const Archive *A,
2401 const Archive::Child *C = nullptr) {
2402 StringRef ArchiveName = A ? A->getFileName() : "";
2404 // Avoid other output when using a raw option.
2407 << ArchiveName << "(" << I->getFileName() << ")"
2408 << ":\tfile format COFF-import-file"
2411 if (ArchiveHeaders && !MachOOpt && C)
2412 printArchiveChild(ArchiveName, *C);
2414 printCOFFSymbolTable(I);
2417 /// Dump each object file in \a a;
2418 static void dumpArchive(const Archive *A) {
2419 Error Err = Error::success();
2420 for (auto &C : A->children(Err)) {
2421 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2423 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2424 report_error(A->getFileName(), C, std::move(E));
2427 if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2428 dumpObject(O, A, &C);
2429 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2430 dumpObject(I, A, &C);
2432 report_error(A->getFileName(), object_error::invalid_file_type);
2435 report_error(A->getFileName(), std::move(Err));
2438 /// Open file and figure out how to dump it.
2439 static void dumpInput(StringRef file) {
2440 // If we are using the Mach-O specific object file parser, then let it parse
2441 // the file and process the command line options. So the -arch flags can
2442 // be used to select specific slices, etc.
2444 parseInputMachO(file);
2448 // Attempt to open the binary.
2449 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2451 report_error(file, BinaryOrErr.takeError());
2452 Binary &Binary = *BinaryOrErr.get().getBinary();
2454 if (Archive *A = dyn_cast<Archive>(&Binary))
2456 else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary))
2458 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
2459 parseInputMachO(UB);
2461 report_error(file, object_error::invalid_file_type);
2464 int main(int argc, char **argv) {
2465 InitLLVM X(argc, argv);
2467 // Initialize targets and assembly printers/parsers.
2468 llvm::InitializeAllTargetInfos();
2469 llvm::InitializeAllTargetMCs();
2470 llvm::InitializeAllDisassemblers();
2472 // Register the target printer for --version.
2473 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2475 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2479 // Defaults to a.out if no filenames specified.
2480 if (InputFilenames.empty())
2481 InputFilenames.push_back("a.out");
2484 FileHeaders = PrivateHeaders = Relocations = SectionHeaders = SymbolTable =
2487 if (DisassembleAll || PrintSource || PrintLines)
2492 && !DynamicRelocations
2499 && !FirstPrivateHeader
2506 && !(UniversalHeaders && MachOOpt)
2508 && !(IndirectSymbols && MachOOpt)
2509 && !(DataInCode && MachOOpt)
2510 && !(LinkOptHints && MachOOpt)
2511 && !(InfoPlist && MachOOpt)
2512 && !(DylibsUsed && MachOOpt)
2513 && !(DylibId && MachOOpt)
2514 && !(ObjcMetaData && MachOOpt)
2515 && !(!FilterSections.empty() && MachOOpt)
2517 && DwarfDumpType == DIDT_Null) {
2518 cl::PrintHelpMessage();
2522 DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2523 DisassembleFunctions.end());
2525 llvm::for_each(InputFilenames, dumpInput);
2527 return EXIT_SUCCESS;