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/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCDisassembler.h"
28 #include "llvm/MC/MCInst.h"
29 #include "llvm/MC/MCInstPrinter.h"
30 #include "llvm/MC/MCInstrAnalysis.h"
31 #include "llvm/MC/MCInstrInfo.h"
32 #include "llvm/MC/MCObjectFileInfo.h"
33 #include "llvm/MC/MCRegisterInfo.h"
34 #include "llvm/MC/MCRelocationInfo.h"
35 #include "llvm/MC/MCSubtargetInfo.h"
36 #include "llvm/Object/Archive.h"
37 #include "llvm/Object/ELFObjectFile.h"
38 #include "llvm/Object/COFF.h"
39 #include "llvm/Object/MachO.h"
40 #include "llvm/Object/ObjectFile.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/Errc.h"
45 #include "llvm/Support/FileSystem.h"
46 #include "llvm/Support/Format.h"
47 #include "llvm/Support/GraphWriter.h"
48 #include "llvm/Support/Host.h"
49 #include "llvm/Support/ManagedStatic.h"
50 #include "llvm/Support/MemoryBuffer.h"
51 #include "llvm/Support/PrettyStackTrace.h"
52 #include "llvm/Support/Signals.h"
53 #include "llvm/Support/SourceMgr.h"
54 #include "llvm/Support/TargetRegistry.h"
55 #include "llvm/Support/TargetSelect.h"
56 #include "llvm/Support/raw_ostream.h"
60 #include <system_error>
63 using namespace object;
65 static cl::list<std::string>
66 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
69 llvm::Disassemble("disassemble",
70 cl::desc("Display assembler mnemonics for the machine instructions"));
72 Disassembled("d", cl::desc("Alias for --disassemble"),
73 cl::aliasopt(Disassemble));
76 llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
79 llvm::SectionContents("s", cl::desc("Display the content of each section"));
82 llvm::SymbolTable("t", cl::desc("Display the symbol table"));
85 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
88 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
91 llvm::Bind("bind", cl::desc("Display mach-o binding info"));
94 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
97 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
100 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
102 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
105 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
106 "see -version for available targets"));
110 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
111 cl::value_desc("cpu-name"),
115 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
116 "see -version for available targets"));
119 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
120 "headers for each section."));
122 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
123 cl::aliasopt(SectionHeaders));
125 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
126 cl::aliasopt(SectionHeaders));
128 cl::list<std::string>
129 llvm::MAttrs("mattr",
131 cl::desc("Target specific attributes"),
132 cl::value_desc("a1,+a2,-a3,..."));
135 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
136 "instructions, do not print "
137 "the instruction bytes."));
140 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
143 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
144 cl::aliasopt(UnwindInfo));
147 llvm::PrivateHeaders("private-headers",
148 cl::desc("Display format specific file headers"));
151 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
152 cl::aliasopt(PrivateHeaders));
155 llvm::PrintImmHex("print-imm-hex",
156 cl::desc("Use hex format for immediate values"));
158 cl::opt<bool> PrintFaultMaps("fault-map-section",
159 cl::desc("Display contents of faultmap section"));
161 static StringRef ToolName;
162 static int ReturnValue = EXIT_SUCCESS;
164 bool llvm::error(std::error_code EC) {
168 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
170 ReturnValue = EXIT_FAILURE;
174 static void report_error(StringRef File, std::error_code EC) {
176 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
177 ReturnValue = EXIT_FAILURE;
180 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
181 // Figure out the target triple.
182 llvm::Triple TheTriple("unknown-unknown-unknown");
183 if (TripleName.empty()) {
185 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
186 // TheTriple defaults to ELF, and COFF doesn't have an environment:
187 // the best we can do here is indicate that it is mach-o.
189 TheTriple.setObjectFormat(Triple::MachO);
192 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
193 if (COFFObj->getArch() == Triple::thumb)
194 TheTriple.setTriple("thumbv7-windows");
198 TheTriple.setTriple(Triple::normalize(TripleName));
200 // Get the target specific parser.
202 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
205 errs() << ToolName << ": " << Error;
209 // Update the triple name and return the found target.
210 TripleName = TheTriple.getTriple();
214 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
215 uint64_t a_addr, b_addr;
216 if (error(a.getOffset(a_addr))) return false;
217 if (error(b.getOffset(b_addr))) return false;
218 return a_addr < b_addr;
222 class PrettyPrinter {
224 virtual ~PrettyPrinter(){}
225 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
226 ArrayRef<uint8_t> Bytes, uint64_t Address,
227 raw_ostream &OS, StringRef Annot,
228 MCSubtargetInfo const &STI) {
229 outs() << format("%8" PRIx64 ":", Address);
230 if (!NoShowRawInsn) {
232 dumpBytes(Bytes, outs());
234 IP.printInst(MI, outs(), "", STI);
237 PrettyPrinter PrettyPrinterInst;
238 class HexagonPrettyPrinter : public PrettyPrinter {
240 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
243 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
244 OS << format("%8" PRIx64 ":", Address);
245 if (!NoShowRawInsn) {
247 dumpBytes(Bytes.slice(0, 4), OS);
248 OS << format("%08" PRIx32, opcode);
251 void printInst(MCInstPrinter &IP, const MCInst *MI,
252 ArrayRef<uint8_t> Bytes, uint64_t Address,
253 raw_ostream &OS, StringRef Annot,
254 MCSubtargetInfo const &STI) override {
257 raw_string_ostream TempStream(Buffer);
258 IP.printInst(MI, TempStream, "", STI);
260 StringRef Contents(Buffer);
261 // Split off bundle attributes
262 auto PacketBundle = Contents.rsplit('\n');
263 // Split off first instruction from the rest
264 auto HeadTail = PacketBundle.first.split('\n');
265 auto Preamble = " { ";
267 while(!HeadTail.first.empty()) {
270 printLead(Bytes, Address, OS);
274 auto Duplex = HeadTail.first.split('\v');
275 if(!Duplex.second.empty()){
278 Inst = Duplex.second;
281 Inst = HeadTail.first;
283 Bytes = Bytes.slice(4);
285 HeadTail = HeadTail.second.split('\n');
287 OS << " } " << PacketBundle.second;
290 HexagonPrettyPrinter HexagonPrettyPrinterInst;
291 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
292 switch(Triple.getArch()) {
294 return PrettyPrinterInst;
295 case Triple::hexagon:
296 return HexagonPrettyPrinterInst;
301 template <class ELFT>
302 static const typename ELFObjectFile<ELFT>::Elf_Rel *
303 getRel(const ELFFile<ELFT> &EF, DataRefImpl Rel) {
304 typedef typename ELFObjectFile<ELFT>::Elf_Rel Elf_Rel;
305 return EF.template getEntry<Elf_Rel>(Rel.d.a, Rel.d.b);
308 template <class ELFT>
309 static const typename ELFObjectFile<ELFT>::Elf_Rela *
310 getRela(const ELFFile<ELFT> &EF, DataRefImpl Rela) {
311 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
312 return EF.template getEntry<Elf_Rela>(Rela.d.a, Rela.d.b);
315 template <class ELFT>
316 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
318 SmallVectorImpl<char> &Result) {
319 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
320 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
321 const ELFFile<ELFT> &EF = *Obj->getELFFile();
323 const Elf_Shdr *sec = EF.getSection(Rel.d.a);
324 const Elf_Shdr *SymTab = EF.getSection(sec->sh_link);
325 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
326 SymTab->sh_type == ELF::SHT_DYNSYM);
327 const Elf_Shdr *StrTabSec = EF.getSection(SymTab->sh_link);
328 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(StrTabSec);
329 if (std::error_code EC = StrTabOrErr.getError())
331 StringRef StrTab = *StrTabOrErr;
335 uint16_t symbol_index = 0;
336 switch (sec->sh_type) {
338 return object_error::parse_failed;
340 type = getRel(EF, Rel)->getType(EF.isMips64EL());
341 symbol_index = getRel(EF, Rel)->getSymbol(EF.isMips64EL());
342 // TODO: Read implicit addend from section data.
345 case ELF::SHT_RELA: {
346 type = getRela(EF, Rel)->getType(EF.isMips64EL());
347 symbol_index = getRela(EF, Rel)->getSymbol(EF.isMips64EL());
348 addend = getRela(EF, Rel)->r_addend;
352 const Elf_Sym *symb =
353 EF.template getEntry<Elf_Sym>(sec->sh_link, symbol_index);
355 const Elf_Shdr *SymSec = EF.getSection(symb);
356 if (symb->getType() == ELF::STT_SECTION) {
357 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
358 if (std::error_code EC = SecName.getError())
362 ErrorOr<StringRef> SymName = symb->getName(StrTab);
364 return SymName.getError();
367 switch (EF.getHeader()->e_machine) {
370 case ELF::R_X86_64_PC8:
371 case ELF::R_X86_64_PC16:
372 case ELF::R_X86_64_PC32: {
374 raw_string_ostream fmt(fmtbuf);
375 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
377 Result.append(fmtbuf.begin(), fmtbuf.end());
379 case ELF::R_X86_64_8:
380 case ELF::R_X86_64_16:
381 case ELF::R_X86_64_32:
382 case ELF::R_X86_64_32S:
383 case ELF::R_X86_64_64: {
385 raw_string_ostream fmt(fmtbuf);
386 fmt << Target << (addend < 0 ? "" : "+") << addend;
388 Result.append(fmtbuf.begin(), fmtbuf.end());
394 case ELF::EM_AARCH64: {
396 raw_string_ostream fmt(fmtbuf);
399 fmt << (addend < 0 ? "" : "+") << addend;
401 Result.append(fmtbuf.begin(), fmtbuf.end());
406 case ELF::EM_HEXAGON:
414 Result.append(res.begin(), res.end());
415 return std::error_code();
418 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
419 const RelocationRef &RelRef,
420 SmallVectorImpl<char> &Result) {
421 DataRefImpl Rel = RelRef.getRawDataRefImpl();
422 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
423 return getRelocationValueString(ELF32LE, Rel, Result);
424 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
425 return getRelocationValueString(ELF64LE, Rel, Result);
426 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
427 return getRelocationValueString(ELF32BE, Rel, Result);
428 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
429 return getRelocationValueString(ELF64BE, Rel, Result);
432 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
433 const RelocationRef &Rel,
434 SmallVectorImpl<char> &Result) {
435 symbol_iterator SymI = Rel.getSymbol();
437 if (std::error_code EC = SymI->getName(SymName))
439 Result.append(SymName.begin(), SymName.end());
440 return std::error_code();
443 static void printRelocationTargetName(const MachOObjectFile *O,
444 const MachO::any_relocation_info &RE,
445 raw_string_ostream &fmt) {
446 bool IsScattered = O->isRelocationScattered(RE);
448 // Target of a scattered relocation is an address. In the interest of
449 // generating pretty output, scan through the symbol table looking for a
450 // symbol that aligns with that address. If we find one, print it.
451 // Otherwise, we just print the hex address of the target.
453 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
455 for (const SymbolRef &Symbol : O->symbols()) {
460 if ((ec = Symbol.getAddress(Addr)))
461 report_fatal_error(ec.message());
464 if ((ec = Symbol.getName(Name)))
465 report_fatal_error(ec.message());
470 // If we couldn't find a symbol that this relocation refers to, try
471 // to find a section beginning instead.
472 for (const SectionRef &Section : O->sections()) {
476 uint64_t Addr = Section.getAddress();
479 if ((ec = Section.getName(Name)))
480 report_fatal_error(ec.message());
485 fmt << format("0x%x", Val);
490 bool isExtern = O->getPlainRelocationExternal(RE);
491 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
494 symbol_iterator SI = O->symbol_begin();
498 section_iterator SI = O->section_begin();
499 // Adjust for the fact that sections are 1-indexed.
500 advance(SI, Val - 1);
507 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
508 const RelocationRef &RelRef,
509 SmallVectorImpl<char> &Result) {
510 DataRefImpl Rel = RelRef.getRawDataRefImpl();
511 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
513 unsigned Arch = Obj->getArch();
516 raw_string_ostream fmt(fmtbuf);
517 unsigned Type = Obj->getAnyRelocationType(RE);
518 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
520 // Determine any addends that should be displayed with the relocation.
521 // These require decoding the relocation type, which is triple-specific.
523 // X86_64 has entirely custom relocation types.
524 if (Arch == Triple::x86_64) {
525 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
528 case MachO::X86_64_RELOC_GOT_LOAD:
529 case MachO::X86_64_RELOC_GOT: {
530 printRelocationTargetName(Obj, RE, fmt);
536 case MachO::X86_64_RELOC_SUBTRACTOR: {
537 DataRefImpl RelNext = Rel;
538 Obj->moveRelocationNext(RelNext);
539 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
541 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
542 // X86_64_RELOC_UNSIGNED.
543 // NOTE: Scattered relocations don't exist on x86_64.
544 unsigned RType = Obj->getAnyRelocationType(RENext);
545 if (RType != MachO::X86_64_RELOC_UNSIGNED)
546 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
547 "X86_64_RELOC_SUBTRACTOR.");
549 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
550 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
551 printRelocationTargetName(Obj, RENext, fmt);
553 printRelocationTargetName(Obj, RE, fmt);
556 case MachO::X86_64_RELOC_TLV:
557 printRelocationTargetName(Obj, RE, fmt);
562 case MachO::X86_64_RELOC_SIGNED_1:
563 printRelocationTargetName(Obj, RE, fmt);
566 case MachO::X86_64_RELOC_SIGNED_2:
567 printRelocationTargetName(Obj, RE, fmt);
570 case MachO::X86_64_RELOC_SIGNED_4:
571 printRelocationTargetName(Obj, RE, fmt);
575 printRelocationTargetName(Obj, RE, fmt);
578 // X86 and ARM share some relocation types in common.
579 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
580 Arch == Triple::ppc) {
581 // Generic relocation types...
583 case MachO::GENERIC_RELOC_PAIR: // prints no info
584 return std::error_code();
585 case MachO::GENERIC_RELOC_SECTDIFF: {
586 DataRefImpl RelNext = Rel;
587 Obj->moveRelocationNext(RelNext);
588 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
590 // X86 sect diff's must be followed by a relocation of type
591 // GENERIC_RELOC_PAIR.
592 unsigned RType = Obj->getAnyRelocationType(RENext);
594 if (RType != MachO::GENERIC_RELOC_PAIR)
595 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
596 "GENERIC_RELOC_SECTDIFF.");
598 printRelocationTargetName(Obj, RE, fmt);
600 printRelocationTargetName(Obj, RENext, fmt);
605 if (Arch == Triple::x86 || Arch == Triple::ppc) {
607 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
608 DataRefImpl RelNext = Rel;
609 Obj->moveRelocationNext(RelNext);
610 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
612 // X86 sect diff's must be followed by a relocation of type
613 // GENERIC_RELOC_PAIR.
614 unsigned RType = Obj->getAnyRelocationType(RENext);
615 if (RType != MachO::GENERIC_RELOC_PAIR)
616 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
617 "GENERIC_RELOC_LOCAL_SECTDIFF.");
619 printRelocationTargetName(Obj, RE, fmt);
621 printRelocationTargetName(Obj, RENext, fmt);
624 case MachO::GENERIC_RELOC_TLV: {
625 printRelocationTargetName(Obj, RE, fmt);
632 printRelocationTargetName(Obj, RE, fmt);
634 } else { // ARM-specific relocations
636 case MachO::ARM_RELOC_HALF:
637 case MachO::ARM_RELOC_HALF_SECTDIFF: {
638 // Half relocations steal a bit from the length field to encode
639 // whether this is an upper16 or a lower16 relocation.
640 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
646 printRelocationTargetName(Obj, RE, fmt);
648 DataRefImpl RelNext = Rel;
649 Obj->moveRelocationNext(RelNext);
650 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
652 // ARM half relocs must be followed by a relocation of type
654 unsigned RType = Obj->getAnyRelocationType(RENext);
655 if (RType != MachO::ARM_RELOC_PAIR)
656 report_fatal_error("Expected ARM_RELOC_PAIR after "
659 // NOTE: The half of the target virtual address is stashed in the
660 // address field of the secondary relocation, but we can't reverse
661 // engineer the constant offset from it without decoding the movw/movt
662 // instruction to find the other half in its immediate field.
664 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
665 // symbol/section pointer of the follow-on relocation.
666 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
668 printRelocationTargetName(Obj, RENext, fmt);
674 default: { printRelocationTargetName(Obj, RE, fmt); }
678 printRelocationTargetName(Obj, RE, fmt);
681 Result.append(fmtbuf.begin(), fmtbuf.end());
682 return std::error_code();
685 static std::error_code getRelocationValueString(const RelocationRef &Rel,
686 SmallVectorImpl<char> &Result) {
687 const ObjectFile *Obj = Rel.getObject();
688 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
689 return getRelocationValueString(ELF, Rel, Result);
690 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
691 return getRelocationValueString(COFF, Rel, Result);
692 auto *MachO = cast<MachOObjectFile>(Obj);
693 return getRelocationValueString(MachO, Rel, Result);
696 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
697 const Target *TheTarget = getTarget(Obj);
698 // getTarget() will have already issued a diagnostic if necessary, so
699 // just bail here if it failed.
703 // Package up features to be passed to target/subtarget
704 std::string FeaturesStr;
706 SubtargetFeatures Features;
707 for (unsigned i = 0; i != MAttrs.size(); ++i)
708 Features.AddFeature(MAttrs[i]);
709 FeaturesStr = Features.getString();
712 std::unique_ptr<const MCRegisterInfo> MRI(
713 TheTarget->createMCRegInfo(TripleName));
715 errs() << "error: no register info for target " << TripleName << "\n";
719 // Set up disassembler.
720 std::unique_ptr<const MCAsmInfo> AsmInfo(
721 TheTarget->createMCAsmInfo(*MRI, TripleName));
723 errs() << "error: no assembly info for target " << TripleName << "\n";
727 std::unique_ptr<const MCSubtargetInfo> STI(
728 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
730 errs() << "error: no subtarget info for target " << TripleName << "\n";
734 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
736 errs() << "error: no instruction info for target " << TripleName << "\n";
740 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
741 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
743 std::unique_ptr<MCDisassembler> DisAsm(
744 TheTarget->createMCDisassembler(*STI, Ctx));
747 errs() << "error: no disassembler for target " << TripleName << "\n";
751 std::unique_ptr<const MCInstrAnalysis> MIA(
752 TheTarget->createMCInstrAnalysis(MII.get()));
754 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
755 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
756 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
758 errs() << "error: no instruction printer for target " << TripleName
762 IP->setPrintImmHex(PrintImmHex);
763 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
765 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
766 "\t\t\t%08" PRIx64 ": ";
768 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
769 // in RelocSecs contain the relocations for section S.
771 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
772 for (const SectionRef &Section : Obj->sections()) {
773 section_iterator Sec2 = Section.getRelocatedSection();
774 if (Sec2 != Obj->section_end())
775 SectionRelocMap[*Sec2].push_back(Section);
778 for (const SectionRef &Section : Obj->sections()) {
779 if (!Section.isText() || Section.isVirtual())
782 uint64_t SectionAddr = Section.getAddress();
783 uint64_t SectSize = Section.getSize();
787 // Make a list of all the symbols in this section.
788 std::vector<std::pair<uint64_t, StringRef>> Symbols;
789 for (const SymbolRef &Symbol : Obj->symbols()) {
790 if (Section.containsSymbol(Symbol)) {
792 if (error(Symbol.getAddress(Address)))
794 if (Address == UnknownAddress)
796 Address -= SectionAddr;
797 if (Address >= SectSize)
801 if (error(Symbol.getName(Name)))
803 Symbols.push_back(std::make_pair(Address, Name));
807 // Sort the symbols by address, just in case they didn't come in that way.
808 array_pod_sort(Symbols.begin(), Symbols.end());
810 // Make a list of all the relocations for this section.
811 std::vector<RelocationRef> Rels;
813 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
814 for (const RelocationRef &Reloc : RelocSec.relocations()) {
815 Rels.push_back(Reloc);
820 // Sort relocations by address.
821 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
823 StringRef SegmentName = "";
824 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
825 DataRefImpl DR = Section.getRawDataRefImpl();
826 SegmentName = MachO->getSectionFinalSegmentName(DR);
829 if (error(Section.getName(name)))
831 outs() << "Disassembly of section ";
832 if (!SegmentName.empty())
833 outs() << SegmentName << ",";
834 outs() << name << ':';
836 // If the section has no symbol at the start, just insert a dummy one.
837 if (Symbols.empty() || Symbols[0].first != 0)
838 Symbols.insert(Symbols.begin(), std::make_pair(0, name));
840 SmallString<40> Comments;
841 raw_svector_ostream CommentStream(Comments);
844 if (error(Section.getContents(BytesStr)))
846 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
852 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
853 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
854 // Disassemble symbol by symbol.
855 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
857 uint64_t Start = Symbols[si].first;
858 // The end is either the section end or the beginning of the next symbol.
859 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
860 // If this symbol has the same address as the next symbol, then skip it.
864 outs() << '\n' << Symbols[si].second << ":\n";
867 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
869 raw_ostream &DebugOut = nulls();
872 for (Index = Start; Index < End; Index += Size) {
875 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
876 SectionAddr + Index, DebugOut,
878 PIP.printInst(*IP, &Inst,
879 Bytes.slice(Index, Size),
880 SectionAddr + Index, outs(), "", *STI);
881 outs() << CommentStream.str();
885 errs() << ToolName << ": warning: invalid instruction encoding\n";
887 Size = 1; // skip illegible bytes
890 // Print relocation for instruction.
891 while (rel_cur != rel_end) {
894 SmallString<16> name;
897 // If this relocation is hidden, skip it.
898 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
899 if (hidden) goto skip_print_rel;
901 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
902 // Stop when rel_cur's address is past the current instruction.
903 if (addr >= Index + Size) break;
904 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
905 if (error(getRelocationValueString(*rel_cur, val)))
907 outs() << format(Fmt.data(), SectionAddr + addr) << name
908 << "\t" << val << "\n";
918 void llvm::PrintRelocations(const ObjectFile *Obj) {
919 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
921 // Regular objdump doesn't print relocations in non-relocatable object
923 if (!Obj->isRelocatableObject())
926 for (const SectionRef &Section : Obj->sections()) {
927 if (Section.relocation_begin() == Section.relocation_end())
930 if (error(Section.getName(secname)))
932 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
933 for (const RelocationRef &Reloc : Section.relocations()) {
936 SmallString<32> relocname;
937 SmallString<32> valuestr;
938 if (error(Reloc.getHidden(hidden)))
942 if (error(Reloc.getTypeName(relocname)))
944 if (error(Reloc.getOffset(address)))
946 if (error(getRelocationValueString(Reloc, valuestr)))
948 outs() << format(Fmt.data(), address) << " " << relocname << " "
955 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
956 outs() << "Sections:\n"
957 "Idx Name Size Address Type\n";
959 for (const SectionRef &Section : Obj->sections()) {
961 if (error(Section.getName(Name)))
963 uint64_t Address = Section.getAddress();
964 uint64_t Size = Section.getSize();
965 bool Text = Section.isText();
966 bool Data = Section.isData();
967 bool BSS = Section.isBSS();
968 std::string Type = (std::string(Text ? "TEXT " : "") +
969 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
970 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
971 Name.str().c_str(), Size, Address, Type.c_str());
976 void llvm::PrintSectionContents(const ObjectFile *Obj) {
978 for (const SectionRef &Section : Obj->sections()) {
981 if (error(Section.getName(Name)))
983 uint64_t BaseAddr = Section.getAddress();
984 uint64_t Size = Section.getSize();
988 outs() << "Contents of section " << Name << ":\n";
989 if (Section.isBSS()) {
990 outs() << format("<skipping contents of bss section at [%04" PRIx64
991 ", %04" PRIx64 ")>\n",
992 BaseAddr, BaseAddr + Size);
996 if (error(Section.getContents(Contents)))
999 // Dump out the content as hex and printable ascii characters.
1000 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1001 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1002 // Dump line of hex.
1003 for (std::size_t i = 0; i < 16; ++i) {
1004 if (i != 0 && i % 4 == 0)
1007 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1008 << hexdigit(Contents[addr + i] & 0xF, true);
1014 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1015 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1016 outs() << Contents[addr + i];
1025 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
1026 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1027 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
1029 if (error(Symbol.getError()))
1032 if (error(coff->getSymbolName(*Symbol, Name)))
1035 outs() << "[" << format("%2d", SI) << "]"
1036 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
1037 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
1038 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1039 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1040 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1041 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
1044 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
1045 if (Symbol->isSectionDefinition()) {
1046 const coff_aux_section_definition *asd;
1047 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
1050 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1053 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1054 , unsigned(asd->Length)
1055 , unsigned(asd->NumberOfRelocations)
1056 , unsigned(asd->NumberOfLinenumbers)
1057 , unsigned(asd->CheckSum))
1058 << format("assoc %d comdat %d\n"
1059 , unsigned(AuxNumber)
1060 , unsigned(asd->Selection));
1061 } else if (Symbol->isFileRecord()) {
1062 const char *FileName;
1063 if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
1066 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1067 coff->getSymbolTableEntrySize());
1068 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
1070 SI = SI + Symbol->getNumberOfAuxSymbols();
1073 outs() << "AUX Unknown\n";
1079 void llvm::PrintSymbolTable(const ObjectFile *o) {
1080 outs() << "SYMBOL TABLE:\n";
1082 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1083 PrintCOFFSymbolTable(coff);
1086 for (const SymbolRef &Symbol : o->symbols()) {
1088 SymbolRef::Type Type = Symbol.getType();
1089 uint32_t Flags = Symbol.getFlags();
1090 section_iterator Section = o->section_end();
1091 if (error(Symbol.getAddress(Address)))
1093 if (error(Symbol.getSection(Section)))
1096 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1097 Section->getName(Name);
1098 } else if (error(Symbol.getName(Name))) {
1102 bool Global = Flags & SymbolRef::SF_Global;
1103 bool Weak = Flags & SymbolRef::SF_Weak;
1104 bool Absolute = Flags & SymbolRef::SF_Absolute;
1105 bool Common = Flags & SymbolRef::SF_Common;
1106 bool Hidden = Flags & SymbolRef::SF_Hidden;
1109 Address = Symbol.getCommonSize();
1111 if (Address == UnknownAddress)
1114 if (Type != SymbolRef::ST_Unknown)
1115 GlobLoc = Global ? 'g' : 'l';
1116 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1118 char FileFunc = ' ';
1119 if (Type == SymbolRef::ST_File)
1121 else if (Type == SymbolRef::ST_Function)
1124 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1127 outs() << format(Fmt, Address) << " "
1128 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1129 << (Weak ? 'w' : ' ') // Weak?
1130 << ' ' // Constructor. Not supported yet.
1131 << ' ' // Warning. Not supported yet.
1132 << ' ' // Indirect reference to another symbol.
1133 << Debug // Debugging (d) or dynamic (D) symbol.
1134 << FileFunc // Name of function (F), file (f) or object (O).
1138 } else if (Common) {
1140 } else if (Section == o->section_end()) {
1143 if (const MachOObjectFile *MachO =
1144 dyn_cast<const MachOObjectFile>(o)) {
1145 DataRefImpl DR = Section->getRawDataRefImpl();
1146 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1147 outs() << SegmentName << ",";
1149 StringRef SectionName;
1150 if (error(Section->getName(SectionName)))
1152 outs() << SectionName;
1156 if (Common || isa<ELFObjectFileBase>(o)) {
1158 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1159 outs() << format("\t %08" PRIx64 " ", Val);
1163 outs() << ".hidden ";
1170 static void PrintUnwindInfo(const ObjectFile *o) {
1171 outs() << "Unwind info:\n\n";
1173 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1174 printCOFFUnwindInfo(coff);
1175 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1176 printMachOUnwindInfo(MachO);
1178 // TODO: Extract DWARF dump tool to objdump.
1179 errs() << "This operation is only currently supported "
1180 "for COFF and MachO object files.\n";
1185 void llvm::printExportsTrie(const ObjectFile *o) {
1186 outs() << "Exports trie:\n";
1187 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1188 printMachOExportsTrie(MachO);
1190 errs() << "This operation is only currently supported "
1191 "for Mach-O executable files.\n";
1196 void llvm::printRebaseTable(const ObjectFile *o) {
1197 outs() << "Rebase table:\n";
1198 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1199 printMachORebaseTable(MachO);
1201 errs() << "This operation is only currently supported "
1202 "for Mach-O executable files.\n";
1207 void llvm::printBindTable(const ObjectFile *o) {
1208 outs() << "Bind table:\n";
1209 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1210 printMachOBindTable(MachO);
1212 errs() << "This operation is only currently supported "
1213 "for Mach-O executable files.\n";
1218 void llvm::printLazyBindTable(const ObjectFile *o) {
1219 outs() << "Lazy bind table:\n";
1220 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1221 printMachOLazyBindTable(MachO);
1223 errs() << "This operation is only currently supported "
1224 "for Mach-O executable files.\n";
1229 void llvm::printWeakBindTable(const ObjectFile *o) {
1230 outs() << "Weak bind table:\n";
1231 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1232 printMachOWeakBindTable(MachO);
1234 errs() << "This operation is only currently supported "
1235 "for Mach-O executable files.\n";
1240 static void printFaultMaps(const ObjectFile *Obj) {
1241 const char *FaultMapSectionName = nullptr;
1243 if (isa<ELFObjectFileBase>(Obj)) {
1244 FaultMapSectionName = ".llvm_faultmaps";
1245 } else if (isa<MachOObjectFile>(Obj)) {
1246 FaultMapSectionName = "__llvm_faultmaps";
1248 errs() << "This operation is only currently supported "
1249 "for ELF and Mach-O executable files.\n";
1253 Optional<object::SectionRef> FaultMapSection;
1255 for (auto Sec : Obj->sections()) {
1258 if (Name == FaultMapSectionName) {
1259 FaultMapSection = Sec;
1264 outs() << "FaultMap table:\n";
1266 if (!FaultMapSection.hasValue()) {
1267 outs() << "<not found>\n";
1271 StringRef FaultMapContents;
1272 if (error(FaultMapSection.getValue().getContents(FaultMapContents))) {
1273 errs() << "Could not read the " << FaultMapContents << " section!\n";
1277 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1278 FaultMapContents.bytes_end());
1283 static void printPrivateFileHeader(const ObjectFile *o) {
1285 printELFFileHeader(o);
1286 } else if (o->isCOFF()) {
1287 printCOFFFileHeader(o);
1288 } else if (o->isMachO()) {
1289 printMachOFileHeader(o);
1293 static void DumpObject(const ObjectFile *o) {
1295 outs() << o->getFileName()
1296 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1299 DisassembleObject(o, Relocations);
1300 if (Relocations && !Disassemble)
1301 PrintRelocations(o);
1303 PrintSectionHeaders(o);
1304 if (SectionContents)
1305 PrintSectionContents(o);
1307 PrintSymbolTable(o);
1311 printPrivateFileHeader(o);
1313 printExportsTrie(o);
1315 printRebaseTable(o);
1319 printLazyBindTable(o);
1321 printWeakBindTable(o);
1326 /// @brief Dump each object file in \a a;
1327 static void DumpArchive(const Archive *a) {
1328 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
1330 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
1331 if (std::error_code EC = ChildOrErr.getError()) {
1332 // Ignore non-object files.
1333 if (EC != object_error::invalid_file_type)
1334 report_error(a->getFileName(), EC);
1337 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
1340 report_error(a->getFileName(), object_error::invalid_file_type);
1344 /// @brief Open file and figure out how to dump it.
1345 static void DumpInput(StringRef file) {
1346 // If file isn't stdin, check that it exists.
1347 if (file != "-" && !sys::fs::exists(file)) {
1348 report_error(file, errc::no_such_file_or_directory);
1352 // If we are using the Mach-O specific object file parser, then let it parse
1353 // the file and process the command line options. So the -arch flags can
1354 // be used to select specific slices, etc.
1356 ParseInputMachO(file);
1360 // Attempt to open the binary.
1361 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1362 if (std::error_code EC = BinaryOrErr.getError()) {
1363 report_error(file, EC);
1366 Binary &Binary = *BinaryOrErr.get().getBinary();
1368 if (Archive *a = dyn_cast<Archive>(&Binary))
1370 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
1373 report_error(file, object_error::invalid_file_type);
1376 int main(int argc, char **argv) {
1377 // Print a stack trace if we signal out.
1378 sys::PrintStackTraceOnErrorSignal();
1379 PrettyStackTraceProgram X(argc, argv);
1380 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1382 // Initialize targets and assembly printers/parsers.
1383 llvm::InitializeAllTargetInfos();
1384 llvm::InitializeAllTargetMCs();
1385 llvm::InitializeAllAsmParsers();
1386 llvm::InitializeAllDisassemblers();
1388 // Register the target printer for --version.
1389 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1391 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1392 TripleName = Triple::normalize(TripleName);
1396 // Defaults to a.out if no filenames specified.
1397 if (InputFilenames.size() == 0)
1398 InputFilenames.push_back("a.out");
1412 && !(UniversalHeaders && MachOOpt)
1413 && !(ArchiveHeaders && MachOOpt)
1414 && !(IndirectSymbols && MachOOpt)
1415 && !(DataInCode && MachOOpt)
1416 && !(LinkOptHints && MachOOpt)
1417 && !(InfoPlist && MachOOpt)
1418 && !(DylibsUsed && MachOOpt)
1419 && !(DylibId && MachOOpt)
1420 && !(ObjcMetaData && MachOOpt)
1421 && !(DumpSections.size() != 0 && MachOOpt)
1422 && !PrintFaultMaps) {
1423 cl::PrintHelpMessage();
1427 std::for_each(InputFilenames.begin(), InputFilenames.end(),