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/FileSystem.h"
43 #include "llvm/Support/Format.h"
44 #include "llvm/Support/GraphWriter.h"
45 #include "llvm/Support/Host.h"
46 #include "llvm/Support/ManagedStatic.h"
47 #include "llvm/Support/MemoryBuffer.h"
48 #include "llvm/Support/PrettyStackTrace.h"
49 #include "llvm/Support/Signals.h"
50 #include "llvm/Support/SourceMgr.h"
51 #include "llvm/Support/TargetRegistry.h"
52 #include "llvm/Support/TargetSelect.h"
53 #include "llvm/Support/raw_ostream.h"
57 #include <system_error>
60 using namespace object;
62 static cl::list<std::string>
63 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
66 llvm::Disassemble("disassemble",
67 cl::desc("Display assembler mnemonics for the machine instructions"));
69 Disassembled("d", cl::desc("Alias for --disassemble"),
70 cl::aliasopt(Disassemble));
73 llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
76 llvm::SectionContents("s", cl::desc("Display the content of each section"));
79 llvm::SymbolTable("t", cl::desc("Display the symbol table"));
82 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
85 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
88 llvm::Bind("bind", cl::desc("Display mach-o binding info"));
91 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
94 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
97 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
99 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
102 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
103 "see -version for available targets"));
107 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
108 cl::value_desc("cpu-name"),
112 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
113 "see -version for available targets"));
116 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
117 "headers for each section."));
119 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
120 cl::aliasopt(SectionHeaders));
122 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
123 cl::aliasopt(SectionHeaders));
125 cl::list<std::string>
126 llvm::MAttrs("mattr",
128 cl::desc("Target specific attributes"),
129 cl::value_desc("a1,+a2,-a3,..."));
132 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
133 "instructions, do not print "
134 "the instruction bytes."));
137 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
140 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
141 cl::aliasopt(UnwindInfo));
144 llvm::PrivateHeaders("private-headers",
145 cl::desc("Display format specific file headers"));
148 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
149 cl::aliasopt(PrivateHeaders));
151 static StringRef ToolName;
152 static int ReturnValue = EXIT_SUCCESS;
154 bool llvm::error(std::error_code EC) {
158 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
160 ReturnValue = EXIT_FAILURE;
164 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
165 // Figure out the target triple.
166 llvm::Triple TheTriple("unknown-unknown-unknown");
167 if (TripleName.empty()) {
169 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
170 // TheTriple defaults to ELF, and COFF doesn't have an environment:
171 // the best we can do here is indicate that it is mach-o.
173 TheTriple.setObjectFormat(Triple::MachO);
176 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
177 if (COFFObj->getArch() == Triple::thumb)
178 TheTriple.setTriple("thumbv7-windows");
182 TheTriple.setTriple(Triple::normalize(TripleName));
184 // Get the target specific parser.
186 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
189 errs() << ToolName << ": " << Error;
193 // Update the triple name and return the found target.
194 TripleName = TheTriple.getTriple();
198 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
199 uint64_t a_addr, b_addr;
200 if (error(a.getOffset(a_addr))) return false;
201 if (error(b.getOffset(b_addr))) return false;
202 return a_addr < b_addr;
206 class PrettyPrinter {
208 virtual ~PrettyPrinter(){}
209 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
210 ArrayRef<uint8_t> Bytes, uint64_t Address,
211 raw_ostream &OS, StringRef Annot,
212 MCSubtargetInfo const &STI) {
213 outs() << format("%8" PRIx64 ":", Address);
214 if (!NoShowRawInsn) {
216 dumpBytes(Bytes, outs());
218 IP.printInst(MI, outs(), "", STI);
221 PrettyPrinter PrettyPrinterInst;
222 class HexagonPrettyPrinter : public PrettyPrinter {
224 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
227 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
228 OS << format("%8" PRIx64 ":", Address);
229 if (!NoShowRawInsn) {
231 dumpBytes(Bytes.slice(0, 4), OS);
232 OS << format("%08" PRIx32, opcode);
235 void printInst(MCInstPrinter &IP, const MCInst *MI,
236 ArrayRef<uint8_t> Bytes, uint64_t Address,
237 raw_ostream &OS, StringRef Annot,
238 MCSubtargetInfo const &STI) override {
241 raw_string_ostream TempStream(Buffer);
242 IP.printInst(MI, TempStream, "", STI);
244 StringRef Contents(Buffer);
245 // Split off bundle attributes
246 auto PacketBundle = Contents.rsplit('\n');
247 // Split off first instruction from the rest
248 auto HeadTail = PacketBundle.first.split('\n');
249 auto Preamble = " { ";
251 while(!HeadTail.first.empty()) {
254 printLead(Bytes, Address, OS);
258 auto Duplex = HeadTail.first.split('\v');
259 if(!Duplex.second.empty()){
262 Inst = Duplex.second;
265 Inst = HeadTail.first;
267 Bytes = Bytes.slice(4);
269 HeadTail = HeadTail.second.split('\n');
271 OS << " } " << PacketBundle.second;
274 HexagonPrettyPrinter HexagonPrettyPrinterInst;
275 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
276 switch(Triple.getArch()) {
278 return PrettyPrinterInst;
279 case Triple::hexagon:
280 return HexagonPrettyPrinterInst;
285 template <class ELFT>
286 static const typename ELFObjectFile<ELFT>::Elf_Rel *
287 getRel(const ELFFile<ELFT> &EF, DataRefImpl Rel) {
288 typedef typename ELFObjectFile<ELFT>::Elf_Rel Elf_Rel;
289 return EF.template getEntry<Elf_Rel>(Rel.d.a, Rel.d.b);
292 template <class ELFT>
293 static const typename ELFObjectFile<ELFT>::Elf_Rela *
294 getRela(const ELFFile<ELFT> &EF, DataRefImpl Rela) {
295 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
296 return EF.template getEntry<Elf_Rela>(Rela.d.a, Rela.d.b);
299 template <class ELFT>
300 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
302 SmallVectorImpl<char> &Result) {
303 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
304 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
305 const ELFFile<ELFT> &EF = *Obj->getELFFile();
307 const Elf_Shdr *sec = EF.getSection(Rel.d.a);
311 uint16_t symbol_index = 0;
312 switch (sec->sh_type) {
314 return object_error::parse_failed;
316 type = getRel(EF, Rel)->getType(EF.isMips64EL());
317 symbol_index = getRel(EF, Rel)->getSymbol(EF.isMips64EL());
318 // TODO: Read implicit addend from section data.
321 case ELF::SHT_RELA: {
322 type = getRela(EF, Rel)->getType(EF.isMips64EL());
323 symbol_index = getRela(EF, Rel)->getSymbol(EF.isMips64EL());
324 addend = getRela(EF, Rel)->r_addend;
328 const Elf_Sym *symb =
329 EF.template getEntry<Elf_Sym>(sec->sh_link, symbol_index);
330 ErrorOr<StringRef> SymName =
331 EF.getSymbolName(EF.getSection(sec->sh_link), symb);
333 return SymName.getError();
334 switch (EF.getHeader()->e_machine) {
337 case ELF::R_X86_64_PC8:
338 case ELF::R_X86_64_PC16:
339 case ELF::R_X86_64_PC32: {
341 raw_string_ostream fmt(fmtbuf);
342 fmt << *SymName << (addend < 0 ? "" : "+") << addend << "-P";
344 Result.append(fmtbuf.begin(), fmtbuf.end());
346 case ELF::R_X86_64_8:
347 case ELF::R_X86_64_16:
348 case ELF::R_X86_64_32:
349 case ELF::R_X86_64_32S:
350 case ELF::R_X86_64_64: {
352 raw_string_ostream fmt(fmtbuf);
353 fmt << *SymName << (addend < 0 ? "" : "+") << addend;
355 Result.append(fmtbuf.begin(), fmtbuf.end());
361 case ELF::EM_AARCH64: {
363 raw_string_ostream fmt(fmtbuf);
366 fmt << (addend < 0 ? "" : "+") << addend;
368 Result.append(fmtbuf.begin(), fmtbuf.end());
373 case ELF::EM_HEXAGON:
381 Result.append(res.begin(), res.end());
382 return object_error::success;
385 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
386 const RelocationRef &RelRef,
387 SmallVectorImpl<char> &Result) {
388 DataRefImpl Rel = RelRef.getRawDataRefImpl();
389 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
390 return getRelocationValueString(ELF32LE, Rel, Result);
391 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
392 return getRelocationValueString(ELF64LE, Rel, Result);
393 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
394 return getRelocationValueString(ELF32BE, Rel, Result);
395 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
396 return getRelocationValueString(ELF64BE, Rel, Result);
399 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
400 const RelocationRef &Rel,
401 SmallVectorImpl<char> &Result) {
402 symbol_iterator SymI = Rel.getSymbol();
404 if (std::error_code EC = SymI->getName(SymName))
406 Result.append(SymName.begin(), SymName.end());
407 return object_error::success;
410 static void printRelocationTargetName(const MachOObjectFile *O,
411 const MachO::any_relocation_info &RE,
412 raw_string_ostream &fmt) {
413 bool IsScattered = O->isRelocationScattered(RE);
415 // Target of a scattered relocation is an address. In the interest of
416 // generating pretty output, scan through the symbol table looking for a
417 // symbol that aligns with that address. If we find one, print it.
418 // Otherwise, we just print the hex address of the target.
420 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
422 for (const SymbolRef &Symbol : O->symbols()) {
427 if ((ec = Symbol.getAddress(Addr)))
428 report_fatal_error(ec.message());
431 if ((ec = Symbol.getName(Name)))
432 report_fatal_error(ec.message());
437 // If we couldn't find a symbol that this relocation refers to, try
438 // to find a section beginning instead.
439 for (const SectionRef &Section : O->sections()) {
443 uint64_t Addr = Section.getAddress();
446 if ((ec = Section.getName(Name)))
447 report_fatal_error(ec.message());
452 fmt << format("0x%x", Val);
457 bool isExtern = O->getPlainRelocationExternal(RE);
458 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
461 symbol_iterator SI = O->symbol_begin();
465 section_iterator SI = O->section_begin();
466 // Adjust for the fact that sections are 1-indexed.
467 advance(SI, Val - 1);
474 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
475 const RelocationRef &RelRef,
476 SmallVectorImpl<char> &Result) {
477 DataRefImpl Rel = RelRef.getRawDataRefImpl();
478 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
480 unsigned Arch = Obj->getArch();
483 raw_string_ostream fmt(fmtbuf);
484 unsigned Type = Obj->getAnyRelocationType(RE);
485 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
487 // Determine any addends that should be displayed with the relocation.
488 // These require decoding the relocation type, which is triple-specific.
490 // X86_64 has entirely custom relocation types.
491 if (Arch == Triple::x86_64) {
492 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
495 case MachO::X86_64_RELOC_GOT_LOAD:
496 case MachO::X86_64_RELOC_GOT: {
497 printRelocationTargetName(Obj, RE, fmt);
503 case MachO::X86_64_RELOC_SUBTRACTOR: {
504 DataRefImpl RelNext = Rel;
505 Obj->moveRelocationNext(RelNext);
506 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
508 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
509 // X86_64_RELOC_UNSIGNED.
510 // NOTE: Scattered relocations don't exist on x86_64.
511 unsigned RType = Obj->getAnyRelocationType(RENext);
512 if (RType != MachO::X86_64_RELOC_UNSIGNED)
513 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
514 "X86_64_RELOC_SUBTRACTOR.");
516 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
517 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
518 printRelocationTargetName(Obj, RENext, fmt);
520 printRelocationTargetName(Obj, RE, fmt);
523 case MachO::X86_64_RELOC_TLV:
524 printRelocationTargetName(Obj, RE, fmt);
529 case MachO::X86_64_RELOC_SIGNED_1:
530 printRelocationTargetName(Obj, RE, fmt);
533 case MachO::X86_64_RELOC_SIGNED_2:
534 printRelocationTargetName(Obj, RE, fmt);
537 case MachO::X86_64_RELOC_SIGNED_4:
538 printRelocationTargetName(Obj, RE, fmt);
542 printRelocationTargetName(Obj, RE, fmt);
545 // X86 and ARM share some relocation types in common.
546 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
547 Arch == Triple::ppc) {
548 // Generic relocation types...
550 case MachO::GENERIC_RELOC_PAIR: // prints no info
551 return object_error::success;
552 case MachO::GENERIC_RELOC_SECTDIFF: {
553 DataRefImpl RelNext = Rel;
554 Obj->moveRelocationNext(RelNext);
555 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
557 // X86 sect diff's must be followed by a relocation of type
558 // GENERIC_RELOC_PAIR.
559 unsigned RType = Obj->getAnyRelocationType(RENext);
561 if (RType != MachO::GENERIC_RELOC_PAIR)
562 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
563 "GENERIC_RELOC_SECTDIFF.");
565 printRelocationTargetName(Obj, RE, fmt);
567 printRelocationTargetName(Obj, RENext, fmt);
572 if (Arch == Triple::x86 || Arch == Triple::ppc) {
574 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
575 DataRefImpl RelNext = Rel;
576 Obj->moveRelocationNext(RelNext);
577 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
579 // X86 sect diff's must be followed by a relocation of type
580 // GENERIC_RELOC_PAIR.
581 unsigned RType = Obj->getAnyRelocationType(RENext);
582 if (RType != MachO::GENERIC_RELOC_PAIR)
583 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
584 "GENERIC_RELOC_LOCAL_SECTDIFF.");
586 printRelocationTargetName(Obj, RE, fmt);
588 printRelocationTargetName(Obj, RENext, fmt);
591 case MachO::GENERIC_RELOC_TLV: {
592 printRelocationTargetName(Obj, RE, fmt);
599 printRelocationTargetName(Obj, RE, fmt);
601 } else { // ARM-specific relocations
603 case MachO::ARM_RELOC_HALF:
604 case MachO::ARM_RELOC_HALF_SECTDIFF: {
605 // Half relocations steal a bit from the length field to encode
606 // whether this is an upper16 or a lower16 relocation.
607 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
613 printRelocationTargetName(Obj, RE, fmt);
615 DataRefImpl RelNext = Rel;
616 Obj->moveRelocationNext(RelNext);
617 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
619 // ARM half relocs must be followed by a relocation of type
621 unsigned RType = Obj->getAnyRelocationType(RENext);
622 if (RType != MachO::ARM_RELOC_PAIR)
623 report_fatal_error("Expected ARM_RELOC_PAIR after "
626 // NOTE: The half of the target virtual address is stashed in the
627 // address field of the secondary relocation, but we can't reverse
628 // engineer the constant offset from it without decoding the movw/movt
629 // instruction to find the other half in its immediate field.
631 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
632 // symbol/section pointer of the follow-on relocation.
633 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
635 printRelocationTargetName(Obj, RENext, fmt);
641 default: { printRelocationTargetName(Obj, RE, fmt); }
645 printRelocationTargetName(Obj, RE, fmt);
648 Result.append(fmtbuf.begin(), fmtbuf.end());
649 return object_error::success;
652 static std::error_code getRelocationValueString(const RelocationRef &Rel,
653 SmallVectorImpl<char> &Result) {
654 const ObjectFile *Obj = Rel.getObjectFile();
655 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
656 return getRelocationValueString(ELF, Rel, Result);
657 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
658 return getRelocationValueString(COFF, Rel, Result);
659 auto *MachO = cast<MachOObjectFile>(Obj);
660 return getRelocationValueString(MachO, Rel, Result);
663 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
664 const Target *TheTarget = getTarget(Obj);
665 // getTarget() will have already issued a diagnostic if necessary, so
666 // just bail here if it failed.
670 // Package up features to be passed to target/subtarget
671 std::string FeaturesStr;
673 SubtargetFeatures Features;
674 for (unsigned i = 0; i != MAttrs.size(); ++i)
675 Features.AddFeature(MAttrs[i]);
676 FeaturesStr = Features.getString();
679 std::unique_ptr<const MCRegisterInfo> MRI(
680 TheTarget->createMCRegInfo(TripleName));
682 errs() << "error: no register info for target " << TripleName << "\n";
686 // Set up disassembler.
687 std::unique_ptr<const MCAsmInfo> AsmInfo(
688 TheTarget->createMCAsmInfo(*MRI, TripleName));
690 errs() << "error: no assembly info for target " << TripleName << "\n";
694 std::unique_ptr<const MCSubtargetInfo> STI(
695 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
697 errs() << "error: no subtarget info for target " << TripleName << "\n";
701 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
703 errs() << "error: no instruction info for target " << TripleName << "\n";
707 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
708 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
710 std::unique_ptr<MCDisassembler> DisAsm(
711 TheTarget->createMCDisassembler(*STI, Ctx));
714 errs() << "error: no disassembler for target " << TripleName << "\n";
718 std::unique_ptr<const MCInstrAnalysis> MIA(
719 TheTarget->createMCInstrAnalysis(MII.get()));
721 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
722 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
723 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
725 errs() << "error: no instruction printer for target " << TripleName
729 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
731 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
732 "\t\t\t%08" PRIx64 ": ";
734 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
735 // in RelocSecs contain the relocations for section S.
737 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
738 for (const SectionRef &Section : Obj->sections()) {
739 section_iterator Sec2 = Section.getRelocatedSection();
740 if (Sec2 != Obj->section_end())
741 SectionRelocMap[*Sec2].push_back(Section);
744 for (const SectionRef &Section : Obj->sections()) {
745 if (!Section.isText() || Section.isVirtual())
748 uint64_t SectionAddr = Section.getAddress();
749 uint64_t SectSize = Section.getSize();
753 // Make a list of all the symbols in this section.
754 std::vector<std::pair<uint64_t, StringRef>> Symbols;
755 for (const SymbolRef &Symbol : Obj->symbols()) {
756 if (Section.containsSymbol(Symbol)) {
758 if (error(Symbol.getAddress(Address)))
760 if (Address == UnknownAddressOrSize)
762 Address -= SectionAddr;
763 if (Address >= SectSize)
767 if (error(Symbol.getName(Name)))
769 Symbols.push_back(std::make_pair(Address, Name));
773 // Sort the symbols by address, just in case they didn't come in that way.
774 array_pod_sort(Symbols.begin(), Symbols.end());
776 // Make a list of all the relocations for this section.
777 std::vector<RelocationRef> Rels;
779 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
780 for (const RelocationRef &Reloc : RelocSec.relocations()) {
781 Rels.push_back(Reloc);
786 // Sort relocations by address.
787 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
789 StringRef SegmentName = "";
790 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
791 DataRefImpl DR = Section.getRawDataRefImpl();
792 SegmentName = MachO->getSectionFinalSegmentName(DR);
795 if (error(Section.getName(name)))
797 outs() << "Disassembly of section ";
798 if (!SegmentName.empty())
799 outs() << SegmentName << ",";
800 outs() << name << ':';
802 // If the section has no symbols just insert a dummy one and disassemble
803 // the whole section.
805 Symbols.push_back(std::make_pair(0, name));
808 SmallString<40> Comments;
809 raw_svector_ostream CommentStream(Comments);
812 if (error(Section.getContents(BytesStr)))
814 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
820 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
821 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
822 // Disassemble symbol by symbol.
823 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
825 uint64_t Start = Symbols[si].first;
826 // The end is either the section end or the beginning of the next symbol.
827 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
828 // If this symbol has the same address as the next symbol, then skip it.
832 outs() << '\n' << Symbols[si].second << ":\n";
835 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
837 raw_ostream &DebugOut = nulls();
840 for (Index = Start; Index < End; Index += Size) {
843 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
844 SectionAddr + Index, DebugOut,
846 PIP.printInst(*IP, &Inst,
847 Bytes.slice(Index, Size),
848 SectionAddr + Index, outs(), "", *STI);
849 outs() << CommentStream.str();
853 errs() << ToolName << ": warning: invalid instruction encoding\n";
855 Size = 1; // skip illegible bytes
858 // Print relocation for instruction.
859 while (rel_cur != rel_end) {
862 SmallString<16> name;
865 // If this relocation is hidden, skip it.
866 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
867 if (hidden) goto skip_print_rel;
869 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
870 // Stop when rel_cur's address is past the current instruction.
871 if (addr >= Index + Size) break;
872 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
873 if (error(getRelocationValueString(*rel_cur, val)))
875 outs() << format(Fmt.data(), SectionAddr + addr) << name
876 << "\t" << val << "\n";
886 void llvm::PrintRelocations(const ObjectFile *Obj) {
887 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
889 // Regular objdump doesn't print relocations in non-relocatable object
891 if (!Obj->isRelocatableObject())
894 for (const SectionRef &Section : Obj->sections()) {
895 if (Section.relocation_begin() == Section.relocation_end())
898 if (error(Section.getName(secname)))
900 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
901 for (const RelocationRef &Reloc : Section.relocations()) {
904 SmallString<32> relocname;
905 SmallString<32> valuestr;
906 if (error(Reloc.getHidden(hidden)))
910 if (error(Reloc.getTypeName(relocname)))
912 if (error(Reloc.getOffset(address)))
914 if (error(getRelocationValueString(Reloc, valuestr)))
916 outs() << format(Fmt.data(), address) << " " << relocname << " "
923 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
924 outs() << "Sections:\n"
925 "Idx Name Size Address Type\n";
927 for (const SectionRef &Section : Obj->sections()) {
929 if (error(Section.getName(Name)))
931 uint64_t Address = Section.getAddress();
932 uint64_t Size = Section.getSize();
933 bool Text = Section.isText();
934 bool Data = Section.isData();
935 bool BSS = Section.isBSS();
936 std::string Type = (std::string(Text ? "TEXT " : "") +
937 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
938 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
939 Name.str().c_str(), Size, Address, Type.c_str());
944 void llvm::PrintSectionContents(const ObjectFile *Obj) {
946 for (const SectionRef &Section : Obj->sections()) {
949 if (error(Section.getName(Name)))
951 uint64_t BaseAddr = Section.getAddress();
952 uint64_t Size = Section.getSize();
956 outs() << "Contents of section " << Name << ":\n";
957 if (Section.isBSS()) {
958 outs() << format("<skipping contents of bss section at [%04" PRIx64
959 ", %04" PRIx64 ")>\n",
960 BaseAddr, BaseAddr + Size);
964 if (error(Section.getContents(Contents)))
967 // Dump out the content as hex and printable ascii characters.
968 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
969 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
971 for (std::size_t i = 0; i < 16; ++i) {
972 if (i != 0 && i % 4 == 0)
975 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
976 << hexdigit(Contents[addr + i] & 0xF, true);
982 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
983 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
984 outs() << Contents[addr + i];
993 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
994 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
995 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
997 if (error(Symbol.getError()))
1000 if (error(coff->getSymbolName(*Symbol, Name)))
1003 outs() << "[" << format("%2d", SI) << "]"
1004 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
1005 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
1006 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1007 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1008 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1009 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
1012 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
1013 if (Symbol->isSectionDefinition()) {
1014 const coff_aux_section_definition *asd;
1015 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
1018 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1021 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1022 , unsigned(asd->Length)
1023 , unsigned(asd->NumberOfRelocations)
1024 , unsigned(asd->NumberOfLinenumbers)
1025 , unsigned(asd->CheckSum))
1026 << format("assoc %d comdat %d\n"
1027 , unsigned(AuxNumber)
1028 , unsigned(asd->Selection));
1029 } else if (Symbol->isFileRecord()) {
1030 const char *FileName;
1031 if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
1034 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1035 coff->getSymbolTableEntrySize());
1036 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
1038 SI = SI + Symbol->getNumberOfAuxSymbols();
1041 outs() << "AUX Unknown\n";
1047 void llvm::PrintSymbolTable(const ObjectFile *o) {
1048 outs() << "SYMBOL TABLE:\n";
1050 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1051 PrintCOFFSymbolTable(coff);
1054 for (const SymbolRef &Symbol : o->symbols()) {
1057 SymbolRef::Type Type;
1058 uint32_t Flags = Symbol.getFlags();
1059 section_iterator Section = o->section_end();
1060 if (error(Symbol.getName(Name)))
1062 if (error(Symbol.getAddress(Address)))
1064 if (error(Symbol.getType(Type)))
1066 uint64_t Size = Symbol.getSize();
1067 if (error(Symbol.getSection(Section)))
1070 bool Global = Flags & SymbolRef::SF_Global;
1071 bool Weak = Flags & SymbolRef::SF_Weak;
1072 bool Absolute = Flags & SymbolRef::SF_Absolute;
1073 bool Common = Flags & SymbolRef::SF_Common;
1074 bool Hidden = Flags & SymbolRef::SF_Hidden;
1077 uint32_t Alignment = Symbol.getAlignment();
1081 if (Address == UnknownAddressOrSize)
1083 if (Size == UnknownAddressOrSize)
1086 if (Type != SymbolRef::ST_Unknown)
1087 GlobLoc = Global ? 'g' : 'l';
1088 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1090 char FileFunc = ' ';
1091 if (Type == SymbolRef::ST_File)
1093 else if (Type == SymbolRef::ST_Function)
1096 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1099 outs() << format(Fmt, Address) << " "
1100 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1101 << (Weak ? 'w' : ' ') // Weak?
1102 << ' ' // Constructor. Not supported yet.
1103 << ' ' // Warning. Not supported yet.
1104 << ' ' // Indirect reference to another symbol.
1105 << Debug // Debugging (d) or dynamic (D) symbol.
1106 << FileFunc // Name of function (F), file (f) or object (O).
1110 } else if (Common) {
1112 } else if (Section == o->section_end()) {
1115 if (const MachOObjectFile *MachO =
1116 dyn_cast<const MachOObjectFile>(o)) {
1117 DataRefImpl DR = Section->getRawDataRefImpl();
1118 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1119 outs() << SegmentName << ",";
1121 StringRef SectionName;
1122 if (error(Section->getName(SectionName)))
1124 outs() << SectionName;
1127 << format("%08" PRIx64 " ", Size);
1129 outs() << ".hidden ";
1136 static void PrintUnwindInfo(const ObjectFile *o) {
1137 outs() << "Unwind info:\n\n";
1139 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1140 printCOFFUnwindInfo(coff);
1141 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1142 printMachOUnwindInfo(MachO);
1144 // TODO: Extract DWARF dump tool to objdump.
1145 errs() << "This operation is only currently supported "
1146 "for COFF and MachO object files.\n";
1151 void llvm::printExportsTrie(const ObjectFile *o) {
1152 outs() << "Exports trie:\n";
1153 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1154 printMachOExportsTrie(MachO);
1156 errs() << "This operation is only currently supported "
1157 "for Mach-O executable files.\n";
1162 void llvm::printRebaseTable(const ObjectFile *o) {
1163 outs() << "Rebase table:\n";
1164 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1165 printMachORebaseTable(MachO);
1167 errs() << "This operation is only currently supported "
1168 "for Mach-O executable files.\n";
1173 void llvm::printBindTable(const ObjectFile *o) {
1174 outs() << "Bind table:\n";
1175 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1176 printMachOBindTable(MachO);
1178 errs() << "This operation is only currently supported "
1179 "for Mach-O executable files.\n";
1184 void llvm::printLazyBindTable(const ObjectFile *o) {
1185 outs() << "Lazy bind table:\n";
1186 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1187 printMachOLazyBindTable(MachO);
1189 errs() << "This operation is only currently supported "
1190 "for Mach-O executable files.\n";
1195 void llvm::printWeakBindTable(const ObjectFile *o) {
1196 outs() << "Weak bind table:\n";
1197 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1198 printMachOWeakBindTable(MachO);
1200 errs() << "This operation is only currently supported "
1201 "for Mach-O executable files.\n";
1206 static void printPrivateFileHeader(const ObjectFile *o) {
1208 printELFFileHeader(o);
1209 } else if (o->isCOFF()) {
1210 printCOFFFileHeader(o);
1211 } else if (o->isMachO()) {
1212 printMachOFileHeader(o);
1216 static void DumpObject(const ObjectFile *o) {
1218 outs() << o->getFileName()
1219 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1222 DisassembleObject(o, Relocations);
1223 if (Relocations && !Disassemble)
1224 PrintRelocations(o);
1226 PrintSectionHeaders(o);
1227 if (SectionContents)
1228 PrintSectionContents(o);
1230 PrintSymbolTable(o);
1234 printPrivateFileHeader(o);
1236 printExportsTrie(o);
1238 printRebaseTable(o);
1242 printLazyBindTable(o);
1244 printWeakBindTable(o);
1247 /// @brief Dump each object file in \a a;
1248 static void DumpArchive(const Archive *a) {
1249 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
1251 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
1252 if (std::error_code EC = ChildOrErr.getError()) {
1253 // Ignore non-object files.
1254 if (EC != object_error::invalid_file_type)
1255 errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
1259 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
1262 errs() << ToolName << ": '" << a->getFileName() << "': "
1263 << "Unrecognized file type.\n";
1267 /// @brief Open file and figure out how to dump it.
1268 static void DumpInput(StringRef file) {
1269 // If file isn't stdin, check that it exists.
1270 if (file != "-" && !sys::fs::exists(file)) {
1271 errs() << ToolName << ": '" << file << "': " << "No such file\n";
1275 // If we are using the Mach-O specific object file parser, then let it parse
1276 // the file and process the command line options. So the -arch flags can
1277 // be used to select specific slices, etc.
1279 ParseInputMachO(file);
1283 // Attempt to open the binary.
1284 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1285 if (std::error_code EC = BinaryOrErr.getError()) {
1286 errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
1289 Binary &Binary = *BinaryOrErr.get().getBinary();
1291 if (Archive *a = dyn_cast<Archive>(&Binary))
1293 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
1296 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
1299 int main(int argc, char **argv) {
1300 // Print a stack trace if we signal out.
1301 sys::PrintStackTraceOnErrorSignal();
1302 PrettyStackTraceProgram X(argc, argv);
1303 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1305 // Initialize targets and assembly printers/parsers.
1306 llvm::InitializeAllTargetInfos();
1307 llvm::InitializeAllTargetMCs();
1308 llvm::InitializeAllAsmParsers();
1309 llvm::InitializeAllDisassemblers();
1311 // Register the target printer for --version.
1312 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1314 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1315 TripleName = Triple::normalize(TripleName);
1319 // Defaults to a.out if no filenames specified.
1320 if (InputFilenames.size() == 0)
1321 InputFilenames.push_back("a.out");
1335 && !(UniversalHeaders && MachOOpt)
1336 && !(ArchiveHeaders && MachOOpt)
1337 && !(IndirectSymbols && MachOOpt)
1338 && !(DataInCode && MachOOpt)
1339 && !(LinkOptHints && MachOOpt)
1340 && !(InfoPlist && MachOOpt)
1341 && !(DylibsUsed && MachOOpt)
1342 && !(DylibId && MachOOpt)
1343 && !(ObjcMetaData && MachOOpt)
1344 && !(DumpSections.size() != 0 && MachOOpt)) {
1345 cl::PrintHelpMessage();
1349 std::for_each(InputFilenames.begin(), InputFilenames.end(),