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 report_fatal_error("can't find target: " + Error);
288 // Update the triple name and return the found target.
289 TripleName = TheTriple.getTriple();
293 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
294 return a.getOffset() < b.getOffset();
298 class PrettyPrinter {
300 virtual ~PrettyPrinter(){}
301 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
302 ArrayRef<uint8_t> Bytes, uint64_t Address,
303 raw_ostream &OS, StringRef Annot,
304 MCSubtargetInfo const &STI) {
305 outs() << format("%8" PRIx64 ":", Address);
306 if (!NoShowRawInsn) {
308 dumpBytes(Bytes, outs());
310 IP.printInst(MI, outs(), "", STI);
313 PrettyPrinter PrettyPrinterInst;
314 class HexagonPrettyPrinter : public PrettyPrinter {
316 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
319 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
320 OS << format("%8" PRIx64 ":", Address);
321 if (!NoShowRawInsn) {
323 dumpBytes(Bytes.slice(0, 4), OS);
324 OS << format("%08" PRIx32, opcode);
327 void printInst(MCInstPrinter &IP, const MCInst *MI,
328 ArrayRef<uint8_t> Bytes, uint64_t Address,
329 raw_ostream &OS, StringRef Annot,
330 MCSubtargetInfo const &STI) override {
333 raw_string_ostream TempStream(Buffer);
334 IP.printInst(MI, TempStream, "", STI);
336 StringRef Contents(Buffer);
337 // Split off bundle attributes
338 auto PacketBundle = Contents.rsplit('\n');
339 // Split off first instruction from the rest
340 auto HeadTail = PacketBundle.first.split('\n');
341 auto Preamble = " { ";
343 while(!HeadTail.first.empty()) {
346 printLead(Bytes, Address, OS);
350 auto Duplex = HeadTail.first.split('\v');
351 if(!Duplex.second.empty()){
354 Inst = Duplex.second;
357 Inst = HeadTail.first;
359 Bytes = Bytes.slice(4);
361 HeadTail = HeadTail.second.split('\n');
363 OS << " } " << PacketBundle.second;
366 HexagonPrettyPrinter HexagonPrettyPrinterInst;
367 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
368 switch(Triple.getArch()) {
370 return PrettyPrinterInst;
371 case Triple::hexagon:
372 return HexagonPrettyPrinterInst;
377 template <class ELFT>
378 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
379 const RelocationRef &RelRef,
380 SmallVectorImpl<char> &Result) {
381 DataRefImpl Rel = RelRef.getRawDataRefImpl();
383 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
384 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
385 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
387 const ELFFile<ELFT> &EF = *Obj->getELFFile();
389 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
390 if (std::error_code EC = SecOrErr.getError())
392 const Elf_Shdr *Sec = *SecOrErr;
393 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
394 if (std::error_code EC = SymTabOrErr.getError())
396 const Elf_Shdr *SymTab = *SymTabOrErr;
397 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
398 SymTab->sh_type == ELF::SHT_DYNSYM);
399 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
400 if (std::error_code EC = StrTabSec.getError())
402 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
403 if (std::error_code EC = StrTabOrErr.getError())
405 StringRef StrTab = *StrTabOrErr;
406 uint8_t type = RelRef.getType();
409 switch (Sec->sh_type) {
411 return object_error::parse_failed;
413 // TODO: Read implicit addend from section data.
416 case ELF::SHT_RELA: {
417 const Elf_Rela *ERela = Obj->getRela(Rel);
418 addend = ERela->r_addend;
422 symbol_iterator SI = RelRef.getSymbol();
423 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
425 if (symb->getType() == ELF::STT_SECTION) {
426 ErrorOr<section_iterator> SymSI = SI->getSection();
427 if (std::error_code EC = SymSI.getError())
429 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
430 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
431 if (std::error_code EC = SecName.getError())
435 ErrorOr<StringRef> SymName = symb->getName(StrTab);
437 return SymName.getError();
440 switch (EF.getHeader()->e_machine) {
443 case ELF::R_X86_64_PC8:
444 case ELF::R_X86_64_PC16:
445 case ELF::R_X86_64_PC32: {
447 raw_string_ostream fmt(fmtbuf);
448 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
450 Result.append(fmtbuf.begin(), fmtbuf.end());
452 case ELF::R_X86_64_8:
453 case ELF::R_X86_64_16:
454 case ELF::R_X86_64_32:
455 case ELF::R_X86_64_32S:
456 case ELF::R_X86_64_64: {
458 raw_string_ostream fmt(fmtbuf);
459 fmt << Target << (addend < 0 ? "" : "+") << addend;
461 Result.append(fmtbuf.begin(), fmtbuf.end());
467 case ELF::EM_AARCH64: {
469 raw_string_ostream fmt(fmtbuf);
472 fmt << (addend < 0 ? "" : "+") << addend;
474 Result.append(fmtbuf.begin(), fmtbuf.end());
480 case ELF::EM_HEXAGON:
488 Result.append(res.begin(), res.end());
489 return std::error_code();
492 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
493 const RelocationRef &Rel,
494 SmallVectorImpl<char> &Result) {
495 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
496 return getRelocationValueString(ELF32LE, Rel, Result);
497 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
498 return getRelocationValueString(ELF64LE, Rel, Result);
499 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
500 return getRelocationValueString(ELF32BE, Rel, Result);
501 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
502 return getRelocationValueString(ELF64BE, Rel, Result);
505 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
506 const RelocationRef &Rel,
507 SmallVectorImpl<char> &Result) {
508 symbol_iterator SymI = Rel.getSymbol();
509 ErrorOr<StringRef> SymNameOrErr = SymI->getName();
510 if (std::error_code EC = SymNameOrErr.getError())
512 StringRef SymName = *SymNameOrErr;
513 Result.append(SymName.begin(), SymName.end());
514 return std::error_code();
517 static void printRelocationTargetName(const MachOObjectFile *O,
518 const MachO::any_relocation_info &RE,
519 raw_string_ostream &fmt) {
520 bool IsScattered = O->isRelocationScattered(RE);
522 // Target of a scattered relocation is an address. In the interest of
523 // generating pretty output, scan through the symbol table looking for a
524 // symbol that aligns with that address. If we find one, print it.
525 // Otherwise, we just print the hex address of the target.
527 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
529 for (const SymbolRef &Symbol : O->symbols()) {
531 ErrorOr<uint64_t> Addr = Symbol.getAddress();
532 if ((ec = Addr.getError()))
533 report_fatal_error(ec.message());
536 ErrorOr<StringRef> Name = Symbol.getName();
537 if (std::error_code EC = Name.getError())
538 report_fatal_error(EC.message());
543 // If we couldn't find a symbol that this relocation refers to, try
544 // to find a section beginning instead.
545 for (const SectionRef &Section : ToolSectionFilter(*O)) {
549 uint64_t Addr = Section.getAddress();
552 if ((ec = Section.getName(Name)))
553 report_fatal_error(ec.message());
558 fmt << format("0x%x", Val);
563 bool isExtern = O->getPlainRelocationExternal(RE);
564 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
567 symbol_iterator SI = O->symbol_begin();
569 ErrorOr<StringRef> SOrErr = SI->getName();
570 error(SOrErr.getError());
573 section_iterator SI = O->section_begin();
574 // Adjust for the fact that sections are 1-indexed.
575 advance(SI, Val - 1);
582 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
583 const RelocationRef &RelRef,
584 SmallVectorImpl<char> &Result) {
585 DataRefImpl Rel = RelRef.getRawDataRefImpl();
586 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
588 unsigned Arch = Obj->getArch();
591 raw_string_ostream fmt(fmtbuf);
592 unsigned Type = Obj->getAnyRelocationType(RE);
593 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
595 // Determine any addends that should be displayed with the relocation.
596 // These require decoding the relocation type, which is triple-specific.
598 // X86_64 has entirely custom relocation types.
599 if (Arch == Triple::x86_64) {
600 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
603 case MachO::X86_64_RELOC_GOT_LOAD:
604 case MachO::X86_64_RELOC_GOT: {
605 printRelocationTargetName(Obj, RE, fmt);
611 case MachO::X86_64_RELOC_SUBTRACTOR: {
612 DataRefImpl RelNext = Rel;
613 Obj->moveRelocationNext(RelNext);
614 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
616 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
617 // X86_64_RELOC_UNSIGNED.
618 // NOTE: Scattered relocations don't exist on x86_64.
619 unsigned RType = Obj->getAnyRelocationType(RENext);
620 if (RType != MachO::X86_64_RELOC_UNSIGNED)
621 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
622 "X86_64_RELOC_SUBTRACTOR.");
624 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
625 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
626 printRelocationTargetName(Obj, RENext, fmt);
628 printRelocationTargetName(Obj, RE, fmt);
631 case MachO::X86_64_RELOC_TLV:
632 printRelocationTargetName(Obj, RE, fmt);
637 case MachO::X86_64_RELOC_SIGNED_1:
638 printRelocationTargetName(Obj, RE, fmt);
641 case MachO::X86_64_RELOC_SIGNED_2:
642 printRelocationTargetName(Obj, RE, fmt);
645 case MachO::X86_64_RELOC_SIGNED_4:
646 printRelocationTargetName(Obj, RE, fmt);
650 printRelocationTargetName(Obj, RE, fmt);
653 // X86 and ARM share some relocation types in common.
654 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
655 Arch == Triple::ppc) {
656 // Generic relocation types...
658 case MachO::GENERIC_RELOC_PAIR: // prints no info
659 return std::error_code();
660 case MachO::GENERIC_RELOC_SECTDIFF: {
661 DataRefImpl RelNext = Rel;
662 Obj->moveRelocationNext(RelNext);
663 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
665 // X86 sect diff's must be followed by a relocation of type
666 // GENERIC_RELOC_PAIR.
667 unsigned RType = Obj->getAnyRelocationType(RENext);
669 if (RType != MachO::GENERIC_RELOC_PAIR)
670 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
671 "GENERIC_RELOC_SECTDIFF.");
673 printRelocationTargetName(Obj, RE, fmt);
675 printRelocationTargetName(Obj, RENext, fmt);
680 if (Arch == Triple::x86 || Arch == Triple::ppc) {
682 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
683 DataRefImpl RelNext = Rel;
684 Obj->moveRelocationNext(RelNext);
685 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
687 // X86 sect diff's must be followed by a relocation of type
688 // GENERIC_RELOC_PAIR.
689 unsigned RType = Obj->getAnyRelocationType(RENext);
690 if (RType != MachO::GENERIC_RELOC_PAIR)
691 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
692 "GENERIC_RELOC_LOCAL_SECTDIFF.");
694 printRelocationTargetName(Obj, RE, fmt);
696 printRelocationTargetName(Obj, RENext, fmt);
699 case MachO::GENERIC_RELOC_TLV: {
700 printRelocationTargetName(Obj, RE, fmt);
707 printRelocationTargetName(Obj, RE, fmt);
709 } else { // ARM-specific relocations
711 case MachO::ARM_RELOC_HALF:
712 case MachO::ARM_RELOC_HALF_SECTDIFF: {
713 // Half relocations steal a bit from the length field to encode
714 // whether this is an upper16 or a lower16 relocation.
715 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
721 printRelocationTargetName(Obj, RE, fmt);
723 DataRefImpl RelNext = Rel;
724 Obj->moveRelocationNext(RelNext);
725 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
727 // ARM half relocs must be followed by a relocation of type
729 unsigned RType = Obj->getAnyRelocationType(RENext);
730 if (RType != MachO::ARM_RELOC_PAIR)
731 report_fatal_error("Expected ARM_RELOC_PAIR after "
734 // NOTE: The half of the target virtual address is stashed in the
735 // address field of the secondary relocation, but we can't reverse
736 // engineer the constant offset from it without decoding the movw/movt
737 // instruction to find the other half in its immediate field.
739 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
740 // symbol/section pointer of the follow-on relocation.
741 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
743 printRelocationTargetName(Obj, RENext, fmt);
749 default: { printRelocationTargetName(Obj, RE, fmt); }
753 printRelocationTargetName(Obj, RE, fmt);
756 Result.append(fmtbuf.begin(), fmtbuf.end());
757 return std::error_code();
760 static std::error_code getRelocationValueString(const RelocationRef &Rel,
761 SmallVectorImpl<char> &Result) {
762 const ObjectFile *Obj = Rel.getObject();
763 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
764 return getRelocationValueString(ELF, Rel, Result);
765 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
766 return getRelocationValueString(COFF, Rel, Result);
767 auto *MachO = cast<MachOObjectFile>(Obj);
768 return getRelocationValueString(MachO, Rel, Result);
771 /// @brief Indicates whether this relocation should hidden when listing
772 /// relocations, usually because it is the trailing part of a multipart
773 /// relocation that will be printed as part of the leading relocation.
774 static bool getHidden(RelocationRef RelRef) {
775 const ObjectFile *Obj = RelRef.getObject();
776 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
780 unsigned Arch = MachO->getArch();
781 DataRefImpl Rel = RelRef.getRawDataRefImpl();
782 uint64_t Type = MachO->getRelocationType(Rel);
784 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
786 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
787 if (Type == MachO::GENERIC_RELOC_PAIR)
789 } else if (Arch == Triple::x86_64) {
790 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
791 // an X86_64_RELOC_SUBTRACTOR.
792 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
793 DataRefImpl RelPrev = Rel;
795 uint64_t PrevType = MachO->getRelocationType(RelPrev);
796 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
804 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
805 const Target *TheTarget = getTarget(Obj);
807 // Package up features to be passed to target/subtarget
808 std::string FeaturesStr;
810 SubtargetFeatures Features;
811 for (unsigned i = 0; i != MAttrs.size(); ++i)
812 Features.AddFeature(MAttrs[i]);
813 FeaturesStr = Features.getString();
816 std::unique_ptr<const MCRegisterInfo> MRI(
817 TheTarget->createMCRegInfo(TripleName));
819 errs() << "error: no register info for target " << TripleName << "\n";
823 // Set up disassembler.
824 std::unique_ptr<const MCAsmInfo> AsmInfo(
825 TheTarget->createMCAsmInfo(*MRI, TripleName));
827 errs() << "error: no assembly info for target " << TripleName << "\n";
831 std::unique_ptr<const MCSubtargetInfo> STI(
832 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
834 errs() << "error: no subtarget info for target " << TripleName << "\n";
838 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
840 errs() << "error: no instruction info for target " << TripleName << "\n";
844 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
845 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
847 std::unique_ptr<MCDisassembler> DisAsm(
848 TheTarget->createMCDisassembler(*STI, Ctx));
851 errs() << "error: no disassembler for target " << TripleName << "\n";
855 std::unique_ptr<const MCInstrAnalysis> MIA(
856 TheTarget->createMCInstrAnalysis(MII.get()));
858 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
859 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
860 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
862 errs() << "error: no instruction printer for target " << TripleName
866 IP->setPrintImmHex(PrintImmHex);
867 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
869 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
870 "\t\t\t%08" PRIx64 ": ";
872 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
873 // in RelocSecs contain the relocations for section S.
875 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
876 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
877 section_iterator Sec2 = Section.getRelocatedSection();
878 if (Sec2 != Obj->section_end())
879 SectionRelocMap[*Sec2].push_back(Section);
882 // Create a mapping from virtual address to symbol name. This is used to
883 // pretty print the symbols while disassembling.
884 typedef std::vector<std::pair<uint64_t, StringRef>> SectionSymbolsTy;
885 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
886 for (const SymbolRef &Symbol : Obj->symbols()) {
887 ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
888 error(AddressOrErr.getError());
889 uint64_t Address = *AddressOrErr;
891 ErrorOr<StringRef> Name = Symbol.getName();
892 error(Name.getError());
896 ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
897 error(SectionOrErr.getError());
898 section_iterator SecI = *SectionOrErr;
899 if (SecI == Obj->section_end())
902 AllSymbols[*SecI].emplace_back(Address, *Name);
905 // Create a mapping from virtual address to section.
906 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
907 for (SectionRef Sec : Obj->sections())
908 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
909 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
911 // Linked executables (.exe and .dll files) typically don't include a real
912 // symbol table but they might contain an export table.
913 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
914 for (const auto &ExportEntry : COFFObj->export_directories()) {
916 error(ExportEntry.getSymbolName(Name));
920 error(ExportEntry.getExportRVA(RVA));
922 uint64_t VA = COFFObj->getImageBase() + RVA;
923 auto Sec = std::upper_bound(
924 SectionAddresses.begin(), SectionAddresses.end(), VA,
925 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
926 return LHS < RHS.first;
928 if (Sec != SectionAddresses.begin())
931 Sec = SectionAddresses.end();
933 if (Sec != SectionAddresses.end())
934 AllSymbols[Sec->second].emplace_back(VA, Name);
938 // Sort all the symbols, this allows us to use a simple binary search to find
939 // a symbol near an address.
940 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
941 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
943 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
944 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
947 uint64_t SectionAddr = Section.getAddress();
948 uint64_t SectSize = Section.getSize();
952 // Get the list of all the symbols in this section.
953 SectionSymbolsTy &Symbols = AllSymbols[Section];
954 std::vector<uint64_t> DataMappingSymsAddr;
955 std::vector<uint64_t> TextMappingSymsAddr;
956 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
957 for (const auto &Symb : Symbols) {
958 uint64_t Address = Symb.first;
959 StringRef Name = Symb.second;
960 if (Name.startswith("$d"))
961 DataMappingSymsAddr.push_back(Address - SectionAddr);
962 if (Name.startswith("$x"))
963 TextMappingSymsAddr.push_back(Address - SectionAddr);
967 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
968 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
970 // Make a list of all the relocations for this section.
971 std::vector<RelocationRef> Rels;
973 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
974 for (const RelocationRef &Reloc : RelocSec.relocations()) {
975 Rels.push_back(Reloc);
980 // Sort relocations by address.
981 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
983 StringRef SegmentName = "";
984 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
985 DataRefImpl DR = Section.getRawDataRefImpl();
986 SegmentName = MachO->getSectionFinalSegmentName(DR);
989 error(Section.getName(name));
990 outs() << "Disassembly of section ";
991 if (!SegmentName.empty())
992 outs() << SegmentName << ",";
993 outs() << name << ':';
995 // If the section has no symbol at the start, just insert a dummy one.
996 if (Symbols.empty() || Symbols[0].first != 0)
997 Symbols.insert(Symbols.begin(), std::make_pair(SectionAddr, name));
999 SmallString<40> Comments;
1000 raw_svector_ostream CommentStream(Comments);
1003 error(Section.getContents(BytesStr));
1004 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1010 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1011 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
1012 // Disassemble symbol by symbol.
1013 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
1015 uint64_t Start = Symbols[si].first - SectionAddr;
1016 // The end is either the section end or the beginning of the next
1019 (si == se - 1) ? SectSize : Symbols[si + 1].first - SectionAddr;
1020 // Don't try to disassemble beyond the end of section contents.
1023 // If this symbol has the same address as the next symbol, then skip it.
1027 outs() << '\n' << Symbols[si].second << ":\n";
1030 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1032 raw_ostream &DebugOut = nulls();
1035 for (Index = Start; Index < End; Index += Size) {
1038 // AArch64 ELF binaries can interleave data and text in the
1039 // same section. We rely on the markers introduced to
1040 // understand what we need to dump.
1041 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1042 uint64_t Stride = 0;
1044 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1045 DataMappingSymsAddr.end(), Index);
1046 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1048 while (Index < End) {
1049 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1051 if (Index + 4 <= End) {
1053 dumpBytes(Bytes.slice(Index, 4), outs());
1054 outs() << "\t.word";
1055 } else if (Index + 2 <= End) {
1057 dumpBytes(Bytes.slice(Index, 2), outs());
1058 outs() << "\t.short";
1061 dumpBytes(Bytes.slice(Index, 1), outs());
1062 outs() << "\t.byte";
1066 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1067 TextMappingSymsAddr.end(), Index);
1068 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1077 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1078 SectionAddr + Index, DebugOut,
1080 PIP.printInst(*IP, &Inst,
1081 Bytes.slice(Index, Size),
1082 SectionAddr + Index, outs(), "", *STI);
1083 outs() << CommentStream.str();
1086 // Try to resolve the target of a call, tail call, etc. to a specific
1088 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1089 MIA->isConditionalBranch(Inst))) {
1091 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1092 // In a relocatable object, the target's section must reside in
1093 // the same section as the call instruction or it is accessed
1094 // through a relocation.
1096 // In a non-relocatable object, the target may be in any section.
1098 // N.B. We don't walk the relocations in the relocatable case yet.
1099 auto *TargetSectionSymbols = &Symbols;
1100 if (!Obj->isRelocatableObject()) {
1101 auto SectionAddress = std::upper_bound(
1102 SectionAddresses.begin(), SectionAddresses.end(), Target,
1104 const std::pair<uint64_t, SectionRef> &RHS) {
1105 return LHS < RHS.first;
1107 if (SectionAddress != SectionAddresses.begin()) {
1109 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1111 TargetSectionSymbols = nullptr;
1115 // Find the first symbol in the section whose offset is less than
1116 // or equal to the target.
1117 if (TargetSectionSymbols) {
1118 auto TargetSym = std::upper_bound(
1119 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1120 Target, [](uint64_t LHS,
1121 const std::pair<uint64_t, StringRef> &RHS) {
1122 return LHS < RHS.first;
1124 if (TargetSym != TargetSectionSymbols->begin()) {
1126 uint64_t TargetAddress = std::get<0>(*TargetSym);
1127 StringRef TargetName = std::get<1>(*TargetSym);
1128 outs() << " <" << TargetName;
1129 uint64_t Disp = Target - TargetAddress;
1131 outs() << '+' << utohexstr(Disp);
1139 errs() << ToolName << ": warning: invalid instruction encoding\n";
1141 Size = 1; // skip illegible bytes
1144 // Print relocation for instruction.
1145 while (rel_cur != rel_end) {
1146 bool hidden = getHidden(*rel_cur);
1147 uint64_t addr = rel_cur->getOffset();
1148 SmallString<16> name;
1149 SmallString<32> val;
1151 // If this relocation is hidden, skip it.
1152 if (hidden) goto skip_print_rel;
1154 // Stop when rel_cur's address is past the current instruction.
1155 if (addr >= Index + Size) break;
1156 rel_cur->getTypeName(name);
1157 error(getRelocationValueString(*rel_cur, val));
1158 outs() << format(Fmt.data(), SectionAddr + addr) << name
1159 << "\t" << val << "\n";
1169 void llvm::PrintRelocations(const ObjectFile *Obj) {
1170 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1172 // Regular objdump doesn't print relocations in non-relocatable object
1174 if (!Obj->isRelocatableObject())
1177 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1178 if (Section.relocation_begin() == Section.relocation_end())
1181 error(Section.getName(secname));
1182 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
1183 for (const RelocationRef &Reloc : Section.relocations()) {
1184 bool hidden = getHidden(Reloc);
1185 uint64_t address = Reloc.getOffset();
1186 SmallString<32> relocname;
1187 SmallString<32> valuestr;
1190 Reloc.getTypeName(relocname);
1191 error(getRelocationValueString(Reloc, valuestr));
1192 outs() << format(Fmt.data(), address) << " " << relocname << " "
1193 << valuestr << "\n";
1199 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
1200 outs() << "Sections:\n"
1201 "Idx Name Size Address Type\n";
1203 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1205 error(Section.getName(Name));
1206 uint64_t Address = Section.getAddress();
1207 uint64_t Size = Section.getSize();
1208 bool Text = Section.isText();
1209 bool Data = Section.isData();
1210 bool BSS = Section.isBSS();
1211 std::string Type = (std::string(Text ? "TEXT " : "") +
1212 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1213 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1214 Name.str().c_str(), Size, Address, Type.c_str());
1219 void llvm::PrintSectionContents(const ObjectFile *Obj) {
1221 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1224 error(Section.getName(Name));
1225 uint64_t BaseAddr = Section.getAddress();
1226 uint64_t Size = Section.getSize();
1230 outs() << "Contents of section " << Name << ":\n";
1231 if (Section.isBSS()) {
1232 outs() << format("<skipping contents of bss section at [%04" PRIx64
1233 ", %04" PRIx64 ")>\n",
1234 BaseAddr, BaseAddr + Size);
1238 error(Section.getContents(Contents));
1240 // Dump out the content as hex and printable ascii characters.
1241 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1242 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1243 // Dump line of hex.
1244 for (std::size_t i = 0; i < 16; ++i) {
1245 if (i != 0 && i % 4 == 0)
1248 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1249 << hexdigit(Contents[addr + i] & 0xF, true);
1255 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1256 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1257 outs() << Contents[addr + i];
1266 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
1267 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1268 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
1270 error(Symbol.getError());
1271 error(coff->getSymbolName(*Symbol, Name));
1273 outs() << "[" << format("%2d", SI) << "]"
1274 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
1275 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
1276 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1277 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1278 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1279 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
1282 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
1283 if (Symbol->isSectionDefinition()) {
1284 const coff_aux_section_definition *asd;
1285 error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd));
1287 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1290 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1291 , unsigned(asd->Length)
1292 , unsigned(asd->NumberOfRelocations)
1293 , unsigned(asd->NumberOfLinenumbers)
1294 , unsigned(asd->CheckSum))
1295 << format("assoc %d comdat %d\n"
1296 , unsigned(AuxNumber)
1297 , unsigned(asd->Selection));
1298 } else if (Symbol->isFileRecord()) {
1299 const char *FileName;
1300 error(coff->getAuxSymbol<char>(SI + 1, FileName));
1302 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1303 coff->getSymbolTableEntrySize());
1304 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
1306 SI = SI + Symbol->getNumberOfAuxSymbols();
1309 outs() << "AUX Unknown\n";
1315 void llvm::PrintSymbolTable(const ObjectFile *o) {
1316 outs() << "SYMBOL TABLE:\n";
1318 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1319 PrintCOFFSymbolTable(coff);
1322 for (const SymbolRef &Symbol : o->symbols()) {
1323 ErrorOr<uint64_t> AddressOrError = Symbol.getAddress();
1324 error(AddressOrError.getError());
1325 uint64_t Address = *AddressOrError;
1326 SymbolRef::Type Type = Symbol.getType();
1327 uint32_t Flags = Symbol.getFlags();
1328 ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
1329 error(SectionOrErr.getError());
1330 section_iterator Section = *SectionOrErr;
1332 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1333 Section->getName(Name);
1335 ErrorOr<StringRef> NameOrErr = Symbol.getName();
1336 error(NameOrErr.getError());
1340 bool Global = Flags & SymbolRef::SF_Global;
1341 bool Weak = Flags & SymbolRef::SF_Weak;
1342 bool Absolute = Flags & SymbolRef::SF_Absolute;
1343 bool Common = Flags & SymbolRef::SF_Common;
1344 bool Hidden = Flags & SymbolRef::SF_Hidden;
1347 if (Type != SymbolRef::ST_Unknown)
1348 GlobLoc = Global ? 'g' : 'l';
1349 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1351 char FileFunc = ' ';
1352 if (Type == SymbolRef::ST_File)
1354 else if (Type == SymbolRef::ST_Function)
1357 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1360 outs() << format(Fmt, Address) << " "
1361 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1362 << (Weak ? 'w' : ' ') // Weak?
1363 << ' ' // Constructor. Not supported yet.
1364 << ' ' // Warning. Not supported yet.
1365 << ' ' // Indirect reference to another symbol.
1366 << Debug // Debugging (d) or dynamic (D) symbol.
1367 << FileFunc // Name of function (F), file (f) or object (O).
1371 } else if (Common) {
1373 } else if (Section == o->section_end()) {
1376 if (const MachOObjectFile *MachO =
1377 dyn_cast<const MachOObjectFile>(o)) {
1378 DataRefImpl DR = Section->getRawDataRefImpl();
1379 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1380 outs() << SegmentName << ",";
1382 StringRef SectionName;
1383 error(Section->getName(SectionName));
1384 outs() << SectionName;
1388 if (Common || isa<ELFObjectFileBase>(o)) {
1390 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1391 outs() << format("\t %08" PRIx64 " ", Val);
1395 outs() << ".hidden ";
1402 static void PrintUnwindInfo(const ObjectFile *o) {
1403 outs() << "Unwind info:\n\n";
1405 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1406 printCOFFUnwindInfo(coff);
1407 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1408 printMachOUnwindInfo(MachO);
1410 // TODO: Extract DWARF dump tool to objdump.
1411 errs() << "This operation is only currently supported "
1412 "for COFF and MachO object files.\n";
1417 void llvm::printExportsTrie(const ObjectFile *o) {
1418 outs() << "Exports trie:\n";
1419 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1420 printMachOExportsTrie(MachO);
1422 errs() << "This operation is only currently supported "
1423 "for Mach-O executable files.\n";
1428 void llvm::printRebaseTable(const ObjectFile *o) {
1429 outs() << "Rebase table:\n";
1430 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1431 printMachORebaseTable(MachO);
1433 errs() << "This operation is only currently supported "
1434 "for Mach-O executable files.\n";
1439 void llvm::printBindTable(const ObjectFile *o) {
1440 outs() << "Bind table:\n";
1441 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1442 printMachOBindTable(MachO);
1444 errs() << "This operation is only currently supported "
1445 "for Mach-O executable files.\n";
1450 void llvm::printLazyBindTable(const ObjectFile *o) {
1451 outs() << "Lazy bind table:\n";
1452 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1453 printMachOLazyBindTable(MachO);
1455 errs() << "This operation is only currently supported "
1456 "for Mach-O executable files.\n";
1461 void llvm::printWeakBindTable(const ObjectFile *o) {
1462 outs() << "Weak bind table:\n";
1463 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1464 printMachOWeakBindTable(MachO);
1466 errs() << "This operation is only currently supported "
1467 "for Mach-O executable files.\n";
1472 /// Dump the raw contents of the __clangast section so the output can be piped
1473 /// into llvm-bcanalyzer.
1474 void llvm::printRawClangAST(const ObjectFile *Obj) {
1475 if (outs().is_displayed()) {
1476 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1477 "the clang ast section.\n"
1478 "Please redirect the output to a file or another program such as "
1479 "llvm-bcanalyzer.\n";
1483 StringRef ClangASTSectionName("__clangast");
1484 if (isa<COFFObjectFile>(Obj)) {
1485 ClangASTSectionName = "clangast";
1488 Optional<object::SectionRef> ClangASTSection;
1489 for (auto Sec : ToolSectionFilter(*Obj)) {
1492 if (Name == ClangASTSectionName) {
1493 ClangASTSection = Sec;
1497 if (!ClangASTSection)
1500 StringRef ClangASTContents;
1501 error(ClangASTSection.getValue().getContents(ClangASTContents));
1502 outs().write(ClangASTContents.data(), ClangASTContents.size());
1505 static void printFaultMaps(const ObjectFile *Obj) {
1506 const char *FaultMapSectionName = nullptr;
1508 if (isa<ELFObjectFileBase>(Obj)) {
1509 FaultMapSectionName = ".llvm_faultmaps";
1510 } else if (isa<MachOObjectFile>(Obj)) {
1511 FaultMapSectionName = "__llvm_faultmaps";
1513 errs() << "This operation is only currently supported "
1514 "for ELF and Mach-O executable files.\n";
1518 Optional<object::SectionRef> FaultMapSection;
1520 for (auto Sec : ToolSectionFilter(*Obj)) {
1523 if (Name == FaultMapSectionName) {
1524 FaultMapSection = Sec;
1529 outs() << "FaultMap table:\n";
1531 if (!FaultMapSection.hasValue()) {
1532 outs() << "<not found>\n";
1536 StringRef FaultMapContents;
1537 error(FaultMapSection.getValue().getContents(FaultMapContents));
1539 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1540 FaultMapContents.bytes_end());
1545 static void printPrivateFileHeader(const ObjectFile *o) {
1547 printELFFileHeader(o);
1548 } else if (o->isCOFF()) {
1549 printCOFFFileHeader(o);
1550 } else if (o->isMachO()) {
1551 printMachOFileHeader(o);
1555 static void DumpObject(const ObjectFile *o) {
1556 // Avoid other output when using a raw option.
1559 outs() << o->getFileName()
1560 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1564 DisassembleObject(o, Relocations);
1565 if (Relocations && !Disassemble)
1566 PrintRelocations(o);
1568 PrintSectionHeaders(o);
1569 if (SectionContents)
1570 PrintSectionContents(o);
1572 PrintSymbolTable(o);
1576 printPrivateFileHeader(o);
1578 printExportsTrie(o);
1580 printRebaseTable(o);
1584 printLazyBindTable(o);
1586 printWeakBindTable(o);
1588 printRawClangAST(o);
1593 /// @brief Dump each object file in \a a;
1594 static void DumpArchive(const Archive *a) {
1595 for (auto &ErrorOrChild : a->children()) {
1596 if (std::error_code EC = ErrorOrChild.getError())
1597 report_error(a->getFileName(), EC);
1598 const Archive::Child &C = *ErrorOrChild;
1599 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1600 if (std::error_code EC = ChildOrErr.getError())
1601 if (EC != object_error::invalid_file_type)
1602 report_error(a->getFileName(), EC);
1603 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
1606 report_error(a->getFileName(), object_error::invalid_file_type);
1610 /// @brief Open file and figure out how to dump it.
1611 static void DumpInput(StringRef file) {
1613 // If we are using the Mach-O specific object file parser, then let it parse
1614 // the file and process the command line options. So the -arch flags can
1615 // be used to select specific slices, etc.
1617 ParseInputMachO(file);
1621 // Attempt to open the binary.
1622 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1623 if (std::error_code EC = BinaryOrErr.getError())
1624 report_error(file, EC);
1625 Binary &Binary = *BinaryOrErr.get().getBinary();
1627 if (Archive *a = dyn_cast<Archive>(&Binary))
1629 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
1632 report_error(file, object_error::invalid_file_type);
1635 int main(int argc, char **argv) {
1636 // Print a stack trace if we signal out.
1637 sys::PrintStackTraceOnErrorSignal();
1638 PrettyStackTraceProgram X(argc, argv);
1639 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1641 // Initialize targets and assembly printers/parsers.
1642 llvm::InitializeAllTargetInfos();
1643 llvm::InitializeAllTargetMCs();
1644 llvm::InitializeAllDisassemblers();
1646 // Register the target printer for --version.
1647 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1649 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1650 TripleName = Triple::normalize(TripleName);
1654 // Defaults to a.out if no filenames specified.
1655 if (InputFilenames.size() == 0)
1656 InputFilenames.push_back("a.out");
1673 && !(UniversalHeaders && MachOOpt)
1674 && !(ArchiveHeaders && MachOOpt)
1675 && !(IndirectSymbols && MachOOpt)
1676 && !(DataInCode && MachOOpt)
1677 && !(LinkOptHints && MachOOpt)
1678 && !(InfoPlist && MachOOpt)
1679 && !(DylibsUsed && MachOOpt)
1680 && !(DylibId && MachOOpt)
1681 && !(ObjcMetaData && MachOOpt)
1682 && !(FilterSections.size() != 0 && MachOOpt)
1683 && !PrintFaultMaps) {
1684 cl::PrintHelpMessage();
1688 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1691 return EXIT_SUCCESS;