1 //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This program is a utility that works like binutils "objdump", that is, it
11 // dumps out a plethora of information about an object file depending on the
14 // The flags and output of this program should be near identical to those of
17 //===----------------------------------------------------------------------===//
19 #include "llvm-objdump.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCContext.h"
26 #include "llvm/MC/MCDisassembler.h"
27 #include "llvm/MC/MCInst.h"
28 #include "llvm/MC/MCInstPrinter.h"
29 #include "llvm/MC/MCInstrAnalysis.h"
30 #include "llvm/MC/MCInstrInfo.h"
31 #include "llvm/MC/MCObjectFileInfo.h"
32 #include "llvm/MC/MCRegisterInfo.h"
33 #include "llvm/MC/MCRelocationInfo.h"
34 #include "llvm/MC/MCSubtargetInfo.h"
35 #include "llvm/Object/Archive.h"
36 #include "llvm/Object/ELFObjectFile.h"
37 #include "llvm/Object/FaultMapParser.h"
38 #include "llvm/Object/COFF.h"
39 #include "llvm/Object/MachO.h"
40 #include "llvm/Object/ObjectFile.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/Errc.h"
45 #include "llvm/Support/FileSystem.h"
46 #include "llvm/Support/Format.h"
47 #include "llvm/Support/GraphWriter.h"
48 #include "llvm/Support/Host.h"
49 #include "llvm/Support/ManagedStatic.h"
50 #include "llvm/Support/MemoryBuffer.h"
51 #include "llvm/Support/PrettyStackTrace.h"
52 #include "llvm/Support/Signals.h"
53 #include "llvm/Support/SourceMgr.h"
54 #include "llvm/Support/TargetRegistry.h"
55 #include "llvm/Support/TargetSelect.h"
56 #include "llvm/Support/raw_ostream.h"
60 #include <system_error>
63 using namespace object;
65 static cl::list<std::string>
66 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
69 llvm::Disassemble("disassemble",
70 cl::desc("Display assembler mnemonics for the machine instructions"));
72 Disassembled("d", cl::desc("Alias for --disassemble"),
73 cl::aliasopt(Disassemble));
76 llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
79 llvm::SectionContents("s", cl::desc("Display the content of each section"));
82 llvm::SymbolTable("t", cl::desc("Display the symbol table"));
85 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
88 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
91 llvm::Bind("bind", cl::desc("Display mach-o binding info"));
94 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
97 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
100 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
102 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
105 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
106 "see -version for available targets"));
110 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
111 cl::value_desc("cpu-name"),
115 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
116 "see -version for available targets"));
119 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
120 "headers for each section."));
122 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
123 cl::aliasopt(SectionHeaders));
125 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
126 cl::aliasopt(SectionHeaders));
128 cl::list<std::string>
129 llvm::MAttrs("mattr",
131 cl::desc("Target specific attributes"),
132 cl::value_desc("a1,+a2,-a3,..."));
135 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
136 "instructions, do not print "
137 "the instruction bytes."));
140 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
143 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
144 cl::aliasopt(UnwindInfo));
147 llvm::PrivateHeaders("private-headers",
148 cl::desc("Display format specific file headers"));
151 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
152 cl::aliasopt(PrivateHeaders));
155 llvm::PrintImmHex("print-imm-hex",
156 cl::desc("Use hex format for immediate values"));
158 cl::opt<bool> PrintFaultMaps("fault-map-section",
159 cl::desc("Display contents of faultmap section"));
161 static StringRef ToolName;
162 static int ReturnValue = EXIT_SUCCESS;
164 bool llvm::error(std::error_code EC) {
168 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
170 ReturnValue = EXIT_FAILURE;
174 static void report_error(StringRef File, std::error_code EC) {
176 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
177 ReturnValue = EXIT_FAILURE;
180 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
181 // Figure out the target triple.
182 llvm::Triple TheTriple("unknown-unknown-unknown");
183 if (TripleName.empty()) {
185 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
186 // TheTriple defaults to ELF, and COFF doesn't have an environment:
187 // the best we can do here is indicate that it is mach-o.
189 TheTriple.setObjectFormat(Triple::MachO);
192 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
193 if (COFFObj->getArch() == Triple::thumb)
194 TheTriple.setTriple("thumbv7-windows");
198 TheTriple.setTriple(Triple::normalize(TripleName));
200 // Get the target specific parser.
202 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
205 errs() << ToolName << ": " << Error;
209 // Update the triple name and return the found target.
210 TripleName = TheTriple.getTriple();
214 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
215 uint64_t a_addr, b_addr;
216 if (error(a.getOffset(a_addr))) return false;
217 if (error(b.getOffset(b_addr))) return false;
218 return a_addr < b_addr;
222 class PrettyPrinter {
224 virtual ~PrettyPrinter(){}
225 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
226 ArrayRef<uint8_t> Bytes, uint64_t Address,
227 raw_ostream &OS, StringRef Annot,
228 MCSubtargetInfo const &STI) {
229 outs() << format("%8" PRIx64 ":", Address);
230 if (!NoShowRawInsn) {
232 dumpBytes(Bytes, outs());
234 IP.printInst(MI, outs(), "", STI);
237 PrettyPrinter PrettyPrinterInst;
238 class HexagonPrettyPrinter : public PrettyPrinter {
240 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
243 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
244 OS << format("%8" PRIx64 ":", Address);
245 if (!NoShowRawInsn) {
247 dumpBytes(Bytes.slice(0, 4), OS);
248 OS << format("%08" PRIx32, opcode);
251 void printInst(MCInstPrinter &IP, const MCInst *MI,
252 ArrayRef<uint8_t> Bytes, uint64_t Address,
253 raw_ostream &OS, StringRef Annot,
254 MCSubtargetInfo const &STI) override {
257 raw_string_ostream TempStream(Buffer);
258 IP.printInst(MI, TempStream, "", STI);
260 StringRef Contents(Buffer);
261 // Split off bundle attributes
262 auto PacketBundle = Contents.rsplit('\n');
263 // Split off first instruction from the rest
264 auto HeadTail = PacketBundle.first.split('\n');
265 auto Preamble = " { ";
267 while(!HeadTail.first.empty()) {
270 printLead(Bytes, Address, OS);
274 auto Duplex = HeadTail.first.split('\v');
275 if(!Duplex.second.empty()){
278 Inst = Duplex.second;
281 Inst = HeadTail.first;
283 Bytes = Bytes.slice(4);
285 HeadTail = HeadTail.second.split('\n');
287 OS << " } " << PacketBundle.second;
290 HexagonPrettyPrinter HexagonPrettyPrinterInst;
291 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
292 switch(Triple.getArch()) {
294 return PrettyPrinterInst;
295 case Triple::hexagon:
296 return HexagonPrettyPrinterInst;
301 template <class ELFT>
302 static const typename ELFObjectFile<ELFT>::Elf_Rel *
303 getRel(const ELFFile<ELFT> &EF, DataRefImpl Rel) {
304 typedef typename ELFObjectFile<ELFT>::Elf_Rel Elf_Rel;
305 return EF.template getEntry<Elf_Rel>(Rel.d.a, Rel.d.b);
308 template <class ELFT>
309 static const typename ELFObjectFile<ELFT>::Elf_Rela *
310 getRela(const ELFFile<ELFT> &EF, DataRefImpl Rela) {
311 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
312 return EF.template getEntry<Elf_Rela>(Rela.d.a, Rela.d.b);
315 template <class ELFT>
316 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
318 SmallVectorImpl<char> &Result) {
319 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
320 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
321 const ELFFile<ELFT> &EF = *Obj->getELFFile();
323 const Elf_Shdr *sec = EF.getSection(Rel.d.a);
327 uint16_t symbol_index = 0;
328 switch (sec->sh_type) {
330 return object_error::parse_failed;
332 type = getRel(EF, Rel)->getType(EF.isMips64EL());
333 symbol_index = getRel(EF, Rel)->getSymbol(EF.isMips64EL());
334 // TODO: Read implicit addend from section data.
337 case ELF::SHT_RELA: {
338 type = getRela(EF, Rel)->getType(EF.isMips64EL());
339 symbol_index = getRela(EF, Rel)->getSymbol(EF.isMips64EL());
340 addend = getRela(EF, Rel)->r_addend;
344 const Elf_Sym *symb =
345 EF.template getEntry<Elf_Sym>(sec->sh_link, symbol_index);
347 const Elf_Shdr *SymSec = EF.getSection(symb);
348 if (symb->getType() == ELF::STT_SECTION) {
349 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
350 if (std::error_code EC = SecName.getError())
354 ErrorOr<StringRef> SymName =
355 EF.getSymbolName(EF.getSection(sec->sh_link), symb);
357 return SymName.getError();
360 switch (EF.getHeader()->e_machine) {
363 case ELF::R_X86_64_PC8:
364 case ELF::R_X86_64_PC16:
365 case ELF::R_X86_64_PC32: {
367 raw_string_ostream fmt(fmtbuf);
368 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
370 Result.append(fmtbuf.begin(), fmtbuf.end());
372 case ELF::R_X86_64_8:
373 case ELF::R_X86_64_16:
374 case ELF::R_X86_64_32:
375 case ELF::R_X86_64_32S:
376 case ELF::R_X86_64_64: {
378 raw_string_ostream fmt(fmtbuf);
379 fmt << Target << (addend < 0 ? "" : "+") << addend;
381 Result.append(fmtbuf.begin(), fmtbuf.end());
387 case ELF::EM_AARCH64: {
389 raw_string_ostream fmt(fmtbuf);
392 fmt << (addend < 0 ? "" : "+") << addend;
394 Result.append(fmtbuf.begin(), fmtbuf.end());
399 case ELF::EM_HEXAGON:
407 Result.append(res.begin(), res.end());
408 return std::error_code();
411 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
412 const RelocationRef &RelRef,
413 SmallVectorImpl<char> &Result) {
414 DataRefImpl Rel = RelRef.getRawDataRefImpl();
415 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
416 return getRelocationValueString(ELF32LE, Rel, Result);
417 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
418 return getRelocationValueString(ELF64LE, Rel, Result);
419 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
420 return getRelocationValueString(ELF32BE, Rel, Result);
421 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
422 return getRelocationValueString(ELF64BE, Rel, Result);
425 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
426 const RelocationRef &Rel,
427 SmallVectorImpl<char> &Result) {
428 symbol_iterator SymI = Rel.getSymbol();
430 if (std::error_code EC = SymI->getName(SymName))
432 Result.append(SymName.begin(), SymName.end());
433 return std::error_code();
436 static void printRelocationTargetName(const MachOObjectFile *O,
437 const MachO::any_relocation_info &RE,
438 raw_string_ostream &fmt) {
439 bool IsScattered = O->isRelocationScattered(RE);
441 // Target of a scattered relocation is an address. In the interest of
442 // generating pretty output, scan through the symbol table looking for a
443 // symbol that aligns with that address. If we find one, print it.
444 // Otherwise, we just print the hex address of the target.
446 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
448 for (const SymbolRef &Symbol : O->symbols()) {
453 if ((ec = Symbol.getAddress(Addr)))
454 report_fatal_error(ec.message());
457 if ((ec = Symbol.getName(Name)))
458 report_fatal_error(ec.message());
463 // If we couldn't find a symbol that this relocation refers to, try
464 // to find a section beginning instead.
465 for (const SectionRef &Section : O->sections()) {
469 uint64_t Addr = Section.getAddress();
472 if ((ec = Section.getName(Name)))
473 report_fatal_error(ec.message());
478 fmt << format("0x%x", Val);
483 bool isExtern = O->getPlainRelocationExternal(RE);
484 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
487 symbol_iterator SI = O->symbol_begin();
491 section_iterator SI = O->section_begin();
492 // Adjust for the fact that sections are 1-indexed.
493 advance(SI, Val - 1);
500 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
501 const RelocationRef &RelRef,
502 SmallVectorImpl<char> &Result) {
503 DataRefImpl Rel = RelRef.getRawDataRefImpl();
504 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
506 unsigned Arch = Obj->getArch();
509 raw_string_ostream fmt(fmtbuf);
510 unsigned Type = Obj->getAnyRelocationType(RE);
511 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
513 // Determine any addends that should be displayed with the relocation.
514 // These require decoding the relocation type, which is triple-specific.
516 // X86_64 has entirely custom relocation types.
517 if (Arch == Triple::x86_64) {
518 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
521 case MachO::X86_64_RELOC_GOT_LOAD:
522 case MachO::X86_64_RELOC_GOT: {
523 printRelocationTargetName(Obj, RE, fmt);
529 case MachO::X86_64_RELOC_SUBTRACTOR: {
530 DataRefImpl RelNext = Rel;
531 Obj->moveRelocationNext(RelNext);
532 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
534 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
535 // X86_64_RELOC_UNSIGNED.
536 // NOTE: Scattered relocations don't exist on x86_64.
537 unsigned RType = Obj->getAnyRelocationType(RENext);
538 if (RType != MachO::X86_64_RELOC_UNSIGNED)
539 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
540 "X86_64_RELOC_SUBTRACTOR.");
542 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
543 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
544 printRelocationTargetName(Obj, RENext, fmt);
546 printRelocationTargetName(Obj, RE, fmt);
549 case MachO::X86_64_RELOC_TLV:
550 printRelocationTargetName(Obj, RE, fmt);
555 case MachO::X86_64_RELOC_SIGNED_1:
556 printRelocationTargetName(Obj, RE, fmt);
559 case MachO::X86_64_RELOC_SIGNED_2:
560 printRelocationTargetName(Obj, RE, fmt);
563 case MachO::X86_64_RELOC_SIGNED_4:
564 printRelocationTargetName(Obj, RE, fmt);
568 printRelocationTargetName(Obj, RE, fmt);
571 // X86 and ARM share some relocation types in common.
572 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
573 Arch == Triple::ppc) {
574 // Generic relocation types...
576 case MachO::GENERIC_RELOC_PAIR: // prints no info
577 return std::error_code();
578 case MachO::GENERIC_RELOC_SECTDIFF: {
579 DataRefImpl RelNext = Rel;
580 Obj->moveRelocationNext(RelNext);
581 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
583 // X86 sect diff's must be followed by a relocation of type
584 // GENERIC_RELOC_PAIR.
585 unsigned RType = Obj->getAnyRelocationType(RENext);
587 if (RType != MachO::GENERIC_RELOC_PAIR)
588 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
589 "GENERIC_RELOC_SECTDIFF.");
591 printRelocationTargetName(Obj, RE, fmt);
593 printRelocationTargetName(Obj, RENext, fmt);
598 if (Arch == Triple::x86 || Arch == Triple::ppc) {
600 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
601 DataRefImpl RelNext = Rel;
602 Obj->moveRelocationNext(RelNext);
603 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
605 // X86 sect diff's must be followed by a relocation of type
606 // GENERIC_RELOC_PAIR.
607 unsigned RType = Obj->getAnyRelocationType(RENext);
608 if (RType != MachO::GENERIC_RELOC_PAIR)
609 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
610 "GENERIC_RELOC_LOCAL_SECTDIFF.");
612 printRelocationTargetName(Obj, RE, fmt);
614 printRelocationTargetName(Obj, RENext, fmt);
617 case MachO::GENERIC_RELOC_TLV: {
618 printRelocationTargetName(Obj, RE, fmt);
625 printRelocationTargetName(Obj, RE, fmt);
627 } else { // ARM-specific relocations
629 case MachO::ARM_RELOC_HALF:
630 case MachO::ARM_RELOC_HALF_SECTDIFF: {
631 // Half relocations steal a bit from the length field to encode
632 // whether this is an upper16 or a lower16 relocation.
633 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
639 printRelocationTargetName(Obj, RE, fmt);
641 DataRefImpl RelNext = Rel;
642 Obj->moveRelocationNext(RelNext);
643 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
645 // ARM half relocs must be followed by a relocation of type
647 unsigned RType = Obj->getAnyRelocationType(RENext);
648 if (RType != MachO::ARM_RELOC_PAIR)
649 report_fatal_error("Expected ARM_RELOC_PAIR after "
652 // NOTE: The half of the target virtual address is stashed in the
653 // address field of the secondary relocation, but we can't reverse
654 // engineer the constant offset from it without decoding the movw/movt
655 // instruction to find the other half in its immediate field.
657 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
658 // symbol/section pointer of the follow-on relocation.
659 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
661 printRelocationTargetName(Obj, RENext, fmt);
667 default: { printRelocationTargetName(Obj, RE, fmt); }
671 printRelocationTargetName(Obj, RE, fmt);
674 Result.append(fmtbuf.begin(), fmtbuf.end());
675 return std::error_code();
678 static std::error_code getRelocationValueString(const RelocationRef &Rel,
679 SmallVectorImpl<char> &Result) {
680 const ObjectFile *Obj = Rel.getObjectFile();
681 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
682 return getRelocationValueString(ELF, Rel, Result);
683 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
684 return getRelocationValueString(COFF, Rel, Result);
685 auto *MachO = cast<MachOObjectFile>(Obj);
686 return getRelocationValueString(MachO, Rel, Result);
689 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
690 const Target *TheTarget = getTarget(Obj);
691 // getTarget() will have already issued a diagnostic if necessary, so
692 // just bail here if it failed.
696 // Package up features to be passed to target/subtarget
697 std::string FeaturesStr;
699 SubtargetFeatures Features;
700 for (unsigned i = 0; i != MAttrs.size(); ++i)
701 Features.AddFeature(MAttrs[i]);
702 FeaturesStr = Features.getString();
705 std::unique_ptr<const MCRegisterInfo> MRI(
706 TheTarget->createMCRegInfo(TripleName));
708 errs() << "error: no register info for target " << TripleName << "\n";
712 // Set up disassembler.
713 std::unique_ptr<const MCAsmInfo> AsmInfo(
714 TheTarget->createMCAsmInfo(*MRI, TripleName));
716 errs() << "error: no assembly info for target " << TripleName << "\n";
720 std::unique_ptr<const MCSubtargetInfo> STI(
721 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
723 errs() << "error: no subtarget info for target " << TripleName << "\n";
727 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
729 errs() << "error: no instruction info for target " << TripleName << "\n";
733 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
734 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
736 std::unique_ptr<MCDisassembler> DisAsm(
737 TheTarget->createMCDisassembler(*STI, Ctx));
740 errs() << "error: no disassembler for target " << TripleName << "\n";
744 std::unique_ptr<const MCInstrAnalysis> MIA(
745 TheTarget->createMCInstrAnalysis(MII.get()));
747 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
748 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
749 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
751 errs() << "error: no instruction printer for target " << TripleName
755 IP->setPrintImmHex(PrintImmHex);
756 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
758 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
759 "\t\t\t%08" PRIx64 ": ";
761 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
762 // in RelocSecs contain the relocations for section S.
764 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
765 for (const SectionRef &Section : Obj->sections()) {
766 section_iterator Sec2 = Section.getRelocatedSection();
767 if (Sec2 != Obj->section_end())
768 SectionRelocMap[*Sec2].push_back(Section);
771 for (const SectionRef &Section : Obj->sections()) {
772 if (!Section.isText() || Section.isVirtual())
775 uint64_t SectionAddr = Section.getAddress();
776 uint64_t SectSize = Section.getSize();
780 // Make a list of all the symbols in this section.
781 std::vector<std::pair<uint64_t, StringRef>> Symbols;
782 for (const SymbolRef &Symbol : Obj->symbols()) {
783 if (Section.containsSymbol(Symbol)) {
785 if (error(Symbol.getAddress(Address)))
787 if (Address == UnknownAddressOrSize)
789 Address -= SectionAddr;
790 if (Address >= SectSize)
794 if (error(Symbol.getName(Name)))
796 Symbols.push_back(std::make_pair(Address, Name));
800 // Sort the symbols by address, just in case they didn't come in that way.
801 array_pod_sort(Symbols.begin(), Symbols.end());
803 // Make a list of all the relocations for this section.
804 std::vector<RelocationRef> Rels;
806 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
807 for (const RelocationRef &Reloc : RelocSec.relocations()) {
808 Rels.push_back(Reloc);
813 // Sort relocations by address.
814 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
816 StringRef SegmentName = "";
817 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
818 DataRefImpl DR = Section.getRawDataRefImpl();
819 SegmentName = MachO->getSectionFinalSegmentName(DR);
822 if (error(Section.getName(name)))
824 outs() << "Disassembly of section ";
825 if (!SegmentName.empty())
826 outs() << SegmentName << ",";
827 outs() << name << ':';
829 // If the section has no symbol at the start, just insert a dummy one.
830 if (Symbols.empty() || Symbols[0].first != 0)
831 Symbols.insert(Symbols.begin(), std::make_pair(0, name));
833 SmallString<40> Comments;
834 raw_svector_ostream CommentStream(Comments);
837 if (error(Section.getContents(BytesStr)))
839 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
845 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
846 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
847 // Disassemble symbol by symbol.
848 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
850 uint64_t Start = Symbols[si].first;
851 // The end is either the section end or the beginning of the next symbol.
852 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
853 // If this symbol has the same address as the next symbol, then skip it.
857 outs() << '\n' << Symbols[si].second << ":\n";
860 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
862 raw_ostream &DebugOut = nulls();
865 for (Index = Start; Index < End; Index += Size) {
868 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
869 SectionAddr + Index, DebugOut,
871 PIP.printInst(*IP, &Inst,
872 Bytes.slice(Index, Size),
873 SectionAddr + Index, outs(), "", *STI);
874 outs() << CommentStream.str();
878 errs() << ToolName << ": warning: invalid instruction encoding\n";
880 Size = 1; // skip illegible bytes
883 // Print relocation for instruction.
884 while (rel_cur != rel_end) {
887 SmallString<16> name;
890 // If this relocation is hidden, skip it.
891 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
892 if (hidden) goto skip_print_rel;
894 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
895 // Stop when rel_cur's address is past the current instruction.
896 if (addr >= Index + Size) break;
897 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
898 if (error(getRelocationValueString(*rel_cur, val)))
900 outs() << format(Fmt.data(), SectionAddr + addr) << name
901 << "\t" << val << "\n";
911 void llvm::PrintRelocations(const ObjectFile *Obj) {
912 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
914 // Regular objdump doesn't print relocations in non-relocatable object
916 if (!Obj->isRelocatableObject())
919 for (const SectionRef &Section : Obj->sections()) {
920 if (Section.relocation_begin() == Section.relocation_end())
923 if (error(Section.getName(secname)))
925 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
926 for (const RelocationRef &Reloc : Section.relocations()) {
929 SmallString<32> relocname;
930 SmallString<32> valuestr;
931 if (error(Reloc.getHidden(hidden)))
935 if (error(Reloc.getTypeName(relocname)))
937 if (error(Reloc.getOffset(address)))
939 if (error(getRelocationValueString(Reloc, valuestr)))
941 outs() << format(Fmt.data(), address) << " " << relocname << " "
948 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
949 outs() << "Sections:\n"
950 "Idx Name Size Address Type\n";
952 for (const SectionRef &Section : Obj->sections()) {
954 if (error(Section.getName(Name)))
956 uint64_t Address = Section.getAddress();
957 uint64_t Size = Section.getSize();
958 bool Text = Section.isText();
959 bool Data = Section.isData();
960 bool BSS = Section.isBSS();
961 std::string Type = (std::string(Text ? "TEXT " : "") +
962 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
963 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
964 Name.str().c_str(), Size, Address, Type.c_str());
969 void llvm::PrintSectionContents(const ObjectFile *Obj) {
971 for (const SectionRef &Section : Obj->sections()) {
974 if (error(Section.getName(Name)))
976 uint64_t BaseAddr = Section.getAddress();
977 uint64_t Size = Section.getSize();
981 outs() << "Contents of section " << Name << ":\n";
982 if (Section.isBSS()) {
983 outs() << format("<skipping contents of bss section at [%04" PRIx64
984 ", %04" PRIx64 ")>\n",
985 BaseAddr, BaseAddr + Size);
989 if (error(Section.getContents(Contents)))
992 // Dump out the content as hex and printable ascii characters.
993 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
994 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
996 for (std::size_t i = 0; i < 16; ++i) {
997 if (i != 0 && i % 4 == 0)
1000 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1001 << hexdigit(Contents[addr + i] & 0xF, true);
1007 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1008 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1009 outs() << Contents[addr + i];
1018 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
1019 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1020 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
1022 if (error(Symbol.getError()))
1025 if (error(coff->getSymbolName(*Symbol, Name)))
1028 outs() << "[" << format("%2d", SI) << "]"
1029 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
1030 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
1031 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1032 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1033 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1034 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
1037 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
1038 if (Symbol->isSectionDefinition()) {
1039 const coff_aux_section_definition *asd;
1040 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
1043 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1046 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1047 , unsigned(asd->Length)
1048 , unsigned(asd->NumberOfRelocations)
1049 , unsigned(asd->NumberOfLinenumbers)
1050 , unsigned(asd->CheckSum))
1051 << format("assoc %d comdat %d\n"
1052 , unsigned(AuxNumber)
1053 , unsigned(asd->Selection));
1054 } else if (Symbol->isFileRecord()) {
1055 const char *FileName;
1056 if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
1059 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1060 coff->getSymbolTableEntrySize());
1061 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
1063 SI = SI + Symbol->getNumberOfAuxSymbols();
1066 outs() << "AUX Unknown\n";
1072 void llvm::PrintSymbolTable(const ObjectFile *o) {
1073 outs() << "SYMBOL TABLE:\n";
1075 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1076 PrintCOFFSymbolTable(coff);
1079 for (const SymbolRef &Symbol : o->symbols()) {
1081 SymbolRef::Type Type;
1082 uint32_t Flags = Symbol.getFlags();
1083 section_iterator Section = o->section_end();
1084 if (error(Symbol.getAddress(Address)))
1086 if (error(Symbol.getType(Type)))
1088 if (error(Symbol.getSection(Section)))
1091 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1092 Section->getName(Name);
1093 } else if (error(Symbol.getName(Name))) {
1097 bool Global = Flags & SymbolRef::SF_Global;
1098 bool Weak = Flags & SymbolRef::SF_Weak;
1099 bool Absolute = Flags & SymbolRef::SF_Absolute;
1100 bool Common = Flags & SymbolRef::SF_Common;
1101 bool Hidden = Flags & SymbolRef::SF_Hidden;
1104 Address = Symbol.getSize();
1106 if (Address == UnknownAddressOrSize)
1109 if (Type != SymbolRef::ST_Unknown)
1110 GlobLoc = Global ? 'g' : 'l';
1111 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1113 char FileFunc = ' ';
1114 if (Type == SymbolRef::ST_File)
1116 else if (Type == SymbolRef::ST_Function)
1119 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1122 outs() << format(Fmt, Address) << " "
1123 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1124 << (Weak ? 'w' : ' ') // Weak?
1125 << ' ' // Constructor. Not supported yet.
1126 << ' ' // Warning. Not supported yet.
1127 << ' ' // Indirect reference to another symbol.
1128 << Debug // Debugging (d) or dynamic (D) symbol.
1129 << FileFunc // Name of function (F), file (f) or object (O).
1133 } else if (Common) {
1135 } else if (Section == o->section_end()) {
1138 if (const MachOObjectFile *MachO =
1139 dyn_cast<const MachOObjectFile>(o)) {
1140 DataRefImpl DR = Section->getRawDataRefImpl();
1141 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1142 outs() << SegmentName << ",";
1144 StringRef SectionName;
1145 if (error(Section->getName(SectionName)))
1147 outs() << SectionName;
1152 outs() << format("%08" PRIx64 " ", Symbol.getAlignment());
1153 else if (isa<ELFObjectFileBase>(o))
1154 outs() << format("%08" PRIx64 " ", Symbol.getSize());
1157 outs() << ".hidden ";
1164 static void PrintUnwindInfo(const ObjectFile *o) {
1165 outs() << "Unwind info:\n\n";
1167 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1168 printCOFFUnwindInfo(coff);
1169 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1170 printMachOUnwindInfo(MachO);
1172 // TODO: Extract DWARF dump tool to objdump.
1173 errs() << "This operation is only currently supported "
1174 "for COFF and MachO object files.\n";
1179 void llvm::printExportsTrie(const ObjectFile *o) {
1180 outs() << "Exports trie:\n";
1181 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1182 printMachOExportsTrie(MachO);
1184 errs() << "This operation is only currently supported "
1185 "for Mach-O executable files.\n";
1190 void llvm::printRebaseTable(const ObjectFile *o) {
1191 outs() << "Rebase table:\n";
1192 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1193 printMachORebaseTable(MachO);
1195 errs() << "This operation is only currently supported "
1196 "for Mach-O executable files.\n";
1201 void llvm::printBindTable(const ObjectFile *o) {
1202 outs() << "Bind table:\n";
1203 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1204 printMachOBindTable(MachO);
1206 errs() << "This operation is only currently supported "
1207 "for Mach-O executable files.\n";
1212 void llvm::printLazyBindTable(const ObjectFile *o) {
1213 outs() << "Lazy bind table:\n";
1214 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1215 printMachOLazyBindTable(MachO);
1217 errs() << "This operation is only currently supported "
1218 "for Mach-O executable files.\n";
1223 void llvm::printWeakBindTable(const ObjectFile *o) {
1224 outs() << "Weak bind table:\n";
1225 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1226 printMachOWeakBindTable(MachO);
1228 errs() << "This operation is only currently supported "
1229 "for Mach-O executable files.\n";
1234 static void printFaultMaps(const ObjectFile *Obj) {
1235 const char *FaultMapSectionName = nullptr;
1237 if (isa<ELFObjectFileBase>(Obj)) {
1238 FaultMapSectionName = ".llvm_faultmaps";
1239 } else if (isa<MachOObjectFile>(Obj)) {
1240 FaultMapSectionName = "__llvm_faultmaps";
1242 errs() << "This operation is only currently supported "
1243 "for ELF and Mach-O executable files.\n";
1247 Optional<object::SectionRef> FaultMapSection;
1249 for (auto Sec : Obj->sections()) {
1252 if (Name == FaultMapSectionName) {
1253 FaultMapSection = Sec;
1258 outs() << "FaultMap table:\n";
1260 if (!FaultMapSection.hasValue()) {
1261 outs() << "<not found>\n";
1265 StringRef FaultMapContents;
1266 if (error(FaultMapSection.getValue().getContents(FaultMapContents))) {
1267 errs() << "Could not read the " << FaultMapContents << " section!\n";
1271 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1272 FaultMapContents.bytes_end());
1277 static void printPrivateFileHeader(const ObjectFile *o) {
1279 printELFFileHeader(o);
1280 } else if (o->isCOFF()) {
1281 printCOFFFileHeader(o);
1282 } else if (o->isMachO()) {
1283 printMachOFileHeader(o);
1287 static void DumpObject(const ObjectFile *o) {
1289 outs() << o->getFileName()
1290 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1293 DisassembleObject(o, Relocations);
1294 if (Relocations && !Disassemble)
1295 PrintRelocations(o);
1297 PrintSectionHeaders(o);
1298 if (SectionContents)
1299 PrintSectionContents(o);
1301 PrintSymbolTable(o);
1305 printPrivateFileHeader(o);
1307 printExportsTrie(o);
1309 printRebaseTable(o);
1313 printLazyBindTable(o);
1315 printWeakBindTable(o);
1320 /// @brief Dump each object file in \a a;
1321 static void DumpArchive(const Archive *a) {
1322 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
1324 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
1325 if (std::error_code EC = ChildOrErr.getError()) {
1326 // Ignore non-object files.
1327 if (EC != object_error::invalid_file_type)
1328 report_error(a->getFileName(), EC);
1331 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
1334 report_error(a->getFileName(), object_error::invalid_file_type);
1338 /// @brief Open file and figure out how to dump it.
1339 static void DumpInput(StringRef file) {
1340 // If file isn't stdin, check that it exists.
1341 if (file != "-" && !sys::fs::exists(file)) {
1342 report_error(file, errc::no_such_file_or_directory);
1346 // If we are using the Mach-O specific object file parser, then let it parse
1347 // the file and process the command line options. So the -arch flags can
1348 // be used to select specific slices, etc.
1350 ParseInputMachO(file);
1354 // Attempt to open the binary.
1355 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1356 if (std::error_code EC = BinaryOrErr.getError()) {
1357 report_error(file, EC);
1360 Binary &Binary = *BinaryOrErr.get().getBinary();
1362 if (Archive *a = dyn_cast<Archive>(&Binary))
1364 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
1367 report_error(file, object_error::invalid_file_type);
1370 int main(int argc, char **argv) {
1371 // Print a stack trace if we signal out.
1372 sys::PrintStackTraceOnErrorSignal();
1373 PrettyStackTraceProgram X(argc, argv);
1374 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1376 // Initialize targets and assembly printers/parsers.
1377 llvm::InitializeAllTargetInfos();
1378 llvm::InitializeAllTargetMCs();
1379 llvm::InitializeAllAsmParsers();
1380 llvm::InitializeAllDisassemblers();
1382 // Register the target printer for --version.
1383 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1385 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1386 TripleName = Triple::normalize(TripleName);
1390 // Defaults to a.out if no filenames specified.
1391 if (InputFilenames.size() == 0)
1392 InputFilenames.push_back("a.out");
1406 && !(UniversalHeaders && MachOOpt)
1407 && !(ArchiveHeaders && MachOOpt)
1408 && !(IndirectSymbols && MachOOpt)
1409 && !(DataInCode && MachOOpt)
1410 && !(LinkOptHints && MachOOpt)
1411 && !(InfoPlist && MachOOpt)
1412 && !(DylibsUsed && MachOOpt)
1413 && !(DylibId && MachOOpt)
1414 && !(ObjcMetaData && MachOOpt)
1415 && !(DumpSections.size() != 0 && MachOOpt)
1416 && !PrintFaultMaps) {
1417 cl::PrintHelpMessage();
1421 std::for_each(InputFilenames.begin(), InputFilenames.end(),