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 = a.getOffset();
216 uint64_t b_addr = b.getOffset();
217 return a_addr < b_addr;
221 class PrettyPrinter {
223 virtual ~PrettyPrinter(){}
224 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
225 ArrayRef<uint8_t> Bytes, uint64_t Address,
226 raw_ostream &OS, StringRef Annot,
227 MCSubtargetInfo const &STI) {
228 outs() << format("%8" PRIx64 ":", Address);
229 if (!NoShowRawInsn) {
231 dumpBytes(Bytes, outs());
233 IP.printInst(MI, outs(), "", STI);
236 PrettyPrinter PrettyPrinterInst;
237 class HexagonPrettyPrinter : public PrettyPrinter {
239 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
242 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
243 OS << format("%8" PRIx64 ":", Address);
244 if (!NoShowRawInsn) {
246 dumpBytes(Bytes.slice(0, 4), OS);
247 OS << format("%08" PRIx32, opcode);
250 void printInst(MCInstPrinter &IP, const MCInst *MI,
251 ArrayRef<uint8_t> Bytes, uint64_t Address,
252 raw_ostream &OS, StringRef Annot,
253 MCSubtargetInfo const &STI) override {
256 raw_string_ostream TempStream(Buffer);
257 IP.printInst(MI, TempStream, "", STI);
259 StringRef Contents(Buffer);
260 // Split off bundle attributes
261 auto PacketBundle = Contents.rsplit('\n');
262 // Split off first instruction from the rest
263 auto HeadTail = PacketBundle.first.split('\n');
264 auto Preamble = " { ";
266 while(!HeadTail.first.empty()) {
269 printLead(Bytes, Address, OS);
273 auto Duplex = HeadTail.first.split('\v');
274 if(!Duplex.second.empty()){
277 Inst = Duplex.second;
280 Inst = HeadTail.first;
282 Bytes = Bytes.slice(4);
284 HeadTail = HeadTail.second.split('\n');
286 OS << " } " << PacketBundle.second;
289 HexagonPrettyPrinter HexagonPrettyPrinterInst;
290 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
291 switch(Triple.getArch()) {
293 return PrettyPrinterInst;
294 case Triple::hexagon:
295 return HexagonPrettyPrinterInst;
300 template <class ELFT>
301 static const typename ELFObjectFile<ELFT>::Elf_Rel *
302 getRel(const ELFFile<ELFT> &EF, DataRefImpl Rel) {
303 typedef typename ELFObjectFile<ELFT>::Elf_Rel Elf_Rel;
304 return EF.template getEntry<Elf_Rel>(Rel.d.a, Rel.d.b);
307 template <class ELFT>
308 static const typename ELFObjectFile<ELFT>::Elf_Rela *
309 getRela(const ELFFile<ELFT> &EF, DataRefImpl Rela) {
310 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
311 return EF.template getEntry<Elf_Rela>(Rela.d.a, Rela.d.b);
314 template <class ELFT>
315 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
317 SmallVectorImpl<char> &Result) {
318 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
319 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
320 const ELFFile<ELFT> &EF = *Obj->getELFFile();
322 const Elf_Shdr *sec = EF.getSection(Rel.d.a);
323 const Elf_Shdr *SymTab = EF.getSection(sec->sh_link);
324 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
325 SymTab->sh_type == ELF::SHT_DYNSYM);
326 const Elf_Shdr *StrTabSec = EF.getSection(SymTab->sh_link);
327 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(StrTabSec);
328 if (std::error_code EC = StrTabOrErr.getError())
330 StringRef StrTab = *StrTabOrErr;
334 uint16_t symbol_index = 0;
335 switch (sec->sh_type) {
337 return object_error::parse_failed;
339 type = getRel(EF, Rel)->getType(EF.isMips64EL());
340 symbol_index = getRel(EF, Rel)->getSymbol(EF.isMips64EL());
341 // TODO: Read implicit addend from section data.
344 case ELF::SHT_RELA: {
345 type = getRela(EF, Rel)->getType(EF.isMips64EL());
346 symbol_index = getRela(EF, Rel)->getSymbol(EF.isMips64EL());
347 addend = getRela(EF, Rel)->r_addend;
351 const Elf_Sym *symb =
352 EF.template getEntry<Elf_Sym>(sec->sh_link, symbol_index);
354 const Elf_Shdr *SymSec = EF.getSection(symb);
355 if (symb->getType() == ELF::STT_SECTION) {
356 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
357 if (std::error_code EC = SecName.getError())
361 ErrorOr<StringRef> SymName = symb->getName(StrTab);
363 return SymName.getError();
366 switch (EF.getHeader()->e_machine) {
369 case ELF::R_X86_64_PC8:
370 case ELF::R_X86_64_PC16:
371 case ELF::R_X86_64_PC32: {
373 raw_string_ostream fmt(fmtbuf);
374 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
376 Result.append(fmtbuf.begin(), fmtbuf.end());
378 case ELF::R_X86_64_8:
379 case ELF::R_X86_64_16:
380 case ELF::R_X86_64_32:
381 case ELF::R_X86_64_32S:
382 case ELF::R_X86_64_64: {
384 raw_string_ostream fmt(fmtbuf);
385 fmt << Target << (addend < 0 ? "" : "+") << addend;
387 Result.append(fmtbuf.begin(), fmtbuf.end());
393 case ELF::EM_AARCH64: {
395 raw_string_ostream fmt(fmtbuf);
398 fmt << (addend < 0 ? "" : "+") << addend;
400 Result.append(fmtbuf.begin(), fmtbuf.end());
405 case ELF::EM_HEXAGON:
413 Result.append(res.begin(), res.end());
414 return std::error_code();
417 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
418 const RelocationRef &RelRef,
419 SmallVectorImpl<char> &Result) {
420 DataRefImpl Rel = RelRef.getRawDataRefImpl();
421 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
422 return getRelocationValueString(ELF32LE, Rel, Result);
423 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
424 return getRelocationValueString(ELF64LE, Rel, Result);
425 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
426 return getRelocationValueString(ELF32BE, Rel, Result);
427 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
428 return getRelocationValueString(ELF64BE, Rel, Result);
431 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
432 const RelocationRef &Rel,
433 SmallVectorImpl<char> &Result) {
434 symbol_iterator SymI = Rel.getSymbol();
436 if (std::error_code EC = SymI->getName(SymName))
438 Result.append(SymName.begin(), SymName.end());
439 return std::error_code();
442 static void printRelocationTargetName(const MachOObjectFile *O,
443 const MachO::any_relocation_info &RE,
444 raw_string_ostream &fmt) {
445 bool IsScattered = O->isRelocationScattered(RE);
447 // Target of a scattered relocation is an address. In the interest of
448 // generating pretty output, scan through the symbol table looking for a
449 // symbol that aligns with that address. If we find one, print it.
450 // Otherwise, we just print the hex address of the target.
452 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
454 for (const SymbolRef &Symbol : O->symbols()) {
459 if ((ec = Symbol.getAddress(Addr)))
460 report_fatal_error(ec.message());
463 if ((ec = Symbol.getName(Name)))
464 report_fatal_error(ec.message());
469 // If we couldn't find a symbol that this relocation refers to, try
470 // to find a section beginning instead.
471 for (const SectionRef &Section : O->sections()) {
475 uint64_t Addr = Section.getAddress();
478 if ((ec = Section.getName(Name)))
479 report_fatal_error(ec.message());
484 fmt << format("0x%x", Val);
489 bool isExtern = O->getPlainRelocationExternal(RE);
490 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
493 symbol_iterator SI = O->symbol_begin();
497 section_iterator SI = O->section_begin();
498 // Adjust for the fact that sections are 1-indexed.
499 advance(SI, Val - 1);
506 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
507 const RelocationRef &RelRef,
508 SmallVectorImpl<char> &Result) {
509 DataRefImpl Rel = RelRef.getRawDataRefImpl();
510 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
512 unsigned Arch = Obj->getArch();
515 raw_string_ostream fmt(fmtbuf);
516 unsigned Type = Obj->getAnyRelocationType(RE);
517 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
519 // Determine any addends that should be displayed with the relocation.
520 // These require decoding the relocation type, which is triple-specific.
522 // X86_64 has entirely custom relocation types.
523 if (Arch == Triple::x86_64) {
524 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
527 case MachO::X86_64_RELOC_GOT_LOAD:
528 case MachO::X86_64_RELOC_GOT: {
529 printRelocationTargetName(Obj, RE, fmt);
535 case MachO::X86_64_RELOC_SUBTRACTOR: {
536 DataRefImpl RelNext = Rel;
537 Obj->moveRelocationNext(RelNext);
538 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
540 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
541 // X86_64_RELOC_UNSIGNED.
542 // NOTE: Scattered relocations don't exist on x86_64.
543 unsigned RType = Obj->getAnyRelocationType(RENext);
544 if (RType != MachO::X86_64_RELOC_UNSIGNED)
545 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
546 "X86_64_RELOC_SUBTRACTOR.");
548 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
549 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
550 printRelocationTargetName(Obj, RENext, fmt);
552 printRelocationTargetName(Obj, RE, fmt);
555 case MachO::X86_64_RELOC_TLV:
556 printRelocationTargetName(Obj, RE, fmt);
561 case MachO::X86_64_RELOC_SIGNED_1:
562 printRelocationTargetName(Obj, RE, fmt);
565 case MachO::X86_64_RELOC_SIGNED_2:
566 printRelocationTargetName(Obj, RE, fmt);
569 case MachO::X86_64_RELOC_SIGNED_4:
570 printRelocationTargetName(Obj, RE, fmt);
574 printRelocationTargetName(Obj, RE, fmt);
577 // X86 and ARM share some relocation types in common.
578 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
579 Arch == Triple::ppc) {
580 // Generic relocation types...
582 case MachO::GENERIC_RELOC_PAIR: // prints no info
583 return std::error_code();
584 case MachO::GENERIC_RELOC_SECTDIFF: {
585 DataRefImpl RelNext = Rel;
586 Obj->moveRelocationNext(RelNext);
587 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
589 // X86 sect diff's must be followed by a relocation of type
590 // GENERIC_RELOC_PAIR.
591 unsigned RType = Obj->getAnyRelocationType(RENext);
593 if (RType != MachO::GENERIC_RELOC_PAIR)
594 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
595 "GENERIC_RELOC_SECTDIFF.");
597 printRelocationTargetName(Obj, RE, fmt);
599 printRelocationTargetName(Obj, RENext, fmt);
604 if (Arch == Triple::x86 || Arch == Triple::ppc) {
606 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
607 DataRefImpl RelNext = Rel;
608 Obj->moveRelocationNext(RelNext);
609 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
611 // X86 sect diff's must be followed by a relocation of type
612 // GENERIC_RELOC_PAIR.
613 unsigned RType = Obj->getAnyRelocationType(RENext);
614 if (RType != MachO::GENERIC_RELOC_PAIR)
615 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
616 "GENERIC_RELOC_LOCAL_SECTDIFF.");
618 printRelocationTargetName(Obj, RE, fmt);
620 printRelocationTargetName(Obj, RENext, fmt);
623 case MachO::GENERIC_RELOC_TLV: {
624 printRelocationTargetName(Obj, RE, fmt);
631 printRelocationTargetName(Obj, RE, fmt);
633 } else { // ARM-specific relocations
635 case MachO::ARM_RELOC_HALF:
636 case MachO::ARM_RELOC_HALF_SECTDIFF: {
637 // Half relocations steal a bit from the length field to encode
638 // whether this is an upper16 or a lower16 relocation.
639 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
645 printRelocationTargetName(Obj, RE, fmt);
647 DataRefImpl RelNext = Rel;
648 Obj->moveRelocationNext(RelNext);
649 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
651 // ARM half relocs must be followed by a relocation of type
653 unsigned RType = Obj->getAnyRelocationType(RENext);
654 if (RType != MachO::ARM_RELOC_PAIR)
655 report_fatal_error("Expected ARM_RELOC_PAIR after "
658 // NOTE: The half of the target virtual address is stashed in the
659 // address field of the secondary relocation, but we can't reverse
660 // engineer the constant offset from it without decoding the movw/movt
661 // instruction to find the other half in its immediate field.
663 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
664 // symbol/section pointer of the follow-on relocation.
665 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
667 printRelocationTargetName(Obj, RENext, fmt);
673 default: { printRelocationTargetName(Obj, RE, fmt); }
677 printRelocationTargetName(Obj, RE, fmt);
680 Result.append(fmtbuf.begin(), fmtbuf.end());
681 return std::error_code();
684 static std::error_code getRelocationValueString(const RelocationRef &Rel,
685 SmallVectorImpl<char> &Result) {
686 const ObjectFile *Obj = Rel.getObject();
687 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
688 return getRelocationValueString(ELF, Rel, Result);
689 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
690 return getRelocationValueString(COFF, Rel, Result);
691 auto *MachO = cast<MachOObjectFile>(Obj);
692 return getRelocationValueString(MachO, Rel, Result);
695 /// @brief Indicates whether this relocation should hidden when listing
696 /// relocations, usually because it is the trailing part of a multipart
697 /// relocation that will be printed as part of the leading relocation.
698 static bool getHidden(RelocationRef RelRef) {
699 const ObjectFile *Obj = RelRef.getObject();
700 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
704 unsigned Arch = MachO->getArch();
705 DataRefImpl Rel = RelRef.getRawDataRefImpl();
706 uint64_t Type = MachO->getRelocationType(Rel);
708 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
710 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
711 if (Type == MachO::GENERIC_RELOC_PAIR)
713 } else if (Arch == Triple::x86_64) {
714 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
715 // an X86_64_RELOC_SUBTRACTOR.
716 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
717 DataRefImpl RelPrev = Rel;
719 uint64_t PrevType = MachO->getRelocationType(RelPrev);
720 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
728 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
729 const Target *TheTarget = getTarget(Obj);
730 // getTarget() will have already issued a diagnostic if necessary, so
731 // just bail here if it failed.
735 // Package up features to be passed to target/subtarget
736 std::string FeaturesStr;
738 SubtargetFeatures Features;
739 for (unsigned i = 0; i != MAttrs.size(); ++i)
740 Features.AddFeature(MAttrs[i]);
741 FeaturesStr = Features.getString();
744 std::unique_ptr<const MCRegisterInfo> MRI(
745 TheTarget->createMCRegInfo(TripleName));
747 errs() << "error: no register info for target " << TripleName << "\n";
751 // Set up disassembler.
752 std::unique_ptr<const MCAsmInfo> AsmInfo(
753 TheTarget->createMCAsmInfo(*MRI, TripleName));
755 errs() << "error: no assembly info for target " << TripleName << "\n";
759 std::unique_ptr<const MCSubtargetInfo> STI(
760 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
762 errs() << "error: no subtarget info for target " << TripleName << "\n";
766 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
768 errs() << "error: no instruction info for target " << TripleName << "\n";
772 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
773 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
775 std::unique_ptr<MCDisassembler> DisAsm(
776 TheTarget->createMCDisassembler(*STI, Ctx));
779 errs() << "error: no disassembler for target " << TripleName << "\n";
783 std::unique_ptr<const MCInstrAnalysis> MIA(
784 TheTarget->createMCInstrAnalysis(MII.get()));
786 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
787 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
788 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
790 errs() << "error: no instruction printer for target " << TripleName
794 IP->setPrintImmHex(PrintImmHex);
795 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
797 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
798 "\t\t\t%08" PRIx64 ": ";
800 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
801 // in RelocSecs contain the relocations for section S.
803 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
804 for (const SectionRef &Section : Obj->sections()) {
805 section_iterator Sec2 = Section.getRelocatedSection();
806 if (Sec2 != Obj->section_end())
807 SectionRelocMap[*Sec2].push_back(Section);
810 for (const SectionRef &Section : Obj->sections()) {
811 if (!Section.isText() || Section.isVirtual())
814 uint64_t SectionAddr = Section.getAddress();
815 uint64_t SectSize = Section.getSize();
819 // Make a list of all the symbols in this section.
820 std::vector<std::pair<uint64_t, StringRef>> Symbols;
821 for (const SymbolRef &Symbol : Obj->symbols()) {
822 if (Section.containsSymbol(Symbol)) {
824 if (error(Symbol.getAddress(Address)))
826 if (Address == UnknownAddress)
828 Address -= SectionAddr;
829 if (Address >= SectSize)
833 if (error(Symbol.getName(Name)))
835 Symbols.push_back(std::make_pair(Address, Name));
839 // Sort the symbols by address, just in case they didn't come in that way.
840 array_pod_sort(Symbols.begin(), Symbols.end());
842 // Make a list of all the relocations for this section.
843 std::vector<RelocationRef> Rels;
845 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
846 for (const RelocationRef &Reloc : RelocSec.relocations()) {
847 Rels.push_back(Reloc);
852 // Sort relocations by address.
853 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
855 StringRef SegmentName = "";
856 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
857 DataRefImpl DR = Section.getRawDataRefImpl();
858 SegmentName = MachO->getSectionFinalSegmentName(DR);
861 if (error(Section.getName(name)))
863 outs() << "Disassembly of section ";
864 if (!SegmentName.empty())
865 outs() << SegmentName << ",";
866 outs() << name << ':';
868 // If the section has no symbol at the start, just insert a dummy one.
869 if (Symbols.empty() || Symbols[0].first != 0)
870 Symbols.insert(Symbols.begin(), std::make_pair(0, name));
872 SmallString<40> Comments;
873 raw_svector_ostream CommentStream(Comments);
876 if (error(Section.getContents(BytesStr)))
878 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
884 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
885 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
886 // Disassemble symbol by symbol.
887 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
889 uint64_t Start = Symbols[si].first;
890 // The end is either the section end or the beginning of the next symbol.
891 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
892 // If this symbol has the same address as the next symbol, then skip it.
896 outs() << '\n' << Symbols[si].second << ":\n";
899 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
901 raw_ostream &DebugOut = nulls();
904 for (Index = Start; Index < End; Index += Size) {
907 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
908 SectionAddr + Index, DebugOut,
910 PIP.printInst(*IP, &Inst,
911 Bytes.slice(Index, Size),
912 SectionAddr + Index, outs(), "", *STI);
913 outs() << CommentStream.str();
917 errs() << ToolName << ": warning: invalid instruction encoding\n";
919 Size = 1; // skip illegible bytes
922 // Print relocation for instruction.
923 while (rel_cur != rel_end) {
924 bool hidden = getHidden(*rel_cur);
925 uint64_t addr = rel_cur->getOffset();
926 SmallString<16> name;
929 // If this relocation is hidden, skip it.
930 if (hidden) goto skip_print_rel;
932 // Stop when rel_cur's address is past the current instruction.
933 if (addr >= Index + Size) break;
934 rel_cur->getTypeName(name);
935 if (error(getRelocationValueString(*rel_cur, val)))
937 outs() << format(Fmt.data(), SectionAddr + addr) << name
938 << "\t" << val << "\n";
948 void llvm::PrintRelocations(const ObjectFile *Obj) {
949 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
951 // Regular objdump doesn't print relocations in non-relocatable object
953 if (!Obj->isRelocatableObject())
956 for (const SectionRef &Section : Obj->sections()) {
957 if (Section.relocation_begin() == Section.relocation_end())
960 if (error(Section.getName(secname)))
962 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
963 for (const RelocationRef &Reloc : Section.relocations()) {
964 bool hidden = getHidden(Reloc);
965 uint64_t address = Reloc.getOffset();
966 SmallString<32> relocname;
967 SmallString<32> valuestr;
970 Reloc.getTypeName(relocname);
971 if (error(getRelocationValueString(Reloc, valuestr)))
973 outs() << format(Fmt.data(), address) << " " << relocname << " "
980 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
981 outs() << "Sections:\n"
982 "Idx Name Size Address Type\n";
984 for (const SectionRef &Section : Obj->sections()) {
986 if (error(Section.getName(Name)))
988 uint64_t Address = Section.getAddress();
989 uint64_t Size = Section.getSize();
990 bool Text = Section.isText();
991 bool Data = Section.isData();
992 bool BSS = Section.isBSS();
993 std::string Type = (std::string(Text ? "TEXT " : "") +
994 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
995 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
996 Name.str().c_str(), Size, Address, Type.c_str());
1001 void llvm::PrintSectionContents(const ObjectFile *Obj) {
1003 for (const SectionRef &Section : Obj->sections()) {
1006 if (error(Section.getName(Name)))
1008 uint64_t BaseAddr = Section.getAddress();
1009 uint64_t Size = Section.getSize();
1013 outs() << "Contents of section " << Name << ":\n";
1014 if (Section.isBSS()) {
1015 outs() << format("<skipping contents of bss section at [%04" PRIx64
1016 ", %04" PRIx64 ")>\n",
1017 BaseAddr, BaseAddr + Size);
1021 if (error(Section.getContents(Contents)))
1024 // Dump out the content as hex and printable ascii characters.
1025 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1026 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1027 // Dump line of hex.
1028 for (std::size_t i = 0; i < 16; ++i) {
1029 if (i != 0 && i % 4 == 0)
1032 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1033 << hexdigit(Contents[addr + i] & 0xF, true);
1039 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1040 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1041 outs() << Contents[addr + i];
1050 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
1051 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1052 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
1054 if (error(Symbol.getError()))
1057 if (error(coff->getSymbolName(*Symbol, Name)))
1060 outs() << "[" << format("%2d", SI) << "]"
1061 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
1062 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
1063 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1064 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1065 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1066 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
1069 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
1070 if (Symbol->isSectionDefinition()) {
1071 const coff_aux_section_definition *asd;
1072 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
1075 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1078 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1079 , unsigned(asd->Length)
1080 , unsigned(asd->NumberOfRelocations)
1081 , unsigned(asd->NumberOfLinenumbers)
1082 , unsigned(asd->CheckSum))
1083 << format("assoc %d comdat %d\n"
1084 , unsigned(AuxNumber)
1085 , unsigned(asd->Selection));
1086 } else if (Symbol->isFileRecord()) {
1087 const char *FileName;
1088 if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
1091 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1092 coff->getSymbolTableEntrySize());
1093 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
1095 SI = SI + Symbol->getNumberOfAuxSymbols();
1098 outs() << "AUX Unknown\n";
1104 void llvm::PrintSymbolTable(const ObjectFile *o) {
1105 outs() << "SYMBOL TABLE:\n";
1107 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1108 PrintCOFFSymbolTable(coff);
1111 for (const SymbolRef &Symbol : o->symbols()) {
1113 SymbolRef::Type Type = Symbol.getType();
1114 uint32_t Flags = Symbol.getFlags();
1115 section_iterator Section = o->section_end();
1116 if (error(Symbol.getAddress(Address)))
1118 if (error(Symbol.getSection(Section)))
1121 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1122 Section->getName(Name);
1123 } else if (error(Symbol.getName(Name))) {
1127 bool Global = Flags & SymbolRef::SF_Global;
1128 bool Weak = Flags & SymbolRef::SF_Weak;
1129 bool Absolute = Flags & SymbolRef::SF_Absolute;
1130 bool Common = Flags & SymbolRef::SF_Common;
1131 bool Hidden = Flags & SymbolRef::SF_Hidden;
1134 Address = Symbol.getCommonSize();
1136 if (Address == UnknownAddress)
1139 if (Type != SymbolRef::ST_Unknown)
1140 GlobLoc = Global ? 'g' : 'l';
1141 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1143 char FileFunc = ' ';
1144 if (Type == SymbolRef::ST_File)
1146 else if (Type == SymbolRef::ST_Function)
1149 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1152 outs() << format(Fmt, Address) << " "
1153 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1154 << (Weak ? 'w' : ' ') // Weak?
1155 << ' ' // Constructor. Not supported yet.
1156 << ' ' // Warning. Not supported yet.
1157 << ' ' // Indirect reference to another symbol.
1158 << Debug // Debugging (d) or dynamic (D) symbol.
1159 << FileFunc // Name of function (F), file (f) or object (O).
1163 } else if (Common) {
1165 } else if (Section == o->section_end()) {
1168 if (const MachOObjectFile *MachO =
1169 dyn_cast<const MachOObjectFile>(o)) {
1170 DataRefImpl DR = Section->getRawDataRefImpl();
1171 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1172 outs() << SegmentName << ",";
1174 StringRef SectionName;
1175 if (error(Section->getName(SectionName)))
1177 outs() << SectionName;
1181 if (Common || isa<ELFObjectFileBase>(o)) {
1183 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1184 outs() << format("\t %08" PRIx64 " ", Val);
1188 outs() << ".hidden ";
1195 static void PrintUnwindInfo(const ObjectFile *o) {
1196 outs() << "Unwind info:\n\n";
1198 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1199 printCOFFUnwindInfo(coff);
1200 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1201 printMachOUnwindInfo(MachO);
1203 // TODO: Extract DWARF dump tool to objdump.
1204 errs() << "This operation is only currently supported "
1205 "for COFF and MachO object files.\n";
1210 void llvm::printExportsTrie(const ObjectFile *o) {
1211 outs() << "Exports trie:\n";
1212 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1213 printMachOExportsTrie(MachO);
1215 errs() << "This operation is only currently supported "
1216 "for Mach-O executable files.\n";
1221 void llvm::printRebaseTable(const ObjectFile *o) {
1222 outs() << "Rebase table:\n";
1223 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1224 printMachORebaseTable(MachO);
1226 errs() << "This operation is only currently supported "
1227 "for Mach-O executable files.\n";
1232 void llvm::printBindTable(const ObjectFile *o) {
1233 outs() << "Bind table:\n";
1234 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1235 printMachOBindTable(MachO);
1237 errs() << "This operation is only currently supported "
1238 "for Mach-O executable files.\n";
1243 void llvm::printLazyBindTable(const ObjectFile *o) {
1244 outs() << "Lazy bind table:\n";
1245 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1246 printMachOLazyBindTable(MachO);
1248 errs() << "This operation is only currently supported "
1249 "for Mach-O executable files.\n";
1254 void llvm::printWeakBindTable(const ObjectFile *o) {
1255 outs() << "Weak bind table:\n";
1256 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1257 printMachOWeakBindTable(MachO);
1259 errs() << "This operation is only currently supported "
1260 "for Mach-O executable files.\n";
1265 static void printFaultMaps(const ObjectFile *Obj) {
1266 const char *FaultMapSectionName = nullptr;
1268 if (isa<ELFObjectFileBase>(Obj)) {
1269 FaultMapSectionName = ".llvm_faultmaps";
1270 } else if (isa<MachOObjectFile>(Obj)) {
1271 FaultMapSectionName = "__llvm_faultmaps";
1273 errs() << "This operation is only currently supported "
1274 "for ELF and Mach-O executable files.\n";
1278 Optional<object::SectionRef> FaultMapSection;
1280 for (auto Sec : Obj->sections()) {
1283 if (Name == FaultMapSectionName) {
1284 FaultMapSection = Sec;
1289 outs() << "FaultMap table:\n";
1291 if (!FaultMapSection.hasValue()) {
1292 outs() << "<not found>\n";
1296 StringRef FaultMapContents;
1297 if (error(FaultMapSection.getValue().getContents(FaultMapContents))) {
1298 errs() << "Could not read the " << FaultMapContents << " section!\n";
1302 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1303 FaultMapContents.bytes_end());
1308 static void printPrivateFileHeader(const ObjectFile *o) {
1310 printELFFileHeader(o);
1311 } else if (o->isCOFF()) {
1312 printCOFFFileHeader(o);
1313 } else if (o->isMachO()) {
1314 printMachOFileHeader(o);
1318 static void DumpObject(const ObjectFile *o) {
1320 outs() << o->getFileName()
1321 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1324 DisassembleObject(o, Relocations);
1325 if (Relocations && !Disassemble)
1326 PrintRelocations(o);
1328 PrintSectionHeaders(o);
1329 if (SectionContents)
1330 PrintSectionContents(o);
1332 PrintSymbolTable(o);
1336 printPrivateFileHeader(o);
1338 printExportsTrie(o);
1340 printRebaseTable(o);
1344 printLazyBindTable(o);
1346 printWeakBindTable(o);
1351 /// @brief Dump each object file in \a a;
1352 static void DumpArchive(const Archive *a) {
1353 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
1355 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
1356 if (std::error_code EC = ChildOrErr.getError()) {
1357 // Ignore non-object files.
1358 if (EC != object_error::invalid_file_type)
1359 report_error(a->getFileName(), EC);
1362 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
1365 report_error(a->getFileName(), object_error::invalid_file_type);
1369 /// @brief Open file and figure out how to dump it.
1370 static void DumpInput(StringRef file) {
1371 // If file isn't stdin, check that it exists.
1372 if (file != "-" && !sys::fs::exists(file)) {
1373 report_error(file, errc::no_such_file_or_directory);
1377 // If we are using the Mach-O specific object file parser, then let it parse
1378 // the file and process the command line options. So the -arch flags can
1379 // be used to select specific slices, etc.
1381 ParseInputMachO(file);
1385 // Attempt to open the binary.
1386 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1387 if (std::error_code EC = BinaryOrErr.getError()) {
1388 report_error(file, EC);
1391 Binary &Binary = *BinaryOrErr.get().getBinary();
1393 if (Archive *a = dyn_cast<Archive>(&Binary))
1395 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
1398 report_error(file, object_error::invalid_file_type);
1401 int main(int argc, char **argv) {
1402 // Print a stack trace if we signal out.
1403 sys::PrintStackTraceOnErrorSignal();
1404 PrettyStackTraceProgram X(argc, argv);
1405 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1407 // Initialize targets and assembly printers/parsers.
1408 llvm::InitializeAllTargetInfos();
1409 llvm::InitializeAllTargetMCs();
1410 llvm::InitializeAllAsmParsers();
1411 llvm::InitializeAllDisassemblers();
1413 // Register the target printer for --version.
1414 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1416 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1417 TripleName = Triple::normalize(TripleName);
1421 // Defaults to a.out if no filenames specified.
1422 if (InputFilenames.size() == 0)
1423 InputFilenames.push_back("a.out");
1437 && !(UniversalHeaders && MachOOpt)
1438 && !(ArchiveHeaders && MachOOpt)
1439 && !(IndirectSymbols && MachOOpt)
1440 && !(DataInCode && MachOOpt)
1441 && !(LinkOptHints && MachOOpt)
1442 && !(InfoPlist && MachOOpt)
1443 && !(DylibsUsed && MachOOpt)
1444 && !(DylibId && MachOOpt)
1445 && !(ObjcMetaData && MachOOpt)
1446 && !(DumpSections.size() != 0 && MachOOpt)
1447 && !PrintFaultMaps) {
1448 cl::PrintHelpMessage();
1452 std::for_each(InputFilenames.begin(), InputFilenames.end(),