1 //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This program is a utility that works like binutils "objdump", that is, it
10 // dumps out a plethora of information about an object file depending on the
13 // The flags and output of this program should be near identical to those of
16 //===----------------------------------------------------------------------===//
18 #include "llvm-objdump.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringSet.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/FaultMaps.h"
25 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
26 #include "llvm/DebugInfo/Symbolize/Symbolize.h"
27 #include "llvm/Demangle/Demangle.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
31 #include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
32 #include "llvm/MC/MCInst.h"
33 #include "llvm/MC/MCInstPrinter.h"
34 #include "llvm/MC/MCInstrAnalysis.h"
35 #include "llvm/MC/MCInstrInfo.h"
36 #include "llvm/MC/MCObjectFileInfo.h"
37 #include "llvm/MC/MCRegisterInfo.h"
38 #include "llvm/MC/MCSubtargetInfo.h"
39 #include "llvm/Object/Archive.h"
40 #include "llvm/Object/COFF.h"
41 #include "llvm/Object/COFFImportFile.h"
42 #include "llvm/Object/ELFObjectFile.h"
43 #include "llvm/Object/MachO.h"
44 #include "llvm/Object/MachOUniversal.h"
45 #include "llvm/Object/ObjectFile.h"
46 #include "llvm/Object/Wasm.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Errc.h"
51 #include "llvm/Support/FileSystem.h"
52 #include "llvm/Support/Format.h"
53 #include "llvm/Support/GraphWriter.h"
54 #include "llvm/Support/Host.h"
55 #include "llvm/Support/InitLLVM.h"
56 #include "llvm/Support/MemoryBuffer.h"
57 #include "llvm/Support/SourceMgr.h"
58 #include "llvm/Support/StringSaver.h"
59 #include "llvm/Support/TargetRegistry.h"
60 #include "llvm/Support/TargetSelect.h"
61 #include "llvm/Support/WithColor.h"
62 #include "llvm/Support/raw_ostream.h"
66 #include <system_error>
67 #include <unordered_map>
71 using namespace object;
73 cl::opt<unsigned long long> AdjustVMA(
75 cl::desc("Increase the displayed address by the specified offset"),
76 cl::value_desc("offset"), cl::init(0));
79 llvm::AllHeaders("all-headers",
80 cl::desc("Display all available header information"));
81 static cl::alias AllHeadersShort("x", cl::desc("Alias for --all-headers"),
82 cl::NotHidden, cl::Grouping,
83 cl::aliasopt(AllHeaders));
85 static cl::list<std::string>
86 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
89 llvm::Disassemble("disassemble",
90 cl::desc("Display assembler mnemonics for the machine instructions"));
91 static cl::alias Disassembled("d", cl::desc("Alias for --disassemble"),
92 cl::NotHidden, cl::Grouping,
93 cl::aliasopt(Disassemble));
96 llvm::DisassembleAll("disassemble-all",
97 cl::desc("Display assembler mnemonics for the machine instructions"));
98 static cl::alias DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
99 cl::NotHidden, cl::Grouping,
100 cl::aliasopt(DisassembleAll));
102 cl::opt<bool> llvm::Demangle("demangle", cl::desc("Demangle symbols names"),
105 static cl::alias DemangleShort("C", cl::desc("Alias for --demangle"),
106 cl::NotHidden, cl::Grouping,
107 cl::aliasopt(llvm::Demangle));
109 static cl::list<std::string>
110 DisassembleFunctions("disassemble-functions",
112 cl::desc("List of functions to disassemble"));
113 static StringSet<> DisasmFuncsSet;
116 llvm::Relocations("reloc",
117 cl::desc("Display the relocation entries in the file"));
118 static cl::alias RelocationsShort("r", cl::desc("Alias for --reloc"),
119 cl::NotHidden, cl::Grouping,
120 cl::aliasopt(llvm::Relocations));
123 llvm::DynamicRelocations("dynamic-reloc",
124 cl::desc("Display the dynamic relocation entries in the file"));
125 static cl::alias DynamicRelocationsd("R", cl::desc("Alias for --dynamic-reloc"),
126 cl::NotHidden, cl::Grouping,
127 cl::aliasopt(DynamicRelocations));
130 llvm::SectionContents("full-contents",
131 cl::desc("Display the content of each section"));
132 static cl::alias SectionContentsShort("s",
133 cl::desc("Alias for --full-contents"),
134 cl::NotHidden, cl::Grouping,
135 cl::aliasopt(SectionContents));
137 cl::opt<bool> llvm::SymbolTable("syms", cl::desc("Display the symbol table"));
138 static cl::alias SymbolTableShort("t", cl::desc("Alias for --syms"),
139 cl::NotHidden, cl::Grouping,
140 cl::aliasopt(llvm::SymbolTable));
143 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
146 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
149 llvm::Bind("bind", cl::desc("Display mach-o binding info"));
152 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
155 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
158 llvm::RawClangAST("raw-clang-ast",
159 cl::desc("Dump the raw binary contents of the clang AST section"));
162 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
163 static cl::alias MachOm("m", cl::desc("Alias for --macho"), cl::NotHidden,
164 cl::Grouping, cl::aliasopt(MachOOpt));
167 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
168 "see -version for available targets"));
172 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
173 cl::value_desc("cpu-name"),
177 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
178 "see -version for available targets"));
181 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
182 "headers for each section."));
183 static cl::alias SectionHeadersShort("headers",
184 cl::desc("Alias for --section-headers"),
186 cl::aliasopt(SectionHeaders));
187 static cl::alias SectionHeadersShorter("h",
188 cl::desc("Alias for --section-headers"),
189 cl::NotHidden, cl::Grouping,
190 cl::aliasopt(SectionHeaders));
194 cl::desc("Display LMA column when dumping ELF section headers"));
196 cl::list<std::string>
197 llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
198 "With -macho dump segment,section"));
199 cl::alias static FilterSectionsj("j", cl::desc("Alias for --section"),
201 cl::aliasopt(llvm::FilterSections));
203 cl::list<std::string>
204 llvm::MAttrs("mattr",
206 cl::desc("Target specific attributes"),
207 cl::value_desc("a1,+a2,-a3,..."));
210 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
211 "instructions, do not print "
212 "the instruction bytes."));
214 llvm::NoLeadingAddr("no-leading-addr", cl::desc("Print no leading address"));
217 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
219 static cl::alias UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
220 cl::NotHidden, cl::Grouping,
221 cl::aliasopt(UnwindInfo));
224 llvm::PrivateHeaders("private-headers",
225 cl::desc("Display format specific file headers"));
228 llvm::FirstPrivateHeader("private-header",
229 cl::desc("Display only the first format specific file "
232 static cl::alias PrivateHeadersShort("p",
233 cl::desc("Alias for --private-headers"),
234 cl::NotHidden, cl::Grouping,
235 cl::aliasopt(PrivateHeaders));
237 cl::opt<bool> llvm::FileHeaders(
239 cl::desc("Display the contents of the overall file header"));
241 static cl::alias FileHeadersShort("f", cl::desc("Alias for --file-headers"),
242 cl::NotHidden, cl::Grouping,
243 cl::aliasopt(FileHeaders));
246 llvm::ArchiveHeaders("archive-headers",
247 cl::desc("Display archive header information"));
249 cl::alias ArchiveHeadersShort("a", cl::desc("Alias for --archive-headers"),
250 cl::NotHidden, cl::Grouping,
251 cl::aliasopt(ArchiveHeaders));
254 llvm::PrintImmHex("print-imm-hex",
255 cl::desc("Use hex format for immediate values"));
257 cl::opt<bool> PrintFaultMaps("fault-map-section",
258 cl::desc("Display contents of faultmap section"));
260 cl::opt<DIDumpType> llvm::DwarfDumpType(
261 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
262 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")));
264 cl::opt<bool> PrintSource(
267 "Display source inlined with disassembly. Implies disassemble object"));
269 cl::alias PrintSourceShort("S", cl::desc("Alias for -source"), cl::NotHidden,
270 cl::Grouping, cl::aliasopt(PrintSource));
272 cl::opt<bool> PrintLines("line-numbers",
273 cl::desc("Display source line numbers with "
274 "disassembly. Implies disassemble object"));
276 cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"),
277 cl::NotHidden, cl::Grouping,
278 cl::aliasopt(PrintLines));
280 cl::opt<unsigned long long>
281 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
282 cl::value_desc("address"), cl::init(0));
283 cl::opt<unsigned long long>
284 StopAddress("stop-address",
285 cl::desc("Stop disassembly at address"),
286 cl::value_desc("address"), cl::init(UINT64_MAX));
288 cl::opt<bool> DisassembleZeroes(
289 "disassemble-zeroes",
290 cl::desc("Do not skip blocks of zeroes when disassembling"));
291 cl::alias DisassembleZeroesShort("z",
292 cl::desc("Alias for --disassemble-zeroes"),
293 cl::NotHidden, cl::Grouping,
294 cl::aliasopt(DisassembleZeroes));
296 static StringRef ToolName;
298 typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
300 SectionFilter llvm::ToolSectionFilter(llvm::object::ObjectFile const &O) {
301 return SectionFilter(
302 [](llvm::object::SectionRef const &S) {
303 if (FilterSections.empty())
305 llvm::StringRef String;
306 std::error_code error = S.getName(String);
309 return is_contained(FilterSections, String);
314 void llvm::error(std::error_code EC) {
317 WithColor::error(errs(), ToolName)
318 << "reading file: " << EC.message() << ".\n";
323 LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
324 WithColor::error(errs(), ToolName) << Message << ".\n";
329 void llvm::warn(StringRef Message) {
330 WithColor::warning(errs(), ToolName) << Message << ".\n";
334 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
336 WithColor::error(errs(), ToolName)
337 << "'" << File << "': " << Message << ".\n";
341 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
342 std::error_code EC) {
344 WithColor::error(errs(), ToolName)
345 << "'" << File << "': " << EC.message() << ".\n";
349 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
353 raw_string_ostream OS(Buf);
354 logAllUnhandledErrors(std::move(E), OS);
356 WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf;
360 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
363 StringRef ArchitectureName) {
365 WithColor::error(errs(), ToolName);
366 if (ArchiveName != "")
367 errs() << ArchiveName << "(" << FileName << ")";
369 errs() << "'" << FileName << "'";
370 if (!ArchitectureName.empty())
371 errs() << " (for architecture " << ArchitectureName << ")";
373 raw_string_ostream OS(Buf);
374 logAllUnhandledErrors(std::move(E), OS);
376 errs() << ": " << Buf;
380 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
381 const object::Archive::Child &C,
383 StringRef ArchitectureName) {
384 Expected<StringRef> NameOrErr = C.getName();
385 // TODO: if we have a error getting the name then it would be nice to print
386 // the index of which archive member this is and or its offset in the
387 // archive instead of "???" as the name.
389 consumeError(NameOrErr.takeError());
390 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
392 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
396 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
397 // Figure out the target triple.
398 llvm::Triple TheTriple("unknown-unknown-unknown");
399 if (TripleName.empty()) {
401 TheTriple = Obj->makeTriple();
403 TheTriple.setTriple(Triple::normalize(TripleName));
405 // Use the triple, but also try to combine with ARM build attributes.
407 auto Arch = Obj->getArch();
408 if (Arch == Triple::arm || Arch == Triple::armeb)
409 Obj->setARMSubArch(TheTriple);
413 // Get the target specific parser.
415 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
419 report_error(Obj->getFileName(), "can't find target: " + Error);
421 error("can't find target: " + Error);
424 // Update the triple name and return the found target.
425 TripleName = TheTriple.getTriple();
429 bool llvm::isRelocAddressLess(RelocationRef A, RelocationRef B) {
430 return A.getOffset() < B.getOffset();
433 static std::error_code getRelocationValueString(const RelocationRef &Rel,
434 SmallVectorImpl<char> &Result) {
435 const ObjectFile *Obj = Rel.getObject();
436 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
437 return getELFRelocationValueString(ELF, Rel, Result);
438 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
439 return getCOFFRelocationValueString(COFF, Rel, Result);
440 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
441 return getWasmRelocationValueString(Wasm, Rel, Result);
442 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
443 return getMachORelocationValueString(MachO, Rel, Result);
444 llvm_unreachable("unknown object file format");
447 /// Indicates whether this relocation should hidden when listing
448 /// relocations, usually because it is the trailing part of a multipart
449 /// relocation that will be printed as part of the leading relocation.
450 static bool getHidden(RelocationRef RelRef) {
451 auto *MachO = dyn_cast<MachOObjectFile>(RelRef.getObject());
455 unsigned Arch = MachO->getArch();
456 DataRefImpl Rel = RelRef.getRawDataRefImpl();
457 uint64_t Type = MachO->getRelocationType(Rel);
459 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
461 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc)
462 return Type == MachO::GENERIC_RELOC_PAIR;
464 if (Arch == Triple::x86_64) {
465 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
466 // an X86_64_RELOC_SUBTRACTOR.
467 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
468 DataRefImpl RelPrev = Rel;
470 uint64_t PrevType = MachO->getRelocationType(RelPrev);
471 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
480 class SourcePrinter {
482 DILineInfo OldLineInfo;
483 const ObjectFile *Obj = nullptr;
484 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
485 // File name to file contents of source
486 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
487 // Mark the line endings of the cached source
488 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
491 bool cacheSource(const DILineInfo& LineInfoFile);
494 SourcePrinter() = default;
495 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
496 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
497 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
499 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
501 virtual ~SourcePrinter() = default;
502 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
503 StringRef Delimiter = "; ");
506 bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
507 std::unique_ptr<MemoryBuffer> Buffer;
508 if (LineInfo.Source) {
509 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);
511 auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName);
514 Buffer = std::move(*BufferOrError);
516 // Chomp the file to get lines
517 size_t BufferSize = Buffer->getBufferSize();
518 const char *BufferStart = Buffer->getBufferStart();
519 for (const char *Start = BufferStart, *End = BufferStart;
520 End < BufferStart + BufferSize; End++)
521 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
522 (*End == '\r' && *(End + 1) == '\n')) {
523 LineCache[LineInfo.FileName].push_back(StringRef(Start, End - Start));
528 SourceCache[LineInfo.FileName] = std::move(Buffer);
532 void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
533 StringRef Delimiter) {
536 DILineInfo LineInfo = DILineInfo();
537 auto ExpectecLineInfo =
538 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
539 if (!ExpectecLineInfo)
540 consumeError(ExpectecLineInfo.takeError());
542 LineInfo = *ExpectecLineInfo;
544 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
549 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
551 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
552 if (!cacheSource(LineInfo))
554 auto FileBuffer = SourceCache.find(LineInfo.FileName);
555 if (FileBuffer != SourceCache.end()) {
556 auto LineBuffer = LineCache.find(LineInfo.FileName);
557 if (LineBuffer != LineCache.end()) {
558 if (LineInfo.Line > LineBuffer->second.size())
560 // Vector begins at 0, line numbers are non-zero
561 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
566 OldLineInfo = LineInfo;
569 static bool isArmElf(const ObjectFile *Obj) {
570 return (Obj->isELF() &&
571 (Obj->getArch() == Triple::aarch64 ||
572 Obj->getArch() == Triple::aarch64_be ||
573 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
574 Obj->getArch() == Triple::thumb ||
575 Obj->getArch() == Triple::thumbeb));
578 static void printRelocation(const RelocationRef &Rel, uint64_t Address,
581 AddrSize > 4 ? "\t\t%016" PRIx64 ": " : "\t\t\t%08" PRIx64 ": ";
582 SmallString<16> Name;
584 Rel.getTypeName(Name);
585 error(getRelocationValueString(Rel, Val));
586 outs() << format(Fmt.data(), Address) << Name << "\t" << Val << "\n";
589 class PrettyPrinter {
591 virtual ~PrettyPrinter() = default;
592 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
593 ArrayRef<uint8_t> Bytes, uint64_t Address,
594 raw_ostream &OS, StringRef Annot,
595 MCSubtargetInfo const &STI, SourcePrinter *SP,
596 std::vector<RelocationRef> *Rels = nullptr) {
597 if (SP && (PrintSource || PrintLines))
598 SP->printSourceLine(OS, Address);
600 OS << format("%8" PRIx64 ":", Address);
601 if (!NoShowRawInsn) {
603 dumpBytes(Bytes, OS);
606 IP.printInst(MI, OS, "", STI);
611 PrettyPrinter PrettyPrinterInst;
612 class HexagonPrettyPrinter : public PrettyPrinter {
614 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
617 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
619 OS << format("%8" PRIx64 ":", Address);
620 if (!NoShowRawInsn) {
622 dumpBytes(Bytes.slice(0, 4), OS);
623 OS << format("%08" PRIx32, opcode);
626 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
627 uint64_t Address, raw_ostream &OS, StringRef Annot,
628 MCSubtargetInfo const &STI, SourcePrinter *SP,
629 std::vector<RelocationRef> *Rels) override {
630 if (SP && (PrintSource || PrintLines))
631 SP->printSourceLine(OS, Address, "");
633 printLead(Bytes, Address, OS);
639 raw_string_ostream TempStream(Buffer);
640 IP.printInst(MI, TempStream, "", STI);
642 StringRef Contents(Buffer);
643 // Split off bundle attributes
644 auto PacketBundle = Contents.rsplit('\n');
645 // Split off first instruction from the rest
646 auto HeadTail = PacketBundle.first.split('\n');
647 auto Preamble = " { ";
650 // Hexagon's packets require relocations to be inline rather than
651 // clustered at the end of the packet.
652 std::vector<RelocationRef>::const_iterator RelCur = Rels->begin();
653 std::vector<RelocationRef>::const_iterator RelEnd = Rels->end();
654 auto PrintReloc = [&]() -> void {
655 while ((RelCur != RelEnd) && (RelCur->getOffset() <= Address)) {
656 if (RelCur->getOffset() == Address) {
657 printRelocation(*RelCur, Address, 4);
664 while (!HeadTail.first.empty()) {
667 if (SP && (PrintSource || PrintLines))
668 SP->printSourceLine(OS, Address, "");
669 printLead(Bytes, Address, OS);
673 auto Duplex = HeadTail.first.split('\v');
674 if (!Duplex.second.empty()) {
677 Inst = Duplex.second;
680 Inst = HeadTail.first;
682 HeadTail = HeadTail.second.split('\n');
683 if (HeadTail.first.empty())
684 OS << " } " << PacketBundle.second;
686 Bytes = Bytes.slice(4);
691 HexagonPrettyPrinter HexagonPrettyPrinterInst;
693 class AMDGCNPrettyPrinter : public PrettyPrinter {
695 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
696 uint64_t Address, raw_ostream &OS, StringRef Annot,
697 MCSubtargetInfo const &STI, SourcePrinter *SP,
698 std::vector<RelocationRef> *Rels) override {
699 if (SP && (PrintSource || PrintLines))
700 SP->printSourceLine(OS, Address);
702 typedef support::ulittle32_t U32;
705 SmallString<40> InstStr;
706 raw_svector_ostream IS(InstStr);
708 IP.printInst(MI, IS, "", STI);
710 OS << left_justify(IS.str(), 60);
712 // an unrecognized encoding - this is probably data so represent it
713 // using the .long directive, or .byte directive if fewer than 4 bytes
715 if (Bytes.size() >= 4) {
716 OS << format("\t.long 0x%08" PRIx32 " ",
717 static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data())));
720 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
721 for (unsigned int i = 1; i < Bytes.size(); i++)
722 OS << format(", 0x%02" PRIx8, Bytes[i]);
723 OS.indent(55 - (6 * Bytes.size()));
727 OS << format("// %012" PRIX64 ": ", Address);
728 if (Bytes.size() >=4) {
729 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
730 Bytes.size() / sizeof(U32)))
731 // D should be explicitly casted to uint32_t here as it is passed
732 // by format to snprintf as vararg.
733 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
735 for (unsigned int i = 0; i < Bytes.size(); i++)
736 OS << format("%02" PRIX8 " ", Bytes[i]);
740 OS << "// " << Annot;
743 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
745 class BPFPrettyPrinter : public PrettyPrinter {
747 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
748 uint64_t Address, raw_ostream &OS, StringRef Annot,
749 MCSubtargetInfo const &STI, SourcePrinter *SP,
750 std::vector<RelocationRef> *Rels) override {
751 if (SP && (PrintSource || PrintLines))
752 SP->printSourceLine(OS, Address);
754 OS << format("%8" PRId64 ":", Address / 8);
755 if (!NoShowRawInsn) {
757 dumpBytes(Bytes, OS);
760 IP.printInst(MI, OS, "", STI);
765 BPFPrettyPrinter BPFPrettyPrinterInst;
767 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
768 switch(Triple.getArch()) {
770 return PrettyPrinterInst;
771 case Triple::hexagon:
772 return HexagonPrettyPrinterInst;
774 return AMDGCNPrettyPrinterInst;
777 return BPFPrettyPrinterInst;
782 static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
783 assert(Obj->isELF());
784 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
785 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
786 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
787 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
788 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
789 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
790 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
791 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
792 llvm_unreachable("Unsupported binary format");
795 template <class ELFT> static void
796 addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
797 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
798 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
799 uint8_t SymbolType = Symbol.getELFType();
800 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
803 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
805 report_error(Obj->getFileName(), AddressOrErr.takeError());
807 Expected<StringRef> Name = Symbol.getName();
809 report_error(Obj->getFileName(), Name.takeError());
813 Expected<section_iterator> SectionOrErr = Symbol.getSection();
815 report_error(Obj->getFileName(), SectionOrErr.takeError());
816 section_iterator SecI = *SectionOrErr;
817 if (SecI == Obj->section_end())
820 AllSymbols[*SecI].emplace_back(*AddressOrErr, *Name, SymbolType);
825 addDynamicElfSymbols(const ObjectFile *Obj,
826 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
827 assert(Obj->isELF());
828 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
829 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
830 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
831 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
832 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
833 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
834 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
835 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
837 llvm_unreachable("Unsupported binary format");
840 static void addPltEntries(const ObjectFile *Obj,
841 std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
842 StringSaver &Saver) {
843 Optional<SectionRef> Plt = None;
844 for (const SectionRef &Section : Obj->sections()) {
846 if (Section.getName(Name))
853 if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) {
854 for (auto PltEntry : ElfObj->getPltAddresses()) {
855 SymbolRef Symbol(PltEntry.first, ElfObj);
856 uint8_t SymbolType = getElfSymbolType(Obj, Symbol);
858 Expected<StringRef> NameOrErr = Symbol.getName();
860 report_error(Obj->getFileName(), NameOrErr.takeError());
861 if (NameOrErr->empty())
863 StringRef Name = Saver.save((*NameOrErr + "@plt").str());
865 AllSymbols[*Plt].emplace_back(PltEntry.second, Name, SymbolType);
870 // Normally the disassembly output will skip blocks of zeroes. This function
871 // returns the number of zero bytes that can be skipped when dumping the
872 // disassembly of the instructions in Buf.
873 static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) {
874 // Find the number of leading zeroes.
876 while (N < Buf.size() && !Buf[N])
879 // We may want to skip blocks of zero bytes, but unless we see
880 // at least 8 of them in a row.
884 // We skip zeroes in multiples of 4 because do not want to truncate an
885 // instruction if it starts with a zero byte.
889 // Returns a map from sections to their relocations.
890 static std::map<SectionRef, std::vector<RelocationRef>>
891 getRelocsMap(llvm::object::ObjectFile const &Obj) {
892 std::map<SectionRef, std::vector<RelocationRef>> Ret;
893 for (const SectionRef &Section : ToolSectionFilter(Obj)) {
894 section_iterator RelSec = Section.getRelocatedSection();
895 if (RelSec == Obj.section_end())
897 std::vector<RelocationRef> &V = Ret[*RelSec];
898 for (const RelocationRef &R : Section.relocations())
900 // Sort relocations by address.
901 llvm::sort(V, isRelocAddressLess);
906 // Used for --adjust-vma to check if address should be adjusted by the
907 // specified value for a given section.
908 // For ELF we do not adjust non-allocatable sections like debug ones,
909 // because they are not loadable.
910 // TODO: implement for other file formats.
911 static bool shouldAdjustVA(const SectionRef &Section) {
912 const ObjectFile *Obj = Section.getObject();
913 if (isa<object::ELFObjectFileBase>(Obj))
914 return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
918 static void disassembleObject(const Target *TheTarget, const ObjectFile *Obj,
919 MCContext &Ctx, MCDisassembler *DisAsm,
920 const MCInstrAnalysis *MIA, MCInstPrinter *IP,
921 const MCSubtargetInfo *STI, PrettyPrinter &PIP,
922 SourcePrinter &SP, bool InlineRelocs) {
923 std::map<SectionRef, std::vector<RelocationRef>> RelocMap;
925 RelocMap = getRelocsMap(*Obj);
927 // Create a mapping from virtual address to symbol name. This is used to
928 // pretty print the symbols while disassembling.
929 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
930 SectionSymbolsTy AbsoluteSymbols;
931 for (const SymbolRef &Symbol : Obj->symbols()) {
932 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
934 report_error(Obj->getFileName(), AddressOrErr.takeError());
935 uint64_t Address = *AddressOrErr;
937 Expected<StringRef> Name = Symbol.getName();
939 report_error(Obj->getFileName(), Name.takeError());
943 Expected<section_iterator> SectionOrErr = Symbol.getSection();
945 report_error(Obj->getFileName(), SectionOrErr.takeError());
947 uint8_t SymbolType = ELF::STT_NOTYPE;
949 SymbolType = getElfSymbolType(Obj, Symbol);
950 if (SymbolType == ELF::STT_SECTION)
954 section_iterator SecI = *SectionOrErr;
955 if (SecI != Obj->section_end())
956 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
958 AbsoluteSymbols.emplace_back(Address, *Name, SymbolType);
962 if (AllSymbols.empty() && Obj->isELF())
963 addDynamicElfSymbols(Obj, AllSymbols);
966 StringSaver Saver(A);
967 addPltEntries(Obj, AllSymbols, Saver);
969 // Create a mapping from virtual address to section.
970 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
971 for (SectionRef Sec : Obj->sections())
972 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
973 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
975 // Linked executables (.exe and .dll files) typically don't include a real
976 // symbol table but they might contain an export table.
977 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
978 for (const auto &ExportEntry : COFFObj->export_directories()) {
980 error(ExportEntry.getSymbolName(Name));
984 error(ExportEntry.getExportRVA(RVA));
986 uint64_t VA = COFFObj->getImageBase() + RVA;
987 auto Sec = std::upper_bound(
988 SectionAddresses.begin(), SectionAddresses.end(), VA,
989 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
990 return LHS < RHS.first;
992 if (Sec != SectionAddresses.begin())
995 Sec = SectionAddresses.end();
997 if (Sec != SectionAddresses.end())
998 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
1000 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
1004 // Sort all the symbols, this allows us to use a simple binary search to find
1005 // a symbol near an address.
1006 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1007 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1008 array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
1010 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1011 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
1014 uint64_t SectionAddr = Section.getAddress();
1015 uint64_t SectSize = Section.getSize();
1019 // Get the list of all the symbols in this section.
1020 SectionSymbolsTy &Symbols = AllSymbols[Section];
1021 std::vector<uint64_t> DataMappingSymsAddr;
1022 std::vector<uint64_t> TextMappingSymsAddr;
1023 if (isArmElf(Obj)) {
1024 for (const auto &Symb : Symbols) {
1025 uint64_t Address = std::get<0>(Symb);
1026 StringRef Name = std::get<1>(Symb);
1027 if (Name.startswith("$d"))
1028 DataMappingSymsAddr.push_back(Address - SectionAddr);
1029 if (Name.startswith("$x"))
1030 TextMappingSymsAddr.push_back(Address - SectionAddr);
1031 if (Name.startswith("$a"))
1032 TextMappingSymsAddr.push_back(Address - SectionAddr);
1033 if (Name.startswith("$t"))
1034 TextMappingSymsAddr.push_back(Address - SectionAddr);
1038 llvm::sort(DataMappingSymsAddr);
1039 llvm::sort(TextMappingSymsAddr);
1041 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1042 // AMDGPU disassembler uses symbolizer for printing labels
1043 std::unique_ptr<MCRelocationInfo> RelInfo(
1044 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1046 std::unique_ptr<MCSymbolizer> Symbolizer(
1047 TheTarget->createMCSymbolizer(
1048 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1049 DisAsm->setSymbolizer(std::move(Symbolizer));
1053 StringRef SegmentName = "";
1054 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
1055 DataRefImpl DR = Section.getRawDataRefImpl();
1056 SegmentName = MachO->getSectionFinalSegmentName(DR);
1058 StringRef SectionName;
1059 error(Section.getName(SectionName));
1061 // If the section has no symbol at the start, just insert a dummy one.
1062 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
1065 std::make_tuple(SectionAddr, SectionName,
1066 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
1069 SmallString<40> Comments;
1070 raw_svector_ostream CommentStream(Comments);
1073 error(Section.getContents(BytesStr));
1074 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1077 uint64_t VMAAdjustment = 0;
1078 if (shouldAdjustVA(Section))
1079 VMAAdjustment = AdjustVMA;
1083 bool PrintedSection = false;
1084 std::vector<RelocationRef> Rels = RelocMap[Section];
1085 std::vector<RelocationRef>::const_iterator RelCur = Rels.begin();
1086 std::vector<RelocationRef>::const_iterator RelEnd = Rels.end();
1087 // Disassemble symbol by symbol.
1088 for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) {
1089 uint64_t Start = std::get<0>(Symbols[SI]) - SectionAddr;
1090 // The end is either the section end or the beginning of the next
1092 uint64_t End = (SI == SE - 1)
1094 : std::get<0>(Symbols[SI + 1]) - SectionAddr;
1095 // Don't try to disassemble beyond the end of section contents.
1098 // If this symbol has the same address as the next symbol, then skip it.
1102 // Check if we need to skip symbol
1103 // Skip if the symbol's data is not between StartAddress and StopAddress
1104 if (End + SectionAddr < StartAddress ||
1105 Start + SectionAddr > StopAddress) {
1109 /// Skip if user requested specific symbols and this is not in the list
1110 if (!DisasmFuncsSet.empty() &&
1111 !DisasmFuncsSet.count(std::get<1>(Symbols[SI])))
1114 if (!PrintedSection) {
1115 PrintedSection = true;
1116 outs() << "Disassembly of section ";
1117 if (!SegmentName.empty())
1118 outs() << SegmentName << ",";
1119 outs() << SectionName << ':';
1122 // Stop disassembly at the stop address specified
1123 if (End + SectionAddr > StopAddress)
1124 End = StopAddress - SectionAddr;
1126 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1127 if (std::get<2>(Symbols[SI]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1128 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1132 std::get<2>(Symbols[SI + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1133 // cut trailing zeroes at the end of kernel
1134 // cut up to 256 bytes
1135 const uint64_t EndAlign = 256;
1136 const auto Limit = End - (std::min)(EndAlign, End - Start);
1137 while (End > Limit &&
1138 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1145 outs() << format("%016" PRIx64 " ",
1146 SectionAddr + Start + VMAAdjustment);
1148 StringRef SymbolName = std::get<1>(Symbols[SI]);
1150 outs() << demangle(SymbolName) << ":\n";
1152 outs() << SymbolName << ":\n";
1154 // Don't print raw contents of a virtual section. A virtual section
1155 // doesn't have any contents in the file.
1156 if (Section.isVirtual()) {
1162 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1164 raw_ostream &DebugOut = nulls();
1167 // Some targets (like WebAssembly) have a special prelude at the start
1169 DisAsm->onSymbolStart(SymbolName, Size, Bytes.slice(Start, End - Start),
1170 SectionAddr + Start, DebugOut, CommentStream);
1173 for (Index = Start; Index < End; Index += Size) {
1176 if (Index + SectionAddr < StartAddress ||
1177 Index + SectionAddr > StopAddress) {
1178 // skip byte by byte till StartAddress is reached
1182 // AArch64 ELF binaries can interleave data and text in the
1183 // same section. We rely on the markers introduced to
1184 // understand what we need to dump. If the data marker is within a
1185 // function, it is denoted as a word/short etc
1186 if (isArmElf(Obj) && std::get<2>(Symbols[SI]) != ELF::STT_OBJECT &&
1188 uint64_t Stride = 0;
1190 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1191 DataMappingSymsAddr.end(), Index);
1192 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1194 while (Index < End) {
1195 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1197 if (Index + 4 <= End) {
1199 dumpBytes(Bytes.slice(Index, 4), outs());
1200 outs() << "\t.word\t";
1202 if (Obj->isLittleEndian()) {
1204 reinterpret_cast<const support::ulittle32_t *>(
1205 Bytes.data() + Index);
1208 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1209 Bytes.data() + Index);
1212 outs() << "0x" << format("%08" PRIx32, Data);
1213 } else if (Index + 2 <= End) {
1215 dumpBytes(Bytes.slice(Index, 2), outs());
1216 outs() << "\t\t.short\t";
1218 if (Obj->isLittleEndian()) {
1220 reinterpret_cast<const support::ulittle16_t *>(
1221 Bytes.data() + Index);
1225 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1229 outs() << "0x" << format("%04" PRIx16, Data);
1232 dumpBytes(Bytes.slice(Index, 1), outs());
1233 outs() << "\t\t.byte\t";
1234 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
1238 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1239 TextMappingSymsAddr.end(), Index);
1240 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1246 // If there is a data symbol inside an ELF text section and we are only
1247 // disassembling text (applicable all architectures),
1248 // we are in a situation where we must print the data and not
1250 if (Obj->isELF() && std::get<2>(Symbols[SI]) == ELF::STT_OBJECT &&
1251 !DisassembleAll && Section.isText()) {
1252 // print out data up to 8 bytes at a time in hex and ascii
1253 uint8_t AsciiData[9] = {'\0'};
1257 for (Index = Start; Index < End; Index += 1) {
1258 if (((SectionAddr + Index) < StartAddress) ||
1259 ((SectionAddr + Index) > StopAddress))
1261 if (NumBytes == 0) {
1262 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1265 Byte = Bytes.slice(Index)[0];
1266 outs() << format(" %02x", Byte);
1267 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
1269 uint8_t IndentOffset = 0;
1271 if (Index == End - 1 || NumBytes > 8) {
1272 // Indent the space for less than 8 bytes data.
1273 // 2 spaces for byte and one for space between bytes
1274 IndentOffset = 3 * (8 - NumBytes);
1275 for (int Excess = NumBytes; Excess < 8; Excess++)
1276 AsciiData[Excess] = '\0';
1279 if (NumBytes == 8) {
1280 AsciiData[8] = '\0';
1281 outs() << std::string(IndentOffset, ' ') << " ";
1282 outs() << reinterpret_cast<char *>(AsciiData);
1291 // When -z or --disassemble-zeroes are given we always dissasemble them.
1292 // Otherwise we might want to skip zero bytes we see.
1293 if (!DisassembleZeroes) {
1294 uint64_t MaxOffset = End - Index;
1295 // For -reloc: print zero blocks patched by relocations, so that
1296 // relocations can be shown in the dump.
1297 if (RelCur != RelEnd)
1298 MaxOffset = RelCur->getOffset() - Index;
1301 countSkippableZeroBytes(Bytes.slice(Index, MaxOffset))) {
1302 outs() << "\t\t..." << '\n';
1309 // Disassemble a real instruction or a data when disassemble all is
1311 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1312 SectionAddr + Index, DebugOut,
1318 *IP, Disassembled ? &Inst : nullptr, Bytes.slice(Index, Size),
1319 SectionAddr + Index + VMAAdjustment, outs(), "", *STI, &SP, &Rels);
1320 outs() << CommentStream.str();
1323 // Try to resolve the target of a call, tail call, etc. to a specific
1325 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1326 MIA->isConditionalBranch(Inst))) {
1328 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1329 // In a relocatable object, the target's section must reside in
1330 // the same section as the call instruction or it is accessed
1331 // through a relocation.
1333 // In a non-relocatable object, the target may be in any section.
1335 // N.B. We don't walk the relocations in the relocatable case yet.
1336 auto *TargetSectionSymbols = &Symbols;
1337 if (!Obj->isRelocatableObject()) {
1338 auto SectionAddress = std::upper_bound(
1339 SectionAddresses.begin(), SectionAddresses.end(), Target,
1341 const std::pair<uint64_t, SectionRef> &RHS) {
1342 return LHS < RHS.first;
1344 if (SectionAddress != SectionAddresses.begin()) {
1346 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1348 TargetSectionSymbols = &AbsoluteSymbols;
1352 // Find the first symbol in the section whose offset is less than
1353 // or equal to the target. If there isn't a section that contains
1354 // the target, find the nearest preceding absolute symbol.
1355 auto TargetSym = std::upper_bound(
1356 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1357 Target, [](uint64_t LHS,
1358 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1359 return LHS < std::get<0>(RHS);
1361 if (TargetSym == TargetSectionSymbols->begin()) {
1362 TargetSectionSymbols = &AbsoluteSymbols;
1363 TargetSym = std::upper_bound(
1364 AbsoluteSymbols.begin(), AbsoluteSymbols.end(),
1365 Target, [](uint64_t LHS,
1366 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1367 return LHS < std::get<0>(RHS);
1370 if (TargetSym != TargetSectionSymbols->begin()) {
1372 uint64_t TargetAddress = std::get<0>(*TargetSym);
1373 StringRef TargetName = std::get<1>(*TargetSym);
1374 outs() << " <" << TargetName;
1375 uint64_t Disp = Target - TargetAddress;
1377 outs() << "+0x" << Twine::utohexstr(Disp);
1384 // Hexagon does this in pretty printer
1385 if (Obj->getArch() != Triple::hexagon) {
1386 // Print relocation for instruction.
1387 while (RelCur != RelEnd) {
1388 uint64_t Offset = RelCur->getOffset();
1389 // If this relocation is hidden, skip it.
1390 if (getHidden(*RelCur) || ((SectionAddr + Offset) < StartAddress)) {
1395 // Stop when RelCur's offset is past the current instruction.
1396 if (Offset >= Index + Size)
1399 // When --adjust-vma is used, update the address printed.
1400 if (RelCur->getSymbol() != Obj->symbol_end()) {
1401 Expected<section_iterator> SymSI =
1402 RelCur->getSymbol()->getSection();
1403 if (SymSI && *SymSI != Obj->section_end() &&
1404 (shouldAdjustVA(**SymSI)))
1405 Offset += AdjustVMA;
1408 printRelocation(*RelCur, SectionAddr + Offset,
1409 Obj->getBytesInAddress());
1418 static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
1419 if (StartAddress > StopAddress)
1420 error("Start address should be less than stop address");
1422 const Target *TheTarget = getTarget(Obj);
1424 // Package up features to be passed to target/subtarget
1425 SubtargetFeatures Features = Obj->getFeatures();
1426 if (!MAttrs.empty())
1427 for (unsigned I = 0; I != MAttrs.size(); ++I)
1428 Features.AddFeature(MAttrs[I]);
1430 std::unique_ptr<const MCRegisterInfo> MRI(
1431 TheTarget->createMCRegInfo(TripleName));
1433 report_error(Obj->getFileName(),
1434 "no register info for target " + TripleName);
1436 // Set up disassembler.
1437 std::unique_ptr<const MCAsmInfo> AsmInfo(
1438 TheTarget->createMCAsmInfo(*MRI, TripleName));
1440 report_error(Obj->getFileName(),
1441 "no assembly info for target " + TripleName);
1442 std::unique_ptr<const MCSubtargetInfo> STI(
1443 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1445 report_error(Obj->getFileName(),
1446 "no subtarget info for target " + TripleName);
1447 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1449 report_error(Obj->getFileName(),
1450 "no instruction info for target " + TripleName);
1451 MCObjectFileInfo MOFI;
1452 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1453 // FIXME: for now initialize MCObjectFileInfo with default values
1454 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
1456 std::unique_ptr<MCDisassembler> DisAsm(
1457 TheTarget->createMCDisassembler(*STI, Ctx));
1459 report_error(Obj->getFileName(),
1460 "no disassembler for target " + TripleName);
1462 std::unique_ptr<const MCInstrAnalysis> MIA(
1463 TheTarget->createMCInstrAnalysis(MII.get()));
1465 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1466 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1467 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
1469 report_error(Obj->getFileName(),
1470 "no instruction printer for target " + TripleName);
1471 IP->setPrintImmHex(PrintImmHex);
1473 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
1474 SourcePrinter SP(Obj, TheTarget->getName());
1476 disassembleObject(TheTarget, Obj, Ctx, DisAsm.get(), MIA.get(), IP.get(),
1477 STI.get(), PIP, SP, InlineRelocs);
1480 void llvm::printRelocations(const ObjectFile *Obj) {
1481 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1483 // Regular objdump doesn't print relocations in non-relocatable object
1485 if (!Obj->isRelocatableObject())
1488 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1489 if (Section.relocation_begin() == Section.relocation_end())
1492 error(Section.getName(SecName));
1493 outs() << "RELOCATION RECORDS FOR [" << SecName << "]:\n";
1494 for (const RelocationRef &Reloc : Section.relocations()) {
1495 uint64_t Address = Reloc.getOffset();
1496 SmallString<32> RelocName;
1497 SmallString<32> ValueStr;
1498 if (Address < StartAddress || Address > StopAddress || getHidden(Reloc))
1500 Reloc.getTypeName(RelocName);
1501 error(getRelocationValueString(Reloc, ValueStr));
1502 outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1503 << ValueStr << "\n";
1509 void llvm::printDynamicRelocations(const ObjectFile *Obj) {
1510 // For the moment, this option is for ELF only
1514 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
1515 if (!Elf || Elf->getEType() != ELF::ET_DYN) {
1516 error("not a dynamic object");
1520 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1521 if (DynRelSec.empty())
1524 outs() << "DYNAMIC RELOCATION RECORDS\n";
1525 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1526 for (const SectionRef &Section : DynRelSec) {
1527 if (Section.relocation_begin() == Section.relocation_end())
1529 for (const RelocationRef &Reloc : Section.relocations()) {
1530 uint64_t Address = Reloc.getOffset();
1531 SmallString<32> RelocName;
1532 SmallString<32> ValueStr;
1533 Reloc.getTypeName(RelocName);
1534 error(getRelocationValueString(Reloc, ValueStr));
1535 outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1536 << ValueStr << "\n";
1541 // Returns true if we need to show LMA column when dumping section headers. We
1542 // show it only when the platform is ELF and either we have at least one section
1543 // whose VMA and LMA are different and/or when --show-lma flag is used.
1544 static bool shouldDisplayLMA(const ObjectFile *Obj) {
1547 for (const SectionRef &S : ToolSectionFilter(*Obj))
1548 if (S.getAddress() != getELFSectionLMA(S))
1553 void llvm::printSectionHeaders(const ObjectFile *Obj) {
1554 bool HasLMAColumn = shouldDisplayLMA(Obj);
1556 outs() << "Sections:\n"
1557 "Idx Name Size VMA LMA "
1560 outs() << "Sections:\n"
1561 "Idx Name Size VMA Type\n";
1563 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1565 error(Section.getName(Name));
1566 uint64_t VMA = Section.getAddress();
1567 if (shouldAdjustVA(Section))
1570 uint64_t Size = Section.getSize();
1571 bool Text = Section.isText();
1572 bool Data = Section.isData();
1573 bool BSS = Section.isBSS();
1574 std::string Type = (std::string(Text ? "TEXT " : "") +
1575 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1578 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %016" PRIx64
1580 (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1581 VMA, getELFSectionLMA(Section), Type.c_str());
1583 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
1584 (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1590 void llvm::printSectionContents(const ObjectFile *Obj) {
1592 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1595 error(Section.getName(Name));
1596 uint64_t BaseAddr = Section.getAddress();
1597 uint64_t Size = Section.getSize();
1601 outs() << "Contents of section " << Name << ":\n";
1602 if (Section.isBSS()) {
1603 outs() << format("<skipping contents of bss section at [%04" PRIx64
1604 ", %04" PRIx64 ")>\n",
1605 BaseAddr, BaseAddr + Size);
1609 error(Section.getContents(Contents));
1611 // Dump out the content as hex and printable ascii characters.
1612 for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) {
1613 outs() << format(" %04" PRIx64 " ", BaseAddr + Addr);
1614 // Dump line of hex.
1615 for (std::size_t I = 0; I < 16; ++I) {
1616 if (I != 0 && I % 4 == 0)
1619 outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true)
1620 << hexdigit(Contents[Addr + I] & 0xF, true);
1626 for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) {
1627 if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF))
1628 outs() << Contents[Addr + I];
1637 void llvm::printSymbolTable(const ObjectFile *O, StringRef ArchiveName,
1638 StringRef ArchitectureName) {
1639 outs() << "SYMBOL TABLE:\n";
1641 if (const COFFObjectFile *Coff = dyn_cast<const COFFObjectFile>(O)) {
1642 printCOFFSymbolTable(Coff);
1646 for (auto I = O->symbol_begin(), E = O->symbol_end(); I != E; ++I) {
1647 // Skip printing the special zero symbol when dumping an ELF file.
1648 // This makes the output consistent with the GNU objdump.
1649 if (I == O->symbol_begin() && isa<ELFObjectFileBase>(O))
1652 const SymbolRef &Symbol = *I;
1653 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1654 if (!AddressOrError)
1655 report_error(ArchiveName, O->getFileName(), AddressOrError.takeError(),
1657 uint64_t Address = *AddressOrError;
1658 if ((Address < StartAddress) || (Address > StopAddress))
1660 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1662 report_error(ArchiveName, O->getFileName(), TypeOrError.takeError(),
1664 SymbolRef::Type Type = *TypeOrError;
1665 uint32_t Flags = Symbol.getFlags();
1666 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1668 report_error(ArchiveName, O->getFileName(), SectionOrErr.takeError(),
1670 section_iterator Section = *SectionOrErr;
1672 if (Type == SymbolRef::ST_Debug && Section != O->section_end()) {
1673 Section->getName(Name);
1675 Expected<StringRef> NameOrErr = Symbol.getName();
1677 report_error(ArchiveName, O->getFileName(), NameOrErr.takeError(),
1682 bool Global = Flags & SymbolRef::SF_Global;
1683 bool Weak = Flags & SymbolRef::SF_Weak;
1684 bool Absolute = Flags & SymbolRef::SF_Absolute;
1685 bool Common = Flags & SymbolRef::SF_Common;
1686 bool Hidden = Flags & SymbolRef::SF_Hidden;
1689 if (Type != SymbolRef::ST_Unknown)
1690 GlobLoc = Global ? 'g' : 'l';
1691 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1693 char FileFunc = ' ';
1694 if (Type == SymbolRef::ST_File)
1696 else if (Type == SymbolRef::ST_Function)
1698 else if (Type == SymbolRef::ST_Data)
1701 const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 :
1704 outs() << format(Fmt, Address) << " "
1705 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1706 << (Weak ? 'w' : ' ') // Weak?
1707 << ' ' // Constructor. Not supported yet.
1708 << ' ' // Warning. Not supported yet.
1709 << ' ' // Indirect reference to another symbol.
1710 << Debug // Debugging (d) or dynamic (D) symbol.
1711 << FileFunc // Name of function (F), file (f) or object (O).
1715 } else if (Common) {
1717 } else if (Section == O->section_end()) {
1720 if (const MachOObjectFile *MachO =
1721 dyn_cast<const MachOObjectFile>(O)) {
1722 DataRefImpl DR = Section->getRawDataRefImpl();
1723 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1724 outs() << SegmentName << ",";
1726 StringRef SectionName;
1727 error(Section->getName(SectionName));
1728 outs() << SectionName;
1732 if (Common || isa<ELFObjectFileBase>(O)) {
1734 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1735 outs() << format("\t %08" PRIx64 " ", Val);
1739 outs() << ".hidden ";
1742 outs() << demangle(Name) << '\n';
1744 outs() << Name << '\n';
1748 static void printUnwindInfo(const ObjectFile *O) {
1749 outs() << "Unwind info:\n\n";
1751 if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O))
1752 printCOFFUnwindInfo(Coff);
1753 else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O))
1754 printMachOUnwindInfo(MachO);
1756 // TODO: Extract DWARF dump tool to objdump.
1757 WithColor::error(errs(), ToolName)
1758 << "This operation is only currently supported "
1759 "for COFF and MachO object files.\n";
1762 void llvm::printExportsTrie(const ObjectFile *o) {
1763 outs() << "Exports trie:\n";
1764 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1765 printMachOExportsTrie(MachO);
1767 WithColor::error(errs(), ToolName)
1768 << "This operation is only currently supported "
1769 "for Mach-O executable files.\n";
1772 void llvm::printRebaseTable(ObjectFile *o) {
1773 outs() << "Rebase table:\n";
1774 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1775 printMachORebaseTable(MachO);
1777 WithColor::error(errs(), ToolName)
1778 << "This operation is only currently supported "
1779 "for Mach-O executable files.\n";
1782 void llvm::printBindTable(ObjectFile *o) {
1783 outs() << "Bind table:\n";
1784 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1785 printMachOBindTable(MachO);
1787 WithColor::error(errs(), ToolName)
1788 << "This operation is only currently supported "
1789 "for Mach-O executable files.\n";
1792 void llvm::printLazyBindTable(ObjectFile *o) {
1793 outs() << "Lazy bind table:\n";
1794 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1795 printMachOLazyBindTable(MachO);
1797 WithColor::error(errs(), ToolName)
1798 << "This operation is only currently supported "
1799 "for Mach-O executable files.\n";
1802 void llvm::printWeakBindTable(ObjectFile *o) {
1803 outs() << "Weak bind table:\n";
1804 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1805 printMachOWeakBindTable(MachO);
1807 WithColor::error(errs(), ToolName)
1808 << "This operation is only currently supported "
1809 "for Mach-O executable files.\n";
1812 /// Dump the raw contents of the __clangast section so the output can be piped
1813 /// into llvm-bcanalyzer.
1814 void llvm::printRawClangAST(const ObjectFile *Obj) {
1815 if (outs().is_displayed()) {
1816 WithColor::error(errs(), ToolName)
1817 << "The -raw-clang-ast option will dump the raw binary contents of "
1818 "the clang ast section.\n"
1819 "Please redirect the output to a file or another program such as "
1820 "llvm-bcanalyzer.\n";
1824 StringRef ClangASTSectionName("__clangast");
1825 if (isa<COFFObjectFile>(Obj)) {
1826 ClangASTSectionName = "clangast";
1829 Optional<object::SectionRef> ClangASTSection;
1830 for (auto Sec : ToolSectionFilter(*Obj)) {
1833 if (Name == ClangASTSectionName) {
1834 ClangASTSection = Sec;
1838 if (!ClangASTSection)
1841 StringRef ClangASTContents;
1842 error(ClangASTSection.getValue().getContents(ClangASTContents));
1843 outs().write(ClangASTContents.data(), ClangASTContents.size());
1846 static void printFaultMaps(const ObjectFile *Obj) {
1847 StringRef FaultMapSectionName;
1849 if (isa<ELFObjectFileBase>(Obj)) {
1850 FaultMapSectionName = ".llvm_faultmaps";
1851 } else if (isa<MachOObjectFile>(Obj)) {
1852 FaultMapSectionName = "__llvm_faultmaps";
1854 WithColor::error(errs(), ToolName)
1855 << "This operation is only currently supported "
1856 "for ELF and Mach-O executable files.\n";
1860 Optional<object::SectionRef> FaultMapSection;
1862 for (auto Sec : ToolSectionFilter(*Obj)) {
1865 if (Name == FaultMapSectionName) {
1866 FaultMapSection = Sec;
1871 outs() << "FaultMap table:\n";
1873 if (!FaultMapSection.hasValue()) {
1874 outs() << "<not found>\n";
1878 StringRef FaultMapContents;
1879 error(FaultMapSection.getValue().getContents(FaultMapContents));
1881 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1882 FaultMapContents.bytes_end());
1887 static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) {
1889 printELFFileHeader(O);
1890 printELFDynamicSection(O);
1891 printELFSymbolVersionInfo(O);
1895 return printCOFFFileHeader(O);
1897 return printWasmFileHeader(O);
1899 printMachOFileHeader(O);
1901 printMachOLoadCommands(O);
1904 report_error(O->getFileName(), "Invalid/Unsupported object file format");
1907 static void printFileHeaders(const ObjectFile *O) {
1908 if (!O->isELF() && !O->isCOFF())
1909 report_error(O->getFileName(), "Invalid/Unsupported object file format");
1911 Triple::ArchType AT = O->getArch();
1912 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
1913 Expected<uint64_t> StartAddrOrErr = O->getStartAddress();
1914 if (!StartAddrOrErr)
1915 report_error(O->getFileName(), StartAddrOrErr.takeError());
1917 StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1918 uint64_t Address = StartAddrOrErr.get();
1919 outs() << "start address: "
1920 << "0x" << format(Fmt.data(), Address) << "\n\n";
1923 static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
1924 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
1926 WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n";
1927 consumeError(ModeOrErr.takeError());
1930 sys::fs::perms Mode = ModeOrErr.get();
1931 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1932 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1933 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1934 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1935 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1936 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1937 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1938 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1939 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
1943 Expected<unsigned> UIDOrErr = C.getUID();
1945 report_error(Filename, UIDOrErr.takeError());
1946 unsigned UID = UIDOrErr.get();
1947 outs() << format("%d/", UID);
1949 Expected<unsigned> GIDOrErr = C.getGID();
1951 report_error(Filename, GIDOrErr.takeError());
1952 unsigned GID = GIDOrErr.get();
1953 outs() << format("%-d ", GID);
1955 Expected<uint64_t> Size = C.getRawSize();
1957 report_error(Filename, Size.takeError());
1958 outs() << format("%6" PRId64, Size.get()) << " ";
1960 StringRef RawLastModified = C.getRawLastModified();
1962 if (RawLastModified.getAsInteger(10, Seconds))
1963 outs() << "(date: \"" << RawLastModified
1964 << "\" contains non-decimal chars) ";
1966 // Since ctime(3) returns a 26 character string of the form:
1967 // "Sun Sep 16 01:03:52 1973\n\0"
1968 // just print 24 characters.
1970 outs() << format("%.24s ", ctime(&t));
1973 StringRef Name = "";
1974 Expected<StringRef> NameOrErr = C.getName();
1976 consumeError(NameOrErr.takeError());
1977 Expected<StringRef> RawNameOrErr = C.getRawName();
1979 report_error(Filename, NameOrErr.takeError());
1980 Name = RawNameOrErr.get();
1982 Name = NameOrErr.get();
1984 outs() << Name << "\n";
1987 static void dumpObject(ObjectFile *O, const Archive *A = nullptr,
1988 const Archive::Child *C = nullptr) {
1989 // Avoid other output when using a raw option.
1993 outs() << A->getFileName() << "(" << O->getFileName() << ")";
1995 outs() << O->getFileName();
1996 outs() << ":\tfile format " << O->getFileFormatName() << "\n\n";
1999 StringRef ArchiveName = A ? A->getFileName() : "";
2001 printFileHeaders(O);
2002 if (ArchiveHeaders && !MachOOpt && C)
2003 printArchiveChild(ArchiveName, *C);
2005 disassembleObject(O, Relocations);
2006 if (Relocations && !Disassemble)
2007 printRelocations(O);
2008 if (DynamicRelocations)
2009 printDynamicRelocations(O);
2011 printSectionHeaders(O);
2012 if (SectionContents)
2013 printSectionContents(O);
2015 printSymbolTable(O, ArchiveName);
2018 if (PrivateHeaders || FirstPrivateHeader)
2019 printPrivateFileHeaders(O, FirstPrivateHeader);
2021 printExportsTrie(O);
2023 printRebaseTable(O);
2027 printLazyBindTable(O);
2029 printWeakBindTable(O);
2031 printRawClangAST(O);
2034 if (DwarfDumpType != DIDT_Null) {
2035 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O);
2036 // Dump the complete DWARF structure.
2037 DIDumpOptions DumpOpts;
2038 DumpOpts.DumpType = DwarfDumpType;
2039 DICtx->dump(outs(), DumpOpts);
2043 static void dumpObject(const COFFImportFile *I, const Archive *A,
2044 const Archive::Child *C = nullptr) {
2045 StringRef ArchiveName = A ? A->getFileName() : "";
2047 // Avoid other output when using a raw option.
2050 << ArchiveName << "(" << I->getFileName() << ")"
2051 << ":\tfile format COFF-import-file"
2054 if (ArchiveHeaders && !MachOOpt && C)
2055 printArchiveChild(ArchiveName, *C);
2057 printCOFFSymbolTable(I);
2060 /// Dump each object file in \a a;
2061 static void dumpArchive(const Archive *A) {
2062 Error Err = Error::success();
2063 for (auto &C : A->children(Err)) {
2064 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2066 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2067 report_error(A->getFileName(), C, std::move(E));
2070 if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2071 dumpObject(O, A, &C);
2072 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2073 dumpObject(I, A, &C);
2075 report_error(A->getFileName(), object_error::invalid_file_type);
2078 report_error(A->getFileName(), std::move(Err));
2081 /// Open file and figure out how to dump it.
2082 static void dumpInput(StringRef file) {
2083 // If we are using the Mach-O specific object file parser, then let it parse
2084 // the file and process the command line options. So the -arch flags can
2085 // be used to select specific slices, etc.
2087 parseInputMachO(file);
2091 // Attempt to open the binary.
2092 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2094 report_error(file, BinaryOrErr.takeError());
2095 Binary &Binary = *BinaryOrErr.get().getBinary();
2097 if (Archive *A = dyn_cast<Archive>(&Binary))
2099 else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary))
2101 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
2102 parseInputMachO(UB);
2104 report_error(file, object_error::invalid_file_type);
2107 int main(int argc, char **argv) {
2108 InitLLVM X(argc, argv);
2110 // Initialize targets and assembly printers/parsers.
2111 llvm::InitializeAllTargetInfos();
2112 llvm::InitializeAllTargetMCs();
2113 llvm::InitializeAllDisassemblers();
2115 // Register the target printer for --version.
2116 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2118 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2122 // Defaults to a.out if no filenames specified.
2123 if (InputFilenames.empty())
2124 InputFilenames.push_back("a.out");
2127 ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations =
2128 SectionHeaders = SymbolTable = true;
2130 if (DisassembleAll || PrintSource || PrintLines)
2135 && !DynamicRelocations
2142 && !FirstPrivateHeader
2149 && !(UniversalHeaders && MachOOpt)
2151 && !(IndirectSymbols && MachOOpt)
2152 && !(DataInCode && MachOOpt)
2153 && !(LinkOptHints && MachOOpt)
2154 && !(InfoPlist && MachOOpt)
2155 && !(DylibsUsed && MachOOpt)
2156 && !(DylibId && MachOOpt)
2157 && !(ObjcMetaData && MachOOpt)
2158 && !(!FilterSections.empty() && MachOOpt)
2160 && DwarfDumpType == DIDT_Null) {
2161 cl::PrintHelpMessage();
2165 DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2166 DisassembleFunctions.end());
2168 llvm::for_each(InputFilenames, dumpInput);
2170 return EXIT_SUCCESS;