1 //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This program is a utility that works like binutils "objdump", that is, it
11 // dumps out a plethora of information about an object file depending on the
14 // The flags and output of this program should be near identical to those of
17 //===----------------------------------------------------------------------===//
19 #include "llvm-objdump.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCDisassembler.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCInstPrinter.h"
28 #include "llvm/MC/MCInstrAnalysis.h"
29 #include "llvm/MC/MCInstrInfo.h"
30 #include "llvm/MC/MCObjectFileInfo.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/MC/MCRelocationInfo.h"
33 #include "llvm/MC/MCSubtargetInfo.h"
34 #include "llvm/Object/Archive.h"
35 #include "llvm/Object/ELFObjectFile.h"
36 #include "llvm/Object/COFF.h"
37 #include "llvm/Object/MachO.h"
38 #include "llvm/Object/ObjectFile.h"
39 #include "llvm/Support/Casting.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/Errc.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/Format.h"
45 #include "llvm/Support/GraphWriter.h"
46 #include "llvm/Support/Host.h"
47 #include "llvm/Support/ManagedStatic.h"
48 #include "llvm/Support/MemoryBuffer.h"
49 #include "llvm/Support/PrettyStackTrace.h"
50 #include "llvm/Support/Signals.h"
51 #include "llvm/Support/SourceMgr.h"
52 #include "llvm/Support/TargetRegistry.h"
53 #include "llvm/Support/TargetSelect.h"
54 #include "llvm/Support/raw_ostream.h"
58 #include <system_error>
61 using namespace object;
63 static cl::list<std::string>
64 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
67 llvm::Disassemble("disassemble",
68 cl::desc("Display assembler mnemonics for the machine instructions"));
70 Disassembled("d", cl::desc("Alias for --disassemble"),
71 cl::aliasopt(Disassemble));
74 llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
77 llvm::SectionContents("s", cl::desc("Display the content of each section"));
80 llvm::SymbolTable("t", cl::desc("Display the symbol table"));
83 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
86 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
89 llvm::Bind("bind", cl::desc("Display mach-o binding info"));
92 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
95 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
98 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
100 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
103 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
104 "see -version for available targets"));
108 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
109 cl::value_desc("cpu-name"),
113 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
114 "see -version for available targets"));
117 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
118 "headers for each section."));
120 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
121 cl::aliasopt(SectionHeaders));
123 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
124 cl::aliasopt(SectionHeaders));
126 cl::list<std::string>
127 llvm::MAttrs("mattr",
129 cl::desc("Target specific attributes"),
130 cl::value_desc("a1,+a2,-a3,..."));
133 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
134 "instructions, do not print "
135 "the instruction bytes."));
138 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
141 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
142 cl::aliasopt(UnwindInfo));
145 llvm::PrivateHeaders("private-headers",
146 cl::desc("Display format specific file headers"));
149 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
150 cl::aliasopt(PrivateHeaders));
153 llvm::PrintImmHex("print-imm-hex",
154 cl::desc("Use hex format for immediate values"));
156 static StringRef ToolName;
157 static int ReturnValue = EXIT_SUCCESS;
159 bool llvm::error(std::error_code EC) {
163 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
165 ReturnValue = EXIT_FAILURE;
169 static void report_error(StringRef File, std::error_code EC) {
171 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
172 ReturnValue = EXIT_FAILURE;
175 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
176 // Figure out the target triple.
177 llvm::Triple TheTriple("unknown-unknown-unknown");
178 if (TripleName.empty()) {
180 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
181 // TheTriple defaults to ELF, and COFF doesn't have an environment:
182 // the best we can do here is indicate that it is mach-o.
184 TheTriple.setObjectFormat(Triple::MachO);
187 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
188 if (COFFObj->getArch() == Triple::thumb)
189 TheTriple.setTriple("thumbv7-windows");
193 TheTriple.setTriple(Triple::normalize(TripleName));
195 // Get the target specific parser.
197 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
200 errs() << ToolName << ": " << Error;
204 // Update the triple name and return the found target.
205 TripleName = TheTriple.getTriple();
209 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
210 uint64_t a_addr, b_addr;
211 if (error(a.getOffset(a_addr))) return false;
212 if (error(b.getOffset(b_addr))) return false;
213 return a_addr < b_addr;
217 class PrettyPrinter {
219 virtual ~PrettyPrinter(){}
220 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
221 ArrayRef<uint8_t> Bytes, uint64_t Address,
222 raw_ostream &OS, StringRef Annot,
223 MCSubtargetInfo const &STI) {
224 outs() << format("%8" PRIx64 ":", Address);
225 if (!NoShowRawInsn) {
227 dumpBytes(Bytes, outs());
229 IP.printInst(MI, outs(), "", STI);
232 PrettyPrinter PrettyPrinterInst;
233 class HexagonPrettyPrinter : public PrettyPrinter {
235 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
238 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
239 OS << format("%8" PRIx64 ":", Address);
240 if (!NoShowRawInsn) {
242 dumpBytes(Bytes.slice(0, 4), OS);
243 OS << format("%08" PRIx32, opcode);
246 void printInst(MCInstPrinter &IP, const MCInst *MI,
247 ArrayRef<uint8_t> Bytes, uint64_t Address,
248 raw_ostream &OS, StringRef Annot,
249 MCSubtargetInfo const &STI) override {
252 raw_string_ostream TempStream(Buffer);
253 IP.printInst(MI, TempStream, "", STI);
255 StringRef Contents(Buffer);
256 // Split off bundle attributes
257 auto PacketBundle = Contents.rsplit('\n');
258 // Split off first instruction from the rest
259 auto HeadTail = PacketBundle.first.split('\n');
260 auto Preamble = " { ";
262 while(!HeadTail.first.empty()) {
265 printLead(Bytes, Address, OS);
269 auto Duplex = HeadTail.first.split('\v');
270 if(!Duplex.second.empty()){
273 Inst = Duplex.second;
276 Inst = HeadTail.first;
278 Bytes = Bytes.slice(4);
280 HeadTail = HeadTail.second.split('\n');
282 OS << " } " << PacketBundle.second;
285 HexagonPrettyPrinter HexagonPrettyPrinterInst;
286 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
287 switch(Triple.getArch()) {
289 return PrettyPrinterInst;
290 case Triple::hexagon:
291 return HexagonPrettyPrinterInst;
296 template <class ELFT>
297 static const typename ELFObjectFile<ELFT>::Elf_Rel *
298 getRel(const ELFFile<ELFT> &EF, DataRefImpl Rel) {
299 typedef typename ELFObjectFile<ELFT>::Elf_Rel Elf_Rel;
300 return EF.template getEntry<Elf_Rel>(Rel.d.a, Rel.d.b);
303 template <class ELFT>
304 static const typename ELFObjectFile<ELFT>::Elf_Rela *
305 getRela(const ELFFile<ELFT> &EF, DataRefImpl Rela) {
306 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
307 return EF.template getEntry<Elf_Rela>(Rela.d.a, Rela.d.b);
310 template <class ELFT>
311 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
313 SmallVectorImpl<char> &Result) {
314 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
315 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
316 const ELFFile<ELFT> &EF = *Obj->getELFFile();
318 const Elf_Shdr *sec = EF.getSection(Rel.d.a);
322 uint16_t symbol_index = 0;
323 switch (sec->sh_type) {
325 return object_error::parse_failed;
327 type = getRel(EF, Rel)->getType(EF.isMips64EL());
328 symbol_index = getRel(EF, Rel)->getSymbol(EF.isMips64EL());
329 // TODO: Read implicit addend from section data.
332 case ELF::SHT_RELA: {
333 type = getRela(EF, Rel)->getType(EF.isMips64EL());
334 symbol_index = getRela(EF, Rel)->getSymbol(EF.isMips64EL());
335 addend = getRela(EF, Rel)->r_addend;
339 const Elf_Sym *symb =
340 EF.template getEntry<Elf_Sym>(sec->sh_link, symbol_index);
342 const Elf_Shdr *SymSec = EF.getSection(symb);
343 if (symb->getType() == ELF::STT_SECTION) {
344 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
345 if (std::error_code EC = SecName.getError())
349 ErrorOr<StringRef> SymName =
350 EF.getSymbolName(EF.getSection(sec->sh_link), symb);
352 return SymName.getError();
355 switch (EF.getHeader()->e_machine) {
358 case ELF::R_X86_64_PC8:
359 case ELF::R_X86_64_PC16:
360 case ELF::R_X86_64_PC32: {
362 raw_string_ostream fmt(fmtbuf);
363 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
365 Result.append(fmtbuf.begin(), fmtbuf.end());
367 case ELF::R_X86_64_8:
368 case ELF::R_X86_64_16:
369 case ELF::R_X86_64_32:
370 case ELF::R_X86_64_32S:
371 case ELF::R_X86_64_64: {
373 raw_string_ostream fmt(fmtbuf);
374 fmt << Target << (addend < 0 ? "" : "+") << addend;
376 Result.append(fmtbuf.begin(), fmtbuf.end());
382 case ELF::EM_AARCH64: {
384 raw_string_ostream fmt(fmtbuf);
387 fmt << (addend < 0 ? "" : "+") << addend;
389 Result.append(fmtbuf.begin(), fmtbuf.end());
394 case ELF::EM_HEXAGON:
402 Result.append(res.begin(), res.end());
403 return std::error_code();
406 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
407 const RelocationRef &RelRef,
408 SmallVectorImpl<char> &Result) {
409 DataRefImpl Rel = RelRef.getRawDataRefImpl();
410 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
411 return getRelocationValueString(ELF32LE, Rel, Result);
412 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
413 return getRelocationValueString(ELF64LE, Rel, Result);
414 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
415 return getRelocationValueString(ELF32BE, Rel, Result);
416 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
417 return getRelocationValueString(ELF64BE, Rel, Result);
420 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
421 const RelocationRef &Rel,
422 SmallVectorImpl<char> &Result) {
423 symbol_iterator SymI = Rel.getSymbol();
425 if (std::error_code EC = SymI->getName(SymName))
427 Result.append(SymName.begin(), SymName.end());
428 return std::error_code();
431 static void printRelocationTargetName(const MachOObjectFile *O,
432 const MachO::any_relocation_info &RE,
433 raw_string_ostream &fmt) {
434 bool IsScattered = O->isRelocationScattered(RE);
436 // Target of a scattered relocation is an address. In the interest of
437 // generating pretty output, scan through the symbol table looking for a
438 // symbol that aligns with that address. If we find one, print it.
439 // Otherwise, we just print the hex address of the target.
441 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
443 for (const SymbolRef &Symbol : O->symbols()) {
448 if ((ec = Symbol.getAddress(Addr)))
449 report_fatal_error(ec.message());
452 if ((ec = Symbol.getName(Name)))
453 report_fatal_error(ec.message());
458 // If we couldn't find a symbol that this relocation refers to, try
459 // to find a section beginning instead.
460 for (const SectionRef &Section : O->sections()) {
464 uint64_t Addr = Section.getAddress();
467 if ((ec = Section.getName(Name)))
468 report_fatal_error(ec.message());
473 fmt << format("0x%x", Val);
478 bool isExtern = O->getPlainRelocationExternal(RE);
479 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
482 symbol_iterator SI = O->symbol_begin();
486 section_iterator SI = O->section_begin();
487 // Adjust for the fact that sections are 1-indexed.
488 advance(SI, Val - 1);
495 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
496 const RelocationRef &RelRef,
497 SmallVectorImpl<char> &Result) {
498 DataRefImpl Rel = RelRef.getRawDataRefImpl();
499 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
501 unsigned Arch = Obj->getArch();
504 raw_string_ostream fmt(fmtbuf);
505 unsigned Type = Obj->getAnyRelocationType(RE);
506 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
508 // Determine any addends that should be displayed with the relocation.
509 // These require decoding the relocation type, which is triple-specific.
511 // X86_64 has entirely custom relocation types.
512 if (Arch == Triple::x86_64) {
513 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
516 case MachO::X86_64_RELOC_GOT_LOAD:
517 case MachO::X86_64_RELOC_GOT: {
518 printRelocationTargetName(Obj, RE, fmt);
524 case MachO::X86_64_RELOC_SUBTRACTOR: {
525 DataRefImpl RelNext = Rel;
526 Obj->moveRelocationNext(RelNext);
527 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
529 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
530 // X86_64_RELOC_UNSIGNED.
531 // NOTE: Scattered relocations don't exist on x86_64.
532 unsigned RType = Obj->getAnyRelocationType(RENext);
533 if (RType != MachO::X86_64_RELOC_UNSIGNED)
534 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
535 "X86_64_RELOC_SUBTRACTOR.");
537 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
538 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
539 printRelocationTargetName(Obj, RENext, fmt);
541 printRelocationTargetName(Obj, RE, fmt);
544 case MachO::X86_64_RELOC_TLV:
545 printRelocationTargetName(Obj, RE, fmt);
550 case MachO::X86_64_RELOC_SIGNED_1:
551 printRelocationTargetName(Obj, RE, fmt);
554 case MachO::X86_64_RELOC_SIGNED_2:
555 printRelocationTargetName(Obj, RE, fmt);
558 case MachO::X86_64_RELOC_SIGNED_4:
559 printRelocationTargetName(Obj, RE, fmt);
563 printRelocationTargetName(Obj, RE, fmt);
566 // X86 and ARM share some relocation types in common.
567 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
568 Arch == Triple::ppc) {
569 // Generic relocation types...
571 case MachO::GENERIC_RELOC_PAIR: // prints no info
572 return std::error_code();
573 case MachO::GENERIC_RELOC_SECTDIFF: {
574 DataRefImpl RelNext = Rel;
575 Obj->moveRelocationNext(RelNext);
576 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
578 // X86 sect diff's must be followed by a relocation of type
579 // GENERIC_RELOC_PAIR.
580 unsigned RType = Obj->getAnyRelocationType(RENext);
582 if (RType != MachO::GENERIC_RELOC_PAIR)
583 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
584 "GENERIC_RELOC_SECTDIFF.");
586 printRelocationTargetName(Obj, RE, fmt);
588 printRelocationTargetName(Obj, RENext, fmt);
593 if (Arch == Triple::x86 || Arch == Triple::ppc) {
595 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
596 DataRefImpl RelNext = Rel;
597 Obj->moveRelocationNext(RelNext);
598 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
600 // X86 sect diff's must be followed by a relocation of type
601 // GENERIC_RELOC_PAIR.
602 unsigned RType = Obj->getAnyRelocationType(RENext);
603 if (RType != MachO::GENERIC_RELOC_PAIR)
604 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
605 "GENERIC_RELOC_LOCAL_SECTDIFF.");
607 printRelocationTargetName(Obj, RE, fmt);
609 printRelocationTargetName(Obj, RENext, fmt);
612 case MachO::GENERIC_RELOC_TLV: {
613 printRelocationTargetName(Obj, RE, fmt);
620 printRelocationTargetName(Obj, RE, fmt);
622 } else { // ARM-specific relocations
624 case MachO::ARM_RELOC_HALF:
625 case MachO::ARM_RELOC_HALF_SECTDIFF: {
626 // Half relocations steal a bit from the length field to encode
627 // whether this is an upper16 or a lower16 relocation.
628 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
634 printRelocationTargetName(Obj, RE, fmt);
636 DataRefImpl RelNext = Rel;
637 Obj->moveRelocationNext(RelNext);
638 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
640 // ARM half relocs must be followed by a relocation of type
642 unsigned RType = Obj->getAnyRelocationType(RENext);
643 if (RType != MachO::ARM_RELOC_PAIR)
644 report_fatal_error("Expected ARM_RELOC_PAIR after "
647 // NOTE: The half of the target virtual address is stashed in the
648 // address field of the secondary relocation, but we can't reverse
649 // engineer the constant offset from it without decoding the movw/movt
650 // instruction to find the other half in its immediate field.
652 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
653 // symbol/section pointer of the follow-on relocation.
654 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
656 printRelocationTargetName(Obj, RENext, fmt);
662 default: { printRelocationTargetName(Obj, RE, fmt); }
666 printRelocationTargetName(Obj, RE, fmt);
669 Result.append(fmtbuf.begin(), fmtbuf.end());
670 return std::error_code();
673 static std::error_code getRelocationValueString(const RelocationRef &Rel,
674 SmallVectorImpl<char> &Result) {
675 const ObjectFile *Obj = Rel.getObjectFile();
676 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
677 return getRelocationValueString(ELF, Rel, Result);
678 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
679 return getRelocationValueString(COFF, Rel, Result);
680 auto *MachO = cast<MachOObjectFile>(Obj);
681 return getRelocationValueString(MachO, Rel, Result);
684 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
685 const Target *TheTarget = getTarget(Obj);
686 // getTarget() will have already issued a diagnostic if necessary, so
687 // just bail here if it failed.
691 // Package up features to be passed to target/subtarget
692 std::string FeaturesStr;
694 SubtargetFeatures Features;
695 for (unsigned i = 0; i != MAttrs.size(); ++i)
696 Features.AddFeature(MAttrs[i]);
697 FeaturesStr = Features.getString();
700 std::unique_ptr<const MCRegisterInfo> MRI(
701 TheTarget->createMCRegInfo(TripleName));
703 errs() << "error: no register info for target " << TripleName << "\n";
707 // Set up disassembler.
708 std::unique_ptr<const MCAsmInfo> AsmInfo(
709 TheTarget->createMCAsmInfo(*MRI, TripleName));
711 errs() << "error: no assembly info for target " << TripleName << "\n";
715 std::unique_ptr<const MCSubtargetInfo> STI(
716 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
718 errs() << "error: no subtarget info for target " << TripleName << "\n";
722 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
724 errs() << "error: no instruction info for target " << TripleName << "\n";
728 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
729 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
731 std::unique_ptr<MCDisassembler> DisAsm(
732 TheTarget->createMCDisassembler(*STI, Ctx));
735 errs() << "error: no disassembler for target " << TripleName << "\n";
739 std::unique_ptr<const MCInstrAnalysis> MIA(
740 TheTarget->createMCInstrAnalysis(MII.get()));
742 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
743 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
744 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
746 errs() << "error: no instruction printer for target " << TripleName
750 IP->setPrintImmHex(PrintImmHex);
751 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
753 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
754 "\t\t\t%08" PRIx64 ": ";
756 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
757 // in RelocSecs contain the relocations for section S.
759 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
760 for (const SectionRef &Section : Obj->sections()) {
761 section_iterator Sec2 = Section.getRelocatedSection();
762 if (Sec2 != Obj->section_end())
763 SectionRelocMap[*Sec2].push_back(Section);
766 for (const SectionRef &Section : Obj->sections()) {
767 if (!Section.isText() || Section.isVirtual())
770 uint64_t SectionAddr = Section.getAddress();
771 uint64_t SectSize = Section.getSize();
775 // Make a list of all the symbols in this section.
776 std::vector<std::pair<uint64_t, StringRef>> Symbols;
777 for (const SymbolRef &Symbol : Obj->symbols()) {
778 if (Section.containsSymbol(Symbol)) {
780 if (error(Symbol.getAddress(Address)))
782 if (Address == UnknownAddressOrSize)
784 Address -= SectionAddr;
785 if (Address >= SectSize)
789 if (error(Symbol.getName(Name)))
791 Symbols.push_back(std::make_pair(Address, Name));
795 // Sort the symbols by address, just in case they didn't come in that way.
796 array_pod_sort(Symbols.begin(), Symbols.end());
798 // Make a list of all the relocations for this section.
799 std::vector<RelocationRef> Rels;
801 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
802 for (const RelocationRef &Reloc : RelocSec.relocations()) {
803 Rels.push_back(Reloc);
808 // Sort relocations by address.
809 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
811 StringRef SegmentName = "";
812 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
813 DataRefImpl DR = Section.getRawDataRefImpl();
814 SegmentName = MachO->getSectionFinalSegmentName(DR);
817 if (error(Section.getName(name)))
819 outs() << "Disassembly of section ";
820 if (!SegmentName.empty())
821 outs() << SegmentName << ",";
822 outs() << name << ':';
824 // If the section has no symbol at the start, just insert a dummy one.
825 if (Symbols.empty() || Symbols[0].first != 0)
826 Symbols.insert(Symbols.begin(), std::make_pair(0, name));
828 SmallString<40> Comments;
829 raw_svector_ostream CommentStream(Comments);
832 if (error(Section.getContents(BytesStr)))
834 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
840 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
841 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
842 // Disassemble symbol by symbol.
843 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
845 uint64_t Start = Symbols[si].first;
846 // The end is either the section end or the beginning of the next symbol.
847 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
848 // If this symbol has the same address as the next symbol, then skip it.
852 outs() << '\n' << Symbols[si].second << ":\n";
855 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
857 raw_ostream &DebugOut = nulls();
860 for (Index = Start; Index < End; Index += Size) {
863 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
864 SectionAddr + Index, DebugOut,
866 PIP.printInst(*IP, &Inst,
867 Bytes.slice(Index, Size),
868 SectionAddr + Index, outs(), "", *STI);
869 outs() << CommentStream.str();
873 errs() << ToolName << ": warning: invalid instruction encoding\n";
875 Size = 1; // skip illegible bytes
878 // Print relocation for instruction.
879 while (rel_cur != rel_end) {
882 SmallString<16> name;
885 // If this relocation is hidden, skip it.
886 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
887 if (hidden) goto skip_print_rel;
889 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
890 // Stop when rel_cur's address is past the current instruction.
891 if (addr >= Index + Size) break;
892 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
893 if (error(getRelocationValueString(*rel_cur, val)))
895 outs() << format(Fmt.data(), SectionAddr + addr) << name
896 << "\t" << val << "\n";
906 void llvm::PrintRelocations(const ObjectFile *Obj) {
907 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
909 // Regular objdump doesn't print relocations in non-relocatable object
911 if (!Obj->isRelocatableObject())
914 for (const SectionRef &Section : Obj->sections()) {
915 if (Section.relocation_begin() == Section.relocation_end())
918 if (error(Section.getName(secname)))
920 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
921 for (const RelocationRef &Reloc : Section.relocations()) {
924 SmallString<32> relocname;
925 SmallString<32> valuestr;
926 if (error(Reloc.getHidden(hidden)))
930 if (error(Reloc.getTypeName(relocname)))
932 if (error(Reloc.getOffset(address)))
934 if (error(getRelocationValueString(Reloc, valuestr)))
936 outs() << format(Fmt.data(), address) << " " << relocname << " "
943 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
944 outs() << "Sections:\n"
945 "Idx Name Size Address Type\n";
947 for (const SectionRef &Section : Obj->sections()) {
949 if (error(Section.getName(Name)))
951 uint64_t Address = Section.getAddress();
952 uint64_t Size = Section.getSize();
953 bool Text = Section.isText();
954 bool Data = Section.isData();
955 bool BSS = Section.isBSS();
956 std::string Type = (std::string(Text ? "TEXT " : "") +
957 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
958 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
959 Name.str().c_str(), Size, Address, Type.c_str());
964 void llvm::PrintSectionContents(const ObjectFile *Obj) {
966 for (const SectionRef &Section : Obj->sections()) {
969 if (error(Section.getName(Name)))
971 uint64_t BaseAddr = Section.getAddress();
972 uint64_t Size = Section.getSize();
976 outs() << "Contents of section " << Name << ":\n";
977 if (Section.isBSS()) {
978 outs() << format("<skipping contents of bss section at [%04" PRIx64
979 ", %04" PRIx64 ")>\n",
980 BaseAddr, BaseAddr + Size);
984 if (error(Section.getContents(Contents)))
987 // Dump out the content as hex and printable ascii characters.
988 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
989 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
991 for (std::size_t i = 0; i < 16; ++i) {
992 if (i != 0 && i % 4 == 0)
995 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
996 << hexdigit(Contents[addr + i] & 0xF, true);
1002 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1003 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1004 outs() << Contents[addr + i];
1013 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
1014 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1015 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
1017 if (error(Symbol.getError()))
1020 if (error(coff->getSymbolName(*Symbol, Name)))
1023 outs() << "[" << format("%2d", SI) << "]"
1024 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
1025 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
1026 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1027 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1028 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1029 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
1032 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
1033 if (Symbol->isSectionDefinition()) {
1034 const coff_aux_section_definition *asd;
1035 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
1038 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1041 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1042 , unsigned(asd->Length)
1043 , unsigned(asd->NumberOfRelocations)
1044 , unsigned(asd->NumberOfLinenumbers)
1045 , unsigned(asd->CheckSum))
1046 << format("assoc %d comdat %d\n"
1047 , unsigned(AuxNumber)
1048 , unsigned(asd->Selection));
1049 } else if (Symbol->isFileRecord()) {
1050 const char *FileName;
1051 if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
1054 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1055 coff->getSymbolTableEntrySize());
1056 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
1058 SI = SI + Symbol->getNumberOfAuxSymbols();
1061 outs() << "AUX Unknown\n";
1067 void llvm::PrintSymbolTable(const ObjectFile *o) {
1068 outs() << "SYMBOL TABLE:\n";
1070 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1071 PrintCOFFSymbolTable(coff);
1074 for (const SymbolRef &Symbol : o->symbols()) {
1076 SymbolRef::Type Type;
1077 uint32_t Flags = Symbol.getFlags();
1078 section_iterator Section = o->section_end();
1079 if (error(Symbol.getAddress(Address)))
1081 if (error(Symbol.getType(Type)))
1083 uint64_t Size = Symbol.getSize();
1084 if (error(Symbol.getSection(Section)))
1087 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1088 Section->getName(Name);
1089 } else if (error(Symbol.getName(Name))) {
1093 bool Global = Flags & SymbolRef::SF_Global;
1094 bool Weak = Flags & SymbolRef::SF_Weak;
1095 bool Absolute = Flags & SymbolRef::SF_Absolute;
1096 bool Common = Flags & SymbolRef::SF_Common;
1097 bool Hidden = Flags & SymbolRef::SF_Hidden;
1100 uint32_t Alignment = Symbol.getAlignment();
1104 if (Address == UnknownAddressOrSize)
1106 if (Size == 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;
1150 << format("%08" PRIx64 " ", Size);
1152 outs() << ".hidden ";
1159 static void PrintUnwindInfo(const ObjectFile *o) {
1160 outs() << "Unwind info:\n\n";
1162 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1163 printCOFFUnwindInfo(coff);
1164 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1165 printMachOUnwindInfo(MachO);
1167 // TODO: Extract DWARF dump tool to objdump.
1168 errs() << "This operation is only currently supported "
1169 "for COFF and MachO object files.\n";
1174 void llvm::printExportsTrie(const ObjectFile *o) {
1175 outs() << "Exports trie:\n";
1176 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1177 printMachOExportsTrie(MachO);
1179 errs() << "This operation is only currently supported "
1180 "for Mach-O executable files.\n";
1185 void llvm::printRebaseTable(const ObjectFile *o) {
1186 outs() << "Rebase table:\n";
1187 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1188 printMachORebaseTable(MachO);
1190 errs() << "This operation is only currently supported "
1191 "for Mach-O executable files.\n";
1196 void llvm::printBindTable(const ObjectFile *o) {
1197 outs() << "Bind table:\n";
1198 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1199 printMachOBindTable(MachO);
1201 errs() << "This operation is only currently supported "
1202 "for Mach-O executable files.\n";
1207 void llvm::printLazyBindTable(const ObjectFile *o) {
1208 outs() << "Lazy bind table:\n";
1209 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1210 printMachOLazyBindTable(MachO);
1212 errs() << "This operation is only currently supported "
1213 "for Mach-O executable files.\n";
1218 void llvm::printWeakBindTable(const ObjectFile *o) {
1219 outs() << "Weak bind table:\n";
1220 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1221 printMachOWeakBindTable(MachO);
1223 errs() << "This operation is only currently supported "
1224 "for Mach-O executable files.\n";
1229 static void printPrivateFileHeader(const ObjectFile *o) {
1231 printELFFileHeader(o);
1232 } else if (o->isCOFF()) {
1233 printCOFFFileHeader(o);
1234 } else if (o->isMachO()) {
1235 printMachOFileHeader(o);
1239 static void DumpObject(const ObjectFile *o) {
1241 outs() << o->getFileName()
1242 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1245 DisassembleObject(o, Relocations);
1246 if (Relocations && !Disassemble)
1247 PrintRelocations(o);
1249 PrintSectionHeaders(o);
1250 if (SectionContents)
1251 PrintSectionContents(o);
1253 PrintSymbolTable(o);
1257 printPrivateFileHeader(o);
1259 printExportsTrie(o);
1261 printRebaseTable(o);
1265 printLazyBindTable(o);
1267 printWeakBindTable(o);
1270 /// @brief Dump each object file in \a a;
1271 static void DumpArchive(const Archive *a) {
1272 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
1274 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
1275 if (std::error_code EC = ChildOrErr.getError()) {
1276 // Ignore non-object files.
1277 if (EC != object_error::invalid_file_type)
1278 report_error(a->getFileName(), EC);
1281 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
1284 report_error(a->getFileName(), object_error::invalid_file_type);
1288 /// @brief Open file and figure out how to dump it.
1289 static void DumpInput(StringRef file) {
1290 // If file isn't stdin, check that it exists.
1291 if (file != "-" && !sys::fs::exists(file)) {
1292 report_error(file, errc::no_such_file_or_directory);
1296 // If we are using the Mach-O specific object file parser, then let it parse
1297 // the file and process the command line options. So the -arch flags can
1298 // be used to select specific slices, etc.
1300 ParseInputMachO(file);
1304 // Attempt to open the binary.
1305 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1306 if (std::error_code EC = BinaryOrErr.getError()) {
1307 report_error(file, EC);
1310 Binary &Binary = *BinaryOrErr.get().getBinary();
1312 if (Archive *a = dyn_cast<Archive>(&Binary))
1314 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
1317 report_error(file, object_error::invalid_file_type);
1320 int main(int argc, char **argv) {
1321 // Print a stack trace if we signal out.
1322 sys::PrintStackTraceOnErrorSignal();
1323 PrettyStackTraceProgram X(argc, argv);
1324 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1326 // Initialize targets and assembly printers/parsers.
1327 llvm::InitializeAllTargetInfos();
1328 llvm::InitializeAllTargetMCs();
1329 llvm::InitializeAllAsmParsers();
1330 llvm::InitializeAllDisassemblers();
1332 // Register the target printer for --version.
1333 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1335 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1336 TripleName = Triple::normalize(TripleName);
1340 // Defaults to a.out if no filenames specified.
1341 if (InputFilenames.size() == 0)
1342 InputFilenames.push_back("a.out");
1356 && !(UniversalHeaders && MachOOpt)
1357 && !(ArchiveHeaders && MachOOpt)
1358 && !(IndirectSymbols && MachOOpt)
1359 && !(DataInCode && MachOOpt)
1360 && !(LinkOptHints && MachOOpt)
1361 && !(InfoPlist && MachOOpt)
1362 && !(DylibsUsed && MachOOpt)
1363 && !(DylibId && MachOOpt)
1364 && !(ObjcMetaData && MachOOpt)
1365 && !(DumpSections.size() != 0 && MachOOpt)) {
1366 cl::PrintHelpMessage();
1370 std::for_each(InputFilenames.begin(), InputFilenames.end(),