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);
331 const Elf_Shdr *SymSec = EF.getSection(symb);
332 if (symb->getType() == ELF::STT_SECTION) {
333 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
334 if (std::error_code EC = SecName.getError())
338 ErrorOr<StringRef> SymName =
339 EF.getSymbolName(EF.getSection(sec->sh_link), symb);
341 return SymName.getError();
344 switch (EF.getHeader()->e_machine) {
347 case ELF::R_X86_64_PC8:
348 case ELF::R_X86_64_PC16:
349 case ELF::R_X86_64_PC32: {
351 raw_string_ostream fmt(fmtbuf);
352 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
354 Result.append(fmtbuf.begin(), fmtbuf.end());
356 case ELF::R_X86_64_8:
357 case ELF::R_X86_64_16:
358 case ELF::R_X86_64_32:
359 case ELF::R_X86_64_32S:
360 case ELF::R_X86_64_64: {
362 raw_string_ostream fmt(fmtbuf);
363 fmt << Target << (addend < 0 ? "" : "+") << addend;
365 Result.append(fmtbuf.begin(), fmtbuf.end());
371 case ELF::EM_AARCH64: {
373 raw_string_ostream fmt(fmtbuf);
376 fmt << (addend < 0 ? "" : "+") << addend;
378 Result.append(fmtbuf.begin(), fmtbuf.end());
383 case ELF::EM_HEXAGON:
391 Result.append(res.begin(), res.end());
392 return object_error::success;
395 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
396 const RelocationRef &RelRef,
397 SmallVectorImpl<char> &Result) {
398 DataRefImpl Rel = RelRef.getRawDataRefImpl();
399 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
400 return getRelocationValueString(ELF32LE, Rel, Result);
401 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
402 return getRelocationValueString(ELF64LE, Rel, Result);
403 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
404 return getRelocationValueString(ELF32BE, Rel, Result);
405 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
406 return getRelocationValueString(ELF64BE, Rel, Result);
409 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
410 const RelocationRef &Rel,
411 SmallVectorImpl<char> &Result) {
412 symbol_iterator SymI = Rel.getSymbol();
414 if (std::error_code EC = SymI->getName(SymName))
416 Result.append(SymName.begin(), SymName.end());
417 return object_error::success;
420 static void printRelocationTargetName(const MachOObjectFile *O,
421 const MachO::any_relocation_info &RE,
422 raw_string_ostream &fmt) {
423 bool IsScattered = O->isRelocationScattered(RE);
425 // Target of a scattered relocation is an address. In the interest of
426 // generating pretty output, scan through the symbol table looking for a
427 // symbol that aligns with that address. If we find one, print it.
428 // Otherwise, we just print the hex address of the target.
430 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
432 for (const SymbolRef &Symbol : O->symbols()) {
437 if ((ec = Symbol.getAddress(Addr)))
438 report_fatal_error(ec.message());
441 if ((ec = Symbol.getName(Name)))
442 report_fatal_error(ec.message());
447 // If we couldn't find a symbol that this relocation refers to, try
448 // to find a section beginning instead.
449 for (const SectionRef &Section : O->sections()) {
453 uint64_t Addr = Section.getAddress();
456 if ((ec = Section.getName(Name)))
457 report_fatal_error(ec.message());
462 fmt << format("0x%x", Val);
467 bool isExtern = O->getPlainRelocationExternal(RE);
468 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
471 symbol_iterator SI = O->symbol_begin();
475 section_iterator SI = O->section_begin();
476 // Adjust for the fact that sections are 1-indexed.
477 advance(SI, Val - 1);
484 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
485 const RelocationRef &RelRef,
486 SmallVectorImpl<char> &Result) {
487 DataRefImpl Rel = RelRef.getRawDataRefImpl();
488 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
490 unsigned Arch = Obj->getArch();
493 raw_string_ostream fmt(fmtbuf);
494 unsigned Type = Obj->getAnyRelocationType(RE);
495 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
497 // Determine any addends that should be displayed with the relocation.
498 // These require decoding the relocation type, which is triple-specific.
500 // X86_64 has entirely custom relocation types.
501 if (Arch == Triple::x86_64) {
502 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
505 case MachO::X86_64_RELOC_GOT_LOAD:
506 case MachO::X86_64_RELOC_GOT: {
507 printRelocationTargetName(Obj, RE, fmt);
513 case MachO::X86_64_RELOC_SUBTRACTOR: {
514 DataRefImpl RelNext = Rel;
515 Obj->moveRelocationNext(RelNext);
516 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
518 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
519 // X86_64_RELOC_UNSIGNED.
520 // NOTE: Scattered relocations don't exist on x86_64.
521 unsigned RType = Obj->getAnyRelocationType(RENext);
522 if (RType != MachO::X86_64_RELOC_UNSIGNED)
523 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
524 "X86_64_RELOC_SUBTRACTOR.");
526 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
527 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
528 printRelocationTargetName(Obj, RENext, fmt);
530 printRelocationTargetName(Obj, RE, fmt);
533 case MachO::X86_64_RELOC_TLV:
534 printRelocationTargetName(Obj, RE, fmt);
539 case MachO::X86_64_RELOC_SIGNED_1:
540 printRelocationTargetName(Obj, RE, fmt);
543 case MachO::X86_64_RELOC_SIGNED_2:
544 printRelocationTargetName(Obj, RE, fmt);
547 case MachO::X86_64_RELOC_SIGNED_4:
548 printRelocationTargetName(Obj, RE, fmt);
552 printRelocationTargetName(Obj, RE, fmt);
555 // X86 and ARM share some relocation types in common.
556 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
557 Arch == Triple::ppc) {
558 // Generic relocation types...
560 case MachO::GENERIC_RELOC_PAIR: // prints no info
561 return object_error::success;
562 case MachO::GENERIC_RELOC_SECTDIFF: {
563 DataRefImpl RelNext = Rel;
564 Obj->moveRelocationNext(RelNext);
565 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
567 // X86 sect diff's must be followed by a relocation of type
568 // GENERIC_RELOC_PAIR.
569 unsigned RType = Obj->getAnyRelocationType(RENext);
571 if (RType != MachO::GENERIC_RELOC_PAIR)
572 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
573 "GENERIC_RELOC_SECTDIFF.");
575 printRelocationTargetName(Obj, RE, fmt);
577 printRelocationTargetName(Obj, RENext, fmt);
582 if (Arch == Triple::x86 || Arch == Triple::ppc) {
584 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
585 DataRefImpl RelNext = Rel;
586 Obj->moveRelocationNext(RelNext);
587 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
589 // X86 sect diff's must be followed by a relocation of type
590 // GENERIC_RELOC_PAIR.
591 unsigned RType = Obj->getAnyRelocationType(RENext);
592 if (RType != MachO::GENERIC_RELOC_PAIR)
593 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
594 "GENERIC_RELOC_LOCAL_SECTDIFF.");
596 printRelocationTargetName(Obj, RE, fmt);
598 printRelocationTargetName(Obj, RENext, fmt);
601 case MachO::GENERIC_RELOC_TLV: {
602 printRelocationTargetName(Obj, RE, fmt);
609 printRelocationTargetName(Obj, RE, fmt);
611 } else { // ARM-specific relocations
613 case MachO::ARM_RELOC_HALF:
614 case MachO::ARM_RELOC_HALF_SECTDIFF: {
615 // Half relocations steal a bit from the length field to encode
616 // whether this is an upper16 or a lower16 relocation.
617 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
623 printRelocationTargetName(Obj, RE, fmt);
625 DataRefImpl RelNext = Rel;
626 Obj->moveRelocationNext(RelNext);
627 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
629 // ARM half relocs must be followed by a relocation of type
631 unsigned RType = Obj->getAnyRelocationType(RENext);
632 if (RType != MachO::ARM_RELOC_PAIR)
633 report_fatal_error("Expected ARM_RELOC_PAIR after "
636 // NOTE: The half of the target virtual address is stashed in the
637 // address field of the secondary relocation, but we can't reverse
638 // engineer the constant offset from it without decoding the movw/movt
639 // instruction to find the other half in its immediate field.
641 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
642 // symbol/section pointer of the follow-on relocation.
643 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
645 printRelocationTargetName(Obj, RENext, fmt);
651 default: { printRelocationTargetName(Obj, RE, fmt); }
655 printRelocationTargetName(Obj, RE, fmt);
658 Result.append(fmtbuf.begin(), fmtbuf.end());
659 return object_error::success;
662 static std::error_code getRelocationValueString(const RelocationRef &Rel,
663 SmallVectorImpl<char> &Result) {
664 const ObjectFile *Obj = Rel.getObjectFile();
665 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
666 return getRelocationValueString(ELF, Rel, Result);
667 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
668 return getRelocationValueString(COFF, Rel, Result);
669 auto *MachO = cast<MachOObjectFile>(Obj);
670 return getRelocationValueString(MachO, Rel, Result);
673 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
674 const Target *TheTarget = getTarget(Obj);
675 // getTarget() will have already issued a diagnostic if necessary, so
676 // just bail here if it failed.
680 // Package up features to be passed to target/subtarget
681 std::string FeaturesStr;
683 SubtargetFeatures Features;
684 for (unsigned i = 0; i != MAttrs.size(); ++i)
685 Features.AddFeature(MAttrs[i]);
686 FeaturesStr = Features.getString();
689 std::unique_ptr<const MCRegisterInfo> MRI(
690 TheTarget->createMCRegInfo(TripleName));
692 errs() << "error: no register info for target " << TripleName << "\n";
696 // Set up disassembler.
697 std::unique_ptr<const MCAsmInfo> AsmInfo(
698 TheTarget->createMCAsmInfo(*MRI, TripleName));
700 errs() << "error: no assembly info for target " << TripleName << "\n";
704 std::unique_ptr<const MCSubtargetInfo> STI(
705 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
707 errs() << "error: no subtarget info for target " << TripleName << "\n";
711 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
713 errs() << "error: no instruction info for target " << TripleName << "\n";
717 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
718 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
720 std::unique_ptr<MCDisassembler> DisAsm(
721 TheTarget->createMCDisassembler(*STI, Ctx));
724 errs() << "error: no disassembler for target " << TripleName << "\n";
728 std::unique_ptr<const MCInstrAnalysis> MIA(
729 TheTarget->createMCInstrAnalysis(MII.get()));
731 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
732 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
733 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
735 errs() << "error: no instruction printer for target " << TripleName
739 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
741 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
742 "\t\t\t%08" PRIx64 ": ";
744 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
745 // in RelocSecs contain the relocations for section S.
747 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
748 for (const SectionRef &Section : Obj->sections()) {
749 section_iterator Sec2 = Section.getRelocatedSection();
750 if (Sec2 != Obj->section_end())
751 SectionRelocMap[*Sec2].push_back(Section);
754 for (const SectionRef &Section : Obj->sections()) {
755 if (!Section.isText() || Section.isVirtual())
758 uint64_t SectionAddr = Section.getAddress();
759 uint64_t SectSize = Section.getSize();
763 // Make a list of all the symbols in this section.
764 std::vector<std::pair<uint64_t, StringRef>> Symbols;
765 for (const SymbolRef &Symbol : Obj->symbols()) {
766 if (Section.containsSymbol(Symbol)) {
768 if (error(Symbol.getAddress(Address)))
770 if (Address == UnknownAddressOrSize)
772 Address -= SectionAddr;
773 if (Address >= SectSize)
777 if (error(Symbol.getName(Name)))
779 Symbols.push_back(std::make_pair(Address, Name));
783 // Sort the symbols by address, just in case they didn't come in that way.
784 array_pod_sort(Symbols.begin(), Symbols.end());
786 // Make a list of all the relocations for this section.
787 std::vector<RelocationRef> Rels;
789 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
790 for (const RelocationRef &Reloc : RelocSec.relocations()) {
791 Rels.push_back(Reloc);
796 // Sort relocations by address.
797 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
799 StringRef SegmentName = "";
800 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
801 DataRefImpl DR = Section.getRawDataRefImpl();
802 SegmentName = MachO->getSectionFinalSegmentName(DR);
805 if (error(Section.getName(name)))
807 outs() << "Disassembly of section ";
808 if (!SegmentName.empty())
809 outs() << SegmentName << ",";
810 outs() << name << ':';
812 // If the section has no symbols just insert a dummy one and disassemble
813 // the whole section.
815 Symbols.push_back(std::make_pair(0, name));
818 SmallString<40> Comments;
819 raw_svector_ostream CommentStream(Comments);
822 if (error(Section.getContents(BytesStr)))
824 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
830 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
831 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
832 // Disassemble symbol by symbol.
833 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
835 uint64_t Start = Symbols[si].first;
836 // The end is either the section end or the beginning of the next symbol.
837 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
838 // If this symbol has the same address as the next symbol, then skip it.
842 outs() << '\n' << Symbols[si].second << ":\n";
845 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
847 raw_ostream &DebugOut = nulls();
850 for (Index = Start; Index < End; Index += Size) {
853 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
854 SectionAddr + Index, DebugOut,
856 PIP.printInst(*IP, &Inst,
857 Bytes.slice(Index, Size),
858 SectionAddr + Index, outs(), "", *STI);
859 outs() << CommentStream.str();
863 errs() << ToolName << ": warning: invalid instruction encoding\n";
865 Size = 1; // skip illegible bytes
868 // Print relocation for instruction.
869 while (rel_cur != rel_end) {
872 SmallString<16> name;
875 // If this relocation is hidden, skip it.
876 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
877 if (hidden) goto skip_print_rel;
879 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
880 // Stop when rel_cur's address is past the current instruction.
881 if (addr >= Index + Size) break;
882 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
883 if (error(getRelocationValueString(*rel_cur, val)))
885 outs() << format(Fmt.data(), SectionAddr + addr) << name
886 << "\t" << val << "\n";
896 void llvm::PrintRelocations(const ObjectFile *Obj) {
897 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
899 // Regular objdump doesn't print relocations in non-relocatable object
901 if (!Obj->isRelocatableObject())
904 for (const SectionRef &Section : Obj->sections()) {
905 if (Section.relocation_begin() == Section.relocation_end())
908 if (error(Section.getName(secname)))
910 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
911 for (const RelocationRef &Reloc : Section.relocations()) {
914 SmallString<32> relocname;
915 SmallString<32> valuestr;
916 if (error(Reloc.getHidden(hidden)))
920 if (error(Reloc.getTypeName(relocname)))
922 if (error(Reloc.getOffset(address)))
924 if (error(getRelocationValueString(Reloc, valuestr)))
926 outs() << format(Fmt.data(), address) << " " << relocname << " "
933 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
934 outs() << "Sections:\n"
935 "Idx Name Size Address Type\n";
937 for (const SectionRef &Section : Obj->sections()) {
939 if (error(Section.getName(Name)))
941 uint64_t Address = Section.getAddress();
942 uint64_t Size = Section.getSize();
943 bool Text = Section.isText();
944 bool Data = Section.isData();
945 bool BSS = Section.isBSS();
946 std::string Type = (std::string(Text ? "TEXT " : "") +
947 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
948 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
949 Name.str().c_str(), Size, Address, Type.c_str());
954 void llvm::PrintSectionContents(const ObjectFile *Obj) {
956 for (const SectionRef &Section : Obj->sections()) {
959 if (error(Section.getName(Name)))
961 uint64_t BaseAddr = Section.getAddress();
962 uint64_t Size = Section.getSize();
966 outs() << "Contents of section " << Name << ":\n";
967 if (Section.isBSS()) {
968 outs() << format("<skipping contents of bss section at [%04" PRIx64
969 ", %04" PRIx64 ")>\n",
970 BaseAddr, BaseAddr + Size);
974 if (error(Section.getContents(Contents)))
977 // Dump out the content as hex and printable ascii characters.
978 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
979 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
981 for (std::size_t i = 0; i < 16; ++i) {
982 if (i != 0 && i % 4 == 0)
985 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
986 << hexdigit(Contents[addr + i] & 0xF, true);
992 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
993 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
994 outs() << Contents[addr + i];
1003 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
1004 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1005 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
1007 if (error(Symbol.getError()))
1010 if (error(coff->getSymbolName(*Symbol, Name)))
1013 outs() << "[" << format("%2d", SI) << "]"
1014 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
1015 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
1016 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1017 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1018 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1019 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
1022 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
1023 if (Symbol->isSectionDefinition()) {
1024 const coff_aux_section_definition *asd;
1025 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
1028 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1031 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1032 , unsigned(asd->Length)
1033 , unsigned(asd->NumberOfRelocations)
1034 , unsigned(asd->NumberOfLinenumbers)
1035 , unsigned(asd->CheckSum))
1036 << format("assoc %d comdat %d\n"
1037 , unsigned(AuxNumber)
1038 , unsigned(asd->Selection));
1039 } else if (Symbol->isFileRecord()) {
1040 const char *FileName;
1041 if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
1044 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1045 coff->getSymbolTableEntrySize());
1046 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
1048 SI = SI + Symbol->getNumberOfAuxSymbols();
1051 outs() << "AUX Unknown\n";
1057 void llvm::PrintSymbolTable(const ObjectFile *o) {
1058 outs() << "SYMBOL TABLE:\n";
1060 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1061 PrintCOFFSymbolTable(coff);
1064 for (const SymbolRef &Symbol : o->symbols()) {
1066 SymbolRef::Type Type;
1067 uint32_t Flags = Symbol.getFlags();
1068 section_iterator Section = o->section_end();
1069 if (error(Symbol.getAddress(Address)))
1071 if (error(Symbol.getType(Type)))
1073 uint64_t Size = Symbol.getSize();
1074 if (error(Symbol.getSection(Section)))
1077 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1078 Section->getName(Name);
1079 } else if (error(Symbol.getName(Name))) {
1083 bool Global = Flags & SymbolRef::SF_Global;
1084 bool Weak = Flags & SymbolRef::SF_Weak;
1085 bool Absolute = Flags & SymbolRef::SF_Absolute;
1086 bool Common = Flags & SymbolRef::SF_Common;
1087 bool Hidden = Flags & SymbolRef::SF_Hidden;
1090 uint32_t Alignment = Symbol.getAlignment();
1094 if (Address == UnknownAddressOrSize)
1096 if (Size == UnknownAddressOrSize)
1099 if (Type != SymbolRef::ST_Unknown)
1100 GlobLoc = Global ? 'g' : 'l';
1101 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1103 char FileFunc = ' ';
1104 if (Type == SymbolRef::ST_File)
1106 else if (Type == SymbolRef::ST_Function)
1109 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1112 outs() << format(Fmt, Address) << " "
1113 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1114 << (Weak ? 'w' : ' ') // Weak?
1115 << ' ' // Constructor. Not supported yet.
1116 << ' ' // Warning. Not supported yet.
1117 << ' ' // Indirect reference to another symbol.
1118 << Debug // Debugging (d) or dynamic (D) symbol.
1119 << FileFunc // Name of function (F), file (f) or object (O).
1123 } else if (Common) {
1125 } else if (Section == o->section_end()) {
1128 if (const MachOObjectFile *MachO =
1129 dyn_cast<const MachOObjectFile>(o)) {
1130 DataRefImpl DR = Section->getRawDataRefImpl();
1131 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1132 outs() << SegmentName << ",";
1134 StringRef SectionName;
1135 if (error(Section->getName(SectionName)))
1137 outs() << SectionName;
1140 << format("%08" PRIx64 " ", Size);
1142 outs() << ".hidden ";
1149 static void PrintUnwindInfo(const ObjectFile *o) {
1150 outs() << "Unwind info:\n\n";
1152 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1153 printCOFFUnwindInfo(coff);
1154 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1155 printMachOUnwindInfo(MachO);
1157 // TODO: Extract DWARF dump tool to objdump.
1158 errs() << "This operation is only currently supported "
1159 "for COFF and MachO object files.\n";
1164 void llvm::printExportsTrie(const ObjectFile *o) {
1165 outs() << "Exports trie:\n";
1166 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1167 printMachOExportsTrie(MachO);
1169 errs() << "This operation is only currently supported "
1170 "for Mach-O executable files.\n";
1175 void llvm::printRebaseTable(const ObjectFile *o) {
1176 outs() << "Rebase table:\n";
1177 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1178 printMachORebaseTable(MachO);
1180 errs() << "This operation is only currently supported "
1181 "for Mach-O executable files.\n";
1186 void llvm::printBindTable(const ObjectFile *o) {
1187 outs() << "Bind table:\n";
1188 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1189 printMachOBindTable(MachO);
1191 errs() << "This operation is only currently supported "
1192 "for Mach-O executable files.\n";
1197 void llvm::printLazyBindTable(const ObjectFile *o) {
1198 outs() << "Lazy bind table:\n";
1199 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1200 printMachOLazyBindTable(MachO);
1202 errs() << "This operation is only currently supported "
1203 "for Mach-O executable files.\n";
1208 void llvm::printWeakBindTable(const ObjectFile *o) {
1209 outs() << "Weak bind table:\n";
1210 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1211 printMachOWeakBindTable(MachO);
1213 errs() << "This operation is only currently supported "
1214 "for Mach-O executable files.\n";
1219 static void printPrivateFileHeader(const ObjectFile *o) {
1221 printELFFileHeader(o);
1222 } else if (o->isCOFF()) {
1223 printCOFFFileHeader(o);
1224 } else if (o->isMachO()) {
1225 printMachOFileHeader(o);
1229 static void DumpObject(const ObjectFile *o) {
1231 outs() << o->getFileName()
1232 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1235 DisassembleObject(o, Relocations);
1236 if (Relocations && !Disassemble)
1237 PrintRelocations(o);
1239 PrintSectionHeaders(o);
1240 if (SectionContents)
1241 PrintSectionContents(o);
1243 PrintSymbolTable(o);
1247 printPrivateFileHeader(o);
1249 printExportsTrie(o);
1251 printRebaseTable(o);
1255 printLazyBindTable(o);
1257 printWeakBindTable(o);
1260 /// @brief Dump each object file in \a a;
1261 static void DumpArchive(const Archive *a) {
1262 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
1264 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
1265 if (std::error_code EC = ChildOrErr.getError()) {
1266 // Ignore non-object files.
1267 if (EC != object_error::invalid_file_type)
1268 errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
1272 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
1275 errs() << ToolName << ": '" << a->getFileName() << "': "
1276 << "Unrecognized file type.\n";
1280 /// @brief Open file and figure out how to dump it.
1281 static void DumpInput(StringRef file) {
1282 // If file isn't stdin, check that it exists.
1283 if (file != "-" && !sys::fs::exists(file)) {
1284 errs() << ToolName << ": '" << file << "': " << "No such file\n";
1288 // If we are using the Mach-O specific object file parser, then let it parse
1289 // the file and process the command line options. So the -arch flags can
1290 // be used to select specific slices, etc.
1292 ParseInputMachO(file);
1296 // Attempt to open the binary.
1297 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1298 if (std::error_code EC = BinaryOrErr.getError()) {
1299 errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
1302 Binary &Binary = *BinaryOrErr.get().getBinary();
1304 if (Archive *a = dyn_cast<Archive>(&Binary))
1306 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
1309 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
1312 int main(int argc, char **argv) {
1313 // Print a stack trace if we signal out.
1314 sys::PrintStackTraceOnErrorSignal();
1315 PrettyStackTraceProgram X(argc, argv);
1316 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1318 // Initialize targets and assembly printers/parsers.
1319 llvm::InitializeAllTargetInfos();
1320 llvm::InitializeAllTargetMCs();
1321 llvm::InitializeAllAsmParsers();
1322 llvm::InitializeAllDisassemblers();
1324 // Register the target printer for --version.
1325 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1327 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1328 TripleName = Triple::normalize(TripleName);
1332 // Defaults to a.out if no filenames specified.
1333 if (InputFilenames.size() == 0)
1334 InputFilenames.push_back("a.out");
1348 && !(UniversalHeaders && MachOOpt)
1349 && !(ArchiveHeaders && MachOOpt)
1350 && !(IndirectSymbols && MachOOpt)
1351 && !(DataInCode && MachOOpt)
1352 && !(LinkOptHints && MachOOpt)
1353 && !(InfoPlist && MachOOpt)
1354 && !(DylibsUsed && MachOOpt)
1355 && !(DylibId && MachOOpt)
1356 && !(ObjcMetaData && MachOOpt)
1357 && !(DumpSections.size() != 0 && MachOOpt)) {
1358 cl::PrintHelpMessage();
1362 std::for_each(InputFilenames.begin(), InputFilenames.end(),