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/raw_ostream.h"
66 #include <system_error>
67 #include <unordered_map>
71 using namespace object;
74 llvm::AllHeaders("all-headers",
75 cl::desc("Display all available header information"));
76 static cl::alias AllHeadersShort("x", cl::desc("Alias for --all-headers"),
77 cl::aliasopt(AllHeaders));
79 static cl::list<std::string>
80 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
83 llvm::Disassemble("disassemble",
84 cl::desc("Display assembler mnemonics for the machine instructions"));
86 Disassembled("d", cl::desc("Alias for --disassemble"),
87 cl::aliasopt(Disassemble));
90 llvm::DisassembleAll("disassemble-all",
91 cl::desc("Display assembler mnemonics for the machine instructions"));
93 DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
94 cl::aliasopt(DisassembleAll));
96 cl::opt<bool> llvm::Demangle("demangle", cl::desc("Demangle symbols names"),
99 static cl::alias DemangleShort("C", cl::desc("Alias for --demangle"),
100 cl::aliasopt(llvm::Demangle));
102 static cl::list<std::string>
103 DisassembleFunctions("df",
105 cl::desc("List of functions to disassemble"));
106 static StringSet<> DisasmFuncsSet;
109 llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
112 llvm::DynamicRelocations("dynamic-reloc",
113 cl::desc("Display the dynamic relocation entries in the file"));
115 DynamicRelocationsd("R", cl::desc("Alias for --dynamic-reloc"),
116 cl::aliasopt(DynamicRelocations));
119 llvm::SectionContents("full-contents",
120 cl::desc("Display the content of each section"));
121 static cl::alias SectionContentsShort("s",
122 cl::desc("Alias for --full-contents"),
123 cl::aliasopt(SectionContents));
125 cl::opt<bool> llvm::SymbolTable("syms", cl::desc("Display the symbol table"));
126 static cl::alias SymbolTableShort("t", cl::desc("Alias for --syms"),
127 cl::aliasopt(llvm::SymbolTable));
130 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
133 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
136 llvm::Bind("bind", cl::desc("Display mach-o binding info"));
139 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
142 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
145 llvm::RawClangAST("raw-clang-ast",
146 cl::desc("Dump the raw binary contents of the clang AST section"));
149 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
151 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
154 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
155 "see -version for available targets"));
159 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
160 cl::value_desc("cpu-name"),
164 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
165 "see -version for available targets"));
168 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
169 "headers for each section."));
171 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
172 cl::aliasopt(SectionHeaders));
174 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
175 cl::aliasopt(SectionHeaders));
177 cl::list<std::string>
178 llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
179 "With -macho dump segment,section"));
181 static FilterSectionsj("j", cl::desc("Alias for --section"),
182 cl::aliasopt(llvm::FilterSections));
184 cl::list<std::string>
185 llvm::MAttrs("mattr",
187 cl::desc("Target specific attributes"),
188 cl::value_desc("a1,+a2,-a3,..."));
191 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
192 "instructions, do not print "
193 "the instruction bytes."));
195 llvm::NoLeadingAddr("no-leading-addr", cl::desc("Print no leading address"));
198 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
201 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
202 cl::aliasopt(UnwindInfo));
205 llvm::PrivateHeaders("private-headers",
206 cl::desc("Display format specific file headers"));
209 llvm::FirstPrivateHeader("private-header",
210 cl::desc("Display only the first format specific file "
214 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
215 cl::aliasopt(PrivateHeaders));
217 cl::opt<bool> llvm::FileHeaders(
219 cl::desc("Display the contents of the overall file header"));
221 static cl::alias FileHeadersShort("f", cl::desc("Alias for --file-headers"),
222 cl::aliasopt(FileHeaders));
225 llvm::ArchiveHeaders("archive-headers",
226 cl::desc("Display archive header information"));
229 ArchiveHeadersShort("a", cl::desc("Alias for --archive-headers"),
230 cl::aliasopt(ArchiveHeaders));
233 llvm::PrintImmHex("print-imm-hex",
234 cl::desc("Use hex format for immediate values"));
236 cl::opt<bool> PrintFaultMaps("fault-map-section",
237 cl::desc("Display contents of faultmap section"));
239 cl::opt<DIDumpType> llvm::DwarfDumpType(
240 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
241 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")));
243 cl::opt<bool> PrintSource(
246 "Display source inlined with disassembly. Implies disassemble object"));
248 cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
249 cl::aliasopt(PrintSource));
251 cl::opt<bool> PrintLines("line-numbers",
252 cl::desc("Display source line numbers with "
253 "disassembly. Implies disassemble object"));
255 cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"),
256 cl::aliasopt(PrintLines));
258 cl::opt<unsigned long long>
259 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
260 cl::value_desc("address"), cl::init(0));
261 cl::opt<unsigned long long>
262 StopAddress("stop-address", cl::desc("Stop disassembly at address"),
263 cl::value_desc("address"), cl::init(UINT64_MAX));
264 static StringRef ToolName;
266 typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
269 typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
271 class SectionFilterIterator {
273 SectionFilterIterator(FilterPredicate P,
274 llvm::object::section_iterator const &I,
275 llvm::object::section_iterator const &E)
276 : Predicate(std::move(P)), Iterator(I), End(E) {
279 const llvm::object::SectionRef &operator*() const { return *Iterator; }
280 SectionFilterIterator &operator++() {
285 bool operator!=(SectionFilterIterator const &Other) const {
286 return Iterator != Other.Iterator;
290 void ScanPredicate() {
291 while (Iterator != End && !Predicate(*Iterator)) {
295 FilterPredicate Predicate;
296 llvm::object::section_iterator Iterator;
297 llvm::object::section_iterator End;
300 class SectionFilter {
302 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
303 : Predicate(std::move(P)), Object(O) {}
304 SectionFilterIterator begin() {
305 return SectionFilterIterator(Predicate, Object.section_begin(),
306 Object.section_end());
308 SectionFilterIterator end() {
309 return SectionFilterIterator(Predicate, Object.section_end(),
310 Object.section_end());
314 FilterPredicate Predicate;
315 llvm::object::ObjectFile const &Object;
317 SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
318 return SectionFilter(
319 [](llvm::object::SectionRef const &S) {
320 if (FilterSections.empty())
322 llvm::StringRef String;
323 std::error_code error = S.getName(String);
326 return is_contained(FilterSections, String);
332 void llvm::error(std::error_code EC) {
336 errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
341 LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
342 errs() << ToolName << ": " << Message << ".\n";
347 void llvm::warn(StringRef Message) {
348 errs() << ToolName << ": warning: " << Message << ".\n";
352 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
354 errs() << ToolName << ": '" << File << "': " << Message << ".\n";
358 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
359 std::error_code EC) {
361 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
365 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
369 raw_string_ostream OS(Buf);
370 logAllUnhandledErrors(std::move(E), OS, "");
372 errs() << ToolName << ": '" << File << "': " << Buf;
376 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
379 StringRef ArchitectureName) {
381 errs() << ToolName << ": ";
382 if (ArchiveName != "")
383 errs() << ArchiveName << "(" << FileName << ")";
385 errs() << "'" << FileName << "'";
386 if (!ArchitectureName.empty())
387 errs() << " (for architecture " << ArchitectureName << ")";
389 raw_string_ostream OS(Buf);
390 logAllUnhandledErrors(std::move(E), OS, "");
392 errs() << ": " << Buf;
396 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
397 const object::Archive::Child &C,
399 StringRef ArchitectureName) {
400 Expected<StringRef> NameOrErr = C.getName();
401 // TODO: if we have a error getting the name then it would be nice to print
402 // the index of which archive member this is and or its offset in the
403 // archive instead of "???" as the name.
405 consumeError(NameOrErr.takeError());
406 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
408 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
412 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
413 // Figure out the target triple.
414 llvm::Triple TheTriple("unknown-unknown-unknown");
415 if (TripleName.empty()) {
417 TheTriple = Obj->makeTriple();
420 TheTriple.setTriple(Triple::normalize(TripleName));
422 // Use the triple, but also try to combine with ARM build attributes.
424 auto Arch = Obj->getArch();
425 if (Arch == Triple::arm || Arch == Triple::armeb) {
426 Obj->setARMSubArch(TheTriple);
431 // Get the target specific parser.
433 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
437 report_error(Obj->getFileName(), "can't find target: " + Error);
439 error("can't find target: " + Error);
442 // Update the triple name and return the found target.
443 TripleName = TheTriple.getTriple();
447 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
448 return a.getOffset() < b.getOffset();
451 template <class ELFT>
452 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
453 const RelocationRef &RelRef,
454 SmallVectorImpl<char> &Result) {
455 DataRefImpl Rel = RelRef.getRawDataRefImpl();
457 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
458 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
459 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
461 const ELFFile<ELFT> &EF = *Obj->getELFFile();
463 auto SecOrErr = EF.getSection(Rel.d.a);
465 return errorToErrorCode(SecOrErr.takeError());
466 const Elf_Shdr *Sec = *SecOrErr;
467 auto SymTabOrErr = EF.getSection(Sec->sh_link);
469 return errorToErrorCode(SymTabOrErr.takeError());
470 const Elf_Shdr *SymTab = *SymTabOrErr;
471 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
472 SymTab->sh_type == ELF::SHT_DYNSYM);
473 auto StrTabSec = EF.getSection(SymTab->sh_link);
475 return errorToErrorCode(StrTabSec.takeError());
476 auto StrTabOrErr = EF.getStringTable(*StrTabSec);
478 return errorToErrorCode(StrTabOrErr.takeError());
479 StringRef StrTab = *StrTabOrErr;
481 // If there is no Symbol associated with the relocation, we set the undef
482 // boolean value to 'true'. This will prevent us from calling functions that
483 // requires the relocation to be associated with a symbol.
485 switch (Sec->sh_type) {
487 return object_error::parse_failed;
489 // TODO: Read implicit addend from section data.
492 case ELF::SHT_RELA: {
493 const Elf_Rela *ERela = Obj->getRela(Rel);
494 addend = ERela->r_addend;
495 undef = ERela->getSymbol(false) == 0;
501 symbol_iterator SI = RelRef.getSymbol();
502 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
503 if (symb->getType() == ELF::STT_SECTION) {
504 Expected<section_iterator> SymSI = SI->getSection();
506 return errorToErrorCode(SymSI.takeError());
507 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
508 auto SecName = EF.getSectionName(SymSec);
510 return errorToErrorCode(SecName.takeError());
513 Expected<StringRef> SymName = symb->getName(StrTab);
515 return errorToErrorCode(SymName.takeError());
521 // Default scheme is to print Target, as well as "+ <addend>" for nonzero
522 // addend. Should be acceptable for all normal purposes.
524 raw_string_ostream fmt(fmtbuf);
527 fmt << (addend < 0 ? "" : "+") << addend;
529 Result.append(fmtbuf.begin(), fmtbuf.end());
530 return std::error_code();
533 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
534 const RelocationRef &Rel,
535 SmallVectorImpl<char> &Result) {
536 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
537 return getRelocationValueString(ELF32LE, Rel, Result);
538 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
539 return getRelocationValueString(ELF64LE, Rel, Result);
540 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
541 return getRelocationValueString(ELF32BE, Rel, Result);
542 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
543 return getRelocationValueString(ELF64BE, Rel, Result);
546 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
547 const RelocationRef &Rel,
548 SmallVectorImpl<char> &Result) {
549 symbol_iterator SymI = Rel.getSymbol();
550 Expected<StringRef> SymNameOrErr = SymI->getName();
552 return errorToErrorCode(SymNameOrErr.takeError());
553 StringRef SymName = *SymNameOrErr;
554 Result.append(SymName.begin(), SymName.end());
555 return std::error_code();
558 static void printRelocationTargetName(const MachOObjectFile *O,
559 const MachO::any_relocation_info &RE,
560 raw_string_ostream &fmt) {
561 bool IsScattered = O->isRelocationScattered(RE);
563 // Target of a scattered relocation is an address. In the interest of
564 // generating pretty output, scan through the symbol table looking for a
565 // symbol that aligns with that address. If we find one, print it.
566 // Otherwise, we just print the hex address of the target.
568 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
570 for (const SymbolRef &Symbol : O->symbols()) {
572 Expected<uint64_t> Addr = Symbol.getAddress();
574 report_error(O->getFileName(), Addr.takeError());
577 Expected<StringRef> Name = Symbol.getName();
579 report_error(O->getFileName(), Name.takeError());
584 // If we couldn't find a symbol that this relocation refers to, try
585 // to find a section beginning instead.
586 for (const SectionRef &Section : ToolSectionFilter(*O)) {
590 uint64_t Addr = Section.getAddress();
593 if ((ec = Section.getName(Name)))
594 report_error(O->getFileName(), ec);
599 fmt << format("0x%x", Val);
604 bool isExtern = O->getPlainRelocationExternal(RE);
605 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
607 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
608 fmt << format("0x%0" PRIx64, Val);
610 } else if (isExtern) {
611 symbol_iterator SI = O->symbol_begin();
613 Expected<StringRef> SOrErr = SI->getName();
615 report_error(O->getFileName(), SOrErr.takeError());
618 section_iterator SI = O->section_begin();
619 // Adjust for the fact that sections are 1-indexed.
624 uint32_t i = Val - 1;
625 while (i != 0 && SI != O->section_end()) {
629 if (SI == O->section_end())
630 fmt << Val << " (?,?)";
638 static std::error_code getRelocationValueString(const WasmObjectFile *Obj,
639 const RelocationRef &RelRef,
640 SmallVectorImpl<char> &Result) {
641 const wasm::WasmRelocation& Rel = Obj->getWasmRelocation(RelRef);
642 symbol_iterator SI = RelRef.getSymbol();
644 raw_string_ostream fmt(fmtbuf);
645 if (SI == Obj->symbol_end()) {
646 // Not all wasm relocations have symbols associated with them.
647 // In particular R_WEBASSEMBLY_TYPE_INDEX_LEB.
650 Expected<StringRef> SymNameOrErr = SI->getName();
652 return errorToErrorCode(SymNameOrErr.takeError());
653 StringRef SymName = *SymNameOrErr;
654 Result.append(SymName.begin(), SymName.end());
656 fmt << (Rel.Addend < 0 ? "" : "+") << Rel.Addend;
658 Result.append(fmtbuf.begin(), fmtbuf.end());
659 return std::error_code();
662 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
663 const RelocationRef &RelRef,
664 SmallVectorImpl<char> &Result) {
665 DataRefImpl Rel = RelRef.getRawDataRefImpl();
666 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
668 unsigned Arch = Obj->getArch();
671 raw_string_ostream fmt(fmtbuf);
672 unsigned Type = Obj->getAnyRelocationType(RE);
673 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
675 // Determine any addends that should be displayed with the relocation.
676 // These require decoding the relocation type, which is triple-specific.
678 // X86_64 has entirely custom relocation types.
679 if (Arch == Triple::x86_64) {
680 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
683 case MachO::X86_64_RELOC_GOT_LOAD:
684 case MachO::X86_64_RELOC_GOT: {
685 printRelocationTargetName(Obj, RE, fmt);
691 case MachO::X86_64_RELOC_SUBTRACTOR: {
692 DataRefImpl RelNext = Rel;
693 Obj->moveRelocationNext(RelNext);
694 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
696 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
697 // X86_64_RELOC_UNSIGNED.
698 // NOTE: Scattered relocations don't exist on x86_64.
699 unsigned RType = Obj->getAnyRelocationType(RENext);
700 if (RType != MachO::X86_64_RELOC_UNSIGNED)
701 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
702 "X86_64_RELOC_SUBTRACTOR.");
704 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
705 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
706 printRelocationTargetName(Obj, RENext, fmt);
708 printRelocationTargetName(Obj, RE, fmt);
711 case MachO::X86_64_RELOC_TLV:
712 printRelocationTargetName(Obj, RE, fmt);
717 case MachO::X86_64_RELOC_SIGNED_1:
718 printRelocationTargetName(Obj, RE, fmt);
721 case MachO::X86_64_RELOC_SIGNED_2:
722 printRelocationTargetName(Obj, RE, fmt);
725 case MachO::X86_64_RELOC_SIGNED_4:
726 printRelocationTargetName(Obj, RE, fmt);
730 printRelocationTargetName(Obj, RE, fmt);
733 // X86 and ARM share some relocation types in common.
734 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
735 Arch == Triple::ppc) {
736 // Generic relocation types...
738 case MachO::GENERIC_RELOC_PAIR: // prints no info
739 return std::error_code();
740 case MachO::GENERIC_RELOC_SECTDIFF: {
741 DataRefImpl RelNext = Rel;
742 Obj->moveRelocationNext(RelNext);
743 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
745 // X86 sect diff's must be followed by a relocation of type
746 // GENERIC_RELOC_PAIR.
747 unsigned RType = Obj->getAnyRelocationType(RENext);
749 if (RType != MachO::GENERIC_RELOC_PAIR)
750 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
751 "GENERIC_RELOC_SECTDIFF.");
753 printRelocationTargetName(Obj, RE, fmt);
755 printRelocationTargetName(Obj, RENext, fmt);
760 if (Arch == Triple::x86 || Arch == Triple::ppc) {
762 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
763 DataRefImpl RelNext = Rel;
764 Obj->moveRelocationNext(RelNext);
765 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
767 // X86 sect diff's must be followed by a relocation of type
768 // GENERIC_RELOC_PAIR.
769 unsigned RType = Obj->getAnyRelocationType(RENext);
770 if (RType != MachO::GENERIC_RELOC_PAIR)
771 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
772 "GENERIC_RELOC_LOCAL_SECTDIFF.");
774 printRelocationTargetName(Obj, RE, fmt);
776 printRelocationTargetName(Obj, RENext, fmt);
779 case MachO::GENERIC_RELOC_TLV: {
780 printRelocationTargetName(Obj, RE, fmt);
787 printRelocationTargetName(Obj, RE, fmt);
789 } else { // ARM-specific relocations
791 case MachO::ARM_RELOC_HALF:
792 case MachO::ARM_RELOC_HALF_SECTDIFF: {
793 // Half relocations steal a bit from the length field to encode
794 // whether this is an upper16 or a lower16 relocation.
795 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
801 printRelocationTargetName(Obj, RE, fmt);
803 DataRefImpl RelNext = Rel;
804 Obj->moveRelocationNext(RelNext);
805 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
807 // ARM half relocs must be followed by a relocation of type
809 unsigned RType = Obj->getAnyRelocationType(RENext);
810 if (RType != MachO::ARM_RELOC_PAIR)
811 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
814 // NOTE: The half of the target virtual address is stashed in the
815 // address field of the secondary relocation, but we can't reverse
816 // engineer the constant offset from it without decoding the movw/movt
817 // instruction to find the other half in its immediate field.
819 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
820 // symbol/section pointer of the follow-on relocation.
821 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
823 printRelocationTargetName(Obj, RENext, fmt);
829 default: { printRelocationTargetName(Obj, RE, fmt); }
833 printRelocationTargetName(Obj, RE, fmt);
836 Result.append(fmtbuf.begin(), fmtbuf.end());
837 return std::error_code();
840 static std::error_code getRelocationValueString(const RelocationRef &Rel,
841 SmallVectorImpl<char> &Result) {
842 const ObjectFile *Obj = Rel.getObject();
843 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
844 return getRelocationValueString(ELF, Rel, Result);
845 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
846 return getRelocationValueString(COFF, Rel, Result);
847 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
848 return getRelocationValueString(Wasm, Rel, Result);
849 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
850 return getRelocationValueString(MachO, Rel, Result);
851 llvm_unreachable("unknown object file format");
854 /// Indicates whether this relocation should hidden when listing
855 /// relocations, usually because it is the trailing part of a multipart
856 /// relocation that will be printed as part of the leading relocation.
857 static bool getHidden(RelocationRef RelRef) {
858 const ObjectFile *Obj = RelRef.getObject();
859 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
863 unsigned Arch = MachO->getArch();
864 DataRefImpl Rel = RelRef.getRawDataRefImpl();
865 uint64_t Type = MachO->getRelocationType(Rel);
867 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
869 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
870 if (Type == MachO::GENERIC_RELOC_PAIR)
872 } else if (Arch == Triple::x86_64) {
873 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
874 // an X86_64_RELOC_SUBTRACTOR.
875 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
876 DataRefImpl RelPrev = Rel;
878 uint64_t PrevType = MachO->getRelocationType(RelPrev);
879 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
888 class SourcePrinter {
890 DILineInfo OldLineInfo;
891 const ObjectFile *Obj = nullptr;
892 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
893 // File name to file contents of source
894 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
895 // Mark the line endings of the cached source
896 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
899 bool cacheSource(const DILineInfo& LineInfoFile);
902 SourcePrinter() = default;
903 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
904 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
905 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
907 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
909 virtual ~SourcePrinter() = default;
910 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
911 StringRef Delimiter = "; ");
914 bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
915 std::unique_ptr<MemoryBuffer> Buffer;
916 if (LineInfo.Source) {
917 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);
919 auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName);
922 Buffer = std::move(*BufferOrError);
924 // Chomp the file to get lines
925 size_t BufferSize = Buffer->getBufferSize();
926 const char *BufferStart = Buffer->getBufferStart();
927 for (const char *Start = BufferStart, *End = BufferStart;
928 End < BufferStart + BufferSize; End++)
929 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
930 (*End == '\r' && *(End + 1) == '\n')) {
931 LineCache[LineInfo.FileName].push_back(StringRef(Start, End - Start));
936 SourceCache[LineInfo.FileName] = std::move(Buffer);
940 void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
941 StringRef Delimiter) {
944 DILineInfo LineInfo = DILineInfo();
945 auto ExpectecLineInfo =
946 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
947 if (!ExpectecLineInfo)
948 consumeError(ExpectecLineInfo.takeError());
950 LineInfo = *ExpectecLineInfo;
952 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
957 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
959 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
960 if (!cacheSource(LineInfo))
962 auto FileBuffer = SourceCache.find(LineInfo.FileName);
963 if (FileBuffer != SourceCache.end()) {
964 auto LineBuffer = LineCache.find(LineInfo.FileName);
965 if (LineBuffer != LineCache.end()) {
966 if (LineInfo.Line > LineBuffer->second.size())
968 // Vector begins at 0, line numbers are non-zero
969 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
974 OldLineInfo = LineInfo;
977 static bool isArmElf(const ObjectFile *Obj) {
978 return (Obj->isELF() &&
979 (Obj->getArch() == Triple::aarch64 ||
980 Obj->getArch() == Triple::aarch64_be ||
981 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
982 Obj->getArch() == Triple::thumb ||
983 Obj->getArch() == Triple::thumbeb));
986 class PrettyPrinter {
988 virtual ~PrettyPrinter() = default;
989 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
990 ArrayRef<uint8_t> Bytes, uint64_t Address,
991 raw_ostream &OS, StringRef Annot,
992 MCSubtargetInfo const &STI, SourcePrinter *SP,
993 std::vector<RelocationRef> *Rels = nullptr) {
994 if (SP && (PrintSource || PrintLines))
995 SP->printSourceLine(OS, Address);
997 OS << format("%8" PRIx64 ":", Address);
998 if (!NoShowRawInsn) {
1000 dumpBytes(Bytes, OS);
1003 IP.printInst(MI, OS, "", STI);
1008 PrettyPrinter PrettyPrinterInst;
1009 class HexagonPrettyPrinter : public PrettyPrinter {
1011 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
1014 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
1016 OS << format("%8" PRIx64 ":", Address);
1017 if (!NoShowRawInsn) {
1019 dumpBytes(Bytes.slice(0, 4), OS);
1020 OS << format("%08" PRIx32, opcode);
1023 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1024 uint64_t Address, raw_ostream &OS, StringRef Annot,
1025 MCSubtargetInfo const &STI, SourcePrinter *SP,
1026 std::vector<RelocationRef> *Rels) override {
1027 if (SP && (PrintSource || PrintLines))
1028 SP->printSourceLine(OS, Address, "");
1030 printLead(Bytes, Address, OS);
1036 raw_string_ostream TempStream(Buffer);
1037 IP.printInst(MI, TempStream, "", STI);
1039 StringRef Contents(Buffer);
1040 // Split off bundle attributes
1041 auto PacketBundle = Contents.rsplit('\n');
1042 // Split off first instruction from the rest
1043 auto HeadTail = PacketBundle.first.split('\n');
1044 auto Preamble = " { ";
1045 auto Separator = "";
1046 StringRef Fmt = "\t\t\t%08" PRIx64 ": ";
1047 std::vector<RelocationRef>::const_iterator rel_cur = Rels->begin();
1048 std::vector<RelocationRef>::const_iterator rel_end = Rels->end();
1050 // Hexagon's packets require relocations to be inline rather than
1051 // clustered at the end of the packet.
1052 auto PrintReloc = [&]() -> void {
1053 while ((rel_cur != rel_end) && (rel_cur->getOffset() <= Address)) {
1054 if (rel_cur->getOffset() == Address) {
1055 SmallString<16> name;
1056 SmallString<32> val;
1057 rel_cur->getTypeName(name);
1058 error(getRelocationValueString(*rel_cur, val));
1059 OS << Separator << format(Fmt.data(), Address) << name << "\t" << val
1067 while(!HeadTail.first.empty()) {
1070 if (SP && (PrintSource || PrintLines))
1071 SP->printSourceLine(OS, Address, "");
1072 printLead(Bytes, Address, OS);
1076 auto Duplex = HeadTail.first.split('\v');
1077 if(!Duplex.second.empty()){
1080 Inst = Duplex.second;
1083 Inst = HeadTail.first;
1085 HeadTail = HeadTail.second.split('\n');
1086 if (HeadTail.first.empty())
1087 OS << " } " << PacketBundle.second;
1089 Bytes = Bytes.slice(4);
1094 HexagonPrettyPrinter HexagonPrettyPrinterInst;
1096 class AMDGCNPrettyPrinter : public PrettyPrinter {
1098 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1099 uint64_t Address, raw_ostream &OS, StringRef Annot,
1100 MCSubtargetInfo const &STI, SourcePrinter *SP,
1101 std::vector<RelocationRef> *Rels) override {
1102 if (SP && (PrintSource || PrintLines))
1103 SP->printSourceLine(OS, Address);
1105 typedef support::ulittle32_t U32;
1108 SmallString<40> InstStr;
1109 raw_svector_ostream IS(InstStr);
1111 IP.printInst(MI, IS, "", STI);
1113 OS << left_justify(IS.str(), 60);
1115 // an unrecognized encoding - this is probably data so represent it
1116 // using the .long directive, or .byte directive if fewer than 4 bytes
1118 if (Bytes.size() >= 4) {
1119 OS << format("\t.long 0x%08" PRIx32 " ",
1120 static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data())));
1123 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
1124 for (unsigned int i = 1; i < Bytes.size(); i++)
1125 OS << format(", 0x%02" PRIx8, Bytes[i]);
1126 OS.indent(55 - (6 * Bytes.size()));
1130 OS << format("// %012" PRIX64 ": ", Address);
1131 if (Bytes.size() >=4) {
1132 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
1133 Bytes.size() / sizeof(U32)))
1134 // D should be explicitly casted to uint32_t here as it is passed
1135 // by format to snprintf as vararg.
1136 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
1138 for (unsigned int i = 0; i < Bytes.size(); i++)
1139 OS << format("%02" PRIX8 " ", Bytes[i]);
1143 OS << "// " << Annot;
1146 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
1148 class BPFPrettyPrinter : public PrettyPrinter {
1150 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1151 uint64_t Address, raw_ostream &OS, StringRef Annot,
1152 MCSubtargetInfo const &STI, SourcePrinter *SP,
1153 std::vector<RelocationRef> *Rels) override {
1154 if (SP && (PrintSource || PrintLines))
1155 SP->printSourceLine(OS, Address);
1157 OS << format("%8" PRId64 ":", Address / 8);
1158 if (!NoShowRawInsn) {
1160 dumpBytes(Bytes, OS);
1163 IP.printInst(MI, OS, "", STI);
1168 BPFPrettyPrinter BPFPrettyPrinterInst;
1170 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
1171 switch(Triple.getArch()) {
1173 return PrettyPrinterInst;
1174 case Triple::hexagon:
1175 return HexagonPrettyPrinterInst;
1176 case Triple::amdgcn:
1177 return AMDGCNPrettyPrinterInst;
1180 return BPFPrettyPrinterInst;
1185 static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1186 assert(Obj->isELF());
1187 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1188 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1189 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1190 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1191 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1192 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1193 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1194 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1195 llvm_unreachable("Unsupported binary format");
1198 template <class ELFT> static void
1199 addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
1200 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1201 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
1202 uint8_t SymbolType = Symbol.getELFType();
1203 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
1206 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1208 report_error(Obj->getFileName(), AddressOrErr.takeError());
1209 uint64_t Address = *AddressOrErr;
1211 Expected<StringRef> Name = Symbol.getName();
1213 report_error(Obj->getFileName(), Name.takeError());
1217 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1219 report_error(Obj->getFileName(), SectionOrErr.takeError());
1220 section_iterator SecI = *SectionOrErr;
1221 if (SecI == Obj->section_end())
1224 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1229 addDynamicElfSymbols(const ObjectFile *Obj,
1230 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1231 assert(Obj->isELF());
1232 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1233 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
1234 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1235 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
1236 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1237 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
1238 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1239 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
1241 llvm_unreachable("Unsupported binary format");
1244 static void addPltEntries(const ObjectFile *Obj,
1245 std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
1246 StringSaver &Saver) {
1247 Optional<SectionRef> Plt = None;
1248 for (const SectionRef &Section : Obj->sections()) {
1250 if (Section.getName(Name))
1257 if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) {
1258 for (auto PltEntry : ElfObj->getPltAddresses()) {
1259 SymbolRef Symbol(PltEntry.first, ElfObj);
1261 uint8_t SymbolType = getElfSymbolType(Obj, Symbol);
1263 Expected<StringRef> NameOrErr = Symbol.getName();
1265 report_error(Obj->getFileName(), NameOrErr.takeError());
1266 if (NameOrErr->empty())
1268 StringRef Name = Saver.save((*NameOrErr + "@plt").str());
1270 AllSymbols[*Plt].emplace_back(PltEntry.second, Name, SymbolType);
1275 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
1276 if (StartAddress > StopAddress)
1277 error("Start address should be less than stop address");
1279 const Target *TheTarget = getTarget(Obj);
1281 // Package up features to be passed to target/subtarget
1282 SubtargetFeatures Features = Obj->getFeatures();
1283 if (MAttrs.size()) {
1284 for (unsigned i = 0; i != MAttrs.size(); ++i)
1285 Features.AddFeature(MAttrs[i]);
1288 std::unique_ptr<const MCRegisterInfo> MRI(
1289 TheTarget->createMCRegInfo(TripleName));
1291 report_error(Obj->getFileName(), "no register info for target " +
1294 // Set up disassembler.
1295 std::unique_ptr<const MCAsmInfo> AsmInfo(
1296 TheTarget->createMCAsmInfo(*MRI, TripleName));
1298 report_error(Obj->getFileName(), "no assembly info for target " +
1300 std::unique_ptr<const MCSubtargetInfo> STI(
1301 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1303 report_error(Obj->getFileName(), "no subtarget info for target " +
1305 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1307 report_error(Obj->getFileName(), "no instruction info for target " +
1309 MCObjectFileInfo MOFI;
1310 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1311 // FIXME: for now initialize MCObjectFileInfo with default values
1312 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
1314 std::unique_ptr<MCDisassembler> DisAsm(
1315 TheTarget->createMCDisassembler(*STI, Ctx));
1317 report_error(Obj->getFileName(), "no disassembler for target " +
1320 std::unique_ptr<const MCInstrAnalysis> MIA(
1321 TheTarget->createMCInstrAnalysis(MII.get()));
1323 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1324 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1325 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
1327 report_error(Obj->getFileName(), "no instruction printer for target " +
1329 IP->setPrintImmHex(PrintImmHex);
1330 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
1332 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
1333 "\t\t\t%08" PRIx64 ": ";
1335 SourcePrinter SP(Obj, TheTarget->getName());
1337 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1338 // in RelocSecs contain the relocations for section S.
1340 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
1341 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1342 section_iterator Sec2 = Section.getRelocatedSection();
1343 if (Sec2 != Obj->section_end())
1344 SectionRelocMap[*Sec2].push_back(Section);
1347 // Create a mapping from virtual address to symbol name. This is used to
1348 // pretty print the symbols while disassembling.
1349 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1350 SectionSymbolsTy AbsoluteSymbols;
1351 for (const SymbolRef &Symbol : Obj->symbols()) {
1352 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1354 report_error(Obj->getFileName(), AddressOrErr.takeError());
1355 uint64_t Address = *AddressOrErr;
1357 Expected<StringRef> Name = Symbol.getName();
1359 report_error(Obj->getFileName(), Name.takeError());
1363 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1365 report_error(Obj->getFileName(), SectionOrErr.takeError());
1367 uint8_t SymbolType = ELF::STT_NOTYPE;
1369 SymbolType = getElfSymbolType(Obj, Symbol);
1371 section_iterator SecI = *SectionOrErr;
1372 if (SecI != Obj->section_end())
1373 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1375 AbsoluteSymbols.emplace_back(Address, *Name, SymbolType);
1379 if (AllSymbols.empty() && Obj->isELF())
1380 addDynamicElfSymbols(Obj, AllSymbols);
1383 StringSaver Saver(A);
1384 addPltEntries(Obj, AllSymbols, Saver);
1386 // Create a mapping from virtual address to section.
1387 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1388 for (SectionRef Sec : Obj->sections())
1389 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1390 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1392 // Linked executables (.exe and .dll files) typically don't include a real
1393 // symbol table but they might contain an export table.
1394 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1395 for (const auto &ExportEntry : COFFObj->export_directories()) {
1397 error(ExportEntry.getSymbolName(Name));
1401 error(ExportEntry.getExportRVA(RVA));
1403 uint64_t VA = COFFObj->getImageBase() + RVA;
1404 auto Sec = std::upper_bound(
1405 SectionAddresses.begin(), SectionAddresses.end(), VA,
1406 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1407 return LHS < RHS.first;
1409 if (Sec != SectionAddresses.begin())
1412 Sec = SectionAddresses.end();
1414 if (Sec != SectionAddresses.end())
1415 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
1417 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
1421 // Sort all the symbols, this allows us to use a simple binary search to find
1422 // a symbol near an address.
1423 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1424 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1425 array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
1427 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1428 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
1431 uint64_t SectionAddr = Section.getAddress();
1432 uint64_t SectSize = Section.getSize();
1436 // Get the list of all the symbols in this section.
1437 SectionSymbolsTy &Symbols = AllSymbols[Section];
1438 std::vector<uint64_t> DataMappingSymsAddr;
1439 std::vector<uint64_t> TextMappingSymsAddr;
1440 if (isArmElf(Obj)) {
1441 for (const auto &Symb : Symbols) {
1442 uint64_t Address = std::get<0>(Symb);
1443 StringRef Name = std::get<1>(Symb);
1444 if (Name.startswith("$d"))
1445 DataMappingSymsAddr.push_back(Address - SectionAddr);
1446 if (Name.startswith("$x"))
1447 TextMappingSymsAddr.push_back(Address - SectionAddr);
1448 if (Name.startswith("$a"))
1449 TextMappingSymsAddr.push_back(Address - SectionAddr);
1450 if (Name.startswith("$t"))
1451 TextMappingSymsAddr.push_back(Address - SectionAddr);
1455 llvm::sort(DataMappingSymsAddr);
1456 llvm::sort(TextMappingSymsAddr);
1458 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1459 // AMDGPU disassembler uses symbolizer for printing labels
1460 std::unique_ptr<MCRelocationInfo> RelInfo(
1461 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1463 std::unique_ptr<MCSymbolizer> Symbolizer(
1464 TheTarget->createMCSymbolizer(
1465 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1466 DisAsm->setSymbolizer(std::move(Symbolizer));
1470 // Make a list of all the relocations for this section.
1471 std::vector<RelocationRef> Rels;
1473 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1474 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1475 Rels.push_back(Reloc);
1480 // Sort relocations by address.
1481 llvm::sort(Rels, RelocAddressLess);
1483 StringRef SegmentName = "";
1484 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
1485 DataRefImpl DR = Section.getRawDataRefImpl();
1486 SegmentName = MachO->getSectionFinalSegmentName(DR);
1488 StringRef SectionName;
1489 error(Section.getName(SectionName));
1491 // If the section has no symbol at the start, just insert a dummy one.
1492 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
1495 std::make_tuple(SectionAddr, SectionName,
1496 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
1499 SmallString<40> Comments;
1500 raw_svector_ostream CommentStream(Comments);
1503 error(Section.getContents(BytesStr));
1504 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1509 bool PrintedSection = false;
1511 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1512 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
1513 // Disassemble symbol by symbol.
1514 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
1515 uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr;
1516 // The end is either the section end or the beginning of the next
1519 (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr;
1520 // Don't try to disassemble beyond the end of section contents.
1523 // If this symbol has the same address as the next symbol, then skip it.
1527 // Check if we need to skip symbol
1528 // Skip if the symbol's data is not between StartAddress and StopAddress
1529 if (End + SectionAddr < StartAddress ||
1530 Start + SectionAddr > StopAddress) {
1534 /// Skip if user requested specific symbols and this is not in the list
1535 if (!DisasmFuncsSet.empty() &&
1536 !DisasmFuncsSet.count(std::get<1>(Symbols[si])))
1539 if (!PrintedSection) {
1540 PrintedSection = true;
1541 outs() << "Disassembly of section ";
1542 if (!SegmentName.empty())
1543 outs() << SegmentName << ",";
1544 outs() << SectionName << ':';
1547 // Stop disassembly at the stop address specified
1548 if (End + SectionAddr > StopAddress)
1549 End = StopAddress - SectionAddr;
1551 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1552 if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1553 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1557 std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1558 // cut trailing zeroes at the end of kernel
1559 // cut up to 256 bytes
1560 const uint64_t EndAlign = 256;
1561 const auto Limit = End - (std::min)(EndAlign, End - Start);
1562 while (End > Limit &&
1563 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1568 auto PrintSymbol = [](StringRef Name) {
1569 outs() << '\n' << Name << ":\n";
1571 StringRef SymbolName = std::get<1>(Symbols[si]);
1573 char *DemangledSymbol = nullptr;
1576 if (SymbolName.startswith("_Z"))
1577 DemangledSymbol = itaniumDemangle(SymbolName.data(), DemangledSymbol,
1579 else if (SymbolName.startswith("?"))
1580 DemangledSymbol = microsoftDemangle(SymbolName.data(),
1581 DemangledSymbol, &Size, &Status);
1583 if (Status == 0 && DemangledSymbol)
1584 PrintSymbol(StringRef(DemangledSymbol));
1586 PrintSymbol(SymbolName);
1588 if (DemangledSymbol)
1589 free(DemangledSymbol);
1591 PrintSymbol(SymbolName);
1593 // Don't print raw contents of a virtual section. A virtual section
1594 // doesn't have any contents in the file.
1595 if (Section.isVirtual()) {
1601 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1603 raw_ostream &DebugOut = nulls();
1606 for (Index = Start; Index < End; Index += Size) {
1609 if (Index + SectionAddr < StartAddress ||
1610 Index + SectionAddr > StopAddress) {
1611 // skip byte by byte till StartAddress is reached
1615 // AArch64 ELF binaries can interleave data and text in the
1616 // same section. We rely on the markers introduced to
1617 // understand what we need to dump. If the data marker is within a
1618 // function, it is denoted as a word/short etc
1619 if (isArmElf(Obj) && std::get<2>(Symbols[si]) != ELF::STT_OBJECT &&
1621 uint64_t Stride = 0;
1623 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1624 DataMappingSymsAddr.end(), Index);
1625 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1627 while (Index < End) {
1628 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1630 if (Index + 4 <= End) {
1632 dumpBytes(Bytes.slice(Index, 4), outs());
1633 outs() << "\t.word\t";
1635 if (Obj->isLittleEndian()) {
1637 reinterpret_cast<const support::ulittle32_t *>(
1638 Bytes.data() + Index);
1641 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1642 Bytes.data() + Index);
1645 outs() << "0x" << format("%08" PRIx32, Data);
1646 } else if (Index + 2 <= End) {
1648 dumpBytes(Bytes.slice(Index, 2), outs());
1649 outs() << "\t\t.short\t";
1651 if (Obj->isLittleEndian()) {
1653 reinterpret_cast<const support::ulittle16_t *>(
1654 Bytes.data() + Index);
1658 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1662 outs() << "0x" << format("%04" PRIx16, Data);
1665 dumpBytes(Bytes.slice(Index, 1), outs());
1666 outs() << "\t\t.byte\t";
1667 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
1671 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1672 TextMappingSymsAddr.end(), Index);
1673 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1679 // If there is a data symbol inside an ELF text section and we are only
1680 // disassembling text (applicable all architectures),
1681 // we are in a situation where we must print the data and not
1683 if (Obj->isELF() && std::get<2>(Symbols[si]) == ELF::STT_OBJECT &&
1684 !DisassembleAll && Section.isText()) {
1685 // print out data up to 8 bytes at a time in hex and ascii
1686 uint8_t AsciiData[9] = {'\0'};
1690 for (Index = Start; Index < End; Index += 1) {
1691 if (((SectionAddr + Index) < StartAddress) ||
1692 ((SectionAddr + Index) > StopAddress))
1694 if (NumBytes == 0) {
1695 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1698 Byte = Bytes.slice(Index)[0];
1699 outs() << format(" %02x", Byte);
1700 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
1702 uint8_t IndentOffset = 0;
1704 if (Index == End - 1 || NumBytes > 8) {
1705 // Indent the space for less than 8 bytes data.
1706 // 2 spaces for byte and one for space between bytes
1707 IndentOffset = 3 * (8 - NumBytes);
1708 for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1709 AsciiData[Excess] = '\0';
1712 if (NumBytes == 8) {
1713 AsciiData[8] = '\0';
1714 outs() << std::string(IndentOffset, ' ') << " ";
1715 outs() << reinterpret_cast<char *>(AsciiData);
1724 // Disassemble a real instruction or a data when disassemble all is
1726 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1727 SectionAddr + Index, DebugOut,
1732 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
1733 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
1735 outs() << CommentStream.str();
1738 // Try to resolve the target of a call, tail call, etc. to a specific
1740 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1741 MIA->isConditionalBranch(Inst))) {
1743 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1744 // In a relocatable object, the target's section must reside in
1745 // the same section as the call instruction or it is accessed
1746 // through a relocation.
1748 // In a non-relocatable object, the target may be in any section.
1750 // N.B. We don't walk the relocations in the relocatable case yet.
1751 auto *TargetSectionSymbols = &Symbols;
1752 if (!Obj->isRelocatableObject()) {
1753 auto SectionAddress = std::upper_bound(
1754 SectionAddresses.begin(), SectionAddresses.end(), Target,
1756 const std::pair<uint64_t, SectionRef> &RHS) {
1757 return LHS < RHS.first;
1759 if (SectionAddress != SectionAddresses.begin()) {
1761 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1763 TargetSectionSymbols = &AbsoluteSymbols;
1767 // Find the first symbol in the section whose offset is less than
1768 // or equal to the target. If there isn't a section that contains
1769 // the target, find the nearest preceding absolute symbol.
1770 auto TargetSym = std::upper_bound(
1771 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1772 Target, [](uint64_t LHS,
1773 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1774 return LHS < std::get<0>(RHS);
1776 if (TargetSym == TargetSectionSymbols->begin()) {
1777 TargetSectionSymbols = &AbsoluteSymbols;
1778 TargetSym = std::upper_bound(
1779 AbsoluteSymbols.begin(), AbsoluteSymbols.end(),
1780 Target, [](uint64_t LHS,
1781 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1782 return LHS < std::get<0>(RHS);
1785 if (TargetSym != TargetSectionSymbols->begin()) {
1787 uint64_t TargetAddress = std::get<0>(*TargetSym);
1788 StringRef TargetName = std::get<1>(*TargetSym);
1789 outs() << " <" << TargetName;
1790 uint64_t Disp = Target - TargetAddress;
1792 outs() << "+0x" << Twine::utohexstr(Disp);
1799 // Hexagon does this in pretty printer
1800 if (Obj->getArch() != Triple::hexagon)
1801 // Print relocation for instruction.
1802 while (rel_cur != rel_end) {
1803 bool hidden = getHidden(*rel_cur);
1804 uint64_t addr = rel_cur->getOffset();
1805 SmallString<16> name;
1806 SmallString<32> val;
1808 // If this relocation is hidden, skip it.
1809 if (hidden || ((SectionAddr + addr) < StartAddress)) {
1814 // Stop when rel_cur's address is past the current instruction.
1815 if (addr >= Index + Size) break;
1816 rel_cur->getTypeName(name);
1817 error(getRelocationValueString(*rel_cur, val));
1818 outs() << format(Fmt.data(), SectionAddr + addr) << name
1819 << "\t" << val << "\n";
1827 void llvm::PrintRelocations(const ObjectFile *Obj) {
1828 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1830 // Regular objdump doesn't print relocations in non-relocatable object
1832 if (!Obj->isRelocatableObject())
1835 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1836 if (Section.relocation_begin() == Section.relocation_end())
1839 error(Section.getName(secname));
1840 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
1841 for (const RelocationRef &Reloc : Section.relocations()) {
1842 bool hidden = getHidden(Reloc);
1843 uint64_t address = Reloc.getOffset();
1844 SmallString<32> relocname;
1845 SmallString<32> valuestr;
1846 if (address < StartAddress || address > StopAddress || hidden)
1848 Reloc.getTypeName(relocname);
1849 error(getRelocationValueString(Reloc, valuestr));
1850 outs() << format(Fmt.data(), address) << " " << relocname << " "
1851 << valuestr << "\n";
1857 void llvm::PrintDynamicRelocations(const ObjectFile *Obj) {
1859 // For the moment, this option is for ELF only
1863 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
1865 if (!Elf || Elf->getEType() != ELF::ET_DYN) {
1866 error("not a dynamic object");
1870 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1872 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1873 if (DynRelSec.empty())
1876 outs() << "DYNAMIC RELOCATION RECORDS\n";
1877 for (const SectionRef &Section : DynRelSec) {
1878 if (Section.relocation_begin() == Section.relocation_end())
1880 for (const RelocationRef &Reloc : Section.relocations()) {
1881 uint64_t address = Reloc.getOffset();
1882 SmallString<32> relocname;
1883 SmallString<32> valuestr;
1884 Reloc.getTypeName(relocname);
1885 error(getRelocationValueString(Reloc, valuestr));
1886 outs() << format(Fmt.data(), address) << " " << relocname << " "
1887 << valuestr << "\n";
1892 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
1893 outs() << "Sections:\n"
1894 "Idx Name Size Address Type\n";
1895 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1897 error(Section.getName(Name));
1898 uint64_t Address = Section.getAddress();
1899 uint64_t Size = Section.getSize();
1900 bool Text = Section.isText();
1901 bool Data = Section.isData();
1902 bool BSS = Section.isBSS();
1903 std::string Type = (std::string(Text ? "TEXT " : "") +
1904 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1905 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
1906 (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1907 Address, Type.c_str());
1911 void llvm::PrintSectionContents(const ObjectFile *Obj) {
1913 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1916 error(Section.getName(Name));
1917 uint64_t BaseAddr = Section.getAddress();
1918 uint64_t Size = Section.getSize();
1922 outs() << "Contents of section " << Name << ":\n";
1923 if (Section.isBSS()) {
1924 outs() << format("<skipping contents of bss section at [%04" PRIx64
1925 ", %04" PRIx64 ")>\n",
1926 BaseAddr, BaseAddr + Size);
1930 error(Section.getContents(Contents));
1932 // Dump out the content as hex and printable ascii characters.
1933 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1934 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1935 // Dump line of hex.
1936 for (std::size_t i = 0; i < 16; ++i) {
1937 if (i != 0 && i % 4 == 0)
1940 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1941 << hexdigit(Contents[addr + i] & 0xF, true);
1947 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1948 if (isPrint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1949 outs() << Contents[addr + i];
1958 void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1959 StringRef ArchitectureName) {
1960 outs() << "SYMBOL TABLE:\n";
1962 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1963 printCOFFSymbolTable(coff);
1966 for (const SymbolRef &Symbol : o->symbols()) {
1967 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1968 if (!AddressOrError)
1969 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError(),
1971 uint64_t Address = *AddressOrError;
1972 if ((Address < StartAddress) || (Address > StopAddress))
1974 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1976 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError(),
1978 SymbolRef::Type Type = *TypeOrError;
1979 uint32_t Flags = Symbol.getFlags();
1980 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1982 report_error(ArchiveName, o->getFileName(), SectionOrErr.takeError(),
1984 section_iterator Section = *SectionOrErr;
1986 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1987 Section->getName(Name);
1989 Expected<StringRef> NameOrErr = Symbol.getName();
1991 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1996 bool Global = Flags & SymbolRef::SF_Global;
1997 bool Weak = Flags & SymbolRef::SF_Weak;
1998 bool Absolute = Flags & SymbolRef::SF_Absolute;
1999 bool Common = Flags & SymbolRef::SF_Common;
2000 bool Hidden = Flags & SymbolRef::SF_Hidden;
2003 if (Type != SymbolRef::ST_Unknown)
2004 GlobLoc = Global ? 'g' : 'l';
2005 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
2007 char FileFunc = ' ';
2008 if (Type == SymbolRef::ST_File)
2010 else if (Type == SymbolRef::ST_Function)
2013 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
2016 outs() << format(Fmt, Address) << " "
2017 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
2018 << (Weak ? 'w' : ' ') // Weak?
2019 << ' ' // Constructor. Not supported yet.
2020 << ' ' // Warning. Not supported yet.
2021 << ' ' // Indirect reference to another symbol.
2022 << Debug // Debugging (d) or dynamic (D) symbol.
2023 << FileFunc // Name of function (F), file (f) or object (O).
2027 } else if (Common) {
2029 } else if (Section == o->section_end()) {
2032 if (const MachOObjectFile *MachO =
2033 dyn_cast<const MachOObjectFile>(o)) {
2034 DataRefImpl DR = Section->getRawDataRefImpl();
2035 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
2036 outs() << SegmentName << ",";
2038 StringRef SectionName;
2039 error(Section->getName(SectionName));
2040 outs() << SectionName;
2044 if (Common || isa<ELFObjectFileBase>(o)) {
2046 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
2047 outs() << format("\t %08" PRIx64 " ", Val);
2051 outs() << ".hidden ";
2058 static void PrintUnwindInfo(const ObjectFile *o) {
2059 outs() << "Unwind info:\n\n";
2061 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
2062 printCOFFUnwindInfo(coff);
2063 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2064 printMachOUnwindInfo(MachO);
2066 // TODO: Extract DWARF dump tool to objdump.
2067 errs() << "This operation is only currently supported "
2068 "for COFF and MachO object files.\n";
2073 void llvm::printExportsTrie(const ObjectFile *o) {
2074 outs() << "Exports trie:\n";
2075 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2076 printMachOExportsTrie(MachO);
2078 errs() << "This operation is only currently supported "
2079 "for Mach-O executable files.\n";
2084 void llvm::printRebaseTable(ObjectFile *o) {
2085 outs() << "Rebase table:\n";
2086 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2087 printMachORebaseTable(MachO);
2089 errs() << "This operation is only currently supported "
2090 "for Mach-O executable files.\n";
2095 void llvm::printBindTable(ObjectFile *o) {
2096 outs() << "Bind table:\n";
2097 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2098 printMachOBindTable(MachO);
2100 errs() << "This operation is only currently supported "
2101 "for Mach-O executable files.\n";
2106 void llvm::printLazyBindTable(ObjectFile *o) {
2107 outs() << "Lazy bind table:\n";
2108 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2109 printMachOLazyBindTable(MachO);
2111 errs() << "This operation is only currently supported "
2112 "for Mach-O executable files.\n";
2117 void llvm::printWeakBindTable(ObjectFile *o) {
2118 outs() << "Weak bind table:\n";
2119 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2120 printMachOWeakBindTable(MachO);
2122 errs() << "This operation is only currently supported "
2123 "for Mach-O executable files.\n";
2128 /// Dump the raw contents of the __clangast section so the output can be piped
2129 /// into llvm-bcanalyzer.
2130 void llvm::printRawClangAST(const ObjectFile *Obj) {
2131 if (outs().is_displayed()) {
2132 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
2133 "the clang ast section.\n"
2134 "Please redirect the output to a file or another program such as "
2135 "llvm-bcanalyzer.\n";
2139 StringRef ClangASTSectionName("__clangast");
2140 if (isa<COFFObjectFile>(Obj)) {
2141 ClangASTSectionName = "clangast";
2144 Optional<object::SectionRef> ClangASTSection;
2145 for (auto Sec : ToolSectionFilter(*Obj)) {
2148 if (Name == ClangASTSectionName) {
2149 ClangASTSection = Sec;
2153 if (!ClangASTSection)
2156 StringRef ClangASTContents;
2157 error(ClangASTSection.getValue().getContents(ClangASTContents));
2158 outs().write(ClangASTContents.data(), ClangASTContents.size());
2161 static void printFaultMaps(const ObjectFile *Obj) {
2162 const char *FaultMapSectionName = nullptr;
2164 if (isa<ELFObjectFileBase>(Obj)) {
2165 FaultMapSectionName = ".llvm_faultmaps";
2166 } else if (isa<MachOObjectFile>(Obj)) {
2167 FaultMapSectionName = "__llvm_faultmaps";
2169 errs() << "This operation is only currently supported "
2170 "for ELF and Mach-O executable files.\n";
2174 Optional<object::SectionRef> FaultMapSection;
2176 for (auto Sec : ToolSectionFilter(*Obj)) {
2179 if (Name == FaultMapSectionName) {
2180 FaultMapSection = Sec;
2185 outs() << "FaultMap table:\n";
2187 if (!FaultMapSection.hasValue()) {
2188 outs() << "<not found>\n";
2192 StringRef FaultMapContents;
2193 error(FaultMapSection.getValue().getContents(FaultMapContents));
2195 FaultMapParser FMP(FaultMapContents.bytes_begin(),
2196 FaultMapContents.bytes_end());
2201 static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) {
2203 printELFFileHeader(o);
2204 return printELFDynamicSection(o);
2207 return printCOFFFileHeader(o);
2209 return printWasmFileHeader(o);
2211 printMachOFileHeader(o);
2213 printMachOLoadCommands(o);
2216 report_error(o->getFileName(), "Invalid/Unsupported object file format");
2219 static void printFileHeaders(const ObjectFile *o) {
2220 if (!o->isELF() && !o->isCOFF())
2221 report_error(o->getFileName(), "Invalid/Unsupported object file format");
2223 Triple::ArchType AT = o->getArch();
2224 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
2225 Expected<uint64_t> StartAddrOrErr = o->getStartAddress();
2226 if (!StartAddrOrErr)
2227 report_error(o->getFileName(), StartAddrOrErr.takeError());
2229 StringRef Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
2230 uint64_t Address = StartAddrOrErr.get();
2231 outs() << "start address: "
2232 << "0x" << format(Fmt.data(), Address)
2236 static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
2237 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
2239 errs() << "ill-formed archive entry.\n";
2240 consumeError(ModeOrErr.takeError());
2243 sys::fs::perms Mode = ModeOrErr.get();
2244 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2245 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2246 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2247 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2248 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2249 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2250 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2251 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2252 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2256 Expected<unsigned> UIDOrErr = C.getUID();
2258 report_error(Filename, UIDOrErr.takeError());
2259 unsigned UID = UIDOrErr.get();
2260 outs() << format("%d/", UID);
2262 Expected<unsigned> GIDOrErr = C.getGID();
2264 report_error(Filename, GIDOrErr.takeError());
2265 unsigned GID = GIDOrErr.get();
2266 outs() << format("%-d ", GID);
2268 Expected<uint64_t> Size = C.getRawSize();
2270 report_error(Filename, Size.takeError());
2271 outs() << format("%6" PRId64, Size.get()) << " ";
2273 StringRef RawLastModified = C.getRawLastModified();
2275 if (RawLastModified.getAsInteger(10, Seconds))
2276 outs() << "(date: \"" << RawLastModified
2277 << "\" contains non-decimal chars) ";
2279 // Since ctime(3) returns a 26 character string of the form:
2280 // "Sun Sep 16 01:03:52 1973\n\0"
2281 // just print 24 characters.
2283 outs() << format("%.24s ", ctime(&t));
2286 StringRef Name = "";
2287 Expected<StringRef> NameOrErr = C.getName();
2289 consumeError(NameOrErr.takeError());
2290 Expected<StringRef> RawNameOrErr = C.getRawName();
2292 report_error(Filename, NameOrErr.takeError());
2293 Name = RawNameOrErr.get();
2295 Name = NameOrErr.get();
2297 outs() << Name << "\n";
2300 static void DumpObject(ObjectFile *o, const Archive *a = nullptr,
2301 const Archive::Child *c = nullptr) {
2302 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
2303 // Avoid other output when using a raw option.
2307 outs() << a->getFileName() << "(" << o->getFileName() << ")";
2309 outs() << o->getFileName();
2310 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
2313 if (ArchiveHeaders && !MachOOpt && c)
2314 printArchiveChild(ArchiveName, *c);
2316 DisassembleObject(o, Relocations);
2317 if (Relocations && !Disassemble)
2318 PrintRelocations(o);
2319 if (DynamicRelocations)
2320 PrintDynamicRelocations(o);
2322 PrintSectionHeaders(o);
2323 if (SectionContents)
2324 PrintSectionContents(o);
2326 PrintSymbolTable(o, ArchiveName);
2329 if (PrivateHeaders || FirstPrivateHeader)
2330 printPrivateFileHeaders(o, FirstPrivateHeader);
2332 printFileHeaders(o);
2334 printExportsTrie(o);
2336 printRebaseTable(o);
2340 printLazyBindTable(o);
2342 printWeakBindTable(o);
2344 printRawClangAST(o);
2347 if (DwarfDumpType != DIDT_Null) {
2348 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*o);
2349 // Dump the complete DWARF structure.
2350 DIDumpOptions DumpOpts;
2351 DumpOpts.DumpType = DwarfDumpType;
2352 DICtx->dump(outs(), DumpOpts);
2356 static void DumpObject(const COFFImportFile *I, const Archive *A,
2357 const Archive::Child *C = nullptr) {
2358 StringRef ArchiveName = A ? A->getFileName() : "";
2360 // Avoid other output when using a raw option.
2363 << ArchiveName << "(" << I->getFileName() << ")"
2364 << ":\tfile format COFF-import-file"
2367 if (ArchiveHeaders && !MachOOpt && C)
2368 printArchiveChild(ArchiveName, *C);
2370 printCOFFSymbolTable(I);
2373 /// Dump each object file in \a a;
2374 static void DumpArchive(const Archive *a) {
2375 Error Err = Error::success();
2376 for (auto &C : a->children(Err)) {
2377 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2379 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2380 report_error(a->getFileName(), C, std::move(E));
2383 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2384 DumpObject(o, a, &C);
2385 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2386 DumpObject(I, a, &C);
2388 report_error(a->getFileName(), object_error::invalid_file_type);
2391 report_error(a->getFileName(), std::move(Err));
2394 /// Open file and figure out how to dump it.
2395 static void DumpInput(StringRef file) {
2397 // If we are using the Mach-O specific object file parser, then let it parse
2398 // the file and process the command line options. So the -arch flags can
2399 // be used to select specific slices, etc.
2401 ParseInputMachO(file);
2405 // Attempt to open the binary.
2406 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2408 report_error(file, BinaryOrErr.takeError());
2409 Binary &Binary = *BinaryOrErr.get().getBinary();
2411 if (Archive *a = dyn_cast<Archive>(&Binary))
2413 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
2415 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
2416 ParseInputMachO(UB);
2418 report_error(file, object_error::invalid_file_type);
2421 int main(int argc, char **argv) {
2422 InitLLVM X(argc, argv);
2424 // Initialize targets and assembly printers/parsers.
2425 llvm::InitializeAllTargetInfos();
2426 llvm::InitializeAllTargetMCs();
2427 llvm::InitializeAllDisassemblers();
2429 // Register the target printer for --version.
2430 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2432 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2436 // Defaults to a.out if no filenames specified.
2437 if (InputFilenames.size() == 0)
2438 InputFilenames.push_back("a.out");
2441 PrivateHeaders = Relocations = SectionHeaders = SymbolTable = true;
2443 if (DisassembleAll || PrintSource || PrintLines)
2448 && !DynamicRelocations
2455 && !FirstPrivateHeader
2462 && !(UniversalHeaders && MachOOpt)
2464 && !(IndirectSymbols && MachOOpt)
2465 && !(DataInCode && MachOOpt)
2466 && !(LinkOptHints && MachOOpt)
2467 && !(InfoPlist && MachOOpt)
2468 && !(DylibsUsed && MachOOpt)
2469 && !(DylibId && MachOOpt)
2470 && !(ObjcMetaData && MachOOpt)
2471 && !(FilterSections.size() != 0 && MachOOpt)
2473 && DwarfDumpType == DIDT_Null) {
2474 cl::PrintHelpMessage();
2478 DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2479 DisassembleFunctions.end());
2481 llvm::for_each(InputFilenames, DumpInput);
2483 return EXIT_SUCCESS;