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/STLExtras.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCDisassembler.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCInstPrinter.h"
28 #include "llvm/MC/MCInstrAnalysis.h"
29 #include "llvm/MC/MCInstrInfo.h"
30 #include "llvm/MC/MCObjectFileInfo.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/MC/MCRelocationInfo.h"
33 #include "llvm/MC/MCSubtargetInfo.h"
34 #include "llvm/Object/Archive.h"
35 #include "llvm/Object/ELFObjectFile.h"
36 #include "llvm/Object/COFF.h"
37 #include "llvm/Object/MachO.h"
38 #include "llvm/Object/ObjectFile.h"
39 #include "llvm/Support/Casting.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/Errc.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/Format.h"
45 #include "llvm/Support/GraphWriter.h"
46 #include "llvm/Support/Host.h"
47 #include "llvm/Support/ManagedStatic.h"
48 #include "llvm/Support/MemoryBuffer.h"
49 #include "llvm/Support/PrettyStackTrace.h"
50 #include "llvm/Support/Signals.h"
51 #include "llvm/Support/SourceMgr.h"
52 #include "llvm/Support/TargetRegistry.h"
53 #include "llvm/Support/TargetSelect.h"
54 #include "llvm/Support/raw_ostream.h"
58 #include <system_error>
61 using namespace object;
63 static cl::list<std::string>
64 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
67 llvm::Disassemble("disassemble",
68 cl::desc("Display assembler mnemonics for the machine instructions"));
70 Disassembled("d", cl::desc("Alias for --disassemble"),
71 cl::aliasopt(Disassemble));
74 llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
77 llvm::SectionContents("s", cl::desc("Display the content of each section"));
80 llvm::SymbolTable("t", cl::desc("Display the symbol table"));
83 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
86 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
89 llvm::Bind("bind", cl::desc("Display mach-o binding info"));
92 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
95 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
98 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
100 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
103 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
104 "see -version for available targets"));
108 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
109 cl::value_desc("cpu-name"),
113 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
114 "see -version for available targets"));
117 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
118 "headers for each section."));
120 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
121 cl::aliasopt(SectionHeaders));
123 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
124 cl::aliasopt(SectionHeaders));
126 cl::list<std::string>
127 llvm::MAttrs("mattr",
129 cl::desc("Target specific attributes"),
130 cl::value_desc("a1,+a2,-a3,..."));
133 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
134 "instructions, do not print "
135 "the instruction bytes."));
138 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
141 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
142 cl::aliasopt(UnwindInfo));
145 llvm::PrivateHeaders("private-headers",
146 cl::desc("Display format specific file headers"));
149 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
150 cl::aliasopt(PrivateHeaders));
152 static StringRef ToolName;
153 static int ReturnValue = EXIT_SUCCESS;
155 bool llvm::error(std::error_code EC) {
159 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
161 ReturnValue = EXIT_FAILURE;
165 static void report_error(StringRef File, std::error_code EC) {
167 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
168 ReturnValue = EXIT_FAILURE;
171 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
172 // Figure out the target triple.
173 llvm::Triple TheTriple("unknown-unknown-unknown");
174 if (TripleName.empty()) {
176 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
177 // TheTriple defaults to ELF, and COFF doesn't have an environment:
178 // the best we can do here is indicate that it is mach-o.
180 TheTriple.setObjectFormat(Triple::MachO);
183 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
184 if (COFFObj->getArch() == Triple::thumb)
185 TheTriple.setTriple("thumbv7-windows");
189 TheTriple.setTriple(Triple::normalize(TripleName));
191 // Get the target specific parser.
193 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
196 errs() << ToolName << ": " << Error;
200 // Update the triple name and return the found target.
201 TripleName = TheTriple.getTriple();
205 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
206 uint64_t a_addr, b_addr;
207 if (error(a.getOffset(a_addr))) return false;
208 if (error(b.getOffset(b_addr))) return false;
209 return a_addr < b_addr;
213 class PrettyPrinter {
215 virtual ~PrettyPrinter(){}
216 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
217 ArrayRef<uint8_t> Bytes, uint64_t Address,
218 raw_ostream &OS, StringRef Annot,
219 MCSubtargetInfo const &STI) {
220 outs() << format("%8" PRIx64 ":", Address);
221 if (!NoShowRawInsn) {
223 dumpBytes(Bytes, outs());
225 IP.printInst(MI, outs(), "", STI);
228 PrettyPrinter PrettyPrinterInst;
229 class HexagonPrettyPrinter : public PrettyPrinter {
231 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
234 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
235 OS << format("%8" PRIx64 ":", Address);
236 if (!NoShowRawInsn) {
238 dumpBytes(Bytes.slice(0, 4), OS);
239 OS << format("%08" PRIx32, opcode);
242 void printInst(MCInstPrinter &IP, const MCInst *MI,
243 ArrayRef<uint8_t> Bytes, uint64_t Address,
244 raw_ostream &OS, StringRef Annot,
245 MCSubtargetInfo const &STI) override {
248 raw_string_ostream TempStream(Buffer);
249 IP.printInst(MI, TempStream, "", STI);
251 StringRef Contents(Buffer);
252 // Split off bundle attributes
253 auto PacketBundle = Contents.rsplit('\n');
254 // Split off first instruction from the rest
255 auto HeadTail = PacketBundle.first.split('\n');
256 auto Preamble = " { ";
258 while(!HeadTail.first.empty()) {
261 printLead(Bytes, Address, OS);
265 auto Duplex = HeadTail.first.split('\v');
266 if(!Duplex.second.empty()){
269 Inst = Duplex.second;
272 Inst = HeadTail.first;
274 Bytes = Bytes.slice(4);
276 HeadTail = HeadTail.second.split('\n');
278 OS << " } " << PacketBundle.second;
281 HexagonPrettyPrinter HexagonPrettyPrinterInst;
282 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
283 switch(Triple.getArch()) {
285 return PrettyPrinterInst;
286 case Triple::hexagon:
287 return HexagonPrettyPrinterInst;
292 template <class ELFT>
293 static const typename ELFObjectFile<ELFT>::Elf_Rel *
294 getRel(const ELFFile<ELFT> &EF, DataRefImpl Rel) {
295 typedef typename ELFObjectFile<ELFT>::Elf_Rel Elf_Rel;
296 return EF.template getEntry<Elf_Rel>(Rel.d.a, Rel.d.b);
299 template <class ELFT>
300 static const typename ELFObjectFile<ELFT>::Elf_Rela *
301 getRela(const ELFFile<ELFT> &EF, DataRefImpl Rela) {
302 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
303 return EF.template getEntry<Elf_Rela>(Rela.d.a, Rela.d.b);
306 template <class ELFT>
307 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
309 SmallVectorImpl<char> &Result) {
310 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
311 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
312 const ELFFile<ELFT> &EF = *Obj->getELFFile();
314 const Elf_Shdr *sec = EF.getSection(Rel.d.a);
318 uint16_t symbol_index = 0;
319 switch (sec->sh_type) {
321 return object_error::parse_failed;
323 type = getRel(EF, Rel)->getType(EF.isMips64EL());
324 symbol_index = getRel(EF, Rel)->getSymbol(EF.isMips64EL());
325 // TODO: Read implicit addend from section data.
328 case ELF::SHT_RELA: {
329 type = getRela(EF, Rel)->getType(EF.isMips64EL());
330 symbol_index = getRela(EF, Rel)->getSymbol(EF.isMips64EL());
331 addend = getRela(EF, Rel)->r_addend;
335 const Elf_Sym *symb =
336 EF.template getEntry<Elf_Sym>(sec->sh_link, symbol_index);
338 const Elf_Shdr *SymSec = EF.getSection(symb);
339 if (symb->getType() == ELF::STT_SECTION) {
340 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
341 if (std::error_code EC = SecName.getError())
345 ErrorOr<StringRef> SymName =
346 EF.getSymbolName(EF.getSection(sec->sh_link), symb);
348 return SymName.getError();
351 switch (EF.getHeader()->e_machine) {
354 case ELF::R_X86_64_PC8:
355 case ELF::R_X86_64_PC16:
356 case ELF::R_X86_64_PC32: {
358 raw_string_ostream fmt(fmtbuf);
359 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
361 Result.append(fmtbuf.begin(), fmtbuf.end());
363 case ELF::R_X86_64_8:
364 case ELF::R_X86_64_16:
365 case ELF::R_X86_64_32:
366 case ELF::R_X86_64_32S:
367 case ELF::R_X86_64_64: {
369 raw_string_ostream fmt(fmtbuf);
370 fmt << Target << (addend < 0 ? "" : "+") << addend;
372 Result.append(fmtbuf.begin(), fmtbuf.end());
378 case ELF::EM_AARCH64: {
380 raw_string_ostream fmt(fmtbuf);
383 fmt << (addend < 0 ? "" : "+") << addend;
385 Result.append(fmtbuf.begin(), fmtbuf.end());
390 case ELF::EM_HEXAGON:
398 Result.append(res.begin(), res.end());
399 return object_error::success;
402 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
403 const RelocationRef &RelRef,
404 SmallVectorImpl<char> &Result) {
405 DataRefImpl Rel = RelRef.getRawDataRefImpl();
406 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
407 return getRelocationValueString(ELF32LE, Rel, Result);
408 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
409 return getRelocationValueString(ELF64LE, Rel, Result);
410 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
411 return getRelocationValueString(ELF32BE, Rel, Result);
412 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
413 return getRelocationValueString(ELF64BE, Rel, Result);
416 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
417 const RelocationRef &Rel,
418 SmallVectorImpl<char> &Result) {
419 symbol_iterator SymI = Rel.getSymbol();
421 if (std::error_code EC = SymI->getName(SymName))
423 Result.append(SymName.begin(), SymName.end());
424 return object_error::success;
427 static void printRelocationTargetName(const MachOObjectFile *O,
428 const MachO::any_relocation_info &RE,
429 raw_string_ostream &fmt) {
430 bool IsScattered = O->isRelocationScattered(RE);
432 // Target of a scattered relocation is an address. In the interest of
433 // generating pretty output, scan through the symbol table looking for a
434 // symbol that aligns with that address. If we find one, print it.
435 // Otherwise, we just print the hex address of the target.
437 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
439 for (const SymbolRef &Symbol : O->symbols()) {
444 if ((ec = Symbol.getAddress(Addr)))
445 report_fatal_error(ec.message());
448 if ((ec = Symbol.getName(Name)))
449 report_fatal_error(ec.message());
454 // If we couldn't find a symbol that this relocation refers to, try
455 // to find a section beginning instead.
456 for (const SectionRef &Section : O->sections()) {
460 uint64_t Addr = Section.getAddress();
463 if ((ec = Section.getName(Name)))
464 report_fatal_error(ec.message());
469 fmt << format("0x%x", Val);
474 bool isExtern = O->getPlainRelocationExternal(RE);
475 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
478 symbol_iterator SI = O->symbol_begin();
482 section_iterator SI = O->section_begin();
483 // Adjust for the fact that sections are 1-indexed.
484 advance(SI, Val - 1);
491 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
492 const RelocationRef &RelRef,
493 SmallVectorImpl<char> &Result) {
494 DataRefImpl Rel = RelRef.getRawDataRefImpl();
495 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
497 unsigned Arch = Obj->getArch();
500 raw_string_ostream fmt(fmtbuf);
501 unsigned Type = Obj->getAnyRelocationType(RE);
502 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
504 // Determine any addends that should be displayed with the relocation.
505 // These require decoding the relocation type, which is triple-specific.
507 // X86_64 has entirely custom relocation types.
508 if (Arch == Triple::x86_64) {
509 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
512 case MachO::X86_64_RELOC_GOT_LOAD:
513 case MachO::X86_64_RELOC_GOT: {
514 printRelocationTargetName(Obj, RE, fmt);
520 case MachO::X86_64_RELOC_SUBTRACTOR: {
521 DataRefImpl RelNext = Rel;
522 Obj->moveRelocationNext(RelNext);
523 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
525 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
526 // X86_64_RELOC_UNSIGNED.
527 // NOTE: Scattered relocations don't exist on x86_64.
528 unsigned RType = Obj->getAnyRelocationType(RENext);
529 if (RType != MachO::X86_64_RELOC_UNSIGNED)
530 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
531 "X86_64_RELOC_SUBTRACTOR.");
533 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
534 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
535 printRelocationTargetName(Obj, RENext, fmt);
537 printRelocationTargetName(Obj, RE, fmt);
540 case MachO::X86_64_RELOC_TLV:
541 printRelocationTargetName(Obj, RE, fmt);
546 case MachO::X86_64_RELOC_SIGNED_1:
547 printRelocationTargetName(Obj, RE, fmt);
550 case MachO::X86_64_RELOC_SIGNED_2:
551 printRelocationTargetName(Obj, RE, fmt);
554 case MachO::X86_64_RELOC_SIGNED_4:
555 printRelocationTargetName(Obj, RE, fmt);
559 printRelocationTargetName(Obj, RE, fmt);
562 // X86 and ARM share some relocation types in common.
563 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
564 Arch == Triple::ppc) {
565 // Generic relocation types...
567 case MachO::GENERIC_RELOC_PAIR: // prints no info
568 return object_error::success;
569 case MachO::GENERIC_RELOC_SECTDIFF: {
570 DataRefImpl RelNext = Rel;
571 Obj->moveRelocationNext(RelNext);
572 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
574 // X86 sect diff's must be followed by a relocation of type
575 // GENERIC_RELOC_PAIR.
576 unsigned RType = Obj->getAnyRelocationType(RENext);
578 if (RType != MachO::GENERIC_RELOC_PAIR)
579 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
580 "GENERIC_RELOC_SECTDIFF.");
582 printRelocationTargetName(Obj, RE, fmt);
584 printRelocationTargetName(Obj, RENext, fmt);
589 if (Arch == Triple::x86 || Arch == Triple::ppc) {
591 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
592 DataRefImpl RelNext = Rel;
593 Obj->moveRelocationNext(RelNext);
594 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
596 // X86 sect diff's must be followed by a relocation of type
597 // GENERIC_RELOC_PAIR.
598 unsigned RType = Obj->getAnyRelocationType(RENext);
599 if (RType != MachO::GENERIC_RELOC_PAIR)
600 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
601 "GENERIC_RELOC_LOCAL_SECTDIFF.");
603 printRelocationTargetName(Obj, RE, fmt);
605 printRelocationTargetName(Obj, RENext, fmt);
608 case MachO::GENERIC_RELOC_TLV: {
609 printRelocationTargetName(Obj, RE, fmt);
616 printRelocationTargetName(Obj, RE, fmt);
618 } else { // ARM-specific relocations
620 case MachO::ARM_RELOC_HALF:
621 case MachO::ARM_RELOC_HALF_SECTDIFF: {
622 // Half relocations steal a bit from the length field to encode
623 // whether this is an upper16 or a lower16 relocation.
624 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
630 printRelocationTargetName(Obj, RE, fmt);
632 DataRefImpl RelNext = Rel;
633 Obj->moveRelocationNext(RelNext);
634 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
636 // ARM half relocs must be followed by a relocation of type
638 unsigned RType = Obj->getAnyRelocationType(RENext);
639 if (RType != MachO::ARM_RELOC_PAIR)
640 report_fatal_error("Expected ARM_RELOC_PAIR after "
643 // NOTE: The half of the target virtual address is stashed in the
644 // address field of the secondary relocation, but we can't reverse
645 // engineer the constant offset from it without decoding the movw/movt
646 // instruction to find the other half in its immediate field.
648 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
649 // symbol/section pointer of the follow-on relocation.
650 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
652 printRelocationTargetName(Obj, RENext, fmt);
658 default: { printRelocationTargetName(Obj, RE, fmt); }
662 printRelocationTargetName(Obj, RE, fmt);
665 Result.append(fmtbuf.begin(), fmtbuf.end());
666 return object_error::success;
669 static std::error_code getRelocationValueString(const RelocationRef &Rel,
670 SmallVectorImpl<char> &Result) {
671 const ObjectFile *Obj = Rel.getObjectFile();
672 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
673 return getRelocationValueString(ELF, Rel, Result);
674 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
675 return getRelocationValueString(COFF, Rel, Result);
676 auto *MachO = cast<MachOObjectFile>(Obj);
677 return getRelocationValueString(MachO, Rel, Result);
680 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
681 const Target *TheTarget = getTarget(Obj);
682 // getTarget() will have already issued a diagnostic if necessary, so
683 // just bail here if it failed.
687 // Package up features to be passed to target/subtarget
688 std::string FeaturesStr;
690 SubtargetFeatures Features;
691 for (unsigned i = 0; i != MAttrs.size(); ++i)
692 Features.AddFeature(MAttrs[i]);
693 FeaturesStr = Features.getString();
696 std::unique_ptr<const MCRegisterInfo> MRI(
697 TheTarget->createMCRegInfo(TripleName));
699 errs() << "error: no register info for target " << TripleName << "\n";
703 // Set up disassembler.
704 std::unique_ptr<const MCAsmInfo> AsmInfo(
705 TheTarget->createMCAsmInfo(*MRI, TripleName));
707 errs() << "error: no assembly info for target " << TripleName << "\n";
711 std::unique_ptr<const MCSubtargetInfo> STI(
712 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
714 errs() << "error: no subtarget info for target " << TripleName << "\n";
718 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
720 errs() << "error: no instruction info for target " << TripleName << "\n";
724 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
725 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
727 std::unique_ptr<MCDisassembler> DisAsm(
728 TheTarget->createMCDisassembler(*STI, Ctx));
731 errs() << "error: no disassembler for target " << TripleName << "\n";
735 std::unique_ptr<const MCInstrAnalysis> MIA(
736 TheTarget->createMCInstrAnalysis(MII.get()));
738 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
739 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
740 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
742 errs() << "error: no instruction printer for target " << TripleName
746 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
748 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
749 "\t\t\t%08" PRIx64 ": ";
751 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
752 // in RelocSecs contain the relocations for section S.
754 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
755 for (const SectionRef &Section : Obj->sections()) {
756 section_iterator Sec2 = Section.getRelocatedSection();
757 if (Sec2 != Obj->section_end())
758 SectionRelocMap[*Sec2].push_back(Section);
761 for (const SectionRef &Section : Obj->sections()) {
762 if (!Section.isText() || Section.isVirtual())
765 uint64_t SectionAddr = Section.getAddress();
766 uint64_t SectSize = Section.getSize();
770 // Make a list of all the symbols in this section.
771 std::vector<std::pair<uint64_t, StringRef>> Symbols;
772 for (const SymbolRef &Symbol : Obj->symbols()) {
773 if (Section.containsSymbol(Symbol)) {
775 if (error(Symbol.getAddress(Address)))
777 if (Address == UnknownAddressOrSize)
779 Address -= SectionAddr;
780 if (Address >= SectSize)
784 if (error(Symbol.getName(Name)))
786 Symbols.push_back(std::make_pair(Address, Name));
790 // Sort the symbols by address, just in case they didn't come in that way.
791 array_pod_sort(Symbols.begin(), Symbols.end());
793 // Make a list of all the relocations for this section.
794 std::vector<RelocationRef> Rels;
796 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
797 for (const RelocationRef &Reloc : RelocSec.relocations()) {
798 Rels.push_back(Reloc);
803 // Sort relocations by address.
804 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
806 StringRef SegmentName = "";
807 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
808 DataRefImpl DR = Section.getRawDataRefImpl();
809 SegmentName = MachO->getSectionFinalSegmentName(DR);
812 if (error(Section.getName(name)))
814 outs() << "Disassembly of section ";
815 if (!SegmentName.empty())
816 outs() << SegmentName << ",";
817 outs() << name << ':';
819 // If the section has no symbol at the start, just insert a dummy one.
820 if (Symbols.empty() || Symbols[0].first != 0)
821 Symbols.insert(Symbols.begin(), std::make_pair(0, name));
823 SmallString<40> Comments;
824 raw_svector_ostream CommentStream(Comments);
827 if (error(Section.getContents(BytesStr)))
829 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
835 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
836 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
837 // Disassemble symbol by symbol.
838 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
840 uint64_t Start = Symbols[si].first;
841 // The end is either the section end or the beginning of the next symbol.
842 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
843 // If this symbol has the same address as the next symbol, then skip it.
847 outs() << '\n' << Symbols[si].second << ":\n";
850 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
852 raw_ostream &DebugOut = nulls();
855 for (Index = Start; Index < End; Index += Size) {
858 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
859 SectionAddr + Index, DebugOut,
861 PIP.printInst(*IP, &Inst,
862 Bytes.slice(Index, Size),
863 SectionAddr + Index, outs(), "", *STI);
864 outs() << CommentStream.str();
868 errs() << ToolName << ": warning: invalid instruction encoding\n";
870 Size = 1; // skip illegible bytes
873 // Print relocation for instruction.
874 while (rel_cur != rel_end) {
877 SmallString<16> name;
880 // If this relocation is hidden, skip it.
881 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
882 if (hidden) goto skip_print_rel;
884 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
885 // Stop when rel_cur's address is past the current instruction.
886 if (addr >= Index + Size) break;
887 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
888 if (error(getRelocationValueString(*rel_cur, val)))
890 outs() << format(Fmt.data(), SectionAddr + addr) << name
891 << "\t" << val << "\n";
901 void llvm::PrintRelocations(const ObjectFile *Obj) {
902 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
904 // Regular objdump doesn't print relocations in non-relocatable object
906 if (!Obj->isRelocatableObject())
909 for (const SectionRef &Section : Obj->sections()) {
910 if (Section.relocation_begin() == Section.relocation_end())
913 if (error(Section.getName(secname)))
915 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
916 for (const RelocationRef &Reloc : Section.relocations()) {
919 SmallString<32> relocname;
920 SmallString<32> valuestr;
921 if (error(Reloc.getHidden(hidden)))
925 if (error(Reloc.getTypeName(relocname)))
927 if (error(Reloc.getOffset(address)))
929 if (error(getRelocationValueString(Reloc, valuestr)))
931 outs() << format(Fmt.data(), address) << " " << relocname << " "
938 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
939 outs() << "Sections:\n"
940 "Idx Name Size Address Type\n";
942 for (const SectionRef &Section : Obj->sections()) {
944 if (error(Section.getName(Name)))
946 uint64_t Address = Section.getAddress();
947 uint64_t Size = Section.getSize();
948 bool Text = Section.isText();
949 bool Data = Section.isData();
950 bool BSS = Section.isBSS();
951 std::string Type = (std::string(Text ? "TEXT " : "") +
952 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
953 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
954 Name.str().c_str(), Size, Address, Type.c_str());
959 void llvm::PrintSectionContents(const ObjectFile *Obj) {
961 for (const SectionRef &Section : Obj->sections()) {
964 if (error(Section.getName(Name)))
966 uint64_t BaseAddr = Section.getAddress();
967 uint64_t Size = Section.getSize();
971 outs() << "Contents of section " << Name << ":\n";
972 if (Section.isBSS()) {
973 outs() << format("<skipping contents of bss section at [%04" PRIx64
974 ", %04" PRIx64 ")>\n",
975 BaseAddr, BaseAddr + Size);
979 if (error(Section.getContents(Contents)))
982 // Dump out the content as hex and printable ascii characters.
983 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
984 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
986 for (std::size_t i = 0; i < 16; ++i) {
987 if (i != 0 && i % 4 == 0)
990 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
991 << hexdigit(Contents[addr + i] & 0xF, true);
997 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
998 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
999 outs() << Contents[addr + i];
1008 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
1009 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1010 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
1012 if (error(Symbol.getError()))
1015 if (error(coff->getSymbolName(*Symbol, Name)))
1018 outs() << "[" << format("%2d", SI) << "]"
1019 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
1020 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
1021 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1022 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1023 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1024 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
1027 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
1028 if (Symbol->isSectionDefinition()) {
1029 const coff_aux_section_definition *asd;
1030 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
1033 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1036 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1037 , unsigned(asd->Length)
1038 , unsigned(asd->NumberOfRelocations)
1039 , unsigned(asd->NumberOfLinenumbers)
1040 , unsigned(asd->CheckSum))
1041 << format("assoc %d comdat %d\n"
1042 , unsigned(AuxNumber)
1043 , unsigned(asd->Selection));
1044 } else if (Symbol->isFileRecord()) {
1045 const char *FileName;
1046 if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
1049 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1050 coff->getSymbolTableEntrySize());
1051 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
1053 SI = SI + Symbol->getNumberOfAuxSymbols();
1056 outs() << "AUX Unknown\n";
1062 void llvm::PrintSymbolTable(const ObjectFile *o) {
1063 outs() << "SYMBOL TABLE:\n";
1065 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1066 PrintCOFFSymbolTable(coff);
1069 for (const SymbolRef &Symbol : o->symbols()) {
1071 SymbolRef::Type Type;
1072 uint32_t Flags = Symbol.getFlags();
1073 section_iterator Section = o->section_end();
1074 if (error(Symbol.getAddress(Address)))
1076 if (error(Symbol.getType(Type)))
1078 uint64_t Size = Symbol.getSize();
1079 if (error(Symbol.getSection(Section)))
1082 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1083 Section->getName(Name);
1084 } else if (error(Symbol.getName(Name))) {
1088 bool Global = Flags & SymbolRef::SF_Global;
1089 bool Weak = Flags & SymbolRef::SF_Weak;
1090 bool Absolute = Flags & SymbolRef::SF_Absolute;
1091 bool Common = Flags & SymbolRef::SF_Common;
1092 bool Hidden = Flags & SymbolRef::SF_Hidden;
1095 uint32_t Alignment = Symbol.getAlignment();
1099 if (Address == UnknownAddressOrSize)
1101 if (Size == UnknownAddressOrSize)
1104 if (Type != SymbolRef::ST_Unknown)
1105 GlobLoc = Global ? 'g' : 'l';
1106 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1108 char FileFunc = ' ';
1109 if (Type == SymbolRef::ST_File)
1111 else if (Type == SymbolRef::ST_Function)
1114 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1117 outs() << format(Fmt, Address) << " "
1118 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1119 << (Weak ? 'w' : ' ') // Weak?
1120 << ' ' // Constructor. Not supported yet.
1121 << ' ' // Warning. Not supported yet.
1122 << ' ' // Indirect reference to another symbol.
1123 << Debug // Debugging (d) or dynamic (D) symbol.
1124 << FileFunc // Name of function (F), file (f) or object (O).
1128 } else if (Common) {
1130 } else if (Section == o->section_end()) {
1133 if (const MachOObjectFile *MachO =
1134 dyn_cast<const MachOObjectFile>(o)) {
1135 DataRefImpl DR = Section->getRawDataRefImpl();
1136 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1137 outs() << SegmentName << ",";
1139 StringRef SectionName;
1140 if (error(Section->getName(SectionName)))
1142 outs() << SectionName;
1145 << format("%08" PRIx64 " ", Size);
1147 outs() << ".hidden ";
1154 static void PrintUnwindInfo(const ObjectFile *o) {
1155 outs() << "Unwind info:\n\n";
1157 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1158 printCOFFUnwindInfo(coff);
1159 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1160 printMachOUnwindInfo(MachO);
1162 // TODO: Extract DWARF dump tool to objdump.
1163 errs() << "This operation is only currently supported "
1164 "for COFF and MachO object files.\n";
1169 void llvm::printExportsTrie(const ObjectFile *o) {
1170 outs() << "Exports trie:\n";
1171 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1172 printMachOExportsTrie(MachO);
1174 errs() << "This operation is only currently supported "
1175 "for Mach-O executable files.\n";
1180 void llvm::printRebaseTable(const ObjectFile *o) {
1181 outs() << "Rebase table:\n";
1182 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1183 printMachORebaseTable(MachO);
1185 errs() << "This operation is only currently supported "
1186 "for Mach-O executable files.\n";
1191 void llvm::printBindTable(const ObjectFile *o) {
1192 outs() << "Bind table:\n";
1193 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1194 printMachOBindTable(MachO);
1196 errs() << "This operation is only currently supported "
1197 "for Mach-O executable files.\n";
1202 void llvm::printLazyBindTable(const ObjectFile *o) {
1203 outs() << "Lazy bind table:\n";
1204 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1205 printMachOLazyBindTable(MachO);
1207 errs() << "This operation is only currently supported "
1208 "for Mach-O executable files.\n";
1213 void llvm::printWeakBindTable(const ObjectFile *o) {
1214 outs() << "Weak bind table:\n";
1215 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1216 printMachOWeakBindTable(MachO);
1218 errs() << "This operation is only currently supported "
1219 "for Mach-O executable files.\n";
1224 static void printPrivateFileHeader(const ObjectFile *o) {
1226 printELFFileHeader(o);
1227 } else if (o->isCOFF()) {
1228 printCOFFFileHeader(o);
1229 } else if (o->isMachO()) {
1230 printMachOFileHeader(o);
1234 static void DumpObject(const ObjectFile *o) {
1236 outs() << o->getFileName()
1237 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1240 DisassembleObject(o, Relocations);
1241 if (Relocations && !Disassemble)
1242 PrintRelocations(o);
1244 PrintSectionHeaders(o);
1245 if (SectionContents)
1246 PrintSectionContents(o);
1248 PrintSymbolTable(o);
1252 printPrivateFileHeader(o);
1254 printExportsTrie(o);
1256 printRebaseTable(o);
1260 printLazyBindTable(o);
1262 printWeakBindTable(o);
1265 /// @brief Dump each object file in \a a;
1266 static void DumpArchive(const Archive *a) {
1267 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
1269 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
1270 if (std::error_code EC = ChildOrErr.getError()) {
1271 // Ignore non-object files.
1272 if (EC != object_error::invalid_file_type)
1273 report_error(a->getFileName(), EC);
1276 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
1279 report_error(a->getFileName(), object_error::invalid_file_type);
1283 /// @brief Open file and figure out how to dump it.
1284 static void DumpInput(StringRef file) {
1285 // If file isn't stdin, check that it exists.
1286 if (file != "-" && !sys::fs::exists(file)) {
1287 report_error(file, errc::no_such_file_or_directory);
1291 // If we are using the Mach-O specific object file parser, then let it parse
1292 // the file and process the command line options. So the -arch flags can
1293 // be used to select specific slices, etc.
1295 ParseInputMachO(file);
1299 // Attempt to open the binary.
1300 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1301 if (std::error_code EC = BinaryOrErr.getError()) {
1302 report_error(file, EC);
1305 Binary &Binary = *BinaryOrErr.get().getBinary();
1307 if (Archive *a = dyn_cast<Archive>(&Binary))
1309 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
1312 report_error(file, object_error::invalid_file_type);
1315 int main(int argc, char **argv) {
1316 // Print a stack trace if we signal out.
1317 sys::PrintStackTraceOnErrorSignal();
1318 PrettyStackTraceProgram X(argc, argv);
1319 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1321 // Initialize targets and assembly printers/parsers.
1322 llvm::InitializeAllTargetInfos();
1323 llvm::InitializeAllTargetMCs();
1324 llvm::InitializeAllAsmParsers();
1325 llvm::InitializeAllDisassemblers();
1327 // Register the target printer for --version.
1328 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1330 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1331 TripleName = Triple::normalize(TripleName);
1335 // Defaults to a.out if no filenames specified.
1336 if (InputFilenames.size() == 0)
1337 InputFilenames.push_back("a.out");
1351 && !(UniversalHeaders && MachOOpt)
1352 && !(ArchiveHeaders && MachOOpt)
1353 && !(IndirectSymbols && MachOOpt)
1354 && !(DataInCode && MachOOpt)
1355 && !(LinkOptHints && MachOOpt)
1356 && !(InfoPlist && MachOOpt)
1357 && !(DylibsUsed && MachOOpt)
1358 && !(DylibId && MachOOpt)
1359 && !(ObjcMetaData && MachOOpt)
1360 && !(DumpSections.size() != 0 && MachOOpt)) {
1361 cl::PrintHelpMessage();
1365 std::for_each(InputFilenames.begin(), InputFilenames.end(),