1 //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This program is a utility that works like binutils "objdump", that is, it
11 // dumps out a plethora of information about an object file depending on the
14 // The flags and output of this program should be near identical to those of
17 //===----------------------------------------------------------------------===//
19 #include "llvm-objdump.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/FaultMaps.h"
25 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
26 #include "llvm/DebugInfo/Symbolize/Symbolize.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
30 #include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCInstPrinter.h"
33 #include "llvm/MC/MCInstrAnalysis.h"
34 #include "llvm/MC/MCInstrInfo.h"
35 #include "llvm/MC/MCObjectFileInfo.h"
36 #include "llvm/MC/MCRegisterInfo.h"
37 #include "llvm/MC/MCSubtargetInfo.h"
38 #include "llvm/Object/Archive.h"
39 #include "llvm/Object/COFF.h"
40 #include "llvm/Object/COFFImportFile.h"
41 #include "llvm/Object/ELFObjectFile.h"
42 #include "llvm/Object/MachO.h"
43 #include "llvm/Object/ObjectFile.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/Errc.h"
48 #include "llvm/Support/FileSystem.h"
49 #include "llvm/Support/Format.h"
50 #include "llvm/Support/GraphWriter.h"
51 #include "llvm/Support/Host.h"
52 #include "llvm/Support/ManagedStatic.h"
53 #include "llvm/Support/MemoryBuffer.h"
54 #include "llvm/Support/PrettyStackTrace.h"
55 #include "llvm/Support/Signals.h"
56 #include "llvm/Support/SourceMgr.h"
57 #include "llvm/Support/TargetRegistry.h"
58 #include "llvm/Support/TargetSelect.h"
59 #include "llvm/Support/raw_ostream.h"
63 #include <system_error>
65 #include <unordered_map>
68 using namespace object;
70 static cl::list<std::string>
71 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
74 llvm::Disassemble("disassemble",
75 cl::desc("Display assembler mnemonics for the machine instructions"));
77 Disassembled("d", cl::desc("Alias for --disassemble"),
78 cl::aliasopt(Disassemble));
81 llvm::DisassembleAll("disassemble-all",
82 cl::desc("Display assembler mnemonics for the machine instructions"));
84 DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
85 cl::aliasopt(DisassembleAll));
88 llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
91 llvm::SectionContents("s", cl::desc("Display the content of each section"));
94 llvm::SymbolTable("t", cl::desc("Display the symbol table"));
97 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
100 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
103 llvm::Bind("bind", cl::desc("Display mach-o binding info"));
106 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
109 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
112 llvm::RawClangAST("raw-clang-ast",
113 cl::desc("Dump the raw binary contents of the clang AST section"));
116 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
118 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
121 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
122 "see -version for available targets"));
126 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
127 cl::value_desc("cpu-name"),
131 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
132 "see -version for available targets"));
135 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
136 "headers for each section."));
138 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
139 cl::aliasopt(SectionHeaders));
141 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
142 cl::aliasopt(SectionHeaders));
144 cl::list<std::string>
145 llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
146 "With -macho dump segment,section"));
148 static FilterSectionsj("j", cl::desc("Alias for --section"),
149 cl::aliasopt(llvm::FilterSections));
151 cl::list<std::string>
152 llvm::MAttrs("mattr",
154 cl::desc("Target specific attributes"),
155 cl::value_desc("a1,+a2,-a3,..."));
158 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
159 "instructions, do not print "
160 "the instruction bytes."));
162 llvm::NoLeadingAddr("no-leading-addr", cl::desc("Print no leading address"));
165 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
168 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
169 cl::aliasopt(UnwindInfo));
172 llvm::PrivateHeaders("private-headers",
173 cl::desc("Display format specific file headers"));
176 llvm::FirstPrivateHeader("private-header",
177 cl::desc("Display only the first format specific file "
181 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
182 cl::aliasopt(PrivateHeaders));
185 llvm::PrintImmHex("print-imm-hex",
186 cl::desc("Use hex format for immediate values"));
188 cl::opt<bool> PrintFaultMaps("fault-map-section",
189 cl::desc("Display contents of faultmap section"));
191 cl::opt<DIDumpType> llvm::DwarfDumpType(
192 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
193 cl::values(clEnumValN(DIDT_Frames, "frames", ".debug_frame")));
195 cl::opt<bool> PrintSource(
198 "Display source inlined with disassembly. Implies disassmble object"));
200 cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
201 cl::aliasopt(PrintSource));
203 cl::opt<bool> PrintLines("line-numbers",
204 cl::desc("Display source line numbers with "
205 "disassembly. Implies disassemble object"));
207 cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"),
208 cl::aliasopt(PrintLines));
210 cl::opt<unsigned long long>
211 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
212 cl::value_desc("address"), cl::init(0));
213 cl::opt<unsigned long long>
214 StopAddress("stop-address", cl::desc("Stop disassembly at address"),
215 cl::value_desc("address"), cl::init(UINT64_MAX));
216 static StringRef ToolName;
218 typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
221 typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
223 class SectionFilterIterator {
225 SectionFilterIterator(FilterPredicate P,
226 llvm::object::section_iterator const &I,
227 llvm::object::section_iterator const &E)
228 : Predicate(std::move(P)), Iterator(I), End(E) {
231 const llvm::object::SectionRef &operator*() const { return *Iterator; }
232 SectionFilterIterator &operator++() {
237 bool operator!=(SectionFilterIterator const &Other) const {
238 return Iterator != Other.Iterator;
242 void ScanPredicate() {
243 while (Iterator != End && !Predicate(*Iterator)) {
247 FilterPredicate Predicate;
248 llvm::object::section_iterator Iterator;
249 llvm::object::section_iterator End;
252 class SectionFilter {
254 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
255 : Predicate(std::move(P)), Object(O) {}
256 SectionFilterIterator begin() {
257 return SectionFilterIterator(Predicate, Object.section_begin(),
258 Object.section_end());
260 SectionFilterIterator end() {
261 return SectionFilterIterator(Predicate, Object.section_end(),
262 Object.section_end());
266 FilterPredicate Predicate;
267 llvm::object::ObjectFile const &Object;
269 SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
270 return SectionFilter(
271 [](llvm::object::SectionRef const &S) {
272 if (FilterSections.empty())
274 llvm::StringRef String;
275 std::error_code error = S.getName(String);
278 return is_contained(FilterSections, String);
284 void llvm::error(std::error_code EC) {
288 errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
293 LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
294 errs() << ToolName << ": " << Message << ".\n";
299 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
301 errs() << ToolName << ": '" << File << "': " << Message << ".\n";
305 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
306 std::error_code EC) {
308 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
312 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
316 raw_string_ostream OS(Buf);
317 logAllUnhandledErrors(std::move(E), OS, "");
319 errs() << ToolName << ": '" << File << "': " << Buf;
323 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
326 StringRef ArchitectureName) {
328 errs() << ToolName << ": ";
329 if (ArchiveName != "")
330 errs() << ArchiveName << "(" << FileName << ")";
332 errs() << "'" << FileName << "'";
333 if (!ArchitectureName.empty())
334 errs() << " (for architecture " << ArchitectureName << ")";
336 raw_string_ostream OS(Buf);
337 logAllUnhandledErrors(std::move(E), OS, "");
339 errs() << ": " << Buf;
343 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
344 const object::Archive::Child &C,
346 StringRef ArchitectureName) {
347 Expected<StringRef> NameOrErr = C.getName();
348 // TODO: if we have a error getting the name then it would be nice to print
349 // the index of which archive member this is and or its offset in the
350 // archive instead of "???" as the name.
352 consumeError(NameOrErr.takeError());
353 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
355 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
359 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
360 // Figure out the target triple.
361 llvm::Triple TheTriple("unknown-unknown-unknown");
362 if (TripleName.empty()) {
364 auto Arch = Obj->getArch();
365 TheTriple.setArch(Triple::ArchType(Arch));
367 // For ARM targets, try to use the build attributes to build determine
368 // the build target. Target features are also added, but later during
370 if (Arch == Triple::arm || Arch == Triple::armeb) {
371 Obj->setARMSubArch(TheTriple);
374 // TheTriple defaults to ELF, and COFF doesn't have an environment:
375 // the best we can do here is indicate that it is mach-o.
377 TheTriple.setObjectFormat(Triple::MachO);
380 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
381 if (COFFObj->getArch() == Triple::thumb)
382 TheTriple.setTriple("thumbv7-windows");
386 TheTriple.setTriple(Triple::normalize(TripleName));
387 // Use the triple, but also try to combine with ARM build attributes.
389 auto Arch = Obj->getArch();
390 if (Arch == Triple::arm || Arch == Triple::armeb) {
391 Obj->setARMSubArch(TheTriple);
396 // Get the target specific parser.
398 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
402 report_error(Obj->getFileName(), "can't find target: " + Error);
404 error("can't find target: " + Error);
407 // Update the triple name and return the found target.
408 TripleName = TheTriple.getTriple();
412 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
413 return a.getOffset() < b.getOffset();
417 class SourcePrinter {
419 DILineInfo OldLineInfo;
420 const ObjectFile *Obj;
421 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
422 // File name to file contents of source
423 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
424 // Mark the line endings of the cached source
425 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
428 bool cacheSource(std::string File);
431 virtual ~SourcePrinter() {}
432 SourcePrinter() : Obj(nullptr), Symbolizer(nullptr) {}
433 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
434 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
435 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
437 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
439 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
440 StringRef Delimiter = "; ");
443 bool SourcePrinter::cacheSource(std::string File) {
444 auto BufferOrError = MemoryBuffer::getFile(File);
447 // Chomp the file to get lines
448 size_t BufferSize = (*BufferOrError)->getBufferSize();
449 const char *BufferStart = (*BufferOrError)->getBufferStart();
450 for (const char *Start = BufferStart, *End = BufferStart;
451 End < BufferStart + BufferSize; End++)
452 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
453 (*End == '\r' && *(End + 1) == '\n')) {
454 LineCache[File].push_back(StringRef(Start, End - Start));
459 SourceCache[File] = std::move(*BufferOrError);
463 void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
464 StringRef Delimiter) {
467 DILineInfo LineInfo = DILineInfo();
468 auto ExpectecLineInfo =
469 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
470 if (!ExpectecLineInfo)
471 consumeError(ExpectecLineInfo.takeError());
473 LineInfo = *ExpectecLineInfo;
475 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
480 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
482 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
483 if (!cacheSource(LineInfo.FileName))
485 auto FileBuffer = SourceCache.find(LineInfo.FileName);
486 if (FileBuffer != SourceCache.end()) {
487 auto LineBuffer = LineCache.find(LineInfo.FileName);
488 if (LineBuffer != LineCache.end())
489 // Vector begins at 0, line numbers are non-zero
490 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
494 OldLineInfo = LineInfo;
497 static bool isArmElf(const ObjectFile *Obj) {
498 return (Obj->isELF() &&
499 (Obj->getArch() == Triple::aarch64 ||
500 Obj->getArch() == Triple::aarch64_be ||
501 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
502 Obj->getArch() == Triple::thumb ||
503 Obj->getArch() == Triple::thumbeb));
506 class PrettyPrinter {
508 virtual ~PrettyPrinter(){}
509 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
510 ArrayRef<uint8_t> Bytes, uint64_t Address,
511 raw_ostream &OS, StringRef Annot,
512 MCSubtargetInfo const &STI, SourcePrinter *SP) {
513 if (SP && (PrintSource || PrintLines))
514 SP->printSourceLine(OS, Address);
516 OS << format("%8" PRIx64 ":", Address);
517 if (!NoShowRawInsn) {
519 dumpBytes(Bytes, OS);
522 IP.printInst(MI, OS, "", STI);
527 PrettyPrinter PrettyPrinterInst;
528 class HexagonPrettyPrinter : public PrettyPrinter {
530 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
533 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
535 OS << format("%8" PRIx64 ":", Address);
536 if (!NoShowRawInsn) {
538 dumpBytes(Bytes.slice(0, 4), OS);
539 OS << format("%08" PRIx32, opcode);
542 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
543 uint64_t Address, raw_ostream &OS, StringRef Annot,
544 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
545 if (SP && (PrintSource || PrintLines))
546 SP->printSourceLine(OS, Address, "");
548 printLead(Bytes, Address, OS);
554 raw_string_ostream TempStream(Buffer);
555 IP.printInst(MI, TempStream, "", STI);
557 StringRef Contents(Buffer);
558 // Split off bundle attributes
559 auto PacketBundle = Contents.rsplit('\n');
560 // Split off first instruction from the rest
561 auto HeadTail = PacketBundle.first.split('\n');
562 auto Preamble = " { ";
564 while(!HeadTail.first.empty()) {
567 if (SP && (PrintSource || PrintLines))
568 SP->printSourceLine(OS, Address, "");
569 printLead(Bytes, Address, OS);
573 auto Duplex = HeadTail.first.split('\v');
574 if(!Duplex.second.empty()){
577 Inst = Duplex.second;
580 Inst = HeadTail.first;
582 Bytes = Bytes.slice(4);
584 HeadTail = HeadTail.second.split('\n');
586 OS << " } " << PacketBundle.second;
589 HexagonPrettyPrinter HexagonPrettyPrinterInst;
591 class AMDGCNPrettyPrinter : public PrettyPrinter {
593 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
594 uint64_t Address, raw_ostream &OS, StringRef Annot,
595 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
596 if (SP && (PrintSource || PrintLines))
597 SP->printSourceLine(OS, Address);
604 SmallString<40> InstStr;
605 raw_svector_ostream IS(InstStr);
607 IP.printInst(MI, IS, "", STI);
609 OS << left_justify(IS.str(), 60) << format("// %012" PRIX64 ": ", Address);
610 typedef support::ulittle32_t U32;
611 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
612 Bytes.size() / sizeof(U32)))
613 // D should be explicitly casted to uint32_t here as it is passed
614 // by format to snprintf as vararg.
615 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
618 OS << "// " << Annot;
621 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
623 class BPFPrettyPrinter : public PrettyPrinter {
625 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
626 uint64_t Address, raw_ostream &OS, StringRef Annot,
627 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
628 if (SP && (PrintSource || PrintLines))
629 SP->printSourceLine(OS, Address);
631 OS << format("%8" PRId64 ":", Address / 8);
632 if (!NoShowRawInsn) {
634 dumpBytes(Bytes, OS);
637 IP.printInst(MI, OS, "", STI);
642 BPFPrettyPrinter BPFPrettyPrinterInst;
644 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
645 switch(Triple.getArch()) {
647 return PrettyPrinterInst;
648 case Triple::hexagon:
649 return HexagonPrettyPrinterInst;
651 return AMDGCNPrettyPrinterInst;
654 return BPFPrettyPrinterInst;
659 template <class ELFT>
660 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
661 const RelocationRef &RelRef,
662 SmallVectorImpl<char> &Result) {
663 DataRefImpl Rel = RelRef.getRawDataRefImpl();
665 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
666 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
667 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
669 const ELFFile<ELFT> &EF = *Obj->getELFFile();
671 auto SecOrErr = EF.getSection(Rel.d.a);
673 return errorToErrorCode(SecOrErr.takeError());
674 const Elf_Shdr *Sec = *SecOrErr;
675 auto SymTabOrErr = EF.getSection(Sec->sh_link);
677 return errorToErrorCode(SymTabOrErr.takeError());
678 const Elf_Shdr *SymTab = *SymTabOrErr;
679 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
680 SymTab->sh_type == ELF::SHT_DYNSYM);
681 auto StrTabSec = EF.getSection(SymTab->sh_link);
683 return errorToErrorCode(StrTabSec.takeError());
684 auto StrTabOrErr = EF.getStringTable(*StrTabSec);
686 return errorToErrorCode(StrTabOrErr.takeError());
687 StringRef StrTab = *StrTabOrErr;
688 uint8_t type = RelRef.getType();
691 switch (Sec->sh_type) {
693 return object_error::parse_failed;
695 // TODO: Read implicit addend from section data.
698 case ELF::SHT_RELA: {
699 const Elf_Rela *ERela = Obj->getRela(Rel);
700 addend = ERela->r_addend;
704 symbol_iterator SI = RelRef.getSymbol();
705 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
707 if (symb->getType() == ELF::STT_SECTION) {
708 Expected<section_iterator> SymSI = SI->getSection();
710 return errorToErrorCode(SymSI.takeError());
711 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
712 auto SecName = EF.getSectionName(SymSec);
714 return errorToErrorCode(SecName.takeError());
717 Expected<StringRef> SymName = symb->getName(StrTab);
719 return errorToErrorCode(SymName.takeError());
722 switch (EF.getHeader()->e_machine) {
725 case ELF::R_X86_64_PC8:
726 case ELF::R_X86_64_PC16:
727 case ELF::R_X86_64_PC32: {
729 raw_string_ostream fmt(fmtbuf);
730 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
732 Result.append(fmtbuf.begin(), fmtbuf.end());
734 case ELF::R_X86_64_8:
735 case ELF::R_X86_64_16:
736 case ELF::R_X86_64_32:
737 case ELF::R_X86_64_32S:
738 case ELF::R_X86_64_64: {
740 raw_string_ostream fmt(fmtbuf);
741 fmt << Target << (addend < 0 ? "" : "+") << addend;
743 Result.append(fmtbuf.begin(), fmtbuf.end());
751 case ELF::EM_AARCH64: {
753 raw_string_ostream fmt(fmtbuf);
756 fmt << (addend < 0 ? "" : "+") << addend;
758 Result.append(fmtbuf.begin(), fmtbuf.end());
764 case ELF::EM_HEXAGON:
770 case ELF::EM_WEBASSEMBLY:
772 case ELF::R_WEBASSEMBLY_DATA: {
774 raw_string_ostream fmt(fmtbuf);
775 fmt << Target << (addend < 0 ? "" : "+") << addend;
777 Result.append(fmtbuf.begin(), fmtbuf.end());
780 case ELF::R_WEBASSEMBLY_FUNCTION:
791 Result.append(res.begin(), res.end());
792 return std::error_code();
795 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
796 const RelocationRef &Rel,
797 SmallVectorImpl<char> &Result) {
798 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
799 return getRelocationValueString(ELF32LE, Rel, Result);
800 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
801 return getRelocationValueString(ELF64LE, Rel, Result);
802 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
803 return getRelocationValueString(ELF32BE, Rel, Result);
804 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
805 return getRelocationValueString(ELF64BE, Rel, Result);
808 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
809 const RelocationRef &Rel,
810 SmallVectorImpl<char> &Result) {
811 symbol_iterator SymI = Rel.getSymbol();
812 Expected<StringRef> SymNameOrErr = SymI->getName();
814 return errorToErrorCode(SymNameOrErr.takeError());
815 StringRef SymName = *SymNameOrErr;
816 Result.append(SymName.begin(), SymName.end());
817 return std::error_code();
820 static void printRelocationTargetName(const MachOObjectFile *O,
821 const MachO::any_relocation_info &RE,
822 raw_string_ostream &fmt) {
823 bool IsScattered = O->isRelocationScattered(RE);
825 // Target of a scattered relocation is an address. In the interest of
826 // generating pretty output, scan through the symbol table looking for a
827 // symbol that aligns with that address. If we find one, print it.
828 // Otherwise, we just print the hex address of the target.
830 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
832 for (const SymbolRef &Symbol : O->symbols()) {
834 Expected<uint64_t> Addr = Symbol.getAddress();
836 report_error(O->getFileName(), Addr.takeError());
839 Expected<StringRef> Name = Symbol.getName();
841 report_error(O->getFileName(), Name.takeError());
846 // If we couldn't find a symbol that this relocation refers to, try
847 // to find a section beginning instead.
848 for (const SectionRef &Section : ToolSectionFilter(*O)) {
852 uint64_t Addr = Section.getAddress();
855 if ((ec = Section.getName(Name)))
856 report_error(O->getFileName(), ec);
861 fmt << format("0x%x", Val);
866 bool isExtern = O->getPlainRelocationExternal(RE);
867 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
870 symbol_iterator SI = O->symbol_begin();
872 Expected<StringRef> SOrErr = SI->getName();
874 report_error(O->getFileName(), SOrErr.takeError());
877 section_iterator SI = O->section_begin();
878 // Adjust for the fact that sections are 1-indexed.
879 advance(SI, Val - 1);
886 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
887 const RelocationRef &RelRef,
888 SmallVectorImpl<char> &Result) {
889 DataRefImpl Rel = RelRef.getRawDataRefImpl();
890 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
892 unsigned Arch = Obj->getArch();
895 raw_string_ostream fmt(fmtbuf);
896 unsigned Type = Obj->getAnyRelocationType(RE);
897 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
899 // Determine any addends that should be displayed with the relocation.
900 // These require decoding the relocation type, which is triple-specific.
902 // X86_64 has entirely custom relocation types.
903 if (Arch == Triple::x86_64) {
904 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
907 case MachO::X86_64_RELOC_GOT_LOAD:
908 case MachO::X86_64_RELOC_GOT: {
909 printRelocationTargetName(Obj, RE, fmt);
915 case MachO::X86_64_RELOC_SUBTRACTOR: {
916 DataRefImpl RelNext = Rel;
917 Obj->moveRelocationNext(RelNext);
918 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
920 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
921 // X86_64_RELOC_UNSIGNED.
922 // NOTE: Scattered relocations don't exist on x86_64.
923 unsigned RType = Obj->getAnyRelocationType(RENext);
924 if (RType != MachO::X86_64_RELOC_UNSIGNED)
925 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
926 "X86_64_RELOC_SUBTRACTOR.");
928 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
929 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
930 printRelocationTargetName(Obj, RENext, fmt);
932 printRelocationTargetName(Obj, RE, fmt);
935 case MachO::X86_64_RELOC_TLV:
936 printRelocationTargetName(Obj, RE, fmt);
941 case MachO::X86_64_RELOC_SIGNED_1:
942 printRelocationTargetName(Obj, RE, fmt);
945 case MachO::X86_64_RELOC_SIGNED_2:
946 printRelocationTargetName(Obj, RE, fmt);
949 case MachO::X86_64_RELOC_SIGNED_4:
950 printRelocationTargetName(Obj, RE, fmt);
954 printRelocationTargetName(Obj, RE, fmt);
957 // X86 and ARM share some relocation types in common.
958 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
959 Arch == Triple::ppc) {
960 // Generic relocation types...
962 case MachO::GENERIC_RELOC_PAIR: // prints no info
963 return std::error_code();
964 case MachO::GENERIC_RELOC_SECTDIFF: {
965 DataRefImpl RelNext = Rel;
966 Obj->moveRelocationNext(RelNext);
967 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
969 // X86 sect diff's must be followed by a relocation of type
970 // GENERIC_RELOC_PAIR.
971 unsigned RType = Obj->getAnyRelocationType(RENext);
973 if (RType != MachO::GENERIC_RELOC_PAIR)
974 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
975 "GENERIC_RELOC_SECTDIFF.");
977 printRelocationTargetName(Obj, RE, fmt);
979 printRelocationTargetName(Obj, RENext, fmt);
984 if (Arch == Triple::x86 || Arch == Triple::ppc) {
986 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
987 DataRefImpl RelNext = Rel;
988 Obj->moveRelocationNext(RelNext);
989 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
991 // X86 sect diff's must be followed by a relocation of type
992 // GENERIC_RELOC_PAIR.
993 unsigned RType = Obj->getAnyRelocationType(RENext);
994 if (RType != MachO::GENERIC_RELOC_PAIR)
995 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
996 "GENERIC_RELOC_LOCAL_SECTDIFF.");
998 printRelocationTargetName(Obj, RE, fmt);
1000 printRelocationTargetName(Obj, RENext, fmt);
1003 case MachO::GENERIC_RELOC_TLV: {
1004 printRelocationTargetName(Obj, RE, fmt);
1011 printRelocationTargetName(Obj, RE, fmt);
1013 } else { // ARM-specific relocations
1015 case MachO::ARM_RELOC_HALF:
1016 case MachO::ARM_RELOC_HALF_SECTDIFF: {
1017 // Half relocations steal a bit from the length field to encode
1018 // whether this is an upper16 or a lower16 relocation.
1019 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
1022 fmt << ":upper16:(";
1024 fmt << ":lower16:(";
1025 printRelocationTargetName(Obj, RE, fmt);
1027 DataRefImpl RelNext = Rel;
1028 Obj->moveRelocationNext(RelNext);
1029 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
1031 // ARM half relocs must be followed by a relocation of type
1033 unsigned RType = Obj->getAnyRelocationType(RENext);
1034 if (RType != MachO::ARM_RELOC_PAIR)
1035 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
1038 // NOTE: The half of the target virtual address is stashed in the
1039 // address field of the secondary relocation, but we can't reverse
1040 // engineer the constant offset from it without decoding the movw/movt
1041 // instruction to find the other half in its immediate field.
1043 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
1044 // symbol/section pointer of the follow-on relocation.
1045 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1047 printRelocationTargetName(Obj, RENext, fmt);
1053 default: { printRelocationTargetName(Obj, RE, fmt); }
1057 printRelocationTargetName(Obj, RE, fmt);
1060 Result.append(fmtbuf.begin(), fmtbuf.end());
1061 return std::error_code();
1064 static std::error_code getRelocationValueString(const RelocationRef &Rel,
1065 SmallVectorImpl<char> &Result) {
1066 const ObjectFile *Obj = Rel.getObject();
1067 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
1068 return getRelocationValueString(ELF, Rel, Result);
1069 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
1070 return getRelocationValueString(COFF, Rel, Result);
1071 auto *MachO = cast<MachOObjectFile>(Obj);
1072 return getRelocationValueString(MachO, Rel, Result);
1075 /// @brief Indicates whether this relocation should hidden when listing
1076 /// relocations, usually because it is the trailing part of a multipart
1077 /// relocation that will be printed as part of the leading relocation.
1078 static bool getHidden(RelocationRef RelRef) {
1079 const ObjectFile *Obj = RelRef.getObject();
1080 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
1084 unsigned Arch = MachO->getArch();
1085 DataRefImpl Rel = RelRef.getRawDataRefImpl();
1086 uint64_t Type = MachO->getRelocationType(Rel);
1088 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
1089 // is always hidden.
1090 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
1091 if (Type == MachO::GENERIC_RELOC_PAIR)
1093 } else if (Arch == Triple::x86_64) {
1094 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
1095 // an X86_64_RELOC_SUBTRACTOR.
1096 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
1097 DataRefImpl RelPrev = Rel;
1099 uint64_t PrevType = MachO->getRelocationType(RelPrev);
1100 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
1108 static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1109 assert(Obj->isELF());
1110 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1111 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1112 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1113 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1114 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1115 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1116 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1117 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1118 llvm_unreachable("Unsupported binary format");
1121 template <class ELFT> static void
1122 addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
1123 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1124 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
1125 uint8_t SymbolType = Symbol.getELFType();
1126 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
1129 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1131 report_error(Obj->getFileName(), AddressOrErr.takeError());
1132 uint64_t Address = *AddressOrErr;
1134 Expected<StringRef> Name = Symbol.getName();
1136 report_error(Obj->getFileName(), Name.takeError());
1140 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1142 report_error(Obj->getFileName(), SectionOrErr.takeError());
1143 section_iterator SecI = *SectionOrErr;
1144 if (SecI == Obj->section_end())
1147 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1152 addDynamicElfSymbols(const ObjectFile *Obj,
1153 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1154 assert(Obj->isELF());
1155 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1156 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
1157 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1158 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
1159 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1160 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
1161 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1162 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
1164 llvm_unreachable("Unsupported binary format");
1167 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
1168 if (StartAddress > StopAddress)
1169 error("Start address should be less than stop address");
1171 const Target *TheTarget = getTarget(Obj);
1173 // Package up features to be passed to target/subtarget
1174 SubtargetFeatures Features = Obj->getFeatures();
1175 if (MAttrs.size()) {
1176 for (unsigned i = 0; i != MAttrs.size(); ++i)
1177 Features.AddFeature(MAttrs[i]);
1180 std::unique_ptr<const MCRegisterInfo> MRI(
1181 TheTarget->createMCRegInfo(TripleName));
1183 report_error(Obj->getFileName(), "no register info for target " +
1186 // Set up disassembler.
1187 std::unique_ptr<const MCAsmInfo> AsmInfo(
1188 TheTarget->createMCAsmInfo(*MRI, TripleName));
1190 report_error(Obj->getFileName(), "no assembly info for target " +
1192 std::unique_ptr<const MCSubtargetInfo> STI(
1193 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1195 report_error(Obj->getFileName(), "no subtarget info for target " +
1197 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1199 report_error(Obj->getFileName(), "no instruction info for target " +
1201 MCObjectFileInfo MOFI;
1202 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1203 // FIXME: for now initialize MCObjectFileInfo with default values
1204 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, CodeModel::Default, Ctx);
1206 std::unique_ptr<MCDisassembler> DisAsm(
1207 TheTarget->createMCDisassembler(*STI, Ctx));
1209 report_error(Obj->getFileName(), "no disassembler for target " +
1212 std::unique_ptr<const MCInstrAnalysis> MIA(
1213 TheTarget->createMCInstrAnalysis(MII.get()));
1215 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1216 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1217 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
1219 report_error(Obj->getFileName(), "no instruction printer for target " +
1221 IP->setPrintImmHex(PrintImmHex);
1222 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
1224 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
1225 "\t\t\t%08" PRIx64 ": ";
1227 SourcePrinter SP(Obj, TheTarget->getName());
1229 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1230 // in RelocSecs contain the relocations for section S.
1232 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
1233 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1234 section_iterator Sec2 = Section.getRelocatedSection();
1235 if (Sec2 != Obj->section_end())
1236 SectionRelocMap[*Sec2].push_back(Section);
1239 // Create a mapping from virtual address to symbol name. This is used to
1240 // pretty print the symbols while disassembling.
1241 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1242 for (const SymbolRef &Symbol : Obj->symbols()) {
1243 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1245 report_error(Obj->getFileName(), AddressOrErr.takeError());
1246 uint64_t Address = *AddressOrErr;
1248 Expected<StringRef> Name = Symbol.getName();
1250 report_error(Obj->getFileName(), Name.takeError());
1254 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1256 report_error(Obj->getFileName(), SectionOrErr.takeError());
1257 section_iterator SecI = *SectionOrErr;
1258 if (SecI == Obj->section_end())
1261 uint8_t SymbolType = ELF::STT_NOTYPE;
1263 SymbolType = getElfSymbolType(Obj, Symbol);
1265 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1268 if (AllSymbols.empty() && Obj->isELF())
1269 addDynamicElfSymbols(Obj, AllSymbols);
1271 // Create a mapping from virtual address to section.
1272 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1273 for (SectionRef Sec : Obj->sections())
1274 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1275 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1277 // Linked executables (.exe and .dll files) typically don't include a real
1278 // symbol table but they might contain an export table.
1279 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1280 for (const auto &ExportEntry : COFFObj->export_directories()) {
1282 error(ExportEntry.getSymbolName(Name));
1286 error(ExportEntry.getExportRVA(RVA));
1288 uint64_t VA = COFFObj->getImageBase() + RVA;
1289 auto Sec = std::upper_bound(
1290 SectionAddresses.begin(), SectionAddresses.end(), VA,
1291 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1292 return LHS < RHS.first;
1294 if (Sec != SectionAddresses.begin())
1297 Sec = SectionAddresses.end();
1299 if (Sec != SectionAddresses.end())
1300 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
1304 // Sort all the symbols, this allows us to use a simple binary search to find
1305 // a symbol near an address.
1306 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1307 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1309 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1310 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
1313 uint64_t SectionAddr = Section.getAddress();
1314 uint64_t SectSize = Section.getSize();
1318 // Get the list of all the symbols in this section.
1319 SectionSymbolsTy &Symbols = AllSymbols[Section];
1320 std::vector<uint64_t> DataMappingSymsAddr;
1321 std::vector<uint64_t> TextMappingSymsAddr;
1322 if (isArmElf(Obj)) {
1323 for (const auto &Symb : Symbols) {
1324 uint64_t Address = std::get<0>(Symb);
1325 StringRef Name = std::get<1>(Symb);
1326 if (Name.startswith("$d"))
1327 DataMappingSymsAddr.push_back(Address - SectionAddr);
1328 if (Name.startswith("$x"))
1329 TextMappingSymsAddr.push_back(Address - SectionAddr);
1330 if (Name.startswith("$a"))
1331 TextMappingSymsAddr.push_back(Address - SectionAddr);
1332 if (Name.startswith("$t"))
1333 TextMappingSymsAddr.push_back(Address - SectionAddr);
1337 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1338 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
1340 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1341 // AMDGPU disassembler uses symbolizer for printing labels
1342 std::unique_ptr<MCRelocationInfo> RelInfo(
1343 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1345 std::unique_ptr<MCSymbolizer> Symbolizer(
1346 TheTarget->createMCSymbolizer(
1347 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1348 DisAsm->setSymbolizer(std::move(Symbolizer));
1352 // Make a list of all the relocations for this section.
1353 std::vector<RelocationRef> Rels;
1355 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1356 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1357 Rels.push_back(Reloc);
1362 // Sort relocations by address.
1363 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
1365 StringRef SegmentName = "";
1366 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
1367 DataRefImpl DR = Section.getRawDataRefImpl();
1368 SegmentName = MachO->getSectionFinalSegmentName(DR);
1371 error(Section.getName(name));
1373 if ((SectionAddr <= StopAddress) &&
1374 (SectionAddr + SectSize) >= StartAddress) {
1375 outs() << "Disassembly of section ";
1376 if (!SegmentName.empty())
1377 outs() << SegmentName << ",";
1378 outs() << name << ':';
1381 // If the section has no symbol at the start, just insert a dummy one.
1382 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
1383 Symbols.insert(Symbols.begin(),
1384 std::make_tuple(SectionAddr, name, Section.isText()
1386 : ELF::STT_OBJECT));
1389 SmallString<40> Comments;
1390 raw_svector_ostream CommentStream(Comments);
1393 error(Section.getContents(BytesStr));
1394 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1400 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1401 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
1402 // Disassemble symbol by symbol.
1403 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
1404 uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr;
1405 // The end is either the section end or the beginning of the next
1408 (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr;
1409 // Don't try to disassemble beyond the end of section contents.
1412 // If this symbol has the same address as the next symbol, then skip it.
1416 // Check if we need to skip symbol
1417 // Skip if the symbol's data is not between StartAddress and StopAddress
1418 if (End + SectionAddr < StartAddress ||
1419 Start + SectionAddr > StopAddress) {
1423 // Stop disassembly at the stop address specified
1424 if (End + SectionAddr > StopAddress)
1425 End = StopAddress - SectionAddr;
1427 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1428 // make size 4 bytes folded
1429 End = Start + ((End - Start) & ~0x3ull);
1430 if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1431 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1435 std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1436 // cut trailing zeroes at the end of kernel
1437 // cut up to 256 bytes
1438 const uint64_t EndAlign = 256;
1439 const auto Limit = End - (std::min)(EndAlign, End - Start);
1440 while (End > Limit &&
1441 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1446 outs() << '\n' << std::get<1>(Symbols[si]) << ":\n";
1449 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1451 raw_ostream &DebugOut = nulls();
1454 for (Index = Start; Index < End; Index += Size) {
1457 if (Index + SectionAddr < StartAddress ||
1458 Index + SectionAddr > StopAddress) {
1459 // skip byte by byte till StartAddress is reached
1463 // AArch64 ELF binaries can interleave data and text in the
1464 // same section. We rely on the markers introduced to
1465 // understand what we need to dump. If the data marker is within a
1466 // function, it is denoted as a word/short etc
1467 if (isArmElf(Obj) && std::get<2>(Symbols[si]) != ELF::STT_OBJECT &&
1469 uint64_t Stride = 0;
1471 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1472 DataMappingSymsAddr.end(), Index);
1473 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1475 while (Index < End) {
1476 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1478 if (Index + 4 <= End) {
1480 dumpBytes(Bytes.slice(Index, 4), outs());
1481 outs() << "\t.word\t";
1483 if (Obj->isLittleEndian()) {
1485 reinterpret_cast<const support::ulittle32_t *>(
1486 Bytes.data() + Index);
1489 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1490 Bytes.data() + Index);
1493 outs() << "0x" << format("%08" PRIx32, Data);
1494 } else if (Index + 2 <= End) {
1496 dumpBytes(Bytes.slice(Index, 2), outs());
1497 outs() << "\t\t.short\t";
1499 if (Obj->isLittleEndian()) {
1501 reinterpret_cast<const support::ulittle16_t *>(
1502 Bytes.data() + Index);
1506 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1510 outs() << "0x" << format("%04" PRIx16, Data);
1513 dumpBytes(Bytes.slice(Index, 1), outs());
1514 outs() << "\t\t.byte\t";
1515 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
1519 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1520 TextMappingSymsAddr.end(), Index);
1521 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1527 // If there is a data symbol inside an ELF text section and we are only
1528 // disassembling text (applicable all architectures),
1529 // we are in a situation where we must print the data and not
1531 if (Obj->isELF() && std::get<2>(Symbols[si]) == ELF::STT_OBJECT &&
1532 !DisassembleAll && Section.isText()) {
1533 // print out data up to 8 bytes at a time in hex and ascii
1534 uint8_t AsciiData[9] = {'\0'};
1538 for (Index = Start; Index < End; Index += 1) {
1539 if (((SectionAddr + Index) < StartAddress) ||
1540 ((SectionAddr + Index) > StopAddress))
1542 if (NumBytes == 0) {
1543 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1546 Byte = Bytes.slice(Index)[0];
1547 outs() << format(" %02x", Byte);
1548 AsciiData[NumBytes] = isprint(Byte) ? Byte : '.';
1550 uint8_t IndentOffset = 0;
1552 if (Index == End - 1 || NumBytes > 8) {
1553 // Indent the space for less than 8 bytes data.
1554 // 2 spaces for byte and one for space between bytes
1555 IndentOffset = 3 * (8 - NumBytes);
1556 for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1557 AsciiData[Excess] = '\0';
1560 if (NumBytes == 8) {
1561 AsciiData[8] = '\0';
1562 outs() << std::string(IndentOffset, ' ') << " ";
1563 outs() << reinterpret_cast<char *>(AsciiData);
1572 // Disassemble a real instruction or a data when disassemble all is
1574 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1575 SectionAddr + Index, DebugOut,
1580 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
1581 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
1583 outs() << CommentStream.str();
1586 // Try to resolve the target of a call, tail call, etc. to a specific
1588 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1589 MIA->isConditionalBranch(Inst))) {
1591 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1592 // In a relocatable object, the target's section must reside in
1593 // the same section as the call instruction or it is accessed
1594 // through a relocation.
1596 // In a non-relocatable object, the target may be in any section.
1598 // N.B. We don't walk the relocations in the relocatable case yet.
1599 auto *TargetSectionSymbols = &Symbols;
1600 if (!Obj->isRelocatableObject()) {
1601 auto SectionAddress = std::upper_bound(
1602 SectionAddresses.begin(), SectionAddresses.end(), Target,
1604 const std::pair<uint64_t, SectionRef> &RHS) {
1605 return LHS < RHS.first;
1607 if (SectionAddress != SectionAddresses.begin()) {
1609 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1611 TargetSectionSymbols = nullptr;
1615 // Find the first symbol in the section whose offset is less than
1616 // or equal to the target.
1617 if (TargetSectionSymbols) {
1618 auto TargetSym = std::upper_bound(
1619 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1620 Target, [](uint64_t LHS,
1621 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1622 return LHS < std::get<0>(RHS);
1624 if (TargetSym != TargetSectionSymbols->begin()) {
1626 uint64_t TargetAddress = std::get<0>(*TargetSym);
1627 StringRef TargetName = std::get<1>(*TargetSym);
1628 outs() << " <" << TargetName;
1629 uint64_t Disp = Target - TargetAddress;
1631 outs() << "+0x" << utohexstr(Disp);
1639 // Print relocation for instruction.
1640 while (rel_cur != rel_end) {
1641 bool hidden = getHidden(*rel_cur);
1642 uint64_t addr = rel_cur->getOffset();
1643 SmallString<16> name;
1644 SmallString<32> val;
1646 // If this relocation is hidden, skip it.
1647 if (hidden || ((SectionAddr + addr) < StartAddress)) {
1652 // Stop when rel_cur's address is past the current instruction.
1653 if (addr >= Index + Size) break;
1654 rel_cur->getTypeName(name);
1655 error(getRelocationValueString(*rel_cur, val));
1656 outs() << format(Fmt.data(), SectionAddr + addr) << name
1657 << "\t" << val << "\n";
1665 void llvm::PrintRelocations(const ObjectFile *Obj) {
1666 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1668 // Regular objdump doesn't print relocations in non-relocatable object
1670 if (!Obj->isRelocatableObject())
1673 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1674 if (Section.relocation_begin() == Section.relocation_end())
1677 error(Section.getName(secname));
1678 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
1679 for (const RelocationRef &Reloc : Section.relocations()) {
1680 bool hidden = getHidden(Reloc);
1681 uint64_t address = Reloc.getOffset();
1682 SmallString<32> relocname;
1683 SmallString<32> valuestr;
1684 if (address < StartAddress || address > StopAddress || hidden)
1686 Reloc.getTypeName(relocname);
1687 error(getRelocationValueString(Reloc, valuestr));
1688 outs() << format(Fmt.data(), address) << " " << relocname << " "
1689 << valuestr << "\n";
1695 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
1696 outs() << "Sections:\n"
1697 "Idx Name Size Address Type\n";
1699 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1701 error(Section.getName(Name));
1702 uint64_t Address = Section.getAddress();
1703 uint64_t Size = Section.getSize();
1704 bool Text = Section.isText();
1705 bool Data = Section.isData();
1706 bool BSS = Section.isBSS();
1707 std::string Type = (std::string(Text ? "TEXT " : "") +
1708 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1709 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1710 Name.str().c_str(), Size, Address, Type.c_str());
1715 void llvm::PrintSectionContents(const ObjectFile *Obj) {
1717 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1720 error(Section.getName(Name));
1721 uint64_t BaseAddr = Section.getAddress();
1722 uint64_t Size = Section.getSize();
1726 outs() << "Contents of section " << Name << ":\n";
1727 if (Section.isBSS()) {
1728 outs() << format("<skipping contents of bss section at [%04" PRIx64
1729 ", %04" PRIx64 ")>\n",
1730 BaseAddr, BaseAddr + Size);
1734 error(Section.getContents(Contents));
1736 // Dump out the content as hex and printable ascii characters.
1737 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1738 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1739 // Dump line of hex.
1740 for (std::size_t i = 0; i < 16; ++i) {
1741 if (i != 0 && i % 4 == 0)
1744 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1745 << hexdigit(Contents[addr + i] & 0xF, true);
1751 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1752 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1753 outs() << Contents[addr + i];
1762 void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1763 StringRef ArchitectureName) {
1764 outs() << "SYMBOL TABLE:\n";
1766 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1767 printCOFFSymbolTable(coff);
1770 for (const SymbolRef &Symbol : o->symbols()) {
1771 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1772 if (!AddressOrError)
1773 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError(),
1775 uint64_t Address = *AddressOrError;
1776 if ((Address < StartAddress) || (Address > StopAddress))
1778 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1780 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError(),
1782 SymbolRef::Type Type = *TypeOrError;
1783 uint32_t Flags = Symbol.getFlags();
1784 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1786 report_error(ArchiveName, o->getFileName(), SectionOrErr.takeError(),
1788 section_iterator Section = *SectionOrErr;
1790 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1791 Section->getName(Name);
1793 Expected<StringRef> NameOrErr = Symbol.getName();
1795 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1800 bool Global = Flags & SymbolRef::SF_Global;
1801 bool Weak = Flags & SymbolRef::SF_Weak;
1802 bool Absolute = Flags & SymbolRef::SF_Absolute;
1803 bool Common = Flags & SymbolRef::SF_Common;
1804 bool Hidden = Flags & SymbolRef::SF_Hidden;
1807 if (Type != SymbolRef::ST_Unknown)
1808 GlobLoc = Global ? 'g' : 'l';
1809 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1811 char FileFunc = ' ';
1812 if (Type == SymbolRef::ST_File)
1814 else if (Type == SymbolRef::ST_Function)
1817 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1820 outs() << format(Fmt, Address) << " "
1821 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1822 << (Weak ? 'w' : ' ') // Weak?
1823 << ' ' // Constructor. Not supported yet.
1824 << ' ' // Warning. Not supported yet.
1825 << ' ' // Indirect reference to another symbol.
1826 << Debug // Debugging (d) or dynamic (D) symbol.
1827 << FileFunc // Name of function (F), file (f) or object (O).
1831 } else if (Common) {
1833 } else if (Section == o->section_end()) {
1836 if (const MachOObjectFile *MachO =
1837 dyn_cast<const MachOObjectFile>(o)) {
1838 DataRefImpl DR = Section->getRawDataRefImpl();
1839 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1840 outs() << SegmentName << ",";
1842 StringRef SectionName;
1843 error(Section->getName(SectionName));
1844 outs() << SectionName;
1848 if (Common || isa<ELFObjectFileBase>(o)) {
1850 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1851 outs() << format("\t %08" PRIx64 " ", Val);
1855 outs() << ".hidden ";
1862 static void PrintUnwindInfo(const ObjectFile *o) {
1863 outs() << "Unwind info:\n\n";
1865 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1866 printCOFFUnwindInfo(coff);
1867 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1868 printMachOUnwindInfo(MachO);
1870 // TODO: Extract DWARF dump tool to objdump.
1871 errs() << "This operation is only currently supported "
1872 "for COFF and MachO object files.\n";
1877 void llvm::printExportsTrie(const ObjectFile *o) {
1878 outs() << "Exports trie:\n";
1879 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1880 printMachOExportsTrie(MachO);
1882 errs() << "This operation is only currently supported "
1883 "for Mach-O executable files.\n";
1888 void llvm::printRebaseTable(ObjectFile *o) {
1889 outs() << "Rebase table:\n";
1890 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1891 printMachORebaseTable(MachO);
1893 errs() << "This operation is only currently supported "
1894 "for Mach-O executable files.\n";
1899 void llvm::printBindTable(ObjectFile *o) {
1900 outs() << "Bind table:\n";
1901 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1902 printMachOBindTable(MachO);
1904 errs() << "This operation is only currently supported "
1905 "for Mach-O executable files.\n";
1910 void llvm::printLazyBindTable(ObjectFile *o) {
1911 outs() << "Lazy bind table:\n";
1912 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1913 printMachOLazyBindTable(MachO);
1915 errs() << "This operation is only currently supported "
1916 "for Mach-O executable files.\n";
1921 void llvm::printWeakBindTable(ObjectFile *o) {
1922 outs() << "Weak bind table:\n";
1923 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1924 printMachOWeakBindTable(MachO);
1926 errs() << "This operation is only currently supported "
1927 "for Mach-O executable files.\n";
1932 /// Dump the raw contents of the __clangast section so the output can be piped
1933 /// into llvm-bcanalyzer.
1934 void llvm::printRawClangAST(const ObjectFile *Obj) {
1935 if (outs().is_displayed()) {
1936 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1937 "the clang ast section.\n"
1938 "Please redirect the output to a file or another program such as "
1939 "llvm-bcanalyzer.\n";
1943 StringRef ClangASTSectionName("__clangast");
1944 if (isa<COFFObjectFile>(Obj)) {
1945 ClangASTSectionName = "clangast";
1948 Optional<object::SectionRef> ClangASTSection;
1949 for (auto Sec : ToolSectionFilter(*Obj)) {
1952 if (Name == ClangASTSectionName) {
1953 ClangASTSection = Sec;
1957 if (!ClangASTSection)
1960 StringRef ClangASTContents;
1961 error(ClangASTSection.getValue().getContents(ClangASTContents));
1962 outs().write(ClangASTContents.data(), ClangASTContents.size());
1965 static void printFaultMaps(const ObjectFile *Obj) {
1966 const char *FaultMapSectionName = nullptr;
1968 if (isa<ELFObjectFileBase>(Obj)) {
1969 FaultMapSectionName = ".llvm_faultmaps";
1970 } else if (isa<MachOObjectFile>(Obj)) {
1971 FaultMapSectionName = "__llvm_faultmaps";
1973 errs() << "This operation is only currently supported "
1974 "for ELF and Mach-O executable files.\n";
1978 Optional<object::SectionRef> FaultMapSection;
1980 for (auto Sec : ToolSectionFilter(*Obj)) {
1983 if (Name == FaultMapSectionName) {
1984 FaultMapSection = Sec;
1989 outs() << "FaultMap table:\n";
1991 if (!FaultMapSection.hasValue()) {
1992 outs() << "<not found>\n";
1996 StringRef FaultMapContents;
1997 error(FaultMapSection.getValue().getContents(FaultMapContents));
1999 FaultMapParser FMP(FaultMapContents.bytes_begin(),
2000 FaultMapContents.bytes_end());
2005 static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) {
2007 return printELFFileHeader(o);
2009 return printCOFFFileHeader(o);
2011 return printWasmFileHeader(o);
2013 printMachOFileHeader(o);
2015 printMachOLoadCommands(o);
2018 report_error(o->getFileName(), "Invalid/Unsupported object file format");
2021 static void DumpObject(ObjectFile *o, const Archive *a = nullptr) {
2022 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
2023 // Avoid other output when using a raw option.
2027 outs() << a->getFileName() << "(" << o->getFileName() << ")";
2029 outs() << o->getFileName();
2030 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
2034 DisassembleObject(o, Relocations);
2035 if (Relocations && !Disassemble)
2036 PrintRelocations(o);
2038 PrintSectionHeaders(o);
2039 if (SectionContents)
2040 PrintSectionContents(o);
2042 PrintSymbolTable(o, ArchiveName);
2045 if (PrivateHeaders || FirstPrivateHeader)
2046 printPrivateFileHeaders(o, FirstPrivateHeader);
2048 printExportsTrie(o);
2050 printRebaseTable(o);
2054 printLazyBindTable(o);
2056 printWeakBindTable(o);
2058 printRawClangAST(o);
2061 if (DwarfDumpType != DIDT_Null) {
2062 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o));
2063 // Dump the complete DWARF structure.
2064 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
2068 static void DumpObject(const COFFImportFile *I, const Archive *A) {
2069 StringRef ArchiveName = A ? A->getFileName() : "";
2071 // Avoid other output when using a raw option.
2074 << ArchiveName << "(" << I->getFileName() << ")"
2075 << ":\tfile format COFF-import-file"
2079 printCOFFSymbolTable(I);
2082 /// @brief Dump each object file in \a a;
2083 static void DumpArchive(const Archive *a) {
2084 Error Err = Error::success();
2085 for (auto &C : a->children(Err)) {
2086 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2088 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2089 report_error(a->getFileName(), C, std::move(E));
2092 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2094 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2097 report_error(a->getFileName(), object_error::invalid_file_type);
2100 report_error(a->getFileName(), std::move(Err));
2103 /// @brief Open file and figure out how to dump it.
2104 static void DumpInput(StringRef file) {
2106 // If we are using the Mach-O specific object file parser, then let it parse
2107 // the file and process the command line options. So the -arch flags can
2108 // be used to select specific slices, etc.
2110 ParseInputMachO(file);
2114 // Attempt to open the binary.
2115 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2117 report_error(file, BinaryOrErr.takeError());
2118 Binary &Binary = *BinaryOrErr.get().getBinary();
2120 if (Archive *a = dyn_cast<Archive>(&Binary))
2122 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
2125 report_error(file, object_error::invalid_file_type);
2128 int main(int argc, char **argv) {
2129 // Print a stack trace if we signal out.
2130 sys::PrintStackTraceOnErrorSignal(argv[0]);
2131 PrettyStackTraceProgram X(argc, argv);
2132 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
2134 // Initialize targets and assembly printers/parsers.
2135 llvm::InitializeAllTargetInfos();
2136 llvm::InitializeAllTargetMCs();
2137 llvm::InitializeAllDisassemblers();
2139 // Register the target printer for --version.
2140 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2142 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2143 TripleName = Triple::normalize(TripleName);
2147 // Defaults to a.out if no filenames specified.
2148 if (InputFilenames.size() == 0)
2149 InputFilenames.push_back("a.out");
2151 if (DisassembleAll || PrintSource || PrintLines)
2160 && !FirstPrivateHeader
2167 && !(UniversalHeaders && MachOOpt)
2168 && !(ArchiveHeaders && MachOOpt)
2169 && !(IndirectSymbols && MachOOpt)
2170 && !(DataInCode && MachOOpt)
2171 && !(LinkOptHints && MachOOpt)
2172 && !(InfoPlist && MachOOpt)
2173 && !(DylibsUsed && MachOOpt)
2174 && !(DylibId && MachOOpt)
2175 && !(ObjcMetaData && MachOOpt)
2176 && !(FilterSections.size() != 0 && MachOOpt)
2178 && DwarfDumpType == DIDT_Null) {
2179 cl::PrintHelpMessage();
2183 std::for_each(InputFilenames.begin(), InputFilenames.end(),
2186 return EXIT_SUCCESS;