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 std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
303 SmallVectorImpl<char> &Result) {
304 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
305 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
306 typedef typename ELFObjectFile<ELFT>::Elf_Rel Elf_Rel;
307 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
309 const ELFFile<ELFT> &EF = *Obj->getELFFile();
311 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
312 if (std::error_code EC = SecOrErr.getError())
314 const Elf_Shdr *Sec = *SecOrErr;
315 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
316 if (std::error_code EC = SymTabOrErr.getError())
318 const Elf_Shdr *SymTab = *SymTabOrErr;
319 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
320 SymTab->sh_type == ELF::SHT_DYNSYM);
321 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
322 if (std::error_code EC = StrTabSec.getError())
324 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
325 if (std::error_code EC = StrTabOrErr.getError())
327 StringRef StrTab = *StrTabOrErr;
331 uint16_t symbol_index = 0;
332 switch (Sec->sh_type) {
334 return object_error::parse_failed;
336 const Elf_Rel *ERel = Obj->getRel(Rel);
337 type = ERel->getType(EF.isMips64EL());
338 symbol_index = ERel->getSymbol(EF.isMips64EL());
339 // TODO: Read implicit addend from section data.
342 case ELF::SHT_RELA: {
343 const Elf_Rela *ERela = Obj->getRela(Rel);
344 type = ERela->getType(EF.isMips64EL());
345 symbol_index = ERela->getSymbol(EF.isMips64EL());
346 addend = ERela->r_addend;
350 const Elf_Sym *symb =
351 EF.template getEntry<Elf_Sym>(Sec->sh_link, symbol_index);
353 ErrorOr<const Elf_Shdr *> SymSec = EF.getSection(symb);
354 if (std::error_code EC = SymSec.getError())
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();
436 ErrorOr<StringRef> SymNameOrErr = SymI->getName();
437 if (std::error_code EC = SymNameOrErr.getError())
439 StringRef SymName = *SymNameOrErr;
440 Result.append(SymName.begin(), SymName.end());
441 return std::error_code();
444 static void printRelocationTargetName(const MachOObjectFile *O,
445 const MachO::any_relocation_info &RE,
446 raw_string_ostream &fmt) {
447 bool IsScattered = O->isRelocationScattered(RE);
449 // Target of a scattered relocation is an address. In the interest of
450 // generating pretty output, scan through the symbol table looking for a
451 // symbol that aligns with that address. If we find one, print it.
452 // Otherwise, we just print the hex address of the target.
454 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
456 for (const SymbolRef &Symbol : O->symbols()) {
458 ErrorOr<uint64_t> Addr = Symbol.getAddress();
459 if ((ec = Addr.getError()))
460 report_fatal_error(ec.message());
463 ErrorOr<StringRef> Name = Symbol.getName();
464 if (std::error_code EC = Name.getError())
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();
496 ErrorOr<StringRef> SOrErr = SI->getName();
497 if (!error(SOrErr.getError()))
500 section_iterator SI = O->section_begin();
501 // Adjust for the fact that sections are 1-indexed.
502 advance(SI, Val - 1);
509 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
510 const RelocationRef &RelRef,
511 SmallVectorImpl<char> &Result) {
512 DataRefImpl Rel = RelRef.getRawDataRefImpl();
513 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
515 unsigned Arch = Obj->getArch();
518 raw_string_ostream fmt(fmtbuf);
519 unsigned Type = Obj->getAnyRelocationType(RE);
520 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
522 // Determine any addends that should be displayed with the relocation.
523 // These require decoding the relocation type, which is triple-specific.
525 // X86_64 has entirely custom relocation types.
526 if (Arch == Triple::x86_64) {
527 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
530 case MachO::X86_64_RELOC_GOT_LOAD:
531 case MachO::X86_64_RELOC_GOT: {
532 printRelocationTargetName(Obj, RE, fmt);
538 case MachO::X86_64_RELOC_SUBTRACTOR: {
539 DataRefImpl RelNext = Rel;
540 Obj->moveRelocationNext(RelNext);
541 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
543 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
544 // X86_64_RELOC_UNSIGNED.
545 // NOTE: Scattered relocations don't exist on x86_64.
546 unsigned RType = Obj->getAnyRelocationType(RENext);
547 if (RType != MachO::X86_64_RELOC_UNSIGNED)
548 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
549 "X86_64_RELOC_SUBTRACTOR.");
551 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
552 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
553 printRelocationTargetName(Obj, RENext, fmt);
555 printRelocationTargetName(Obj, RE, fmt);
558 case MachO::X86_64_RELOC_TLV:
559 printRelocationTargetName(Obj, RE, fmt);
564 case MachO::X86_64_RELOC_SIGNED_1:
565 printRelocationTargetName(Obj, RE, fmt);
568 case MachO::X86_64_RELOC_SIGNED_2:
569 printRelocationTargetName(Obj, RE, fmt);
572 case MachO::X86_64_RELOC_SIGNED_4:
573 printRelocationTargetName(Obj, RE, fmt);
577 printRelocationTargetName(Obj, RE, fmt);
580 // X86 and ARM share some relocation types in common.
581 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
582 Arch == Triple::ppc) {
583 // Generic relocation types...
585 case MachO::GENERIC_RELOC_PAIR: // prints no info
586 return std::error_code();
587 case MachO::GENERIC_RELOC_SECTDIFF: {
588 DataRefImpl RelNext = Rel;
589 Obj->moveRelocationNext(RelNext);
590 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
592 // X86 sect diff's must be followed by a relocation of type
593 // GENERIC_RELOC_PAIR.
594 unsigned RType = Obj->getAnyRelocationType(RENext);
596 if (RType != MachO::GENERIC_RELOC_PAIR)
597 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
598 "GENERIC_RELOC_SECTDIFF.");
600 printRelocationTargetName(Obj, RE, fmt);
602 printRelocationTargetName(Obj, RENext, fmt);
607 if (Arch == Triple::x86 || Arch == Triple::ppc) {
609 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
610 DataRefImpl RelNext = Rel;
611 Obj->moveRelocationNext(RelNext);
612 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
614 // X86 sect diff's must be followed by a relocation of type
615 // GENERIC_RELOC_PAIR.
616 unsigned RType = Obj->getAnyRelocationType(RENext);
617 if (RType != MachO::GENERIC_RELOC_PAIR)
618 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
619 "GENERIC_RELOC_LOCAL_SECTDIFF.");
621 printRelocationTargetName(Obj, RE, fmt);
623 printRelocationTargetName(Obj, RENext, fmt);
626 case MachO::GENERIC_RELOC_TLV: {
627 printRelocationTargetName(Obj, RE, fmt);
634 printRelocationTargetName(Obj, RE, fmt);
636 } else { // ARM-specific relocations
638 case MachO::ARM_RELOC_HALF:
639 case MachO::ARM_RELOC_HALF_SECTDIFF: {
640 // Half relocations steal a bit from the length field to encode
641 // whether this is an upper16 or a lower16 relocation.
642 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
648 printRelocationTargetName(Obj, RE, fmt);
650 DataRefImpl RelNext = Rel;
651 Obj->moveRelocationNext(RelNext);
652 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
654 // ARM half relocs must be followed by a relocation of type
656 unsigned RType = Obj->getAnyRelocationType(RENext);
657 if (RType != MachO::ARM_RELOC_PAIR)
658 report_fatal_error("Expected ARM_RELOC_PAIR after "
661 // NOTE: The half of the target virtual address is stashed in the
662 // address field of the secondary relocation, but we can't reverse
663 // engineer the constant offset from it without decoding the movw/movt
664 // instruction to find the other half in its immediate field.
666 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
667 // symbol/section pointer of the follow-on relocation.
668 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
670 printRelocationTargetName(Obj, RENext, fmt);
676 default: { printRelocationTargetName(Obj, RE, fmt); }
680 printRelocationTargetName(Obj, RE, fmt);
683 Result.append(fmtbuf.begin(), fmtbuf.end());
684 return std::error_code();
687 static std::error_code getRelocationValueString(const RelocationRef &Rel,
688 SmallVectorImpl<char> &Result) {
689 const ObjectFile *Obj = Rel.getObject();
690 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
691 return getRelocationValueString(ELF, Rel, Result);
692 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
693 return getRelocationValueString(COFF, Rel, Result);
694 auto *MachO = cast<MachOObjectFile>(Obj);
695 return getRelocationValueString(MachO, Rel, Result);
698 /// @brief Indicates whether this relocation should hidden when listing
699 /// relocations, usually because it is the trailing part of a multipart
700 /// relocation that will be printed as part of the leading relocation.
701 static bool getHidden(RelocationRef RelRef) {
702 const ObjectFile *Obj = RelRef.getObject();
703 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
707 unsigned Arch = MachO->getArch();
708 DataRefImpl Rel = RelRef.getRawDataRefImpl();
709 uint64_t Type = MachO->getRelocationType(Rel);
711 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
713 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
714 if (Type == MachO::GENERIC_RELOC_PAIR)
716 } else if (Arch == Triple::x86_64) {
717 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
718 // an X86_64_RELOC_SUBTRACTOR.
719 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
720 DataRefImpl RelPrev = Rel;
722 uint64_t PrevType = MachO->getRelocationType(RelPrev);
723 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
731 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
732 const Target *TheTarget = getTarget(Obj);
733 // getTarget() will have already issued a diagnostic if necessary, so
734 // just bail here if it failed.
738 // Package up features to be passed to target/subtarget
739 std::string FeaturesStr;
741 SubtargetFeatures Features;
742 for (unsigned i = 0; i != MAttrs.size(); ++i)
743 Features.AddFeature(MAttrs[i]);
744 FeaturesStr = Features.getString();
747 std::unique_ptr<const MCRegisterInfo> MRI(
748 TheTarget->createMCRegInfo(TripleName));
750 errs() << "error: no register info for target " << TripleName << "\n";
754 // Set up disassembler.
755 std::unique_ptr<const MCAsmInfo> AsmInfo(
756 TheTarget->createMCAsmInfo(*MRI, TripleName));
758 errs() << "error: no assembly info for target " << TripleName << "\n";
762 std::unique_ptr<const MCSubtargetInfo> STI(
763 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
765 errs() << "error: no subtarget info for target " << TripleName << "\n";
769 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
771 errs() << "error: no instruction info for target " << TripleName << "\n";
775 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
776 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
778 std::unique_ptr<MCDisassembler> DisAsm(
779 TheTarget->createMCDisassembler(*STI, Ctx));
782 errs() << "error: no disassembler for target " << TripleName << "\n";
786 std::unique_ptr<const MCInstrAnalysis> MIA(
787 TheTarget->createMCInstrAnalysis(MII.get()));
789 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
790 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
791 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
793 errs() << "error: no instruction printer for target " << TripleName
797 IP->setPrintImmHex(PrintImmHex);
798 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
800 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
801 "\t\t\t%08" PRIx64 ": ";
803 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
804 // in RelocSecs contain the relocations for section S.
806 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
807 for (const SectionRef &Section : Obj->sections()) {
808 section_iterator Sec2 = Section.getRelocatedSection();
809 if (Sec2 != Obj->section_end())
810 SectionRelocMap[*Sec2].push_back(Section);
813 for (const SectionRef &Section : Obj->sections()) {
814 if (!Section.isText() || Section.isVirtual())
817 uint64_t SectionAddr = Section.getAddress();
818 uint64_t SectSize = Section.getSize();
822 // Make a list of all the symbols in this section.
823 std::vector<std::pair<uint64_t, StringRef>> Symbols;
824 for (const SymbolRef &Symbol : Obj->symbols()) {
825 if (Section.containsSymbol(Symbol)) {
826 ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
827 if (error(AddressOrErr.getError()))
829 uint64_t Address = *AddressOrErr;
830 if (Address == UnknownAddress)
832 Address -= SectionAddr;
833 if (Address >= SectSize)
836 ErrorOr<StringRef> Name = Symbol.getName();
837 if (error(Name.getError()))
839 Symbols.push_back(std::make_pair(Address, *Name));
843 // Sort the symbols by address, just in case they didn't come in that way.
844 array_pod_sort(Symbols.begin(), Symbols.end());
846 // Make a list of all the relocations for this section.
847 std::vector<RelocationRef> Rels;
849 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
850 for (const RelocationRef &Reloc : RelocSec.relocations()) {
851 Rels.push_back(Reloc);
856 // Sort relocations by address.
857 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
859 StringRef SegmentName = "";
860 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
861 DataRefImpl DR = Section.getRawDataRefImpl();
862 SegmentName = MachO->getSectionFinalSegmentName(DR);
865 if (error(Section.getName(name)))
867 outs() << "Disassembly of section ";
868 if (!SegmentName.empty())
869 outs() << SegmentName << ",";
870 outs() << name << ':';
872 // If the section has no symbol at the start, just insert a dummy one.
873 if (Symbols.empty() || Symbols[0].first != 0)
874 Symbols.insert(Symbols.begin(), std::make_pair(0, name));
876 SmallString<40> Comments;
877 raw_svector_ostream CommentStream(Comments);
880 if (error(Section.getContents(BytesStr)))
882 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
888 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
889 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
890 // Disassemble symbol by symbol.
891 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
893 uint64_t Start = Symbols[si].first;
894 // The end is either the section end or the beginning of the next symbol.
895 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
896 // If this symbol has the same address as the next symbol, then skip it.
900 outs() << '\n' << Symbols[si].second << ":\n";
903 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
905 raw_ostream &DebugOut = nulls();
908 for (Index = Start; Index < End; Index += Size) {
911 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
912 SectionAddr + Index, DebugOut,
914 PIP.printInst(*IP, &Inst,
915 Bytes.slice(Index, Size),
916 SectionAddr + Index, outs(), "", *STI);
917 outs() << CommentStream.str();
921 errs() << ToolName << ": warning: invalid instruction encoding\n";
923 Size = 1; // skip illegible bytes
926 // Print relocation for instruction.
927 while (rel_cur != rel_end) {
928 bool hidden = getHidden(*rel_cur);
929 uint64_t addr = rel_cur->getOffset();
930 SmallString<16> name;
933 // If this relocation is hidden, skip it.
934 if (hidden) goto skip_print_rel;
936 // Stop when rel_cur's address is past the current instruction.
937 if (addr >= Index + Size) break;
938 rel_cur->getTypeName(name);
939 if (error(getRelocationValueString(*rel_cur, val)))
941 outs() << format(Fmt.data(), SectionAddr + addr) << name
942 << "\t" << val << "\n";
952 void llvm::PrintRelocations(const ObjectFile *Obj) {
953 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
955 // Regular objdump doesn't print relocations in non-relocatable object
957 if (!Obj->isRelocatableObject())
960 for (const SectionRef &Section : Obj->sections()) {
961 if (Section.relocation_begin() == Section.relocation_end())
964 if (error(Section.getName(secname)))
966 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
967 for (const RelocationRef &Reloc : Section.relocations()) {
968 bool hidden = getHidden(Reloc);
969 uint64_t address = Reloc.getOffset();
970 SmallString<32> relocname;
971 SmallString<32> valuestr;
974 Reloc.getTypeName(relocname);
975 if (error(getRelocationValueString(Reloc, valuestr)))
977 outs() << format(Fmt.data(), address) << " " << relocname << " "
984 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
985 outs() << "Sections:\n"
986 "Idx Name Size Address Type\n";
988 for (const SectionRef &Section : Obj->sections()) {
990 if (error(Section.getName(Name)))
992 uint64_t Address = Section.getAddress();
993 uint64_t Size = Section.getSize();
994 bool Text = Section.isText();
995 bool Data = Section.isData();
996 bool BSS = Section.isBSS();
997 std::string Type = (std::string(Text ? "TEXT " : "") +
998 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
999 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1000 Name.str().c_str(), Size, Address, Type.c_str());
1005 void llvm::PrintSectionContents(const ObjectFile *Obj) {
1007 for (const SectionRef &Section : Obj->sections()) {
1010 if (error(Section.getName(Name)))
1012 uint64_t BaseAddr = Section.getAddress();
1013 uint64_t Size = Section.getSize();
1017 outs() << "Contents of section " << Name << ":\n";
1018 if (Section.isBSS()) {
1019 outs() << format("<skipping contents of bss section at [%04" PRIx64
1020 ", %04" PRIx64 ")>\n",
1021 BaseAddr, BaseAddr + Size);
1025 if (error(Section.getContents(Contents)))
1028 // Dump out the content as hex and printable ascii characters.
1029 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1030 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1031 // Dump line of hex.
1032 for (std::size_t i = 0; i < 16; ++i) {
1033 if (i != 0 && i % 4 == 0)
1036 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1037 << hexdigit(Contents[addr + i] & 0xF, true);
1043 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1044 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1045 outs() << Contents[addr + i];
1054 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
1055 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1056 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
1058 if (error(Symbol.getError()))
1061 if (error(coff->getSymbolName(*Symbol, Name)))
1064 outs() << "[" << format("%2d", SI) << "]"
1065 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
1066 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
1067 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1068 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1069 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1070 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
1073 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
1074 if (Symbol->isSectionDefinition()) {
1075 const coff_aux_section_definition *asd;
1076 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
1079 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1082 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1083 , unsigned(asd->Length)
1084 , unsigned(asd->NumberOfRelocations)
1085 , unsigned(asd->NumberOfLinenumbers)
1086 , unsigned(asd->CheckSum))
1087 << format("assoc %d comdat %d\n"
1088 , unsigned(AuxNumber)
1089 , unsigned(asd->Selection));
1090 } else if (Symbol->isFileRecord()) {
1091 const char *FileName;
1092 if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
1095 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1096 coff->getSymbolTableEntrySize());
1097 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
1099 SI = SI + Symbol->getNumberOfAuxSymbols();
1102 outs() << "AUX Unknown\n";
1108 void llvm::PrintSymbolTable(const ObjectFile *o) {
1109 outs() << "SYMBOL TABLE:\n";
1111 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1112 PrintCOFFSymbolTable(coff);
1115 for (const SymbolRef &Symbol : o->symbols()) {
1116 ErrorOr<uint64_t> AddressOrError = Symbol.getAddress();
1117 if (error(AddressOrError.getError()))
1119 uint64_t Address = *AddressOrError;
1120 SymbolRef::Type Type = Symbol.getType();
1121 uint32_t Flags = Symbol.getFlags();
1122 section_iterator Section = o->section_end();
1123 if (error(Symbol.getSection(Section)))
1126 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1127 Section->getName(Name);
1129 ErrorOr<StringRef> NameOrErr = Symbol.getName();
1130 if (error(NameOrErr.getError()))
1135 bool Global = Flags & SymbolRef::SF_Global;
1136 bool Weak = Flags & SymbolRef::SF_Weak;
1137 bool Absolute = Flags & SymbolRef::SF_Absolute;
1138 bool Common = Flags & SymbolRef::SF_Common;
1139 bool Hidden = Flags & SymbolRef::SF_Hidden;
1142 Address = Symbol.getCommonSize();
1144 if (Address == UnknownAddress)
1147 if (Type != SymbolRef::ST_Unknown)
1148 GlobLoc = Global ? 'g' : 'l';
1149 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1151 char FileFunc = ' ';
1152 if (Type == SymbolRef::ST_File)
1154 else if (Type == SymbolRef::ST_Function)
1157 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1160 outs() << format(Fmt, Address) << " "
1161 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1162 << (Weak ? 'w' : ' ') // Weak?
1163 << ' ' // Constructor. Not supported yet.
1164 << ' ' // Warning. Not supported yet.
1165 << ' ' // Indirect reference to another symbol.
1166 << Debug // Debugging (d) or dynamic (D) symbol.
1167 << FileFunc // Name of function (F), file (f) or object (O).
1171 } else if (Common) {
1173 } else if (Section == o->section_end()) {
1176 if (const MachOObjectFile *MachO =
1177 dyn_cast<const MachOObjectFile>(o)) {
1178 DataRefImpl DR = Section->getRawDataRefImpl();
1179 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1180 outs() << SegmentName << ",";
1182 StringRef SectionName;
1183 if (error(Section->getName(SectionName)))
1185 outs() << SectionName;
1189 if (Common || isa<ELFObjectFileBase>(o)) {
1191 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1192 outs() << format("\t %08" PRIx64 " ", Val);
1196 outs() << ".hidden ";
1203 static void PrintUnwindInfo(const ObjectFile *o) {
1204 outs() << "Unwind info:\n\n";
1206 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1207 printCOFFUnwindInfo(coff);
1208 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1209 printMachOUnwindInfo(MachO);
1211 // TODO: Extract DWARF dump tool to objdump.
1212 errs() << "This operation is only currently supported "
1213 "for COFF and MachO object files.\n";
1218 void llvm::printExportsTrie(const ObjectFile *o) {
1219 outs() << "Exports trie:\n";
1220 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1221 printMachOExportsTrie(MachO);
1223 errs() << "This operation is only currently supported "
1224 "for Mach-O executable files.\n";
1229 void llvm::printRebaseTable(const ObjectFile *o) {
1230 outs() << "Rebase table:\n";
1231 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1232 printMachORebaseTable(MachO);
1234 errs() << "This operation is only currently supported "
1235 "for Mach-O executable files.\n";
1240 void llvm::printBindTable(const ObjectFile *o) {
1241 outs() << "Bind table:\n";
1242 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1243 printMachOBindTable(MachO);
1245 errs() << "This operation is only currently supported "
1246 "for Mach-O executable files.\n";
1251 void llvm::printLazyBindTable(const ObjectFile *o) {
1252 outs() << "Lazy bind table:\n";
1253 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1254 printMachOLazyBindTable(MachO);
1256 errs() << "This operation is only currently supported "
1257 "for Mach-O executable files.\n";
1262 void llvm::printWeakBindTable(const ObjectFile *o) {
1263 outs() << "Weak bind table:\n";
1264 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1265 printMachOWeakBindTable(MachO);
1267 errs() << "This operation is only currently supported "
1268 "for Mach-O executable files.\n";
1273 static void printFaultMaps(const ObjectFile *Obj) {
1274 const char *FaultMapSectionName = nullptr;
1276 if (isa<ELFObjectFileBase>(Obj)) {
1277 FaultMapSectionName = ".llvm_faultmaps";
1278 } else if (isa<MachOObjectFile>(Obj)) {
1279 FaultMapSectionName = "__llvm_faultmaps";
1281 errs() << "This operation is only currently supported "
1282 "for ELF and Mach-O executable files.\n";
1286 Optional<object::SectionRef> FaultMapSection;
1288 for (auto Sec : Obj->sections()) {
1291 if (Name == FaultMapSectionName) {
1292 FaultMapSection = Sec;
1297 outs() << "FaultMap table:\n";
1299 if (!FaultMapSection.hasValue()) {
1300 outs() << "<not found>\n";
1304 StringRef FaultMapContents;
1305 if (error(FaultMapSection.getValue().getContents(FaultMapContents))) {
1306 errs() << "Could not read the " << FaultMapContents << " section!\n";
1310 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1311 FaultMapContents.bytes_end());
1316 static void printPrivateFileHeader(const ObjectFile *o) {
1318 printELFFileHeader(o);
1319 } else if (o->isCOFF()) {
1320 printCOFFFileHeader(o);
1321 } else if (o->isMachO()) {
1322 printMachOFileHeader(o);
1326 static void DumpObject(const ObjectFile *o) {
1328 outs() << o->getFileName()
1329 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1332 DisassembleObject(o, Relocations);
1333 if (Relocations && !Disassemble)
1334 PrintRelocations(o);
1336 PrintSectionHeaders(o);
1337 if (SectionContents)
1338 PrintSectionContents(o);
1340 PrintSymbolTable(o);
1344 printPrivateFileHeader(o);
1346 printExportsTrie(o);
1348 printRebaseTable(o);
1352 printLazyBindTable(o);
1354 printWeakBindTable(o);
1359 /// @brief Dump each object file in \a a;
1360 static void DumpArchive(const Archive *a) {
1361 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
1363 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
1364 if (std::error_code EC = ChildOrErr.getError()) {
1365 // Ignore non-object files.
1366 if (EC != object_error::invalid_file_type)
1367 report_error(a->getFileName(), EC);
1370 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
1373 report_error(a->getFileName(), object_error::invalid_file_type);
1377 /// @brief Open file and figure out how to dump it.
1378 static void DumpInput(StringRef file) {
1379 // If file isn't stdin, check that it exists.
1380 if (file != "-" && !sys::fs::exists(file)) {
1381 report_error(file, errc::no_such_file_or_directory);
1385 // If we are using the Mach-O specific object file parser, then let it parse
1386 // the file and process the command line options. So the -arch flags can
1387 // be used to select specific slices, etc.
1389 ParseInputMachO(file);
1393 // Attempt to open the binary.
1394 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1395 if (std::error_code EC = BinaryOrErr.getError()) {
1396 report_error(file, EC);
1399 Binary &Binary = *BinaryOrErr.get().getBinary();
1401 if (Archive *a = dyn_cast<Archive>(&Binary))
1403 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
1406 report_error(file, object_error::invalid_file_type);
1409 int main(int argc, char **argv) {
1410 // Print a stack trace if we signal out.
1411 sys::PrintStackTraceOnErrorSignal();
1412 PrettyStackTraceProgram X(argc, argv);
1413 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1415 // Initialize targets and assembly printers/parsers.
1416 llvm::InitializeAllTargetInfos();
1417 llvm::InitializeAllTargetMCs();
1418 llvm::InitializeAllAsmParsers();
1419 llvm::InitializeAllDisassemblers();
1421 // Register the target printer for --version.
1422 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1424 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1425 TripleName = Triple::normalize(TripleName);
1429 // Defaults to a.out if no filenames specified.
1430 if (InputFilenames.size() == 0)
1431 InputFilenames.push_back("a.out");
1445 && !(UniversalHeaders && MachOOpt)
1446 && !(ArchiveHeaders && MachOOpt)
1447 && !(IndirectSymbols && MachOOpt)
1448 && !(DataInCode && MachOOpt)
1449 && !(LinkOptHints && MachOOpt)
1450 && !(InfoPlist && MachOOpt)
1451 && !(DylibsUsed && MachOOpt)
1452 && !(DylibId && MachOOpt)
1453 && !(ObjcMetaData && MachOOpt)
1454 && !(DumpSections.size() != 0 && MachOOpt)
1455 && !PrintFaultMaps) {
1456 cl::PrintHelpMessage();
1460 std::for_each(InputFilenames.begin(), InputFilenames.end(),