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/CodeGen/FaultMaps.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCDisassembler.h"
28 #include "llvm/MC/MCInst.h"
29 #include "llvm/MC/MCInstPrinter.h"
30 #include "llvm/MC/MCInstrAnalysis.h"
31 #include "llvm/MC/MCInstrInfo.h"
32 #include "llvm/MC/MCObjectFileInfo.h"
33 #include "llvm/MC/MCRegisterInfo.h"
34 #include "llvm/MC/MCRelocationInfo.h"
35 #include "llvm/MC/MCSubtargetInfo.h"
36 #include "llvm/Object/Archive.h"
37 #include "llvm/Object/ELFObjectFile.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::DisassembleAll("disassemble-all",
77 cl::desc("Display assembler mnemonics for the machine instructions"));
79 DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
80 cl::aliasopt(DisassembleAll));
83 llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
86 llvm::SectionContents("s", cl::desc("Display the content of each section"));
89 llvm::SymbolTable("t", cl::desc("Display the symbol table"));
92 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
95 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
98 llvm::Bind("bind", cl::desc("Display mach-o binding info"));
101 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
104 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
107 llvm::RawClangAST("raw-clang-ast",
108 cl::desc("Dump the raw binary contents of the clang AST section"));
111 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
113 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
116 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
117 "see -version for available targets"));
121 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
122 cl::value_desc("cpu-name"),
126 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
127 "see -version for available targets"));
130 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
131 "headers for each section."));
133 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
134 cl::aliasopt(SectionHeaders));
136 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
137 cl::aliasopt(SectionHeaders));
139 cl::list<std::string>
140 llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
141 "With -macho dump segment,section"));
143 static FilterSectionsj("j", cl::desc("Alias for --section"),
144 cl::aliasopt(llvm::FilterSections));
146 cl::list<std::string>
147 llvm::MAttrs("mattr",
149 cl::desc("Target specific attributes"),
150 cl::value_desc("a1,+a2,-a3,..."));
153 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
154 "instructions, do not print "
155 "the instruction bytes."));
158 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
161 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
162 cl::aliasopt(UnwindInfo));
165 llvm::PrivateHeaders("private-headers",
166 cl::desc("Display format specific file headers"));
169 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
170 cl::aliasopt(PrivateHeaders));
173 llvm::PrintImmHex("print-imm-hex",
174 cl::desc("Use hex format for immediate values"));
176 cl::opt<bool> PrintFaultMaps("fault-map-section",
177 cl::desc("Display contents of faultmap section"));
179 static StringRef ToolName;
182 typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
184 class SectionFilterIterator {
186 SectionFilterIterator(FilterPredicate P,
187 llvm::object::section_iterator const &I,
188 llvm::object::section_iterator const &E)
189 : Predicate(P), Iterator(I), End(E) {
192 const llvm::object::SectionRef &operator*() const { return *Iterator; }
193 SectionFilterIterator &operator++() {
198 bool operator!=(SectionFilterIterator const &Other) const {
199 return Iterator != Other.Iterator;
203 void ScanPredicate() {
204 while (Iterator != End && !Predicate(*Iterator)) {
208 FilterPredicate Predicate;
209 llvm::object::section_iterator Iterator;
210 llvm::object::section_iterator End;
213 class SectionFilter {
215 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
216 : Predicate(P), Object(O) {}
217 SectionFilterIterator begin() {
218 return SectionFilterIterator(Predicate, Object.section_begin(),
219 Object.section_end());
221 SectionFilterIterator end() {
222 return SectionFilterIterator(Predicate, Object.section_end(),
223 Object.section_end());
227 FilterPredicate Predicate;
228 llvm::object::ObjectFile const &Object;
230 SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
231 return SectionFilter([](llvm::object::SectionRef const &S) {
232 if(FilterSections.empty())
234 llvm::StringRef String;
235 std::error_code error = S.getName(String);
238 return std::find(FilterSections.begin(),
239 FilterSections.end(),
240 String) != FilterSections.end();
246 void llvm::error(std::error_code EC) {
250 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
255 static void report_error(StringRef File, std::error_code EC) {
257 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
261 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
262 // Figure out the target triple.
263 llvm::Triple TheTriple("unknown-unknown-unknown");
264 if (TripleName.empty()) {
266 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
267 // TheTriple defaults to ELF, and COFF doesn't have an environment:
268 // the best we can do here is indicate that it is mach-o.
270 TheTriple.setObjectFormat(Triple::MachO);
273 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
274 if (COFFObj->getArch() == Triple::thumb)
275 TheTriple.setTriple("thumbv7-windows");
279 TheTriple.setTriple(Triple::normalize(TripleName));
281 // Get the target specific parser.
283 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
286 errs() << ToolName << ": " << Error;
290 // Update the triple name and return the found target.
291 TripleName = TheTriple.getTriple();
295 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
296 return a.getOffset() < b.getOffset();
300 class PrettyPrinter {
302 virtual ~PrettyPrinter(){}
303 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
304 ArrayRef<uint8_t> Bytes, uint64_t Address,
305 raw_ostream &OS, StringRef Annot,
306 MCSubtargetInfo const &STI) {
307 outs() << format("%8" PRIx64 ":", Address);
308 if (!NoShowRawInsn) {
310 dumpBytes(Bytes, outs());
312 IP.printInst(MI, outs(), "", STI);
315 PrettyPrinter PrettyPrinterInst;
316 class HexagonPrettyPrinter : public PrettyPrinter {
318 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
321 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
322 OS << format("%8" PRIx64 ":", Address);
323 if (!NoShowRawInsn) {
325 dumpBytes(Bytes.slice(0, 4), OS);
326 OS << format("%08" PRIx32, opcode);
329 void printInst(MCInstPrinter &IP, const MCInst *MI,
330 ArrayRef<uint8_t> Bytes, uint64_t Address,
331 raw_ostream &OS, StringRef Annot,
332 MCSubtargetInfo const &STI) override {
335 raw_string_ostream TempStream(Buffer);
336 IP.printInst(MI, TempStream, "", STI);
338 StringRef Contents(Buffer);
339 // Split off bundle attributes
340 auto PacketBundle = Contents.rsplit('\n');
341 // Split off first instruction from the rest
342 auto HeadTail = PacketBundle.first.split('\n');
343 auto Preamble = " { ";
345 while(!HeadTail.first.empty()) {
348 printLead(Bytes, Address, OS);
352 auto Duplex = HeadTail.first.split('\v');
353 if(!Duplex.second.empty()){
356 Inst = Duplex.second;
359 Inst = HeadTail.first;
361 Bytes = Bytes.slice(4);
363 HeadTail = HeadTail.second.split('\n');
365 OS << " } " << PacketBundle.second;
368 HexagonPrettyPrinter HexagonPrettyPrinterInst;
369 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
370 switch(Triple.getArch()) {
372 return PrettyPrinterInst;
373 case Triple::hexagon:
374 return HexagonPrettyPrinterInst;
379 template <class ELFT>
380 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
381 const RelocationRef &RelRef,
382 SmallVectorImpl<char> &Result) {
383 DataRefImpl Rel = RelRef.getRawDataRefImpl();
385 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
386 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
387 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
389 const ELFFile<ELFT> &EF = *Obj->getELFFile();
391 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
392 if (std::error_code EC = SecOrErr.getError())
394 const Elf_Shdr *Sec = *SecOrErr;
395 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
396 if (std::error_code EC = SymTabOrErr.getError())
398 const Elf_Shdr *SymTab = *SymTabOrErr;
399 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
400 SymTab->sh_type == ELF::SHT_DYNSYM);
401 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
402 if (std::error_code EC = StrTabSec.getError())
404 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
405 if (std::error_code EC = StrTabOrErr.getError())
407 StringRef StrTab = *StrTabOrErr;
408 uint8_t type = RelRef.getType();
411 switch (Sec->sh_type) {
413 return object_error::parse_failed;
415 // TODO: Read implicit addend from section data.
418 case ELF::SHT_RELA: {
419 const Elf_Rela *ERela = Obj->getRela(Rel);
420 addend = ERela->r_addend;
424 symbol_iterator SI = RelRef.getSymbol();
425 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
427 if (symb->getType() == ELF::STT_SECTION) {
428 ErrorOr<section_iterator> SymSI = SI->getSection();
429 if (std::error_code EC = SymSI.getError())
431 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
432 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
433 if (std::error_code EC = SecName.getError())
437 ErrorOr<StringRef> SymName = symb->getName(StrTab);
439 return SymName.getError();
442 switch (EF.getHeader()->e_machine) {
445 case ELF::R_X86_64_PC8:
446 case ELF::R_X86_64_PC16:
447 case ELF::R_X86_64_PC32: {
449 raw_string_ostream fmt(fmtbuf);
450 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
452 Result.append(fmtbuf.begin(), fmtbuf.end());
454 case ELF::R_X86_64_8:
455 case ELF::R_X86_64_16:
456 case ELF::R_X86_64_32:
457 case ELF::R_X86_64_32S:
458 case ELF::R_X86_64_64: {
460 raw_string_ostream fmt(fmtbuf);
461 fmt << Target << (addend < 0 ? "" : "+") << addend;
463 Result.append(fmtbuf.begin(), fmtbuf.end());
469 case ELF::EM_AARCH64: {
471 raw_string_ostream fmt(fmtbuf);
474 fmt << (addend < 0 ? "" : "+") << addend;
476 Result.append(fmtbuf.begin(), fmtbuf.end());
482 case ELF::EM_HEXAGON:
490 Result.append(res.begin(), res.end());
491 return std::error_code();
494 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
495 const RelocationRef &Rel,
496 SmallVectorImpl<char> &Result) {
497 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
498 return getRelocationValueString(ELF32LE, Rel, Result);
499 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
500 return getRelocationValueString(ELF64LE, Rel, Result);
501 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
502 return getRelocationValueString(ELF32BE, Rel, Result);
503 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
504 return getRelocationValueString(ELF64BE, Rel, Result);
507 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
508 const RelocationRef &Rel,
509 SmallVectorImpl<char> &Result) {
510 symbol_iterator SymI = Rel.getSymbol();
511 ErrorOr<StringRef> SymNameOrErr = SymI->getName();
512 if (std::error_code EC = SymNameOrErr.getError())
514 StringRef SymName = *SymNameOrErr;
515 Result.append(SymName.begin(), SymName.end());
516 return std::error_code();
519 static void printRelocationTargetName(const MachOObjectFile *O,
520 const MachO::any_relocation_info &RE,
521 raw_string_ostream &fmt) {
522 bool IsScattered = O->isRelocationScattered(RE);
524 // Target of a scattered relocation is an address. In the interest of
525 // generating pretty output, scan through the symbol table looking for a
526 // symbol that aligns with that address. If we find one, print it.
527 // Otherwise, we just print the hex address of the target.
529 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
531 for (const SymbolRef &Symbol : O->symbols()) {
533 ErrorOr<uint64_t> Addr = Symbol.getAddress();
534 if ((ec = Addr.getError()))
535 report_fatal_error(ec.message());
538 ErrorOr<StringRef> Name = Symbol.getName();
539 if (std::error_code EC = Name.getError())
540 report_fatal_error(EC.message());
545 // If we couldn't find a symbol that this relocation refers to, try
546 // to find a section beginning instead.
547 for (const SectionRef &Section : ToolSectionFilter(*O)) {
551 uint64_t Addr = Section.getAddress();
554 if ((ec = Section.getName(Name)))
555 report_fatal_error(ec.message());
560 fmt << format("0x%x", Val);
565 bool isExtern = O->getPlainRelocationExternal(RE);
566 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
569 symbol_iterator SI = O->symbol_begin();
571 ErrorOr<StringRef> SOrErr = SI->getName();
572 error(SOrErr.getError());
575 section_iterator SI = O->section_begin();
576 // Adjust for the fact that sections are 1-indexed.
577 advance(SI, Val - 1);
584 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
585 const RelocationRef &RelRef,
586 SmallVectorImpl<char> &Result) {
587 DataRefImpl Rel = RelRef.getRawDataRefImpl();
588 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
590 unsigned Arch = Obj->getArch();
593 raw_string_ostream fmt(fmtbuf);
594 unsigned Type = Obj->getAnyRelocationType(RE);
595 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
597 // Determine any addends that should be displayed with the relocation.
598 // These require decoding the relocation type, which is triple-specific.
600 // X86_64 has entirely custom relocation types.
601 if (Arch == Triple::x86_64) {
602 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
605 case MachO::X86_64_RELOC_GOT_LOAD:
606 case MachO::X86_64_RELOC_GOT: {
607 printRelocationTargetName(Obj, RE, fmt);
613 case MachO::X86_64_RELOC_SUBTRACTOR: {
614 DataRefImpl RelNext = Rel;
615 Obj->moveRelocationNext(RelNext);
616 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
618 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
619 // X86_64_RELOC_UNSIGNED.
620 // NOTE: Scattered relocations don't exist on x86_64.
621 unsigned RType = Obj->getAnyRelocationType(RENext);
622 if (RType != MachO::X86_64_RELOC_UNSIGNED)
623 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
624 "X86_64_RELOC_SUBTRACTOR.");
626 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
627 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
628 printRelocationTargetName(Obj, RENext, fmt);
630 printRelocationTargetName(Obj, RE, fmt);
633 case MachO::X86_64_RELOC_TLV:
634 printRelocationTargetName(Obj, RE, fmt);
639 case MachO::X86_64_RELOC_SIGNED_1:
640 printRelocationTargetName(Obj, RE, fmt);
643 case MachO::X86_64_RELOC_SIGNED_2:
644 printRelocationTargetName(Obj, RE, fmt);
647 case MachO::X86_64_RELOC_SIGNED_4:
648 printRelocationTargetName(Obj, RE, fmt);
652 printRelocationTargetName(Obj, RE, fmt);
655 // X86 and ARM share some relocation types in common.
656 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
657 Arch == Triple::ppc) {
658 // Generic relocation types...
660 case MachO::GENERIC_RELOC_PAIR: // prints no info
661 return std::error_code();
662 case MachO::GENERIC_RELOC_SECTDIFF: {
663 DataRefImpl RelNext = Rel;
664 Obj->moveRelocationNext(RelNext);
665 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
667 // X86 sect diff's must be followed by a relocation of type
668 // GENERIC_RELOC_PAIR.
669 unsigned RType = Obj->getAnyRelocationType(RENext);
671 if (RType != MachO::GENERIC_RELOC_PAIR)
672 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
673 "GENERIC_RELOC_SECTDIFF.");
675 printRelocationTargetName(Obj, RE, fmt);
677 printRelocationTargetName(Obj, RENext, fmt);
682 if (Arch == Triple::x86 || Arch == Triple::ppc) {
684 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
685 DataRefImpl RelNext = Rel;
686 Obj->moveRelocationNext(RelNext);
687 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
689 // X86 sect diff's must be followed by a relocation of type
690 // GENERIC_RELOC_PAIR.
691 unsigned RType = Obj->getAnyRelocationType(RENext);
692 if (RType != MachO::GENERIC_RELOC_PAIR)
693 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
694 "GENERIC_RELOC_LOCAL_SECTDIFF.");
696 printRelocationTargetName(Obj, RE, fmt);
698 printRelocationTargetName(Obj, RENext, fmt);
701 case MachO::GENERIC_RELOC_TLV: {
702 printRelocationTargetName(Obj, RE, fmt);
709 printRelocationTargetName(Obj, RE, fmt);
711 } else { // ARM-specific relocations
713 case MachO::ARM_RELOC_HALF:
714 case MachO::ARM_RELOC_HALF_SECTDIFF: {
715 // Half relocations steal a bit from the length field to encode
716 // whether this is an upper16 or a lower16 relocation.
717 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
723 printRelocationTargetName(Obj, RE, fmt);
725 DataRefImpl RelNext = Rel;
726 Obj->moveRelocationNext(RelNext);
727 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
729 // ARM half relocs must be followed by a relocation of type
731 unsigned RType = Obj->getAnyRelocationType(RENext);
732 if (RType != MachO::ARM_RELOC_PAIR)
733 report_fatal_error("Expected ARM_RELOC_PAIR after "
736 // NOTE: The half of the target virtual address is stashed in the
737 // address field of the secondary relocation, but we can't reverse
738 // engineer the constant offset from it without decoding the movw/movt
739 // instruction to find the other half in its immediate field.
741 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
742 // symbol/section pointer of the follow-on relocation.
743 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
745 printRelocationTargetName(Obj, RENext, fmt);
751 default: { printRelocationTargetName(Obj, RE, fmt); }
755 printRelocationTargetName(Obj, RE, fmt);
758 Result.append(fmtbuf.begin(), fmtbuf.end());
759 return std::error_code();
762 static std::error_code getRelocationValueString(const RelocationRef &Rel,
763 SmallVectorImpl<char> &Result) {
764 const ObjectFile *Obj = Rel.getObject();
765 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
766 return getRelocationValueString(ELF, Rel, Result);
767 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
768 return getRelocationValueString(COFF, Rel, Result);
769 auto *MachO = cast<MachOObjectFile>(Obj);
770 return getRelocationValueString(MachO, Rel, Result);
773 /// @brief Indicates whether this relocation should hidden when listing
774 /// relocations, usually because it is the trailing part of a multipart
775 /// relocation that will be printed as part of the leading relocation.
776 static bool getHidden(RelocationRef RelRef) {
777 const ObjectFile *Obj = RelRef.getObject();
778 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
782 unsigned Arch = MachO->getArch();
783 DataRefImpl Rel = RelRef.getRawDataRefImpl();
784 uint64_t Type = MachO->getRelocationType(Rel);
786 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
788 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
789 if (Type == MachO::GENERIC_RELOC_PAIR)
791 } else if (Arch == Triple::x86_64) {
792 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
793 // an X86_64_RELOC_SUBTRACTOR.
794 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
795 DataRefImpl RelPrev = Rel;
797 uint64_t PrevType = MachO->getRelocationType(RelPrev);
798 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
806 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
807 const Target *TheTarget = getTarget(Obj);
808 // getTarget() will have already issued a diagnostic if necessary, so
809 // just bail here if it failed.
813 // Package up features to be passed to target/subtarget
814 std::string FeaturesStr;
816 SubtargetFeatures Features;
817 for (unsigned i = 0; i != MAttrs.size(); ++i)
818 Features.AddFeature(MAttrs[i]);
819 FeaturesStr = Features.getString();
822 std::unique_ptr<const MCRegisterInfo> MRI(
823 TheTarget->createMCRegInfo(TripleName));
825 errs() << "error: no register info for target " << TripleName << "\n";
829 // Set up disassembler.
830 std::unique_ptr<const MCAsmInfo> AsmInfo(
831 TheTarget->createMCAsmInfo(*MRI, TripleName));
833 errs() << "error: no assembly info for target " << TripleName << "\n";
837 std::unique_ptr<const MCSubtargetInfo> STI(
838 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
840 errs() << "error: no subtarget info for target " << TripleName << "\n";
844 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
846 errs() << "error: no instruction info for target " << TripleName << "\n";
850 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
851 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
853 std::unique_ptr<MCDisassembler> DisAsm(
854 TheTarget->createMCDisassembler(*STI, Ctx));
857 errs() << "error: no disassembler for target " << TripleName << "\n";
861 std::unique_ptr<const MCInstrAnalysis> MIA(
862 TheTarget->createMCInstrAnalysis(MII.get()));
864 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
865 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
866 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
868 errs() << "error: no instruction printer for target " << TripleName
872 IP->setPrintImmHex(PrintImmHex);
873 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
875 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
876 "\t\t\t%08" PRIx64 ": ";
878 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
879 // in RelocSecs contain the relocations for section S.
881 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
882 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
883 section_iterator Sec2 = Section.getRelocatedSection();
884 if (Sec2 != Obj->section_end())
885 SectionRelocMap[*Sec2].push_back(Section);
888 // Create a mapping from virtual address to symbol name. This is used to
889 // pretty print the symbols while disassembling.
890 typedef std::vector<std::pair<uint64_t, StringRef>> SectionSymbolsTy;
891 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
892 for (const SymbolRef &Symbol : Obj->symbols()) {
893 ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
894 error(AddressOrErr.getError());
895 uint64_t Address = *AddressOrErr;
897 ErrorOr<StringRef> Name = Symbol.getName();
898 error(Name.getError());
902 ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
903 error(SectionOrErr.getError());
904 section_iterator SecI = *SectionOrErr;
905 if (SecI == Obj->section_end())
908 AllSymbols[*SecI].emplace_back(Address, *Name);
911 // Create a mapping from virtual address to section.
912 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
913 for (SectionRef Sec : Obj->sections())
914 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
915 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
917 // Linked executables (.exe and .dll files) typically don't include a real
918 // symbol table but they might contain an export table.
919 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
920 for (const auto &ExportEntry : COFFObj->export_directories()) {
922 error(ExportEntry.getSymbolName(Name));
926 error(ExportEntry.getExportRVA(RVA));
928 uint64_t VA = COFFObj->getImageBase() + RVA;
929 auto Sec = std::upper_bound(
930 SectionAddresses.begin(), SectionAddresses.end(), VA,
931 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
932 return LHS < RHS.first;
934 if (Sec != SectionAddresses.begin())
937 Sec = SectionAddresses.end();
939 if (Sec != SectionAddresses.end())
940 AllSymbols[Sec->second].emplace_back(VA, Name);
944 // Sort all the symbols, this allows us to use a simple binary search to find
945 // a symbol near an address.
946 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
947 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
949 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
950 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
953 uint64_t SectionAddr = Section.getAddress();
954 uint64_t SectSize = Section.getSize();
958 // Get the list of all the symbols in this section.
959 SectionSymbolsTy &Symbols = AllSymbols[Section];
960 std::vector<uint64_t> DataMappingSymsAddr;
961 std::vector<uint64_t> TextMappingSymsAddr;
962 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
963 for (const auto &Symb : Symbols) {
964 uint64_t Address = Symb.first;
965 StringRef Name = Symb.second;
966 if (Name.startswith("$d"))
967 DataMappingSymsAddr.push_back(Address - SectionAddr);
968 if (Name.startswith("$x"))
969 TextMappingSymsAddr.push_back(Address - SectionAddr);
973 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
974 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
976 // Make a list of all the relocations for this section.
977 std::vector<RelocationRef> Rels;
979 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
980 for (const RelocationRef &Reloc : RelocSec.relocations()) {
981 Rels.push_back(Reloc);
986 // Sort relocations by address.
987 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
989 StringRef SegmentName = "";
990 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
991 DataRefImpl DR = Section.getRawDataRefImpl();
992 SegmentName = MachO->getSectionFinalSegmentName(DR);
995 error(Section.getName(name));
996 outs() << "Disassembly of section ";
997 if (!SegmentName.empty())
998 outs() << SegmentName << ",";
999 outs() << name << ':';
1001 // If the section has no symbol at the start, just insert a dummy one.
1002 if (Symbols.empty() || Symbols[0].first != 0)
1003 Symbols.insert(Symbols.begin(), std::make_pair(SectionAddr, name));
1005 SmallString<40> Comments;
1006 raw_svector_ostream CommentStream(Comments);
1009 error(Section.getContents(BytesStr));
1010 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1016 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1017 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
1018 // Disassemble symbol by symbol.
1019 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
1021 uint64_t Start = Symbols[si].first - SectionAddr;
1022 // The end is either the section end or the beginning of the next
1025 (si == se - 1) ? SectSize : Symbols[si + 1].first - SectionAddr;
1026 // Don't try to disassemble beyond the end of section contents.
1029 // If this symbol has the same address as the next symbol, then skip it.
1033 outs() << '\n' << Symbols[si].second << ":\n";
1036 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1038 raw_ostream &DebugOut = nulls();
1041 for (Index = Start; Index < End; Index += Size) {
1044 // AArch64 ELF binaries can interleave data and text in the
1045 // same section. We rely on the markers introduced to
1046 // understand what we need to dump.
1047 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1048 uint64_t Stride = 0;
1050 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1051 DataMappingSymsAddr.end(), Index);
1052 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1054 while (Index < End) {
1055 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1057 if (Index + 4 <= End) {
1059 dumpBytes(Bytes.slice(Index, 4), outs());
1060 outs() << "\t.word";
1061 } else if (Index + 2 <= End) {
1063 dumpBytes(Bytes.slice(Index, 2), outs());
1064 outs() << "\t.short";
1067 dumpBytes(Bytes.slice(Index, 1), outs());
1068 outs() << "\t.byte";
1072 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1073 TextMappingSymsAddr.end(), Index);
1074 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1083 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1084 SectionAddr + Index, DebugOut,
1086 PIP.printInst(*IP, &Inst,
1087 Bytes.slice(Index, Size),
1088 SectionAddr + Index, outs(), "", *STI);
1089 outs() << CommentStream.str();
1092 // Try to resolve the target of a call, tail call, etc. to a specific
1094 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1095 MIA->isConditionalBranch(Inst))) {
1097 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1098 // In a relocatable object, the target's section must reside in
1099 // the same section as the call instruction or it is accessed
1100 // through a relocation.
1102 // In a non-relocatable object, the target may be in any section.
1104 // N.B. We don't walk the relocations in the relocatable case yet.
1105 auto *TargetSectionSymbols = &Symbols;
1106 if (!Obj->isRelocatableObject()) {
1107 auto SectionAddress = std::upper_bound(
1108 SectionAddresses.begin(), SectionAddresses.end(), Target,
1110 const std::pair<uint64_t, SectionRef> &RHS) {
1111 return LHS < RHS.first;
1113 if (SectionAddress != SectionAddresses.begin()) {
1115 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1117 TargetSectionSymbols = nullptr;
1121 // Find the first symbol in the section whose offset is less than
1122 // or equal to the target.
1123 if (TargetSectionSymbols) {
1124 auto TargetSym = std::upper_bound(
1125 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1126 Target, [](uint64_t LHS,
1127 const std::pair<uint64_t, StringRef> &RHS) {
1128 return LHS < RHS.first;
1130 if (TargetSym != TargetSectionSymbols->begin()) {
1132 uint64_t TargetAddress = std::get<0>(*TargetSym);
1133 StringRef TargetName = std::get<1>(*TargetSym);
1134 outs() << " <" << TargetName;
1135 uint64_t Disp = Target - TargetAddress;
1137 outs() << '+' << utohexstr(Disp);
1145 errs() << ToolName << ": warning: invalid instruction encoding\n";
1147 Size = 1; // skip illegible bytes
1150 // Print relocation for instruction.
1151 while (rel_cur != rel_end) {
1152 bool hidden = getHidden(*rel_cur);
1153 uint64_t addr = rel_cur->getOffset();
1154 SmallString<16> name;
1155 SmallString<32> val;
1157 // If this relocation is hidden, skip it.
1158 if (hidden) goto skip_print_rel;
1160 // Stop when rel_cur's address is past the current instruction.
1161 if (addr >= Index + Size) break;
1162 rel_cur->getTypeName(name);
1163 error(getRelocationValueString(*rel_cur, val));
1164 outs() << format(Fmt.data(), SectionAddr + addr) << name
1165 << "\t" << val << "\n";
1175 void llvm::PrintRelocations(const ObjectFile *Obj) {
1176 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1178 // Regular objdump doesn't print relocations in non-relocatable object
1180 if (!Obj->isRelocatableObject())
1183 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1184 if (Section.relocation_begin() == Section.relocation_end())
1187 error(Section.getName(secname));
1188 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
1189 for (const RelocationRef &Reloc : Section.relocations()) {
1190 bool hidden = getHidden(Reloc);
1191 uint64_t address = Reloc.getOffset();
1192 SmallString<32> relocname;
1193 SmallString<32> valuestr;
1196 Reloc.getTypeName(relocname);
1197 error(getRelocationValueString(Reloc, valuestr));
1198 outs() << format(Fmt.data(), address) << " " << relocname << " "
1199 << valuestr << "\n";
1205 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
1206 outs() << "Sections:\n"
1207 "Idx Name Size Address Type\n";
1209 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1211 error(Section.getName(Name));
1212 uint64_t Address = Section.getAddress();
1213 uint64_t Size = Section.getSize();
1214 bool Text = Section.isText();
1215 bool Data = Section.isData();
1216 bool BSS = Section.isBSS();
1217 std::string Type = (std::string(Text ? "TEXT " : "") +
1218 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1219 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1220 Name.str().c_str(), Size, Address, Type.c_str());
1225 void llvm::PrintSectionContents(const ObjectFile *Obj) {
1227 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1230 error(Section.getName(Name));
1231 uint64_t BaseAddr = Section.getAddress();
1232 uint64_t Size = Section.getSize();
1236 outs() << "Contents of section " << Name << ":\n";
1237 if (Section.isBSS()) {
1238 outs() << format("<skipping contents of bss section at [%04" PRIx64
1239 ", %04" PRIx64 ")>\n",
1240 BaseAddr, BaseAddr + Size);
1244 error(Section.getContents(Contents));
1246 // Dump out the content as hex and printable ascii characters.
1247 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1248 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1249 // Dump line of hex.
1250 for (std::size_t i = 0; i < 16; ++i) {
1251 if (i != 0 && i % 4 == 0)
1254 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1255 << hexdigit(Contents[addr + i] & 0xF, true);
1261 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1262 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1263 outs() << Contents[addr + i];
1272 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
1273 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1274 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
1276 error(Symbol.getError());
1277 error(coff->getSymbolName(*Symbol, Name));
1279 outs() << "[" << format("%2d", SI) << "]"
1280 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
1281 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
1282 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1283 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1284 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1285 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
1288 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
1289 if (Symbol->isSectionDefinition()) {
1290 const coff_aux_section_definition *asd;
1291 error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd));
1293 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1296 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1297 , unsigned(asd->Length)
1298 , unsigned(asd->NumberOfRelocations)
1299 , unsigned(asd->NumberOfLinenumbers)
1300 , unsigned(asd->CheckSum))
1301 << format("assoc %d comdat %d\n"
1302 , unsigned(AuxNumber)
1303 , unsigned(asd->Selection));
1304 } else if (Symbol->isFileRecord()) {
1305 const char *FileName;
1306 error(coff->getAuxSymbol<char>(SI + 1, FileName));
1308 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1309 coff->getSymbolTableEntrySize());
1310 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
1312 SI = SI + Symbol->getNumberOfAuxSymbols();
1315 outs() << "AUX Unknown\n";
1321 void llvm::PrintSymbolTable(const ObjectFile *o) {
1322 outs() << "SYMBOL TABLE:\n";
1324 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1325 PrintCOFFSymbolTable(coff);
1328 for (const SymbolRef &Symbol : o->symbols()) {
1329 ErrorOr<uint64_t> AddressOrError = Symbol.getAddress();
1330 error(AddressOrError.getError());
1331 uint64_t Address = *AddressOrError;
1332 SymbolRef::Type Type = Symbol.getType();
1333 uint32_t Flags = Symbol.getFlags();
1334 ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
1335 error(SectionOrErr.getError());
1336 section_iterator Section = *SectionOrErr;
1338 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1339 Section->getName(Name);
1341 ErrorOr<StringRef> NameOrErr = Symbol.getName();
1342 error(NameOrErr.getError());
1346 bool Global = Flags & SymbolRef::SF_Global;
1347 bool Weak = Flags & SymbolRef::SF_Weak;
1348 bool Absolute = Flags & SymbolRef::SF_Absolute;
1349 bool Common = Flags & SymbolRef::SF_Common;
1350 bool Hidden = Flags & SymbolRef::SF_Hidden;
1353 if (Type != SymbolRef::ST_Unknown)
1354 GlobLoc = Global ? 'g' : 'l';
1355 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1357 char FileFunc = ' ';
1358 if (Type == SymbolRef::ST_File)
1360 else if (Type == SymbolRef::ST_Function)
1363 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1366 outs() << format(Fmt, Address) << " "
1367 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1368 << (Weak ? 'w' : ' ') // Weak?
1369 << ' ' // Constructor. Not supported yet.
1370 << ' ' // Warning. Not supported yet.
1371 << ' ' // Indirect reference to another symbol.
1372 << Debug // Debugging (d) or dynamic (D) symbol.
1373 << FileFunc // Name of function (F), file (f) or object (O).
1377 } else if (Common) {
1379 } else if (Section == o->section_end()) {
1382 if (const MachOObjectFile *MachO =
1383 dyn_cast<const MachOObjectFile>(o)) {
1384 DataRefImpl DR = Section->getRawDataRefImpl();
1385 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1386 outs() << SegmentName << ",";
1388 StringRef SectionName;
1389 error(Section->getName(SectionName));
1390 outs() << SectionName;
1394 if (Common || isa<ELFObjectFileBase>(o)) {
1396 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1397 outs() << format("\t %08" PRIx64 " ", Val);
1401 outs() << ".hidden ";
1408 static void PrintUnwindInfo(const ObjectFile *o) {
1409 outs() << "Unwind info:\n\n";
1411 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1412 printCOFFUnwindInfo(coff);
1413 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1414 printMachOUnwindInfo(MachO);
1416 // TODO: Extract DWARF dump tool to objdump.
1417 errs() << "This operation is only currently supported "
1418 "for COFF and MachO object files.\n";
1423 void llvm::printExportsTrie(const ObjectFile *o) {
1424 outs() << "Exports trie:\n";
1425 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1426 printMachOExportsTrie(MachO);
1428 errs() << "This operation is only currently supported "
1429 "for Mach-O executable files.\n";
1434 void llvm::printRebaseTable(const ObjectFile *o) {
1435 outs() << "Rebase table:\n";
1436 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1437 printMachORebaseTable(MachO);
1439 errs() << "This operation is only currently supported "
1440 "for Mach-O executable files.\n";
1445 void llvm::printBindTable(const ObjectFile *o) {
1446 outs() << "Bind table:\n";
1447 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1448 printMachOBindTable(MachO);
1450 errs() << "This operation is only currently supported "
1451 "for Mach-O executable files.\n";
1456 void llvm::printLazyBindTable(const ObjectFile *o) {
1457 outs() << "Lazy bind table:\n";
1458 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1459 printMachOLazyBindTable(MachO);
1461 errs() << "This operation is only currently supported "
1462 "for Mach-O executable files.\n";
1467 void llvm::printWeakBindTable(const ObjectFile *o) {
1468 outs() << "Weak bind table:\n";
1469 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1470 printMachOWeakBindTable(MachO);
1472 errs() << "This operation is only currently supported "
1473 "for Mach-O executable files.\n";
1478 /// Dump the raw contents of the __clangast section so the output can be piped
1479 /// into llvm-bcanalyzer.
1480 void llvm::printRawClangAST(const ObjectFile *Obj) {
1481 if (outs().is_displayed()) {
1482 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1483 "the clang ast section.\n"
1484 "Please redirect the output to a file or another program such as "
1485 "llvm-bcanalyzer.\n";
1489 StringRef ClangASTSectionName("__clangast");
1490 if (isa<COFFObjectFile>(Obj)) {
1491 ClangASTSectionName = "clangast";
1494 Optional<object::SectionRef> ClangASTSection;
1495 for (auto Sec : ToolSectionFilter(*Obj)) {
1498 if (Name == ClangASTSectionName) {
1499 ClangASTSection = Sec;
1503 if (!ClangASTSection)
1506 StringRef ClangASTContents;
1507 error(ClangASTSection.getValue().getContents(ClangASTContents));
1508 outs().write(ClangASTContents.data(), ClangASTContents.size());
1511 static void printFaultMaps(const ObjectFile *Obj) {
1512 const char *FaultMapSectionName = nullptr;
1514 if (isa<ELFObjectFileBase>(Obj)) {
1515 FaultMapSectionName = ".llvm_faultmaps";
1516 } else if (isa<MachOObjectFile>(Obj)) {
1517 FaultMapSectionName = "__llvm_faultmaps";
1519 errs() << "This operation is only currently supported "
1520 "for ELF and Mach-O executable files.\n";
1524 Optional<object::SectionRef> FaultMapSection;
1526 for (auto Sec : ToolSectionFilter(*Obj)) {
1529 if (Name == FaultMapSectionName) {
1530 FaultMapSection = Sec;
1535 outs() << "FaultMap table:\n";
1537 if (!FaultMapSection.hasValue()) {
1538 outs() << "<not found>\n";
1542 StringRef FaultMapContents;
1543 error(FaultMapSection.getValue().getContents(FaultMapContents));
1545 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1546 FaultMapContents.bytes_end());
1551 static void printPrivateFileHeader(const ObjectFile *o) {
1553 printELFFileHeader(o);
1554 } else if (o->isCOFF()) {
1555 printCOFFFileHeader(o);
1556 } else if (o->isMachO()) {
1557 printMachOFileHeader(o);
1561 static void DumpObject(const ObjectFile *o) {
1562 // Avoid other output when using a raw option.
1565 outs() << o->getFileName()
1566 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1570 DisassembleObject(o, Relocations);
1571 if (Relocations && !Disassemble)
1572 PrintRelocations(o);
1574 PrintSectionHeaders(o);
1575 if (SectionContents)
1576 PrintSectionContents(o);
1578 PrintSymbolTable(o);
1582 printPrivateFileHeader(o);
1584 printExportsTrie(o);
1586 printRebaseTable(o);
1590 printLazyBindTable(o);
1592 printWeakBindTable(o);
1594 printRawClangAST(o);
1599 /// @brief Dump each object file in \a a;
1600 static void DumpArchive(const Archive *a) {
1601 for (auto &ErrorOrChild : a->children()) {
1602 if (std::error_code EC = ErrorOrChild.getError())
1603 report_error(a->getFileName(), EC);
1604 const Archive::Child &C = *ErrorOrChild;
1605 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1606 if (std::error_code EC = ChildOrErr.getError())
1607 if (EC != object_error::invalid_file_type)
1608 report_error(a->getFileName(), EC);
1609 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
1612 report_error(a->getFileName(), object_error::invalid_file_type);
1616 /// @brief Open file and figure out how to dump it.
1617 static void DumpInput(StringRef file) {
1619 // If we are using the Mach-O specific object file parser, then let it parse
1620 // the file and process the command line options. So the -arch flags can
1621 // be used to select specific slices, etc.
1623 ParseInputMachO(file);
1627 // Attempt to open the binary.
1628 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1629 if (std::error_code EC = BinaryOrErr.getError())
1630 report_error(file, EC);
1631 Binary &Binary = *BinaryOrErr.get().getBinary();
1633 if (Archive *a = dyn_cast<Archive>(&Binary))
1635 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
1638 report_error(file, object_error::invalid_file_type);
1641 int main(int argc, char **argv) {
1642 // Print a stack trace if we signal out.
1643 sys::PrintStackTraceOnErrorSignal();
1644 PrettyStackTraceProgram X(argc, argv);
1645 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1647 // Initialize targets and assembly printers/parsers.
1648 llvm::InitializeAllTargetInfos();
1649 llvm::InitializeAllTargetMCs();
1650 llvm::InitializeAllDisassemblers();
1652 // Register the target printer for --version.
1653 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1655 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1656 TripleName = Triple::normalize(TripleName);
1660 // Defaults to a.out if no filenames specified.
1661 if (InputFilenames.size() == 0)
1662 InputFilenames.push_back("a.out");
1679 && !(UniversalHeaders && MachOOpt)
1680 && !(ArchiveHeaders && MachOOpt)
1681 && !(IndirectSymbols && MachOOpt)
1682 && !(DataInCode && MachOOpt)
1683 && !(LinkOptHints && MachOOpt)
1684 && !(InfoPlist && MachOOpt)
1685 && !(DylibsUsed && MachOOpt)
1686 && !(DylibId && MachOOpt)
1687 && !(ObjcMetaData && MachOOpt)
1688 && !(FilterSections.size() != 0 && MachOOpt)
1689 && !PrintFaultMaps) {
1690 cl::PrintHelpMessage();
1694 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1697 return EXIT_SUCCESS;