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."));
163 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
166 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
167 cl::aliasopt(UnwindInfo));
170 llvm::PrivateHeaders("private-headers",
171 cl::desc("Display format specific file headers"));
174 llvm::FirstPrivateHeader("private-header",
175 cl::desc("Display only the first format specific file "
179 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
180 cl::aliasopt(PrivateHeaders));
183 llvm::PrintImmHex("print-imm-hex",
184 cl::desc("Use hex format for immediate values"));
186 cl::opt<bool> PrintFaultMaps("fault-map-section",
187 cl::desc("Display contents of faultmap section"));
189 cl::opt<DIDumpType> llvm::DwarfDumpType(
190 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
191 cl::values(clEnumValN(DIDT_Frames, "frames", ".debug_frame")));
193 cl::opt<bool> PrintSource(
196 "Display source inlined with disassembly. Implies disassmble object"));
198 cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
199 cl::aliasopt(PrintSource));
201 cl::opt<bool> PrintLines("line-numbers",
202 cl::desc("Display source line numbers with "
203 "disassembly. Implies disassemble object"));
205 cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"),
206 cl::aliasopt(PrintLines));
208 cl::opt<unsigned long long>
209 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
210 cl::value_desc("address"), cl::init(0));
211 cl::opt<unsigned long long>
212 StopAddress("stop-address", cl::desc("Stop disassembly at address"),
213 cl::value_desc("address"), cl::init(UINT64_MAX));
214 static StringRef ToolName;
217 typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
219 class SectionFilterIterator {
221 SectionFilterIterator(FilterPredicate P,
222 llvm::object::section_iterator const &I,
223 llvm::object::section_iterator const &E)
224 : Predicate(std::move(P)), Iterator(I), End(E) {
227 const llvm::object::SectionRef &operator*() const { return *Iterator; }
228 SectionFilterIterator &operator++() {
233 bool operator!=(SectionFilterIterator const &Other) const {
234 return Iterator != Other.Iterator;
238 void ScanPredicate() {
239 while (Iterator != End && !Predicate(*Iterator)) {
243 FilterPredicate Predicate;
244 llvm::object::section_iterator Iterator;
245 llvm::object::section_iterator End;
248 class SectionFilter {
250 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
251 : Predicate(std::move(P)), Object(O) {}
252 SectionFilterIterator begin() {
253 return SectionFilterIterator(Predicate, Object.section_begin(),
254 Object.section_end());
256 SectionFilterIterator end() {
257 return SectionFilterIterator(Predicate, Object.section_end(),
258 Object.section_end());
262 FilterPredicate Predicate;
263 llvm::object::ObjectFile const &Object;
265 SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
266 return SectionFilter(
267 [](llvm::object::SectionRef const &S) {
268 if (FilterSections.empty())
270 llvm::StringRef String;
271 std::error_code error = S.getName(String);
274 return is_contained(FilterSections, String);
280 void llvm::error(std::error_code EC) {
284 errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
289 LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
290 errs() << ToolName << ": " << Message << ".\n";
295 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
297 errs() << ToolName << ": '" << File << "': " << Message << ".\n";
301 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
302 std::error_code EC) {
304 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
308 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
312 raw_string_ostream OS(Buf);
313 logAllUnhandledErrors(std::move(E), OS, "");
315 errs() << ToolName << ": '" << File << "': " << Buf;
319 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
322 StringRef ArchitectureName) {
324 errs() << ToolName << ": ";
325 if (ArchiveName != "")
326 errs() << ArchiveName << "(" << FileName << ")";
328 errs() << "'" << FileName << "'";
329 if (!ArchitectureName.empty())
330 errs() << " (for architecture " << ArchitectureName << ")";
332 raw_string_ostream OS(Buf);
333 logAllUnhandledErrors(std::move(E), OS, "");
335 errs() << ": " << Buf;
339 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
340 const object::Archive::Child &C,
342 StringRef ArchitectureName) {
343 Expected<StringRef> NameOrErr = C.getName();
344 // TODO: if we have a error getting the name then it would be nice to print
345 // the index of which archive member this is and or its offset in the
346 // archive instead of "???" as the name.
348 consumeError(NameOrErr.takeError());
349 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
351 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
355 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
356 // Figure out the target triple.
357 llvm::Triple TheTriple("unknown-unknown-unknown");
358 if (TripleName.empty()) {
360 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
361 // TheTriple defaults to ELF, and COFF doesn't have an environment:
362 // the best we can do here is indicate that it is mach-o.
364 TheTriple.setObjectFormat(Triple::MachO);
367 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
368 if (COFFObj->getArch() == Triple::thumb)
369 TheTriple.setTriple("thumbv7-windows");
373 TheTriple.setTriple(Triple::normalize(TripleName));
375 // Get the target specific parser.
377 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
381 report_error(Obj->getFileName(), "can't find target: " + Error);
383 error("can't find target: " + Error);
386 // Update the triple name and return the found target.
387 TripleName = TheTriple.getTriple();
391 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
392 return a.getOffset() < b.getOffset();
396 class SourcePrinter {
398 DILineInfo OldLineInfo;
399 const ObjectFile *Obj;
400 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
401 // File name to file contents of source
402 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
403 // Mark the line endings of the cached source
404 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
407 bool cacheSource(std::string File);
410 virtual ~SourcePrinter() {}
411 SourcePrinter() : Obj(nullptr), Symbolizer(nullptr) {}
412 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
413 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
414 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
416 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
418 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
419 StringRef Delimiter = "; ");
422 bool SourcePrinter::cacheSource(std::string File) {
423 auto BufferOrError = MemoryBuffer::getFile(File);
426 // Chomp the file to get lines
427 size_t BufferSize = (*BufferOrError)->getBufferSize();
428 const char *BufferStart = (*BufferOrError)->getBufferStart();
429 for (const char *Start = BufferStart, *End = BufferStart;
430 End < BufferStart + BufferSize; End++)
431 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
432 (*End == '\r' && *(End + 1) == '\n')) {
433 LineCache[File].push_back(StringRef(Start, End - Start));
438 SourceCache[File] = std::move(*BufferOrError);
442 void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
443 StringRef Delimiter) {
446 DILineInfo LineInfo = DILineInfo();
447 auto ExpectecLineInfo =
448 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
449 if (!ExpectecLineInfo)
450 consumeError(ExpectecLineInfo.takeError());
452 LineInfo = *ExpectecLineInfo;
454 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
459 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
461 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
462 if (!cacheSource(LineInfo.FileName))
464 auto FileBuffer = SourceCache.find(LineInfo.FileName);
465 if (FileBuffer != SourceCache.end()) {
466 auto LineBuffer = LineCache.find(LineInfo.FileName);
467 if (LineBuffer != LineCache.end())
468 // Vector begins at 0, line numbers are non-zero
469 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
473 OldLineInfo = LineInfo;
476 static bool isArmElf(const ObjectFile *Obj) {
477 return (Obj->isELF() &&
478 (Obj->getArch() == Triple::aarch64 ||
479 Obj->getArch() == Triple::aarch64_be ||
480 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
481 Obj->getArch() == Triple::thumb ||
482 Obj->getArch() == Triple::thumbeb));
485 class PrettyPrinter {
487 virtual ~PrettyPrinter(){}
488 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
489 ArrayRef<uint8_t> Bytes, uint64_t Address,
490 raw_ostream &OS, StringRef Annot,
491 MCSubtargetInfo const &STI, SourcePrinter *SP) {
492 if (SP && (PrintSource || PrintLines))
493 SP->printSourceLine(OS, Address);
494 OS << format("%8" PRIx64 ":", Address);
495 if (!NoShowRawInsn) {
497 dumpBytes(Bytes, OS);
500 IP.printInst(MI, OS, "", STI);
505 PrettyPrinter PrettyPrinterInst;
506 class HexagonPrettyPrinter : public PrettyPrinter {
508 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
511 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
512 OS << format("%8" PRIx64 ":", Address);
513 if (!NoShowRawInsn) {
515 dumpBytes(Bytes.slice(0, 4), OS);
516 OS << format("%08" PRIx32, opcode);
519 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
520 uint64_t Address, raw_ostream &OS, StringRef Annot,
521 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
522 if (SP && (PrintSource || PrintLines))
523 SP->printSourceLine(OS, Address, "");
525 printLead(Bytes, Address, OS);
531 raw_string_ostream TempStream(Buffer);
532 IP.printInst(MI, TempStream, "", STI);
534 StringRef Contents(Buffer);
535 // Split off bundle attributes
536 auto PacketBundle = Contents.rsplit('\n');
537 // Split off first instruction from the rest
538 auto HeadTail = PacketBundle.first.split('\n');
539 auto Preamble = " { ";
541 while(!HeadTail.first.empty()) {
544 if (SP && (PrintSource || PrintLines))
545 SP->printSourceLine(OS, Address, "");
546 printLead(Bytes, Address, OS);
550 auto Duplex = HeadTail.first.split('\v');
551 if(!Duplex.second.empty()){
554 Inst = Duplex.second;
557 Inst = HeadTail.first;
559 Bytes = Bytes.slice(4);
561 HeadTail = HeadTail.second.split('\n');
563 OS << " } " << PacketBundle.second;
566 HexagonPrettyPrinter HexagonPrettyPrinterInst;
568 class AMDGCNPrettyPrinter : public PrettyPrinter {
570 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
571 uint64_t Address, raw_ostream &OS, StringRef Annot,
572 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
578 SmallString<40> InstStr;
579 raw_svector_ostream IS(InstStr);
581 IP.printInst(MI, IS, "", STI);
583 OS << left_justify(IS.str(), 60) << format("// %012" PRIX64 ": ", Address);
584 typedef support::ulittle32_t U32;
585 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
586 Bytes.size() / sizeof(U32)))
587 // D should be explicitly casted to uint32_t here as it is passed
588 // by format to snprintf as vararg.
589 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
592 OS << "// " << Annot;
595 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
597 class BPFPrettyPrinter : public PrettyPrinter {
599 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
600 uint64_t Address, raw_ostream &OS, StringRef Annot,
601 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
602 if (SP && (PrintSource || PrintLines))
603 SP->printSourceLine(OS, Address);
604 OS << format("%8" PRId64 ":", Address / 8);
605 if (!NoShowRawInsn) {
607 dumpBytes(Bytes, OS);
610 IP.printInst(MI, OS, "", STI);
615 BPFPrettyPrinter BPFPrettyPrinterInst;
617 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
618 switch(Triple.getArch()) {
620 return PrettyPrinterInst;
621 case Triple::hexagon:
622 return HexagonPrettyPrinterInst;
624 return AMDGCNPrettyPrinterInst;
627 return BPFPrettyPrinterInst;
632 template <class ELFT>
633 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
634 const RelocationRef &RelRef,
635 SmallVectorImpl<char> &Result) {
636 DataRefImpl Rel = RelRef.getRawDataRefImpl();
638 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
639 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
640 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
642 const ELFFile<ELFT> &EF = *Obj->getELFFile();
644 auto SecOrErr = EF.getSection(Rel.d.a);
646 return errorToErrorCode(SecOrErr.takeError());
647 const Elf_Shdr *Sec = *SecOrErr;
648 auto SymTabOrErr = EF.getSection(Sec->sh_link);
650 return errorToErrorCode(SymTabOrErr.takeError());
651 const Elf_Shdr *SymTab = *SymTabOrErr;
652 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
653 SymTab->sh_type == ELF::SHT_DYNSYM);
654 auto StrTabSec = EF.getSection(SymTab->sh_link);
656 return errorToErrorCode(StrTabSec.takeError());
657 auto StrTabOrErr = EF.getStringTable(*StrTabSec);
659 return errorToErrorCode(StrTabOrErr.takeError());
660 StringRef StrTab = *StrTabOrErr;
661 uint8_t type = RelRef.getType();
664 switch (Sec->sh_type) {
666 return object_error::parse_failed;
668 // TODO: Read implicit addend from section data.
671 case ELF::SHT_RELA: {
672 const Elf_Rela *ERela = Obj->getRela(Rel);
673 addend = ERela->r_addend;
677 symbol_iterator SI = RelRef.getSymbol();
678 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
680 if (symb->getType() == ELF::STT_SECTION) {
681 Expected<section_iterator> SymSI = SI->getSection();
683 return errorToErrorCode(SymSI.takeError());
684 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
685 auto SecName = EF.getSectionName(SymSec);
687 return errorToErrorCode(SecName.takeError());
690 Expected<StringRef> SymName = symb->getName(StrTab);
692 return errorToErrorCode(SymName.takeError());
695 switch (EF.getHeader()->e_machine) {
698 case ELF::R_X86_64_PC8:
699 case ELF::R_X86_64_PC16:
700 case ELF::R_X86_64_PC32: {
702 raw_string_ostream fmt(fmtbuf);
703 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
705 Result.append(fmtbuf.begin(), fmtbuf.end());
707 case ELF::R_X86_64_8:
708 case ELF::R_X86_64_16:
709 case ELF::R_X86_64_32:
710 case ELF::R_X86_64_32S:
711 case ELF::R_X86_64_64: {
713 raw_string_ostream fmt(fmtbuf);
714 fmt << Target << (addend < 0 ? "" : "+") << addend;
716 Result.append(fmtbuf.begin(), fmtbuf.end());
724 case ELF::EM_AARCH64: {
726 raw_string_ostream fmt(fmtbuf);
729 fmt << (addend < 0 ? "" : "+") << addend;
731 Result.append(fmtbuf.begin(), fmtbuf.end());
737 case ELF::EM_HEXAGON:
743 case ELF::EM_WEBASSEMBLY:
745 case ELF::R_WEBASSEMBLY_DATA: {
747 raw_string_ostream fmt(fmtbuf);
748 fmt << Target << (addend < 0 ? "" : "+") << addend;
750 Result.append(fmtbuf.begin(), fmtbuf.end());
753 case ELF::R_WEBASSEMBLY_FUNCTION:
764 Result.append(res.begin(), res.end());
765 return std::error_code();
768 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
769 const RelocationRef &Rel,
770 SmallVectorImpl<char> &Result) {
771 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
772 return getRelocationValueString(ELF32LE, Rel, Result);
773 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
774 return getRelocationValueString(ELF64LE, Rel, Result);
775 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
776 return getRelocationValueString(ELF32BE, Rel, Result);
777 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
778 return getRelocationValueString(ELF64BE, Rel, Result);
781 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
782 const RelocationRef &Rel,
783 SmallVectorImpl<char> &Result) {
784 symbol_iterator SymI = Rel.getSymbol();
785 Expected<StringRef> SymNameOrErr = SymI->getName();
787 return errorToErrorCode(SymNameOrErr.takeError());
788 StringRef SymName = *SymNameOrErr;
789 Result.append(SymName.begin(), SymName.end());
790 return std::error_code();
793 static void printRelocationTargetName(const MachOObjectFile *O,
794 const MachO::any_relocation_info &RE,
795 raw_string_ostream &fmt) {
796 bool IsScattered = O->isRelocationScattered(RE);
798 // Target of a scattered relocation is an address. In the interest of
799 // generating pretty output, scan through the symbol table looking for a
800 // symbol that aligns with that address. If we find one, print it.
801 // Otherwise, we just print the hex address of the target.
803 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
805 for (const SymbolRef &Symbol : O->symbols()) {
807 Expected<uint64_t> Addr = Symbol.getAddress();
809 report_error(O->getFileName(), Addr.takeError());
812 Expected<StringRef> Name = Symbol.getName();
814 report_error(O->getFileName(), Name.takeError());
819 // If we couldn't find a symbol that this relocation refers to, try
820 // to find a section beginning instead.
821 for (const SectionRef &Section : ToolSectionFilter(*O)) {
825 uint64_t Addr = Section.getAddress();
828 if ((ec = Section.getName(Name)))
829 report_error(O->getFileName(), ec);
834 fmt << format("0x%x", Val);
839 bool isExtern = O->getPlainRelocationExternal(RE);
840 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
843 symbol_iterator SI = O->symbol_begin();
845 Expected<StringRef> SOrErr = SI->getName();
847 report_error(O->getFileName(), SOrErr.takeError());
850 section_iterator SI = O->section_begin();
851 // Adjust for the fact that sections are 1-indexed.
852 advance(SI, Val - 1);
859 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
860 const RelocationRef &RelRef,
861 SmallVectorImpl<char> &Result) {
862 DataRefImpl Rel = RelRef.getRawDataRefImpl();
863 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
865 unsigned Arch = Obj->getArch();
868 raw_string_ostream fmt(fmtbuf);
869 unsigned Type = Obj->getAnyRelocationType(RE);
870 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
872 // Determine any addends that should be displayed with the relocation.
873 // These require decoding the relocation type, which is triple-specific.
875 // X86_64 has entirely custom relocation types.
876 if (Arch == Triple::x86_64) {
877 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
880 case MachO::X86_64_RELOC_GOT_LOAD:
881 case MachO::X86_64_RELOC_GOT: {
882 printRelocationTargetName(Obj, RE, fmt);
888 case MachO::X86_64_RELOC_SUBTRACTOR: {
889 DataRefImpl RelNext = Rel;
890 Obj->moveRelocationNext(RelNext);
891 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
893 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
894 // X86_64_RELOC_UNSIGNED.
895 // NOTE: Scattered relocations don't exist on x86_64.
896 unsigned RType = Obj->getAnyRelocationType(RENext);
897 if (RType != MachO::X86_64_RELOC_UNSIGNED)
898 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
899 "X86_64_RELOC_SUBTRACTOR.");
901 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
902 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
903 printRelocationTargetName(Obj, RENext, fmt);
905 printRelocationTargetName(Obj, RE, fmt);
908 case MachO::X86_64_RELOC_TLV:
909 printRelocationTargetName(Obj, RE, fmt);
914 case MachO::X86_64_RELOC_SIGNED_1:
915 printRelocationTargetName(Obj, RE, fmt);
918 case MachO::X86_64_RELOC_SIGNED_2:
919 printRelocationTargetName(Obj, RE, fmt);
922 case MachO::X86_64_RELOC_SIGNED_4:
923 printRelocationTargetName(Obj, RE, fmt);
927 printRelocationTargetName(Obj, RE, fmt);
930 // X86 and ARM share some relocation types in common.
931 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
932 Arch == Triple::ppc) {
933 // Generic relocation types...
935 case MachO::GENERIC_RELOC_PAIR: // prints no info
936 return std::error_code();
937 case MachO::GENERIC_RELOC_SECTDIFF: {
938 DataRefImpl RelNext = Rel;
939 Obj->moveRelocationNext(RelNext);
940 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
942 // X86 sect diff's must be followed by a relocation of type
943 // GENERIC_RELOC_PAIR.
944 unsigned RType = Obj->getAnyRelocationType(RENext);
946 if (RType != MachO::GENERIC_RELOC_PAIR)
947 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
948 "GENERIC_RELOC_SECTDIFF.");
950 printRelocationTargetName(Obj, RE, fmt);
952 printRelocationTargetName(Obj, RENext, fmt);
957 if (Arch == Triple::x86 || Arch == Triple::ppc) {
959 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
960 DataRefImpl RelNext = Rel;
961 Obj->moveRelocationNext(RelNext);
962 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
964 // X86 sect diff's must be followed by a relocation of type
965 // GENERIC_RELOC_PAIR.
966 unsigned RType = Obj->getAnyRelocationType(RENext);
967 if (RType != MachO::GENERIC_RELOC_PAIR)
968 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
969 "GENERIC_RELOC_LOCAL_SECTDIFF.");
971 printRelocationTargetName(Obj, RE, fmt);
973 printRelocationTargetName(Obj, RENext, fmt);
976 case MachO::GENERIC_RELOC_TLV: {
977 printRelocationTargetName(Obj, RE, fmt);
984 printRelocationTargetName(Obj, RE, fmt);
986 } else { // ARM-specific relocations
988 case MachO::ARM_RELOC_HALF:
989 case MachO::ARM_RELOC_HALF_SECTDIFF: {
990 // Half relocations steal a bit from the length field to encode
991 // whether this is an upper16 or a lower16 relocation.
992 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
998 printRelocationTargetName(Obj, RE, fmt);
1000 DataRefImpl RelNext = Rel;
1001 Obj->moveRelocationNext(RelNext);
1002 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
1004 // ARM half relocs must be followed by a relocation of type
1006 unsigned RType = Obj->getAnyRelocationType(RENext);
1007 if (RType != MachO::ARM_RELOC_PAIR)
1008 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
1011 // NOTE: The half of the target virtual address is stashed in the
1012 // address field of the secondary relocation, but we can't reverse
1013 // engineer the constant offset from it without decoding the movw/movt
1014 // instruction to find the other half in its immediate field.
1016 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
1017 // symbol/section pointer of the follow-on relocation.
1018 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1020 printRelocationTargetName(Obj, RENext, fmt);
1026 default: { printRelocationTargetName(Obj, RE, fmt); }
1030 printRelocationTargetName(Obj, RE, fmt);
1033 Result.append(fmtbuf.begin(), fmtbuf.end());
1034 return std::error_code();
1037 static std::error_code getRelocationValueString(const RelocationRef &Rel,
1038 SmallVectorImpl<char> &Result) {
1039 const ObjectFile *Obj = Rel.getObject();
1040 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
1041 return getRelocationValueString(ELF, Rel, Result);
1042 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
1043 return getRelocationValueString(COFF, Rel, Result);
1044 auto *MachO = cast<MachOObjectFile>(Obj);
1045 return getRelocationValueString(MachO, Rel, Result);
1048 /// @brief Indicates whether this relocation should hidden when listing
1049 /// relocations, usually because it is the trailing part of a multipart
1050 /// relocation that will be printed as part of the leading relocation.
1051 static bool getHidden(RelocationRef RelRef) {
1052 const ObjectFile *Obj = RelRef.getObject();
1053 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
1057 unsigned Arch = MachO->getArch();
1058 DataRefImpl Rel = RelRef.getRawDataRefImpl();
1059 uint64_t Type = MachO->getRelocationType(Rel);
1061 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
1062 // is always hidden.
1063 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
1064 if (Type == MachO::GENERIC_RELOC_PAIR)
1066 } else if (Arch == Triple::x86_64) {
1067 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
1068 // an X86_64_RELOC_SUBTRACTOR.
1069 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
1070 DataRefImpl RelPrev = Rel;
1072 uint64_t PrevType = MachO->getRelocationType(RelPrev);
1073 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
1081 static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1082 assert(Obj->isELF());
1083 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1084 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1085 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1086 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1087 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1088 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1089 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1090 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1091 llvm_unreachable("Unsupported binary format");
1094 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
1095 if (StartAddress > StopAddress)
1096 error("Start address should be less than stop address");
1098 const Target *TheTarget = getTarget(Obj);
1100 // Package up features to be passed to target/subtarget
1101 SubtargetFeatures Features = Obj->getFeatures();
1102 if (MAttrs.size()) {
1103 for (unsigned i = 0; i != MAttrs.size(); ++i)
1104 Features.AddFeature(MAttrs[i]);
1107 std::unique_ptr<const MCRegisterInfo> MRI(
1108 TheTarget->createMCRegInfo(TripleName));
1110 report_error(Obj->getFileName(), "no register info for target " +
1113 // Set up disassembler.
1114 std::unique_ptr<const MCAsmInfo> AsmInfo(
1115 TheTarget->createMCAsmInfo(*MRI, TripleName));
1117 report_error(Obj->getFileName(), "no assembly info for target " +
1119 std::unique_ptr<const MCSubtargetInfo> STI(
1120 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1122 report_error(Obj->getFileName(), "no subtarget info for target " +
1124 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1126 report_error(Obj->getFileName(), "no instruction info for target " +
1128 MCObjectFileInfo MOFI;
1129 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1130 // FIXME: for now initialize MCObjectFileInfo with default values
1131 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, CodeModel::Default, Ctx);
1133 std::unique_ptr<MCDisassembler> DisAsm(
1134 TheTarget->createMCDisassembler(*STI, Ctx));
1136 report_error(Obj->getFileName(), "no disassembler for target " +
1139 std::unique_ptr<const MCInstrAnalysis> MIA(
1140 TheTarget->createMCInstrAnalysis(MII.get()));
1142 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1143 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1144 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
1146 report_error(Obj->getFileName(), "no instruction printer for target " +
1148 IP->setPrintImmHex(PrintImmHex);
1149 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
1151 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
1152 "\t\t\t%08" PRIx64 ": ";
1154 SourcePrinter SP(Obj, TheTarget->getName());
1156 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1157 // in RelocSecs contain the relocations for section S.
1159 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
1160 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1161 section_iterator Sec2 = Section.getRelocatedSection();
1162 if (Sec2 != Obj->section_end())
1163 SectionRelocMap[*Sec2].push_back(Section);
1166 // Create a mapping from virtual address to symbol name. This is used to
1167 // pretty print the symbols while disassembling.
1168 typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
1169 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1170 for (const SymbolRef &Symbol : Obj->symbols()) {
1171 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1173 report_error(Obj->getFileName(), AddressOrErr.takeError());
1174 uint64_t Address = *AddressOrErr;
1176 Expected<StringRef> Name = Symbol.getName();
1178 report_error(Obj->getFileName(), Name.takeError());
1182 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1184 report_error(Obj->getFileName(), SectionOrErr.takeError());
1185 section_iterator SecI = *SectionOrErr;
1186 if (SecI == Obj->section_end())
1189 uint8_t SymbolType = ELF::STT_NOTYPE;
1191 SymbolType = getElfSymbolType(Obj, Symbol);
1193 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1197 // Create a mapping from virtual address to section.
1198 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1199 for (SectionRef Sec : Obj->sections())
1200 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1201 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1203 // Linked executables (.exe and .dll files) typically don't include a real
1204 // symbol table but they might contain an export table.
1205 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1206 for (const auto &ExportEntry : COFFObj->export_directories()) {
1208 error(ExportEntry.getSymbolName(Name));
1212 error(ExportEntry.getExportRVA(RVA));
1214 uint64_t VA = COFFObj->getImageBase() + RVA;
1215 auto Sec = std::upper_bound(
1216 SectionAddresses.begin(), SectionAddresses.end(), VA,
1217 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1218 return LHS < RHS.first;
1220 if (Sec != SectionAddresses.begin())
1223 Sec = SectionAddresses.end();
1225 if (Sec != SectionAddresses.end())
1226 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
1230 // Sort all the symbols, this allows us to use a simple binary search to find
1231 // a symbol near an address.
1232 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1233 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1235 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1236 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
1239 uint64_t SectionAddr = Section.getAddress();
1240 uint64_t SectSize = Section.getSize();
1244 // Get the list of all the symbols in this section.
1245 SectionSymbolsTy &Symbols = AllSymbols[Section];
1246 std::vector<uint64_t> DataMappingSymsAddr;
1247 std::vector<uint64_t> TextMappingSymsAddr;
1248 if (isArmElf(Obj)) {
1249 for (const auto &Symb : Symbols) {
1250 uint64_t Address = std::get<0>(Symb);
1251 StringRef Name = std::get<1>(Symb);
1252 if (Name.startswith("$d"))
1253 DataMappingSymsAddr.push_back(Address - SectionAddr);
1254 if (Name.startswith("$x"))
1255 TextMappingSymsAddr.push_back(Address - SectionAddr);
1256 if (Name.startswith("$a"))
1257 TextMappingSymsAddr.push_back(Address - SectionAddr);
1258 if (Name.startswith("$t"))
1259 TextMappingSymsAddr.push_back(Address - SectionAddr);
1263 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1264 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
1266 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1267 // AMDGPU disassembler uses symbolizer for printing labels
1268 std::unique_ptr<MCRelocationInfo> RelInfo(
1269 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1271 std::unique_ptr<MCSymbolizer> Symbolizer(
1272 TheTarget->createMCSymbolizer(
1273 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1274 DisAsm->setSymbolizer(std::move(Symbolizer));
1278 // Make a list of all the relocations for this section.
1279 std::vector<RelocationRef> Rels;
1281 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1282 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1283 Rels.push_back(Reloc);
1288 // Sort relocations by address.
1289 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
1291 StringRef SegmentName = "";
1292 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
1293 DataRefImpl DR = Section.getRawDataRefImpl();
1294 SegmentName = MachO->getSectionFinalSegmentName(DR);
1297 error(Section.getName(name));
1299 if ((SectionAddr <= StopAddress) &&
1300 (SectionAddr + SectSize) >= StartAddress) {
1301 outs() << "Disassembly of section ";
1302 if (!SegmentName.empty())
1303 outs() << SegmentName << ",";
1304 outs() << name << ':';
1307 // If the section has no symbol at the start, just insert a dummy one.
1308 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
1309 Symbols.insert(Symbols.begin(),
1310 std::make_tuple(SectionAddr, name, Section.isText()
1312 : ELF::STT_OBJECT));
1315 SmallString<40> Comments;
1316 raw_svector_ostream CommentStream(Comments);
1319 error(Section.getContents(BytesStr));
1320 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1326 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1327 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
1328 // Disassemble symbol by symbol.
1329 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
1330 uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr;
1331 // The end is either the section end or the beginning of the next
1334 (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr;
1335 // Don't try to disassemble beyond the end of section contents.
1338 // If this symbol has the same address as the next symbol, then skip it.
1342 // Check if we need to skip symbol
1343 // Skip if the symbol's data is not between StartAddress and StopAddress
1344 if (End + SectionAddr < StartAddress ||
1345 Start + SectionAddr > StopAddress) {
1349 // Stop disassembly at the stop address specified
1350 if (End + SectionAddr > StopAddress)
1351 End = StopAddress - SectionAddr;
1353 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1354 // make size 4 bytes folded
1355 End = Start + ((End - Start) & ~0x3ull);
1356 if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1357 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1361 std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1362 // cut trailing zeroes at the end of kernel
1363 // cut up to 256 bytes
1364 const uint64_t EndAlign = 256;
1365 const auto Limit = End - (std::min)(EndAlign, End - Start);
1366 while (End > Limit &&
1367 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1372 outs() << '\n' << std::get<1>(Symbols[si]) << ":\n";
1375 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1377 raw_ostream &DebugOut = nulls();
1380 for (Index = Start; Index < End; Index += Size) {
1383 if (Index + SectionAddr < StartAddress ||
1384 Index + SectionAddr > StopAddress) {
1385 // skip byte by byte till StartAddress is reached
1389 // AArch64 ELF binaries can interleave data and text in the
1390 // same section. We rely on the markers introduced to
1391 // understand what we need to dump. If the data marker is within a
1392 // function, it is denoted as a word/short etc
1393 if (isArmElf(Obj) && std::get<2>(Symbols[si]) != ELF::STT_OBJECT &&
1395 uint64_t Stride = 0;
1397 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1398 DataMappingSymsAddr.end(), Index);
1399 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1401 while (Index < End) {
1402 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1404 if (Index + 4 <= End) {
1406 dumpBytes(Bytes.slice(Index, 4), outs());
1407 outs() << "\t.word\t";
1409 if (Obj->isLittleEndian()) {
1411 reinterpret_cast<const support::ulittle32_t *>(
1412 Bytes.data() + Index);
1415 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1416 Bytes.data() + Index);
1419 outs() << "0x" << format("%08" PRIx32, Data);
1420 } else if (Index + 2 <= End) {
1422 dumpBytes(Bytes.slice(Index, 2), outs());
1423 outs() << "\t\t.short\t";
1425 if (Obj->isLittleEndian()) {
1427 reinterpret_cast<const support::ulittle16_t *>(
1428 Bytes.data() + Index);
1432 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1436 outs() << "0x" << format("%04" PRIx16, Data);
1439 dumpBytes(Bytes.slice(Index, 1), outs());
1440 outs() << "\t\t.byte\t";
1441 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
1445 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1446 TextMappingSymsAddr.end(), Index);
1447 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1453 // If there is a data symbol inside an ELF text section and we are only
1454 // disassembling text (applicable all architectures),
1455 // we are in a situation where we must print the data and not
1457 if (Obj->isELF() && std::get<2>(Symbols[si]) == ELF::STT_OBJECT &&
1458 !DisassembleAll && Section.isText()) {
1459 // print out data up to 8 bytes at a time in hex and ascii
1460 uint8_t AsciiData[9] = {'\0'};
1464 for (Index = Start; Index < End; Index += 1) {
1465 if (((SectionAddr + Index) < StartAddress) ||
1466 ((SectionAddr + Index) > StopAddress))
1468 if (NumBytes == 0) {
1469 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1472 Byte = Bytes.slice(Index)[0];
1473 outs() << format(" %02x", Byte);
1474 AsciiData[NumBytes] = isprint(Byte) ? Byte : '.';
1476 uint8_t IndentOffset = 0;
1478 if (Index == End - 1 || NumBytes > 8) {
1479 // Indent the space for less than 8 bytes data.
1480 // 2 spaces for byte and one for space between bytes
1481 IndentOffset = 3 * (8 - NumBytes);
1482 for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1483 AsciiData[Excess] = '\0';
1486 if (NumBytes == 8) {
1487 AsciiData[8] = '\0';
1488 outs() << std::string(IndentOffset, ' ') << " ";
1489 outs() << reinterpret_cast<char *>(AsciiData);
1498 // Disassemble a real instruction or a data when disassemble all is
1500 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1501 SectionAddr + Index, DebugOut,
1506 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
1507 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
1509 outs() << CommentStream.str();
1512 // Try to resolve the target of a call, tail call, etc. to a specific
1514 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1515 MIA->isConditionalBranch(Inst))) {
1517 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1518 // In a relocatable object, the target's section must reside in
1519 // the same section as the call instruction or it is accessed
1520 // through a relocation.
1522 // In a non-relocatable object, the target may be in any section.
1524 // N.B. We don't walk the relocations in the relocatable case yet.
1525 auto *TargetSectionSymbols = &Symbols;
1526 if (!Obj->isRelocatableObject()) {
1527 auto SectionAddress = std::upper_bound(
1528 SectionAddresses.begin(), SectionAddresses.end(), Target,
1530 const std::pair<uint64_t, SectionRef> &RHS) {
1531 return LHS < RHS.first;
1533 if (SectionAddress != SectionAddresses.begin()) {
1535 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1537 TargetSectionSymbols = nullptr;
1541 // Find the first symbol in the section whose offset is less than
1542 // or equal to the target.
1543 if (TargetSectionSymbols) {
1544 auto TargetSym = std::upper_bound(
1545 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1546 Target, [](uint64_t LHS,
1547 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1548 return LHS < std::get<0>(RHS);
1550 if (TargetSym != TargetSectionSymbols->begin()) {
1552 uint64_t TargetAddress = std::get<0>(*TargetSym);
1553 StringRef TargetName = std::get<1>(*TargetSym);
1554 outs() << " <" << TargetName;
1555 uint64_t Disp = Target - TargetAddress;
1557 outs() << "+0x" << utohexstr(Disp);
1565 // Print relocation for instruction.
1566 while (rel_cur != rel_end) {
1567 bool hidden = getHidden(*rel_cur);
1568 uint64_t addr = rel_cur->getOffset();
1569 SmallString<16> name;
1570 SmallString<32> val;
1572 // If this relocation is hidden, skip it.
1573 if (hidden || ((SectionAddr + addr) < StartAddress)) {
1578 // Stop when rel_cur's address is past the current instruction.
1579 if (addr >= Index + Size) break;
1580 rel_cur->getTypeName(name);
1581 error(getRelocationValueString(*rel_cur, val));
1582 outs() << format(Fmt.data(), SectionAddr + addr) << name
1583 << "\t" << val << "\n";
1591 void llvm::PrintRelocations(const ObjectFile *Obj) {
1592 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1594 // Regular objdump doesn't print relocations in non-relocatable object
1596 if (!Obj->isRelocatableObject())
1599 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1600 if (Section.relocation_begin() == Section.relocation_end())
1603 error(Section.getName(secname));
1604 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
1605 for (const RelocationRef &Reloc : Section.relocations()) {
1606 bool hidden = getHidden(Reloc);
1607 uint64_t address = Reloc.getOffset();
1608 SmallString<32> relocname;
1609 SmallString<32> valuestr;
1610 if (address < StartAddress || address > StopAddress || hidden)
1612 Reloc.getTypeName(relocname);
1613 error(getRelocationValueString(Reloc, valuestr));
1614 outs() << format(Fmt.data(), address) << " " << relocname << " "
1615 << valuestr << "\n";
1621 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
1622 outs() << "Sections:\n"
1623 "Idx Name Size Address Type\n";
1625 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1627 error(Section.getName(Name));
1628 uint64_t Address = Section.getAddress();
1629 uint64_t Size = Section.getSize();
1630 bool Text = Section.isText();
1631 bool Data = Section.isData();
1632 bool BSS = Section.isBSS();
1633 std::string Type = (std::string(Text ? "TEXT " : "") +
1634 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1635 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1636 Name.str().c_str(), Size, Address, Type.c_str());
1641 void llvm::PrintSectionContents(const ObjectFile *Obj) {
1643 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1646 error(Section.getName(Name));
1647 uint64_t BaseAddr = Section.getAddress();
1648 uint64_t Size = Section.getSize();
1652 outs() << "Contents of section " << Name << ":\n";
1653 if (Section.isBSS()) {
1654 outs() << format("<skipping contents of bss section at [%04" PRIx64
1655 ", %04" PRIx64 ")>\n",
1656 BaseAddr, BaseAddr + Size);
1660 error(Section.getContents(Contents));
1662 // Dump out the content as hex and printable ascii characters.
1663 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1664 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1665 // Dump line of hex.
1666 for (std::size_t i = 0; i < 16; ++i) {
1667 if (i != 0 && i % 4 == 0)
1670 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1671 << hexdigit(Contents[addr + i] & 0xF, true);
1677 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1678 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1679 outs() << Contents[addr + i];
1688 void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1689 StringRef ArchitectureName) {
1690 outs() << "SYMBOL TABLE:\n";
1692 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1693 printCOFFSymbolTable(coff);
1696 for (const SymbolRef &Symbol : o->symbols()) {
1697 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1698 if (!AddressOrError)
1699 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError(),
1701 uint64_t Address = *AddressOrError;
1702 if ((Address < StartAddress) || (Address > StopAddress))
1704 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1706 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError(),
1708 SymbolRef::Type Type = *TypeOrError;
1709 uint32_t Flags = Symbol.getFlags();
1710 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1712 report_error(ArchiveName, o->getFileName(), SectionOrErr.takeError(),
1714 section_iterator Section = *SectionOrErr;
1716 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1717 Section->getName(Name);
1719 Expected<StringRef> NameOrErr = Symbol.getName();
1721 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1726 bool Global = Flags & SymbolRef::SF_Global;
1727 bool Weak = Flags & SymbolRef::SF_Weak;
1728 bool Absolute = Flags & SymbolRef::SF_Absolute;
1729 bool Common = Flags & SymbolRef::SF_Common;
1730 bool Hidden = Flags & SymbolRef::SF_Hidden;
1733 if (Type != SymbolRef::ST_Unknown)
1734 GlobLoc = Global ? 'g' : 'l';
1735 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1737 char FileFunc = ' ';
1738 if (Type == SymbolRef::ST_File)
1740 else if (Type == SymbolRef::ST_Function)
1743 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1746 outs() << format(Fmt, Address) << " "
1747 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1748 << (Weak ? 'w' : ' ') // Weak?
1749 << ' ' // Constructor. Not supported yet.
1750 << ' ' // Warning. Not supported yet.
1751 << ' ' // Indirect reference to another symbol.
1752 << Debug // Debugging (d) or dynamic (D) symbol.
1753 << FileFunc // Name of function (F), file (f) or object (O).
1757 } else if (Common) {
1759 } else if (Section == o->section_end()) {
1762 if (const MachOObjectFile *MachO =
1763 dyn_cast<const MachOObjectFile>(o)) {
1764 DataRefImpl DR = Section->getRawDataRefImpl();
1765 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1766 outs() << SegmentName << ",";
1768 StringRef SectionName;
1769 error(Section->getName(SectionName));
1770 outs() << SectionName;
1774 if (Common || isa<ELFObjectFileBase>(o)) {
1776 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1777 outs() << format("\t %08" PRIx64 " ", Val);
1781 outs() << ".hidden ";
1788 static void PrintUnwindInfo(const ObjectFile *o) {
1789 outs() << "Unwind info:\n\n";
1791 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1792 printCOFFUnwindInfo(coff);
1793 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1794 printMachOUnwindInfo(MachO);
1796 // TODO: Extract DWARF dump tool to objdump.
1797 errs() << "This operation is only currently supported "
1798 "for COFF and MachO object files.\n";
1803 void llvm::printExportsTrie(const ObjectFile *o) {
1804 outs() << "Exports trie:\n";
1805 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1806 printMachOExportsTrie(MachO);
1808 errs() << "This operation is only currently supported "
1809 "for Mach-O executable files.\n";
1814 void llvm::printRebaseTable(const ObjectFile *o) {
1815 outs() << "Rebase table:\n";
1816 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1817 printMachORebaseTable(MachO);
1819 errs() << "This operation is only currently supported "
1820 "for Mach-O executable files.\n";
1825 void llvm::printBindTable(const ObjectFile *o) {
1826 outs() << "Bind table:\n";
1827 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1828 printMachOBindTable(MachO);
1830 errs() << "This operation is only currently supported "
1831 "for Mach-O executable files.\n";
1836 void llvm::printLazyBindTable(const ObjectFile *o) {
1837 outs() << "Lazy bind table:\n";
1838 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1839 printMachOLazyBindTable(MachO);
1841 errs() << "This operation is only currently supported "
1842 "for Mach-O executable files.\n";
1847 void llvm::printWeakBindTable(const ObjectFile *o) {
1848 outs() << "Weak bind table:\n";
1849 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1850 printMachOWeakBindTable(MachO);
1852 errs() << "This operation is only currently supported "
1853 "for Mach-O executable files.\n";
1858 /// Dump the raw contents of the __clangast section so the output can be piped
1859 /// into llvm-bcanalyzer.
1860 void llvm::printRawClangAST(const ObjectFile *Obj) {
1861 if (outs().is_displayed()) {
1862 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1863 "the clang ast section.\n"
1864 "Please redirect the output to a file or another program such as "
1865 "llvm-bcanalyzer.\n";
1869 StringRef ClangASTSectionName("__clangast");
1870 if (isa<COFFObjectFile>(Obj)) {
1871 ClangASTSectionName = "clangast";
1874 Optional<object::SectionRef> ClangASTSection;
1875 for (auto Sec : ToolSectionFilter(*Obj)) {
1878 if (Name == ClangASTSectionName) {
1879 ClangASTSection = Sec;
1883 if (!ClangASTSection)
1886 StringRef ClangASTContents;
1887 error(ClangASTSection.getValue().getContents(ClangASTContents));
1888 outs().write(ClangASTContents.data(), ClangASTContents.size());
1891 static void printFaultMaps(const ObjectFile *Obj) {
1892 const char *FaultMapSectionName = nullptr;
1894 if (isa<ELFObjectFileBase>(Obj)) {
1895 FaultMapSectionName = ".llvm_faultmaps";
1896 } else if (isa<MachOObjectFile>(Obj)) {
1897 FaultMapSectionName = "__llvm_faultmaps";
1899 errs() << "This operation is only currently supported "
1900 "for ELF and Mach-O executable files.\n";
1904 Optional<object::SectionRef> FaultMapSection;
1906 for (auto Sec : ToolSectionFilter(*Obj)) {
1909 if (Name == FaultMapSectionName) {
1910 FaultMapSection = Sec;
1915 outs() << "FaultMap table:\n";
1917 if (!FaultMapSection.hasValue()) {
1918 outs() << "<not found>\n";
1922 StringRef FaultMapContents;
1923 error(FaultMapSection.getValue().getContents(FaultMapContents));
1925 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1926 FaultMapContents.bytes_end());
1931 static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) {
1933 return printELFFileHeader(o);
1935 return printCOFFFileHeader(o);
1937 return printWasmFileHeader(o);
1939 printMachOFileHeader(o);
1941 printMachOLoadCommands(o);
1944 report_error(o->getFileName(), "Invalid/Unsupported object file format");
1947 static void DumpObject(const ObjectFile *o, const Archive *a = nullptr) {
1948 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
1949 // Avoid other output when using a raw option.
1953 outs() << a->getFileName() << "(" << o->getFileName() << ")";
1955 outs() << o->getFileName();
1956 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
1960 DisassembleObject(o, Relocations);
1961 if (Relocations && !Disassemble)
1962 PrintRelocations(o);
1964 PrintSectionHeaders(o);
1965 if (SectionContents)
1966 PrintSectionContents(o);
1968 PrintSymbolTable(o, ArchiveName);
1971 if (PrivateHeaders || FirstPrivateHeader)
1972 printPrivateFileHeaders(o, FirstPrivateHeader);
1974 printExportsTrie(o);
1976 printRebaseTable(o);
1980 printLazyBindTable(o);
1982 printWeakBindTable(o);
1984 printRawClangAST(o);
1987 if (DwarfDumpType != DIDT_Null) {
1988 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o));
1989 // Dump the complete DWARF structure.
1990 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1994 static void DumpObject(const COFFImportFile *I, const Archive *A) {
1995 StringRef ArchiveName = A ? A->getFileName() : "";
1997 // Avoid other output when using a raw option.
2000 << ArchiveName << "(" << I->getFileName() << ")"
2001 << ":\tfile format COFF-import-file"
2005 printCOFFSymbolTable(I);
2008 /// @brief Dump each object file in \a a;
2009 static void DumpArchive(const Archive *a) {
2010 Error Err = Error::success();
2011 for (auto &C : a->children(Err)) {
2012 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2014 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2015 report_error(a->getFileName(), C, std::move(E));
2018 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2020 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2023 report_error(a->getFileName(), object_error::invalid_file_type);
2026 report_error(a->getFileName(), std::move(Err));
2029 /// @brief Open file and figure out how to dump it.
2030 static void DumpInput(StringRef file) {
2032 // If we are using the Mach-O specific object file parser, then let it parse
2033 // the file and process the command line options. So the -arch flags can
2034 // be used to select specific slices, etc.
2036 ParseInputMachO(file);
2040 // Attempt to open the binary.
2041 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2043 report_error(file, BinaryOrErr.takeError());
2044 Binary &Binary = *BinaryOrErr.get().getBinary();
2046 if (Archive *a = dyn_cast<Archive>(&Binary))
2048 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
2051 report_error(file, object_error::invalid_file_type);
2054 int main(int argc, char **argv) {
2055 // Print a stack trace if we signal out.
2056 sys::PrintStackTraceOnErrorSignal(argv[0]);
2057 PrettyStackTraceProgram X(argc, argv);
2058 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
2060 // Initialize targets and assembly printers/parsers.
2061 llvm::InitializeAllTargetInfos();
2062 llvm::InitializeAllTargetMCs();
2063 llvm::InitializeAllDisassemblers();
2065 // Register the target printer for --version.
2066 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2068 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2069 TripleName = Triple::normalize(TripleName);
2073 // Defaults to a.out if no filenames specified.
2074 if (InputFilenames.size() == 0)
2075 InputFilenames.push_back("a.out");
2077 if (DisassembleAll || PrintSource || PrintLines)
2086 && !FirstPrivateHeader
2093 && !(UniversalHeaders && MachOOpt)
2094 && !(ArchiveHeaders && MachOOpt)
2095 && !(IndirectSymbols && MachOOpt)
2096 && !(DataInCode && MachOOpt)
2097 && !(LinkOptHints && MachOOpt)
2098 && !(InfoPlist && MachOOpt)
2099 && !(DylibsUsed && MachOOpt)
2100 && !(DylibId && MachOOpt)
2101 && !(ObjcMetaData && MachOOpt)
2102 && !(FilterSections.size() != 0 && MachOOpt)
2104 && DwarfDumpType == DIDT_Null) {
2105 cl::PrintHelpMessage();
2109 std::for_each(InputFilenames.begin(), InputFilenames.end(),
2112 return EXIT_SUCCESS;