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 if (LineInfo.Line > LineBuffer->second.size())
491 // Vector begins at 0, line numbers are non-zero
492 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
497 OldLineInfo = LineInfo;
500 static bool isArmElf(const ObjectFile *Obj) {
501 return (Obj->isELF() &&
502 (Obj->getArch() == Triple::aarch64 ||
503 Obj->getArch() == Triple::aarch64_be ||
504 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
505 Obj->getArch() == Triple::thumb ||
506 Obj->getArch() == Triple::thumbeb));
509 class PrettyPrinter {
511 virtual ~PrettyPrinter(){}
512 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
513 ArrayRef<uint8_t> Bytes, uint64_t Address,
514 raw_ostream &OS, StringRef Annot,
515 MCSubtargetInfo const &STI, SourcePrinter *SP) {
516 if (SP && (PrintSource || PrintLines))
517 SP->printSourceLine(OS, Address);
519 OS << format("%8" PRIx64 ":", Address);
520 if (!NoShowRawInsn) {
522 dumpBytes(Bytes, OS);
525 IP.printInst(MI, OS, "", STI);
530 PrettyPrinter PrettyPrinterInst;
531 class HexagonPrettyPrinter : public PrettyPrinter {
533 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
536 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
538 OS << format("%8" PRIx64 ":", Address);
539 if (!NoShowRawInsn) {
541 dumpBytes(Bytes.slice(0, 4), OS);
542 OS << format("%08" PRIx32, opcode);
545 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
546 uint64_t Address, raw_ostream &OS, StringRef Annot,
547 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
548 if (SP && (PrintSource || PrintLines))
549 SP->printSourceLine(OS, Address, "");
551 printLead(Bytes, Address, OS);
557 raw_string_ostream TempStream(Buffer);
558 IP.printInst(MI, TempStream, "", STI);
560 StringRef Contents(Buffer);
561 // Split off bundle attributes
562 auto PacketBundle = Contents.rsplit('\n');
563 // Split off first instruction from the rest
564 auto HeadTail = PacketBundle.first.split('\n');
565 auto Preamble = " { ";
567 while(!HeadTail.first.empty()) {
570 if (SP && (PrintSource || PrintLines))
571 SP->printSourceLine(OS, Address, "");
572 printLead(Bytes, Address, OS);
576 auto Duplex = HeadTail.first.split('\v');
577 if(!Duplex.second.empty()){
580 Inst = Duplex.second;
583 Inst = HeadTail.first;
585 Bytes = Bytes.slice(4);
587 HeadTail = HeadTail.second.split('\n');
589 OS << " } " << PacketBundle.second;
592 HexagonPrettyPrinter HexagonPrettyPrinterInst;
594 class AMDGCNPrettyPrinter : public PrettyPrinter {
596 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
597 uint64_t Address, raw_ostream &OS, StringRef Annot,
598 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
599 if (SP && (PrintSource || PrintLines))
600 SP->printSourceLine(OS, Address);
607 SmallString<40> InstStr;
608 raw_svector_ostream IS(InstStr);
610 IP.printInst(MI, IS, "", STI);
612 OS << left_justify(IS.str(), 60) << format("// %012" PRIX64 ": ", Address);
613 typedef support::ulittle32_t U32;
614 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
615 Bytes.size() / sizeof(U32)))
616 // D should be explicitly casted to uint32_t here as it is passed
617 // by format to snprintf as vararg.
618 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
621 OS << "// " << Annot;
624 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
626 class BPFPrettyPrinter : public PrettyPrinter {
628 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
629 uint64_t Address, raw_ostream &OS, StringRef Annot,
630 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
631 if (SP && (PrintSource || PrintLines))
632 SP->printSourceLine(OS, Address);
634 OS << format("%8" PRId64 ":", Address / 8);
635 if (!NoShowRawInsn) {
637 dumpBytes(Bytes, OS);
640 IP.printInst(MI, OS, "", STI);
645 BPFPrettyPrinter BPFPrettyPrinterInst;
647 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
648 switch(Triple.getArch()) {
650 return PrettyPrinterInst;
651 case Triple::hexagon:
652 return HexagonPrettyPrinterInst;
654 return AMDGCNPrettyPrinterInst;
657 return BPFPrettyPrinterInst;
662 template <class ELFT>
663 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
664 const RelocationRef &RelRef,
665 SmallVectorImpl<char> &Result) {
666 DataRefImpl Rel = RelRef.getRawDataRefImpl();
668 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
669 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
670 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
672 const ELFFile<ELFT> &EF = *Obj->getELFFile();
674 auto SecOrErr = EF.getSection(Rel.d.a);
676 return errorToErrorCode(SecOrErr.takeError());
677 const Elf_Shdr *Sec = *SecOrErr;
678 auto SymTabOrErr = EF.getSection(Sec->sh_link);
680 return errorToErrorCode(SymTabOrErr.takeError());
681 const Elf_Shdr *SymTab = *SymTabOrErr;
682 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
683 SymTab->sh_type == ELF::SHT_DYNSYM);
684 auto StrTabSec = EF.getSection(SymTab->sh_link);
686 return errorToErrorCode(StrTabSec.takeError());
687 auto StrTabOrErr = EF.getStringTable(*StrTabSec);
689 return errorToErrorCode(StrTabOrErr.takeError());
690 StringRef StrTab = *StrTabOrErr;
691 uint8_t type = RelRef.getType();
694 switch (Sec->sh_type) {
696 return object_error::parse_failed;
698 // TODO: Read implicit addend from section data.
701 case ELF::SHT_RELA: {
702 const Elf_Rela *ERela = Obj->getRela(Rel);
703 addend = ERela->r_addend;
707 symbol_iterator SI = RelRef.getSymbol();
708 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
710 if (symb->getType() == ELF::STT_SECTION) {
711 Expected<section_iterator> SymSI = SI->getSection();
713 return errorToErrorCode(SymSI.takeError());
714 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
715 auto SecName = EF.getSectionName(SymSec);
717 return errorToErrorCode(SecName.takeError());
720 Expected<StringRef> SymName = symb->getName(StrTab);
722 return errorToErrorCode(SymName.takeError());
725 switch (EF.getHeader()->e_machine) {
728 case ELF::R_X86_64_PC8:
729 case ELF::R_X86_64_PC16:
730 case ELF::R_X86_64_PC32: {
732 raw_string_ostream fmt(fmtbuf);
733 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
735 Result.append(fmtbuf.begin(), fmtbuf.end());
737 case ELF::R_X86_64_8:
738 case ELF::R_X86_64_16:
739 case ELF::R_X86_64_32:
740 case ELF::R_X86_64_32S:
741 case ELF::R_X86_64_64: {
743 raw_string_ostream fmt(fmtbuf);
744 fmt << Target << (addend < 0 ? "" : "+") << addend;
746 Result.append(fmtbuf.begin(), fmtbuf.end());
754 case ELF::EM_AARCH64: {
756 raw_string_ostream fmt(fmtbuf);
759 fmt << (addend < 0 ? "" : "+") << addend;
761 Result.append(fmtbuf.begin(), fmtbuf.end());
767 case ELF::EM_HEXAGON:
773 case ELF::EM_WEBASSEMBLY:
775 case ELF::R_WEBASSEMBLY_DATA: {
777 raw_string_ostream fmt(fmtbuf);
778 fmt << Target << (addend < 0 ? "" : "+") << addend;
780 Result.append(fmtbuf.begin(), fmtbuf.end());
783 case ELF::R_WEBASSEMBLY_FUNCTION:
794 Result.append(res.begin(), res.end());
795 return std::error_code();
798 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
799 const RelocationRef &Rel,
800 SmallVectorImpl<char> &Result) {
801 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
802 return getRelocationValueString(ELF32LE, Rel, Result);
803 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
804 return getRelocationValueString(ELF64LE, Rel, Result);
805 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
806 return getRelocationValueString(ELF32BE, Rel, Result);
807 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
808 return getRelocationValueString(ELF64BE, Rel, Result);
811 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
812 const RelocationRef &Rel,
813 SmallVectorImpl<char> &Result) {
814 symbol_iterator SymI = Rel.getSymbol();
815 Expected<StringRef> SymNameOrErr = SymI->getName();
817 return errorToErrorCode(SymNameOrErr.takeError());
818 StringRef SymName = *SymNameOrErr;
819 Result.append(SymName.begin(), SymName.end());
820 return std::error_code();
823 static void printRelocationTargetName(const MachOObjectFile *O,
824 const MachO::any_relocation_info &RE,
825 raw_string_ostream &fmt) {
826 bool IsScattered = O->isRelocationScattered(RE);
828 // Target of a scattered relocation is an address. In the interest of
829 // generating pretty output, scan through the symbol table looking for a
830 // symbol that aligns with that address. If we find one, print it.
831 // Otherwise, we just print the hex address of the target.
833 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
835 for (const SymbolRef &Symbol : O->symbols()) {
837 Expected<uint64_t> Addr = Symbol.getAddress();
839 report_error(O->getFileName(), Addr.takeError());
842 Expected<StringRef> Name = Symbol.getName();
844 report_error(O->getFileName(), Name.takeError());
849 // If we couldn't find a symbol that this relocation refers to, try
850 // to find a section beginning instead.
851 for (const SectionRef &Section : ToolSectionFilter(*O)) {
855 uint64_t Addr = Section.getAddress();
858 if ((ec = Section.getName(Name)))
859 report_error(O->getFileName(), ec);
864 fmt << format("0x%x", Val);
869 bool isExtern = O->getPlainRelocationExternal(RE);
870 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
873 symbol_iterator SI = O->symbol_begin();
875 Expected<StringRef> SOrErr = SI->getName();
877 report_error(O->getFileName(), SOrErr.takeError());
880 section_iterator SI = O->section_begin();
881 // Adjust for the fact that sections are 1-indexed.
882 advance(SI, Val - 1);
889 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
890 const RelocationRef &RelRef,
891 SmallVectorImpl<char> &Result) {
892 DataRefImpl Rel = RelRef.getRawDataRefImpl();
893 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
895 unsigned Arch = Obj->getArch();
898 raw_string_ostream fmt(fmtbuf);
899 unsigned Type = Obj->getAnyRelocationType(RE);
900 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
902 // Determine any addends that should be displayed with the relocation.
903 // These require decoding the relocation type, which is triple-specific.
905 // X86_64 has entirely custom relocation types.
906 if (Arch == Triple::x86_64) {
907 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
910 case MachO::X86_64_RELOC_GOT_LOAD:
911 case MachO::X86_64_RELOC_GOT: {
912 printRelocationTargetName(Obj, RE, fmt);
918 case MachO::X86_64_RELOC_SUBTRACTOR: {
919 DataRefImpl RelNext = Rel;
920 Obj->moveRelocationNext(RelNext);
921 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
923 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
924 // X86_64_RELOC_UNSIGNED.
925 // NOTE: Scattered relocations don't exist on x86_64.
926 unsigned RType = Obj->getAnyRelocationType(RENext);
927 if (RType != MachO::X86_64_RELOC_UNSIGNED)
928 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
929 "X86_64_RELOC_SUBTRACTOR.");
931 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
932 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
933 printRelocationTargetName(Obj, RENext, fmt);
935 printRelocationTargetName(Obj, RE, fmt);
938 case MachO::X86_64_RELOC_TLV:
939 printRelocationTargetName(Obj, RE, fmt);
944 case MachO::X86_64_RELOC_SIGNED_1:
945 printRelocationTargetName(Obj, RE, fmt);
948 case MachO::X86_64_RELOC_SIGNED_2:
949 printRelocationTargetName(Obj, RE, fmt);
952 case MachO::X86_64_RELOC_SIGNED_4:
953 printRelocationTargetName(Obj, RE, fmt);
957 printRelocationTargetName(Obj, RE, fmt);
960 // X86 and ARM share some relocation types in common.
961 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
962 Arch == Triple::ppc) {
963 // Generic relocation types...
965 case MachO::GENERIC_RELOC_PAIR: // prints no info
966 return std::error_code();
967 case MachO::GENERIC_RELOC_SECTDIFF: {
968 DataRefImpl RelNext = Rel;
969 Obj->moveRelocationNext(RelNext);
970 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
972 // X86 sect diff's must be followed by a relocation of type
973 // GENERIC_RELOC_PAIR.
974 unsigned RType = Obj->getAnyRelocationType(RENext);
976 if (RType != MachO::GENERIC_RELOC_PAIR)
977 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
978 "GENERIC_RELOC_SECTDIFF.");
980 printRelocationTargetName(Obj, RE, fmt);
982 printRelocationTargetName(Obj, RENext, fmt);
987 if (Arch == Triple::x86 || Arch == Triple::ppc) {
989 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
990 DataRefImpl RelNext = Rel;
991 Obj->moveRelocationNext(RelNext);
992 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
994 // X86 sect diff's must be followed by a relocation of type
995 // GENERIC_RELOC_PAIR.
996 unsigned RType = Obj->getAnyRelocationType(RENext);
997 if (RType != MachO::GENERIC_RELOC_PAIR)
998 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
999 "GENERIC_RELOC_LOCAL_SECTDIFF.");
1001 printRelocationTargetName(Obj, RE, fmt);
1003 printRelocationTargetName(Obj, RENext, fmt);
1006 case MachO::GENERIC_RELOC_TLV: {
1007 printRelocationTargetName(Obj, RE, fmt);
1014 printRelocationTargetName(Obj, RE, fmt);
1016 } else { // ARM-specific relocations
1018 case MachO::ARM_RELOC_HALF:
1019 case MachO::ARM_RELOC_HALF_SECTDIFF: {
1020 // Half relocations steal a bit from the length field to encode
1021 // whether this is an upper16 or a lower16 relocation.
1022 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
1025 fmt << ":upper16:(";
1027 fmt << ":lower16:(";
1028 printRelocationTargetName(Obj, RE, fmt);
1030 DataRefImpl RelNext = Rel;
1031 Obj->moveRelocationNext(RelNext);
1032 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
1034 // ARM half relocs must be followed by a relocation of type
1036 unsigned RType = Obj->getAnyRelocationType(RENext);
1037 if (RType != MachO::ARM_RELOC_PAIR)
1038 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
1041 // NOTE: The half of the target virtual address is stashed in the
1042 // address field of the secondary relocation, but we can't reverse
1043 // engineer the constant offset from it without decoding the movw/movt
1044 // instruction to find the other half in its immediate field.
1046 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
1047 // symbol/section pointer of the follow-on relocation.
1048 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1050 printRelocationTargetName(Obj, RENext, fmt);
1056 default: { printRelocationTargetName(Obj, RE, fmt); }
1060 printRelocationTargetName(Obj, RE, fmt);
1063 Result.append(fmtbuf.begin(), fmtbuf.end());
1064 return std::error_code();
1067 static std::error_code getRelocationValueString(const RelocationRef &Rel,
1068 SmallVectorImpl<char> &Result) {
1069 const ObjectFile *Obj = Rel.getObject();
1070 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
1071 return getRelocationValueString(ELF, Rel, Result);
1072 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
1073 return getRelocationValueString(COFF, Rel, Result);
1074 auto *MachO = cast<MachOObjectFile>(Obj);
1075 return getRelocationValueString(MachO, Rel, Result);
1078 /// @brief Indicates whether this relocation should hidden when listing
1079 /// relocations, usually because it is the trailing part of a multipart
1080 /// relocation that will be printed as part of the leading relocation.
1081 static bool getHidden(RelocationRef RelRef) {
1082 const ObjectFile *Obj = RelRef.getObject();
1083 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
1087 unsigned Arch = MachO->getArch();
1088 DataRefImpl Rel = RelRef.getRawDataRefImpl();
1089 uint64_t Type = MachO->getRelocationType(Rel);
1091 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
1092 // is always hidden.
1093 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
1094 if (Type == MachO::GENERIC_RELOC_PAIR)
1096 } else if (Arch == Triple::x86_64) {
1097 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
1098 // an X86_64_RELOC_SUBTRACTOR.
1099 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
1100 DataRefImpl RelPrev = Rel;
1102 uint64_t PrevType = MachO->getRelocationType(RelPrev);
1103 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
1111 static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1112 assert(Obj->isELF());
1113 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1114 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1115 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1116 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1117 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1118 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1119 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1120 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1121 llvm_unreachable("Unsupported binary format");
1124 template <class ELFT> static void
1125 addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
1126 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1127 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
1128 uint8_t SymbolType = Symbol.getELFType();
1129 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
1132 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1134 report_error(Obj->getFileName(), AddressOrErr.takeError());
1135 uint64_t Address = *AddressOrErr;
1137 Expected<StringRef> Name = Symbol.getName();
1139 report_error(Obj->getFileName(), Name.takeError());
1143 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1145 report_error(Obj->getFileName(), SectionOrErr.takeError());
1146 section_iterator SecI = *SectionOrErr;
1147 if (SecI == Obj->section_end())
1150 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1155 addDynamicElfSymbols(const ObjectFile *Obj,
1156 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1157 assert(Obj->isELF());
1158 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1159 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
1160 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1161 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
1162 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1163 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
1164 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1165 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
1167 llvm_unreachable("Unsupported binary format");
1170 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
1171 if (StartAddress > StopAddress)
1172 error("Start address should be less than stop address");
1174 const Target *TheTarget = getTarget(Obj);
1176 // Package up features to be passed to target/subtarget
1177 SubtargetFeatures Features = Obj->getFeatures();
1178 if (MAttrs.size()) {
1179 for (unsigned i = 0; i != MAttrs.size(); ++i)
1180 Features.AddFeature(MAttrs[i]);
1183 std::unique_ptr<const MCRegisterInfo> MRI(
1184 TheTarget->createMCRegInfo(TripleName));
1186 report_error(Obj->getFileName(), "no register info for target " +
1189 // Set up disassembler.
1190 std::unique_ptr<const MCAsmInfo> AsmInfo(
1191 TheTarget->createMCAsmInfo(*MRI, TripleName));
1193 report_error(Obj->getFileName(), "no assembly info for target " +
1195 std::unique_ptr<const MCSubtargetInfo> STI(
1196 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1198 report_error(Obj->getFileName(), "no subtarget info for target " +
1200 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1202 report_error(Obj->getFileName(), "no instruction info for target " +
1204 MCObjectFileInfo MOFI;
1205 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1206 // FIXME: for now initialize MCObjectFileInfo with default values
1207 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, CodeModel::Default, Ctx);
1209 std::unique_ptr<MCDisassembler> DisAsm(
1210 TheTarget->createMCDisassembler(*STI, Ctx));
1212 report_error(Obj->getFileName(), "no disassembler for target " +
1215 std::unique_ptr<const MCInstrAnalysis> MIA(
1216 TheTarget->createMCInstrAnalysis(MII.get()));
1218 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1219 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1220 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
1222 report_error(Obj->getFileName(), "no instruction printer for target " +
1224 IP->setPrintImmHex(PrintImmHex);
1225 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
1227 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
1228 "\t\t\t%08" PRIx64 ": ";
1230 SourcePrinter SP(Obj, TheTarget->getName());
1232 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1233 // in RelocSecs contain the relocations for section S.
1235 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
1236 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1237 section_iterator Sec2 = Section.getRelocatedSection();
1238 if (Sec2 != Obj->section_end())
1239 SectionRelocMap[*Sec2].push_back(Section);
1242 // Create a mapping from virtual address to symbol name. This is used to
1243 // pretty print the symbols while disassembling.
1244 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1245 for (const SymbolRef &Symbol : Obj->symbols()) {
1246 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1248 report_error(Obj->getFileName(), AddressOrErr.takeError());
1249 uint64_t Address = *AddressOrErr;
1251 Expected<StringRef> Name = Symbol.getName();
1253 report_error(Obj->getFileName(), Name.takeError());
1257 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1259 report_error(Obj->getFileName(), SectionOrErr.takeError());
1260 section_iterator SecI = *SectionOrErr;
1261 if (SecI == Obj->section_end())
1264 uint8_t SymbolType = ELF::STT_NOTYPE;
1266 SymbolType = getElfSymbolType(Obj, Symbol);
1268 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1271 if (AllSymbols.empty() && Obj->isELF())
1272 addDynamicElfSymbols(Obj, AllSymbols);
1274 // Create a mapping from virtual address to section.
1275 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1276 for (SectionRef Sec : Obj->sections())
1277 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1278 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1280 // Linked executables (.exe and .dll files) typically don't include a real
1281 // symbol table but they might contain an export table.
1282 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1283 for (const auto &ExportEntry : COFFObj->export_directories()) {
1285 error(ExportEntry.getSymbolName(Name));
1289 error(ExportEntry.getExportRVA(RVA));
1291 uint64_t VA = COFFObj->getImageBase() + RVA;
1292 auto Sec = std::upper_bound(
1293 SectionAddresses.begin(), SectionAddresses.end(), VA,
1294 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1295 return LHS < RHS.first;
1297 if (Sec != SectionAddresses.begin())
1300 Sec = SectionAddresses.end();
1302 if (Sec != SectionAddresses.end())
1303 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
1307 // Sort all the symbols, this allows us to use a simple binary search to find
1308 // a symbol near an address.
1309 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1310 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1312 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1313 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
1316 uint64_t SectionAddr = Section.getAddress();
1317 uint64_t SectSize = Section.getSize();
1321 // Get the list of all the symbols in this section.
1322 SectionSymbolsTy &Symbols = AllSymbols[Section];
1323 std::vector<uint64_t> DataMappingSymsAddr;
1324 std::vector<uint64_t> TextMappingSymsAddr;
1325 if (isArmElf(Obj)) {
1326 for (const auto &Symb : Symbols) {
1327 uint64_t Address = std::get<0>(Symb);
1328 StringRef Name = std::get<1>(Symb);
1329 if (Name.startswith("$d"))
1330 DataMappingSymsAddr.push_back(Address - SectionAddr);
1331 if (Name.startswith("$x"))
1332 TextMappingSymsAddr.push_back(Address - SectionAddr);
1333 if (Name.startswith("$a"))
1334 TextMappingSymsAddr.push_back(Address - SectionAddr);
1335 if (Name.startswith("$t"))
1336 TextMappingSymsAddr.push_back(Address - SectionAddr);
1340 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1341 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
1343 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1344 // AMDGPU disassembler uses symbolizer for printing labels
1345 std::unique_ptr<MCRelocationInfo> RelInfo(
1346 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1348 std::unique_ptr<MCSymbolizer> Symbolizer(
1349 TheTarget->createMCSymbolizer(
1350 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1351 DisAsm->setSymbolizer(std::move(Symbolizer));
1355 // Make a list of all the relocations for this section.
1356 std::vector<RelocationRef> Rels;
1358 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1359 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1360 Rels.push_back(Reloc);
1365 // Sort relocations by address.
1366 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
1368 StringRef SegmentName = "";
1369 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
1370 DataRefImpl DR = Section.getRawDataRefImpl();
1371 SegmentName = MachO->getSectionFinalSegmentName(DR);
1374 error(Section.getName(name));
1376 if ((SectionAddr <= StopAddress) &&
1377 (SectionAddr + SectSize) >= StartAddress) {
1378 outs() << "Disassembly of section ";
1379 if (!SegmentName.empty())
1380 outs() << SegmentName << ",";
1381 outs() << name << ':';
1384 // If the section has no symbol at the start, just insert a dummy one.
1385 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
1386 Symbols.insert(Symbols.begin(),
1387 std::make_tuple(SectionAddr, name, Section.isText()
1389 : ELF::STT_OBJECT));
1392 SmallString<40> Comments;
1393 raw_svector_ostream CommentStream(Comments);
1396 error(Section.getContents(BytesStr));
1397 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1403 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1404 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
1405 // Disassemble symbol by symbol.
1406 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
1407 uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr;
1408 // The end is either the section end or the beginning of the next
1411 (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr;
1412 // Don't try to disassemble beyond the end of section contents.
1415 // If this symbol has the same address as the next symbol, then skip it.
1419 // Check if we need to skip symbol
1420 // Skip if the symbol's data is not between StartAddress and StopAddress
1421 if (End + SectionAddr < StartAddress ||
1422 Start + SectionAddr > StopAddress) {
1426 // Stop disassembly at the stop address specified
1427 if (End + SectionAddr > StopAddress)
1428 End = StopAddress - SectionAddr;
1430 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1431 // make size 4 bytes folded
1432 End = Start + ((End - Start) & ~0x3ull);
1433 if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1434 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1438 std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1439 // cut trailing zeroes at the end of kernel
1440 // cut up to 256 bytes
1441 const uint64_t EndAlign = 256;
1442 const auto Limit = End - (std::min)(EndAlign, End - Start);
1443 while (End > Limit &&
1444 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1449 outs() << '\n' << std::get<1>(Symbols[si]) << ":\n";
1452 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1454 raw_ostream &DebugOut = nulls();
1457 for (Index = Start; Index < End; Index += Size) {
1460 if (Index + SectionAddr < StartAddress ||
1461 Index + SectionAddr > StopAddress) {
1462 // skip byte by byte till StartAddress is reached
1466 // AArch64 ELF binaries can interleave data and text in the
1467 // same section. We rely on the markers introduced to
1468 // understand what we need to dump. If the data marker is within a
1469 // function, it is denoted as a word/short etc
1470 if (isArmElf(Obj) && std::get<2>(Symbols[si]) != ELF::STT_OBJECT &&
1472 uint64_t Stride = 0;
1474 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1475 DataMappingSymsAddr.end(), Index);
1476 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1478 while (Index < End) {
1479 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1481 if (Index + 4 <= End) {
1483 dumpBytes(Bytes.slice(Index, 4), outs());
1484 outs() << "\t.word\t";
1486 if (Obj->isLittleEndian()) {
1488 reinterpret_cast<const support::ulittle32_t *>(
1489 Bytes.data() + Index);
1492 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1493 Bytes.data() + Index);
1496 outs() << "0x" << format("%08" PRIx32, Data);
1497 } else if (Index + 2 <= End) {
1499 dumpBytes(Bytes.slice(Index, 2), outs());
1500 outs() << "\t\t.short\t";
1502 if (Obj->isLittleEndian()) {
1504 reinterpret_cast<const support::ulittle16_t *>(
1505 Bytes.data() + Index);
1509 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1513 outs() << "0x" << format("%04" PRIx16, Data);
1516 dumpBytes(Bytes.slice(Index, 1), outs());
1517 outs() << "\t\t.byte\t";
1518 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
1522 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1523 TextMappingSymsAddr.end(), Index);
1524 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1530 // If there is a data symbol inside an ELF text section and we are only
1531 // disassembling text (applicable all architectures),
1532 // we are in a situation where we must print the data and not
1534 if (Obj->isELF() && std::get<2>(Symbols[si]) == ELF::STT_OBJECT &&
1535 !DisassembleAll && Section.isText()) {
1536 // print out data up to 8 bytes at a time in hex and ascii
1537 uint8_t AsciiData[9] = {'\0'};
1541 for (Index = Start; Index < End; Index += 1) {
1542 if (((SectionAddr + Index) < StartAddress) ||
1543 ((SectionAddr + Index) > StopAddress))
1545 if (NumBytes == 0) {
1546 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1549 Byte = Bytes.slice(Index)[0];
1550 outs() << format(" %02x", Byte);
1551 AsciiData[NumBytes] = isprint(Byte) ? Byte : '.';
1553 uint8_t IndentOffset = 0;
1555 if (Index == End - 1 || NumBytes > 8) {
1556 // Indent the space for less than 8 bytes data.
1557 // 2 spaces for byte and one for space between bytes
1558 IndentOffset = 3 * (8 - NumBytes);
1559 for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1560 AsciiData[Excess] = '\0';
1563 if (NumBytes == 8) {
1564 AsciiData[8] = '\0';
1565 outs() << std::string(IndentOffset, ' ') << " ";
1566 outs() << reinterpret_cast<char *>(AsciiData);
1575 // Disassemble a real instruction or a data when disassemble all is
1577 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1578 SectionAddr + Index, DebugOut,
1583 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
1584 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
1586 outs() << CommentStream.str();
1589 // Try to resolve the target of a call, tail call, etc. to a specific
1591 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1592 MIA->isConditionalBranch(Inst))) {
1594 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1595 // In a relocatable object, the target's section must reside in
1596 // the same section as the call instruction or it is accessed
1597 // through a relocation.
1599 // In a non-relocatable object, the target may be in any section.
1601 // N.B. We don't walk the relocations in the relocatable case yet.
1602 auto *TargetSectionSymbols = &Symbols;
1603 if (!Obj->isRelocatableObject()) {
1604 auto SectionAddress = std::upper_bound(
1605 SectionAddresses.begin(), SectionAddresses.end(), Target,
1607 const std::pair<uint64_t, SectionRef> &RHS) {
1608 return LHS < RHS.first;
1610 if (SectionAddress != SectionAddresses.begin()) {
1612 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1614 TargetSectionSymbols = nullptr;
1618 // Find the first symbol in the section whose offset is less than
1619 // or equal to the target.
1620 if (TargetSectionSymbols) {
1621 auto TargetSym = std::upper_bound(
1622 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1623 Target, [](uint64_t LHS,
1624 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1625 return LHS < std::get<0>(RHS);
1627 if (TargetSym != TargetSectionSymbols->begin()) {
1629 uint64_t TargetAddress = std::get<0>(*TargetSym);
1630 StringRef TargetName = std::get<1>(*TargetSym);
1631 outs() << " <" << TargetName;
1632 uint64_t Disp = Target - TargetAddress;
1634 outs() << "+0x" << utohexstr(Disp);
1642 // Print relocation for instruction.
1643 while (rel_cur != rel_end) {
1644 bool hidden = getHidden(*rel_cur);
1645 uint64_t addr = rel_cur->getOffset();
1646 SmallString<16> name;
1647 SmallString<32> val;
1649 // If this relocation is hidden, skip it.
1650 if (hidden || ((SectionAddr + addr) < StartAddress)) {
1655 // Stop when rel_cur's address is past the current instruction.
1656 if (addr >= Index + Size) break;
1657 rel_cur->getTypeName(name);
1658 error(getRelocationValueString(*rel_cur, val));
1659 outs() << format(Fmt.data(), SectionAddr + addr) << name
1660 << "\t" << val << "\n";
1668 void llvm::PrintRelocations(const ObjectFile *Obj) {
1669 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1671 // Regular objdump doesn't print relocations in non-relocatable object
1673 if (!Obj->isRelocatableObject())
1676 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1677 if (Section.relocation_begin() == Section.relocation_end())
1680 error(Section.getName(secname));
1681 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
1682 for (const RelocationRef &Reloc : Section.relocations()) {
1683 bool hidden = getHidden(Reloc);
1684 uint64_t address = Reloc.getOffset();
1685 SmallString<32> relocname;
1686 SmallString<32> valuestr;
1687 if (address < StartAddress || address > StopAddress || hidden)
1689 Reloc.getTypeName(relocname);
1690 error(getRelocationValueString(Reloc, valuestr));
1691 outs() << format(Fmt.data(), address) << " " << relocname << " "
1692 << valuestr << "\n";
1698 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
1699 outs() << "Sections:\n"
1700 "Idx Name Size Address Type\n";
1702 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1704 error(Section.getName(Name));
1705 uint64_t Address = Section.getAddress();
1706 uint64_t Size = Section.getSize();
1707 bool Text = Section.isText();
1708 bool Data = Section.isData();
1709 bool BSS = Section.isBSS();
1710 std::string Type = (std::string(Text ? "TEXT " : "") +
1711 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1712 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1713 Name.str().c_str(), Size, Address, Type.c_str());
1718 void llvm::PrintSectionContents(const ObjectFile *Obj) {
1720 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1723 error(Section.getName(Name));
1724 uint64_t BaseAddr = Section.getAddress();
1725 uint64_t Size = Section.getSize();
1729 outs() << "Contents of section " << Name << ":\n";
1730 if (Section.isBSS()) {
1731 outs() << format("<skipping contents of bss section at [%04" PRIx64
1732 ", %04" PRIx64 ")>\n",
1733 BaseAddr, BaseAddr + Size);
1737 error(Section.getContents(Contents));
1739 // Dump out the content as hex and printable ascii characters.
1740 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1741 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1742 // Dump line of hex.
1743 for (std::size_t i = 0; i < 16; ++i) {
1744 if (i != 0 && i % 4 == 0)
1747 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1748 << hexdigit(Contents[addr + i] & 0xF, true);
1754 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1755 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1756 outs() << Contents[addr + i];
1765 void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1766 StringRef ArchitectureName) {
1767 outs() << "SYMBOL TABLE:\n";
1769 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1770 printCOFFSymbolTable(coff);
1773 for (const SymbolRef &Symbol : o->symbols()) {
1774 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1775 if (!AddressOrError)
1776 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError(),
1778 uint64_t Address = *AddressOrError;
1779 if ((Address < StartAddress) || (Address > StopAddress))
1781 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1783 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError(),
1785 SymbolRef::Type Type = *TypeOrError;
1786 uint32_t Flags = Symbol.getFlags();
1787 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1789 report_error(ArchiveName, o->getFileName(), SectionOrErr.takeError(),
1791 section_iterator Section = *SectionOrErr;
1793 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1794 Section->getName(Name);
1796 Expected<StringRef> NameOrErr = Symbol.getName();
1798 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1803 bool Global = Flags & SymbolRef::SF_Global;
1804 bool Weak = Flags & SymbolRef::SF_Weak;
1805 bool Absolute = Flags & SymbolRef::SF_Absolute;
1806 bool Common = Flags & SymbolRef::SF_Common;
1807 bool Hidden = Flags & SymbolRef::SF_Hidden;
1810 if (Type != SymbolRef::ST_Unknown)
1811 GlobLoc = Global ? 'g' : 'l';
1812 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1814 char FileFunc = ' ';
1815 if (Type == SymbolRef::ST_File)
1817 else if (Type == SymbolRef::ST_Function)
1820 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1823 outs() << format(Fmt, Address) << " "
1824 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1825 << (Weak ? 'w' : ' ') // Weak?
1826 << ' ' // Constructor. Not supported yet.
1827 << ' ' // Warning. Not supported yet.
1828 << ' ' // Indirect reference to another symbol.
1829 << Debug // Debugging (d) or dynamic (D) symbol.
1830 << FileFunc // Name of function (F), file (f) or object (O).
1834 } else if (Common) {
1836 } else if (Section == o->section_end()) {
1839 if (const MachOObjectFile *MachO =
1840 dyn_cast<const MachOObjectFile>(o)) {
1841 DataRefImpl DR = Section->getRawDataRefImpl();
1842 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1843 outs() << SegmentName << ",";
1845 StringRef SectionName;
1846 error(Section->getName(SectionName));
1847 outs() << SectionName;
1851 if (Common || isa<ELFObjectFileBase>(o)) {
1853 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1854 outs() << format("\t %08" PRIx64 " ", Val);
1858 outs() << ".hidden ";
1865 static void PrintUnwindInfo(const ObjectFile *o) {
1866 outs() << "Unwind info:\n\n";
1868 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1869 printCOFFUnwindInfo(coff);
1870 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1871 printMachOUnwindInfo(MachO);
1873 // TODO: Extract DWARF dump tool to objdump.
1874 errs() << "This operation is only currently supported "
1875 "for COFF and MachO object files.\n";
1880 void llvm::printExportsTrie(const ObjectFile *o) {
1881 outs() << "Exports trie:\n";
1882 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1883 printMachOExportsTrie(MachO);
1885 errs() << "This operation is only currently supported "
1886 "for Mach-O executable files.\n";
1891 void llvm::printRebaseTable(ObjectFile *o) {
1892 outs() << "Rebase table:\n";
1893 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1894 printMachORebaseTable(MachO);
1896 errs() << "This operation is only currently supported "
1897 "for Mach-O executable files.\n";
1902 void llvm::printBindTable(ObjectFile *o) {
1903 outs() << "Bind table:\n";
1904 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1905 printMachOBindTable(MachO);
1907 errs() << "This operation is only currently supported "
1908 "for Mach-O executable files.\n";
1913 void llvm::printLazyBindTable(ObjectFile *o) {
1914 outs() << "Lazy bind table:\n";
1915 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1916 printMachOLazyBindTable(MachO);
1918 errs() << "This operation is only currently supported "
1919 "for Mach-O executable files.\n";
1924 void llvm::printWeakBindTable(ObjectFile *o) {
1925 outs() << "Weak bind table:\n";
1926 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1927 printMachOWeakBindTable(MachO);
1929 errs() << "This operation is only currently supported "
1930 "for Mach-O executable files.\n";
1935 /// Dump the raw contents of the __clangast section so the output can be piped
1936 /// into llvm-bcanalyzer.
1937 void llvm::printRawClangAST(const ObjectFile *Obj) {
1938 if (outs().is_displayed()) {
1939 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1940 "the clang ast section.\n"
1941 "Please redirect the output to a file or another program such as "
1942 "llvm-bcanalyzer.\n";
1946 StringRef ClangASTSectionName("__clangast");
1947 if (isa<COFFObjectFile>(Obj)) {
1948 ClangASTSectionName = "clangast";
1951 Optional<object::SectionRef> ClangASTSection;
1952 for (auto Sec : ToolSectionFilter(*Obj)) {
1955 if (Name == ClangASTSectionName) {
1956 ClangASTSection = Sec;
1960 if (!ClangASTSection)
1963 StringRef ClangASTContents;
1964 error(ClangASTSection.getValue().getContents(ClangASTContents));
1965 outs().write(ClangASTContents.data(), ClangASTContents.size());
1968 static void printFaultMaps(const ObjectFile *Obj) {
1969 const char *FaultMapSectionName = nullptr;
1971 if (isa<ELFObjectFileBase>(Obj)) {
1972 FaultMapSectionName = ".llvm_faultmaps";
1973 } else if (isa<MachOObjectFile>(Obj)) {
1974 FaultMapSectionName = "__llvm_faultmaps";
1976 errs() << "This operation is only currently supported "
1977 "for ELF and Mach-O executable files.\n";
1981 Optional<object::SectionRef> FaultMapSection;
1983 for (auto Sec : ToolSectionFilter(*Obj)) {
1986 if (Name == FaultMapSectionName) {
1987 FaultMapSection = Sec;
1992 outs() << "FaultMap table:\n";
1994 if (!FaultMapSection.hasValue()) {
1995 outs() << "<not found>\n";
1999 StringRef FaultMapContents;
2000 error(FaultMapSection.getValue().getContents(FaultMapContents));
2002 FaultMapParser FMP(FaultMapContents.bytes_begin(),
2003 FaultMapContents.bytes_end());
2008 static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) {
2010 return printELFFileHeader(o);
2012 return printCOFFFileHeader(o);
2014 return printWasmFileHeader(o);
2016 printMachOFileHeader(o);
2018 printMachOLoadCommands(o);
2021 report_error(o->getFileName(), "Invalid/Unsupported object file format");
2024 static void DumpObject(ObjectFile *o, const Archive *a = nullptr) {
2025 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
2026 // Avoid other output when using a raw option.
2030 outs() << a->getFileName() << "(" << o->getFileName() << ")";
2032 outs() << o->getFileName();
2033 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
2037 DisassembleObject(o, Relocations);
2038 if (Relocations && !Disassemble)
2039 PrintRelocations(o);
2041 PrintSectionHeaders(o);
2042 if (SectionContents)
2043 PrintSectionContents(o);
2045 PrintSymbolTable(o, ArchiveName);
2048 if (PrivateHeaders || FirstPrivateHeader)
2049 printPrivateFileHeaders(o, FirstPrivateHeader);
2051 printExportsTrie(o);
2053 printRebaseTable(o);
2057 printLazyBindTable(o);
2059 printWeakBindTable(o);
2061 printRawClangAST(o);
2064 if (DwarfDumpType != DIDT_Null) {
2065 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o));
2066 // Dump the complete DWARF structure.
2067 DIDumpOptions DumpOpts;
2068 DumpOpts.DumpType = DwarfDumpType;
2069 DumpOpts.DumpEH = true;
2070 DICtx->dump(outs(), DumpOpts);
2074 static void DumpObject(const COFFImportFile *I, const Archive *A) {
2075 StringRef ArchiveName = A ? A->getFileName() : "";
2077 // Avoid other output when using a raw option.
2080 << ArchiveName << "(" << I->getFileName() << ")"
2081 << ":\tfile format COFF-import-file"
2085 printCOFFSymbolTable(I);
2088 /// @brief Dump each object file in \a a;
2089 static void DumpArchive(const Archive *a) {
2090 Error Err = Error::success();
2091 for (auto &C : a->children(Err)) {
2092 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2094 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2095 report_error(a->getFileName(), C, std::move(E));
2098 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2100 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2103 report_error(a->getFileName(), object_error::invalid_file_type);
2106 report_error(a->getFileName(), std::move(Err));
2109 /// @brief Open file and figure out how to dump it.
2110 static void DumpInput(StringRef file) {
2112 // If we are using the Mach-O specific object file parser, then let it parse
2113 // the file and process the command line options. So the -arch flags can
2114 // be used to select specific slices, etc.
2116 ParseInputMachO(file);
2120 // Attempt to open the binary.
2121 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2123 report_error(file, BinaryOrErr.takeError());
2124 Binary &Binary = *BinaryOrErr.get().getBinary();
2126 if (Archive *a = dyn_cast<Archive>(&Binary))
2128 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
2131 report_error(file, object_error::invalid_file_type);
2134 int main(int argc, char **argv) {
2135 // Print a stack trace if we signal out.
2136 sys::PrintStackTraceOnErrorSignal(argv[0]);
2137 PrettyStackTraceProgram X(argc, argv);
2138 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
2140 // Initialize targets and assembly printers/parsers.
2141 llvm::InitializeAllTargetInfos();
2142 llvm::InitializeAllTargetMCs();
2143 llvm::InitializeAllDisassemblers();
2145 // Register the target printer for --version.
2146 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2148 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2149 TripleName = Triple::normalize(TripleName);
2153 // Defaults to a.out if no filenames specified.
2154 if (InputFilenames.size() == 0)
2155 InputFilenames.push_back("a.out");
2157 if (DisassembleAll || PrintSource || PrintLines)
2166 && !FirstPrivateHeader
2173 && !(UniversalHeaders && MachOOpt)
2174 && !(ArchiveHeaders && MachOOpt)
2175 && !(IndirectSymbols && MachOOpt)
2176 && !(DataInCode && MachOOpt)
2177 && !(LinkOptHints && MachOOpt)
2178 && !(InfoPlist && MachOOpt)
2179 && !(DylibsUsed && MachOOpt)
2180 && !(DylibId && MachOOpt)
2181 && !(ObjcMetaData && MachOOpt)
2182 && !(FilterSections.size() != 0 && MachOOpt)
2184 && DwarfDumpType == DIDT_Null) {
2185 cl::PrintHelpMessage();
2189 std::for_each(InputFilenames.begin(), InputFilenames.end(),
2192 return EXIT_SUCCESS;