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/SetOperations.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringSet.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/CodeGen/FaultMaps.h"
26 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
27 #include "llvm/DebugInfo/Symbolize/Symbolize.h"
28 #include "llvm/Demangle/Demangle.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/MC/MCContext.h"
31 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
32 #include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
33 #include "llvm/MC/MCInst.h"
34 #include "llvm/MC/MCInstPrinter.h"
35 #include "llvm/MC/MCInstrAnalysis.h"
36 #include "llvm/MC/MCInstrInfo.h"
37 #include "llvm/MC/MCObjectFileInfo.h"
38 #include "llvm/MC/MCRegisterInfo.h"
39 #include "llvm/MC/MCSubtargetInfo.h"
40 #include "llvm/Object/Archive.h"
41 #include "llvm/Object/COFF.h"
42 #include "llvm/Object/COFFImportFile.h"
43 #include "llvm/Object/ELFObjectFile.h"
44 #include "llvm/Object/MachO.h"
45 #include "llvm/Object/MachOUniversal.h"
46 #include "llvm/Object/ObjectFile.h"
47 #include "llvm/Object/Wasm.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/Errc.h"
52 #include "llvm/Support/FileSystem.h"
53 #include "llvm/Support/Format.h"
54 #include "llvm/Support/GraphWriter.h"
55 #include "llvm/Support/Host.h"
56 #include "llvm/Support/InitLLVM.h"
57 #include "llvm/Support/MemoryBuffer.h"
58 #include "llvm/Support/SourceMgr.h"
59 #include "llvm/Support/StringSaver.h"
60 #include "llvm/Support/TargetRegistry.h"
61 #include "llvm/Support/TargetSelect.h"
62 #include "llvm/Support/WithColor.h"
63 #include "llvm/Support/raw_ostream.h"
67 #include <system_error>
68 #include <unordered_map>
71 using namespace llvm::object;
75 cl::OptionCategory ObjdumpCat("llvm-objdump Options");
78 extern cl::OptionCategory MachOCat;
79 extern cl::opt<bool> Bind;
80 extern cl::opt<bool> DataInCode;
81 extern cl::opt<bool> DylibsUsed;
82 extern cl::opt<bool> DylibId;
83 extern cl::opt<bool> ExportsTrie;
84 extern cl::opt<bool> FirstPrivateHeader;
85 extern cl::opt<bool> IndirectSymbols;
86 extern cl::opt<bool> InfoPlist;
87 extern cl::opt<bool> LazyBind;
88 extern cl::opt<bool> LinkOptHints;
89 extern cl::opt<bool> ObjcMetaData;
90 extern cl::opt<bool> Rebase;
91 extern cl::opt<bool> UniversalHeaders;
92 extern cl::opt<bool> WeakBind;
94 static cl::opt<uint64_t> AdjustVMA(
96 cl::desc("Increase the displayed address by the specified offset"),
97 cl::value_desc("offset"), cl::init(0), cl::cat(ObjdumpCat));
100 AllHeaders("all-headers",
101 cl::desc("Display all available header information"),
102 cl::cat(ObjdumpCat));
103 static cl::alias AllHeadersShort("x", cl::desc("Alias for --all-headers"),
104 cl::NotHidden, cl::Grouping,
105 cl::aliasopt(AllHeaders));
107 static cl::opt<std::string>
108 ArchName("arch-name",
109 cl::desc("Target arch to disassemble for, "
110 "see -version for available targets"),
111 cl::cat(ObjdumpCat));
113 cl::opt<bool> ArchiveHeaders("archive-headers",
114 cl::desc("Display archive header information"),
115 cl::cat(ObjdumpCat));
116 static cl::alias ArchiveHeadersShort("a",
117 cl::desc("Alias for --archive-headers"),
118 cl::NotHidden, cl::Grouping,
119 cl::aliasopt(ArchiveHeaders));
121 cl::opt<bool> Demangle("demangle", cl::desc("Demangle symbols names"),
122 cl::init(false), cl::cat(ObjdumpCat));
123 static cl::alias DemangleShort("C", cl::desc("Alias for --demangle"),
124 cl::NotHidden, cl::Grouping,
125 cl::aliasopt(Demangle));
127 cl::opt<bool> Disassemble(
129 cl::desc("Display assembler mnemonics for the machine instructions"),
130 cl::cat(ObjdumpCat));
131 static cl::alias DisassembleShort("d", cl::desc("Alias for --disassemble"),
132 cl::NotHidden, cl::Grouping,
133 cl::aliasopt(Disassemble));
135 cl::opt<bool> DisassembleAll(
137 cl::desc("Display assembler mnemonics for the machine instructions"),
138 cl::cat(ObjdumpCat));
139 static cl::alias DisassembleAllShort("D",
140 cl::desc("Alias for --disassemble-all"),
141 cl::NotHidden, cl::Grouping,
142 cl::aliasopt(DisassembleAll));
144 static cl::list<std::string>
145 DisassembleFunctions("disassemble-functions", cl::CommaSeparated,
146 cl::desc("List of functions to disassemble"),
147 cl::cat(ObjdumpCat));
149 static cl::opt<bool> DisassembleZeroes(
150 "disassemble-zeroes",
151 cl::desc("Do not skip blocks of zeroes when disassembling"),
152 cl::cat(ObjdumpCat));
154 DisassembleZeroesShort("z", cl::desc("Alias for --disassemble-zeroes"),
155 cl::NotHidden, cl::Grouping,
156 cl::aliasopt(DisassembleZeroes));
158 static cl::list<std::string>
159 DisassemblerOptions("disassembler-options",
160 cl::desc("Pass target specific disassembler options"),
161 cl::value_desc("options"), cl::CommaSeparated,
162 cl::cat(ObjdumpCat));
164 DisassemblerOptionsShort("M", cl::desc("Alias for --disassembler-options"),
165 cl::NotHidden, cl::Grouping, cl::Prefix,
167 cl::aliasopt(DisassemblerOptions));
169 cl::opt<DIDumpType> DwarfDumpType(
170 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
171 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")),
172 cl::cat(ObjdumpCat));
174 static cl::opt<bool> DynamicRelocations(
176 cl::desc("Display the dynamic relocation entries in the file"),
177 cl::cat(ObjdumpCat));
178 static cl::alias DynamicRelocationShort("R",
179 cl::desc("Alias for --dynamic-reloc"),
180 cl::NotHidden, cl::Grouping,
181 cl::aliasopt(DynamicRelocations));
184 FaultMapSection("fault-map-section",
185 cl::desc("Display contents of faultmap section"),
186 cl::cat(ObjdumpCat));
189 FileHeaders("file-headers",
190 cl::desc("Display the contents of the overall file header"),
191 cl::cat(ObjdumpCat));
192 static cl::alias FileHeadersShort("f", cl::desc("Alias for --file-headers"),
193 cl::NotHidden, cl::Grouping,
194 cl::aliasopt(FileHeaders));
196 cl::opt<bool> SectionContents("full-contents",
197 cl::desc("Display the content of each section"),
198 cl::cat(ObjdumpCat));
199 static cl::alias SectionContentsShort("s",
200 cl::desc("Alias for --full-contents"),
201 cl::NotHidden, cl::Grouping,
202 cl::aliasopt(SectionContents));
204 static cl::list<std::string> InputFilenames(cl::Positional,
205 cl::desc("<input object files>"),
207 cl::cat(ObjdumpCat));
210 PrintLines("line-numbers",
211 cl::desc("Display source line numbers with "
212 "disassembly. Implies disassemble object"),
213 cl::cat(ObjdumpCat));
214 static cl::alias PrintLinesShort("l", cl::desc("Alias for --line-numbers"),
215 cl::NotHidden, cl::Grouping,
216 cl::aliasopt(PrintLines));
218 static cl::opt<bool> MachOOpt("macho",
219 cl::desc("Use MachO specific object file parser"),
220 cl::cat(ObjdumpCat));
221 static cl::alias MachOm("m", cl::desc("Alias for --macho"), cl::NotHidden,
222 cl::Grouping, cl::aliasopt(MachOOpt));
226 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
227 cl::value_desc("cpu-name"), cl::init(""), cl::cat(ObjdumpCat));
229 cl::list<std::string> MAttrs("mattr", cl::CommaSeparated,
230 cl::desc("Target specific attributes"),
231 cl::value_desc("a1,+a2,-a3,..."),
232 cl::cat(ObjdumpCat));
234 cl::opt<bool> NoShowRawInsn("no-show-raw-insn",
235 cl::desc("When disassembling "
236 "instructions, do not print "
237 "the instruction bytes."),
238 cl::cat(ObjdumpCat));
239 cl::opt<bool> NoLeadingAddr("no-leading-addr",
240 cl::desc("Print no leading address"),
241 cl::cat(ObjdumpCat));
243 static cl::opt<bool> RawClangAST(
245 cl::desc("Dump the raw binary contents of the clang AST section"),
246 cl::cat(ObjdumpCat));
249 Relocations("reloc", cl::desc("Display the relocation entries in the file"),
250 cl::cat(ObjdumpCat));
251 static cl::alias RelocationsShort("r", cl::desc("Alias for --reloc"),
252 cl::NotHidden, cl::Grouping,
253 cl::aliasopt(Relocations));
255 cl::opt<bool> PrintImmHex("print-imm-hex",
256 cl::desc("Use hex format for immediate values"),
257 cl::cat(ObjdumpCat));
259 cl::opt<bool> PrivateHeaders("private-headers",
260 cl::desc("Display format specific file headers"),
261 cl::cat(ObjdumpCat));
262 static cl::alias PrivateHeadersShort("p",
263 cl::desc("Alias for --private-headers"),
264 cl::NotHidden, cl::Grouping,
265 cl::aliasopt(PrivateHeaders));
267 cl::list<std::string>
268 FilterSections("section",
269 cl::desc("Operate on the specified sections only. "
270 "With -macho dump segment,section"),
271 cl::cat(ObjdumpCat));
272 static cl::alias FilterSectionsj("j", cl::desc("Alias for --section"),
273 cl::NotHidden, cl::Grouping, cl::Prefix,
274 cl::aliasopt(FilterSections));
276 cl::opt<bool> SectionHeaders("section-headers",
277 cl::desc("Display summaries of the "
278 "headers for each section."),
279 cl::cat(ObjdumpCat));
280 static cl::alias SectionHeadersShort("headers",
281 cl::desc("Alias for --section-headers"),
283 cl::aliasopt(SectionHeaders));
284 static cl::alias SectionHeadersShorter("h",
285 cl::desc("Alias for --section-headers"),
286 cl::NotHidden, cl::Grouping,
287 cl::aliasopt(SectionHeaders));
291 cl::desc("Display LMA column when dumping ELF section headers"),
292 cl::cat(ObjdumpCat));
294 static cl::opt<bool> PrintSource(
297 "Display source inlined with disassembly. Implies disassemble object"),
298 cl::cat(ObjdumpCat));
299 static cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
300 cl::NotHidden, cl::Grouping,
301 cl::aliasopt(PrintSource));
303 static cl::opt<uint64_t>
304 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
305 cl::value_desc("address"), cl::init(0), cl::cat(ObjdumpCat));
306 static cl::opt<uint64_t> StopAddress("stop-address",
307 cl::desc("Stop disassembly at address"),
308 cl::value_desc("address"),
309 cl::init(UINT64_MAX), cl::cat(ObjdumpCat));
311 cl::opt<bool> SymbolTable("syms", cl::desc("Display the symbol table"),
312 cl::cat(ObjdumpCat));
313 static cl::alias SymbolTableShort("t", cl::desc("Alias for --syms"),
314 cl::NotHidden, cl::Grouping,
315 cl::aliasopt(SymbolTable));
317 cl::opt<std::string> TripleName("triple",
318 cl::desc("Target triple to disassemble for, "
319 "see -version for available targets"),
320 cl::cat(ObjdumpCat));
322 cl::opt<bool> UnwindInfo("unwind-info", cl::desc("Display unwind information"),
323 cl::cat(ObjdumpCat));
324 static cl::alias UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
325 cl::NotHidden, cl::Grouping,
326 cl::aliasopt(UnwindInfo));
329 Wide("wide", cl::desc("Ignored for compatibility with GNU objdump"),
330 cl::cat(ObjdumpCat));
331 static cl::alias WideShort("w", cl::Grouping, cl::aliasopt(Wide));
333 static StringSet<> DisasmFuncsSet;
334 static StringRef ToolName;
336 typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
338 static bool shouldKeep(object::SectionRef S) {
339 if (FilterSections.empty())
342 std::error_code error = S.getName(String);
345 return is_contained(FilterSections, String);
348 SectionFilter ToolSectionFilter(object::ObjectFile const &O) {
349 return SectionFilter([](object::SectionRef S) { return shouldKeep(S); }, O);
352 void error(std::error_code EC) {
355 WithColor::error(errs(), ToolName)
356 << "reading file: " << EC.message() << ".\n";
361 void error(Error E) {
364 WithColor::error(errs(), ToolName) << toString(std::move(E));
368 LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
369 WithColor::error(errs(), ToolName) << Message << ".\n";
374 void warn(StringRef Message) {
375 WithColor::warning(errs(), ToolName) << Message << ".\n";
379 void warn(Twine Message) {
380 WithColor::warning(errs(), ToolName) << Message << "\n";
383 LLVM_ATTRIBUTE_NORETURN void report_error(StringRef File, Twine Message) {
384 WithColor::error(errs(), ToolName)
385 << "'" << File << "': " << Message << ".\n";
389 LLVM_ATTRIBUTE_NORETURN void report_error(Error E, StringRef File) {
392 raw_string_ostream OS(Buf);
393 logAllUnhandledErrors(std::move(E), OS);
395 WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf;
399 LLVM_ATTRIBUTE_NORETURN void report_error(Error E, StringRef ArchiveName,
401 StringRef ArchitectureName) {
403 WithColor::error(errs(), ToolName);
404 if (ArchiveName != "")
405 errs() << ArchiveName << "(" << FileName << ")";
407 errs() << "'" << FileName << "'";
408 if (!ArchitectureName.empty())
409 errs() << " (for architecture " << ArchitectureName << ")";
411 raw_string_ostream OS(Buf);
412 logAllUnhandledErrors(std::move(E), OS);
414 errs() << ": " << Buf;
418 LLVM_ATTRIBUTE_NORETURN void report_error(Error E, StringRef ArchiveName,
419 const object::Archive::Child &C,
420 StringRef ArchitectureName) {
421 Expected<StringRef> NameOrErr = C.getName();
422 // TODO: if we have a error getting the name then it would be nice to print
423 // the index of which archive member this is and or its offset in the
424 // archive instead of "???" as the name.
426 consumeError(NameOrErr.takeError());
427 report_error(std::move(E), ArchiveName, "???", ArchitectureName);
429 report_error(std::move(E), ArchiveName, NameOrErr.get(), ArchitectureName);
432 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
433 // Figure out the target triple.
434 Triple TheTriple("unknown-unknown-unknown");
435 if (TripleName.empty()) {
437 TheTriple = Obj->makeTriple();
439 TheTriple.setTriple(Triple::normalize(TripleName));
441 // Use the triple, but also try to combine with ARM build attributes.
443 auto Arch = Obj->getArch();
444 if (Arch == Triple::arm || Arch == Triple::armeb)
445 Obj->setARMSubArch(TheTriple);
449 // Get the target specific parser.
451 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
455 report_error(Obj->getFileName(), "can't find target: " + Error);
457 error("can't find target: " + Error);
460 // Update the triple name and return the found target.
461 TripleName = TheTriple.getTriple();
465 bool isRelocAddressLess(RelocationRef A, RelocationRef B) {
466 return A.getOffset() < B.getOffset();
469 static Error getRelocationValueString(const RelocationRef &Rel,
470 SmallVectorImpl<char> &Result) {
471 const ObjectFile *Obj = Rel.getObject();
472 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
473 return getELFRelocationValueString(ELF, Rel, Result);
474 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
475 return getCOFFRelocationValueString(COFF, Rel, Result);
476 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
477 return getWasmRelocationValueString(Wasm, Rel, Result);
478 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
479 return getMachORelocationValueString(MachO, Rel, Result);
480 llvm_unreachable("unknown object file format");
483 /// Indicates whether this relocation should hidden when listing
484 /// relocations, usually because it is the trailing part of a multipart
485 /// relocation that will be printed as part of the leading relocation.
486 static bool getHidden(RelocationRef RelRef) {
487 auto *MachO = dyn_cast<MachOObjectFile>(RelRef.getObject());
491 unsigned Arch = MachO->getArch();
492 DataRefImpl Rel = RelRef.getRawDataRefImpl();
493 uint64_t Type = MachO->getRelocationType(Rel);
495 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
497 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc)
498 return Type == MachO::GENERIC_RELOC_PAIR;
500 if (Arch == Triple::x86_64) {
501 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
502 // an X86_64_RELOC_SUBTRACTOR.
503 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
504 DataRefImpl RelPrev = Rel;
506 uint64_t PrevType = MachO->getRelocationType(RelPrev);
507 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
516 class SourcePrinter {
518 DILineInfo OldLineInfo;
519 const ObjectFile *Obj = nullptr;
520 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
521 // File name to file contents of source
522 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
523 // Mark the line endings of the cached source
524 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
527 bool cacheSource(const DILineInfo& LineInfoFile);
530 SourcePrinter() = default;
531 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
532 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
533 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
535 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
537 virtual ~SourcePrinter() = default;
538 virtual void printSourceLine(raw_ostream &OS,
539 object::SectionedAddress Address,
540 StringRef Delimiter = "; ");
543 bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
544 std::unique_ptr<MemoryBuffer> Buffer;
545 if (LineInfo.Source) {
546 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);
548 auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName);
551 Buffer = std::move(*BufferOrError);
553 // Chomp the file to get lines
554 const char *BufferStart = Buffer->getBufferStart(),
555 *BufferEnd = Buffer->getBufferEnd();
556 std::vector<StringRef> &Lines = LineCache[LineInfo.FileName];
557 const char *Start = BufferStart;
558 for (const char *I = BufferStart; I != BufferEnd; ++I)
560 Lines.emplace_back(Start, I - Start - (BufferStart < I && I[-1] == '\r'));
563 if (Start < BufferEnd)
564 Lines.emplace_back(Start, BufferEnd - Start);
565 SourceCache[LineInfo.FileName] = std::move(Buffer);
569 void SourcePrinter::printSourceLine(raw_ostream &OS,
570 object::SectionedAddress Address,
571 StringRef Delimiter) {
574 DILineInfo LineInfo = DILineInfo();
575 auto ExpectedLineInfo =
576 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
577 if (!ExpectedLineInfo)
578 consumeError(ExpectedLineInfo.takeError());
580 LineInfo = *ExpectedLineInfo;
582 if ((LineInfo.FileName == "<invalid>") || LineInfo.Line == 0 ||
583 ((OldLineInfo.Line == LineInfo.Line) &&
584 (OldLineInfo.FileName == LineInfo.FileName)))
588 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
590 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
591 if (!cacheSource(LineInfo))
593 auto LineBuffer = LineCache.find(LineInfo.FileName);
594 if (LineBuffer != LineCache.end()) {
595 if (LineInfo.Line > LineBuffer->second.size())
597 // Vector begins at 0, line numbers are non-zero
598 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1] << '\n';
601 OldLineInfo = LineInfo;
604 static bool isArmElf(const ObjectFile *Obj) {
605 return (Obj->isELF() &&
606 (Obj->getArch() == Triple::aarch64 ||
607 Obj->getArch() == Triple::aarch64_be ||
608 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
609 Obj->getArch() == Triple::thumb ||
610 Obj->getArch() == Triple::thumbeb));
613 static void printRelocation(const RelocationRef &Rel, uint64_t Address,
616 AddrSize > 4 ? "\t\t%016" PRIx64 ": " : "\t\t\t%08" PRIx64 ": ";
617 SmallString<16> Name;
619 Rel.getTypeName(Name);
620 error(getRelocationValueString(Rel, Val));
621 outs() << format(Fmt.data(), Address) << Name << "\t" << Val << "\n";
624 class PrettyPrinter {
626 virtual ~PrettyPrinter() = default;
627 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
628 ArrayRef<uint8_t> Bytes,
629 object::SectionedAddress Address, raw_ostream &OS,
630 StringRef Annot, MCSubtargetInfo const &STI,
632 std::vector<RelocationRef> *Rels = nullptr) {
633 if (SP && (PrintSource || PrintLines))
634 SP->printSourceLine(OS, Address);
637 formatted_raw_ostream FOS(OS);
639 FOS << format("%8" PRIx64 ":", Address.Address);
640 if (!NoShowRawInsn) {
642 dumpBytes(Bytes, FOS);
645 // The output of printInst starts with a tab. Print some spaces so that
646 // the tab has 1 column and advances to the target tab stop.
647 unsigned TabStop = NoShowRawInsn ? 16 : 40;
648 unsigned Column = FOS.getColumn();
649 FOS.indent(Column < TabStop - 1 ? TabStop - 1 - Column : 7 - Column % 8);
651 // The dtor calls flush() to ensure the indent comes before printInst().
655 IP.printInst(MI, OS, "", STI);
660 PrettyPrinter PrettyPrinterInst;
661 class HexagonPrettyPrinter : public PrettyPrinter {
663 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
666 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
668 OS << format("%8" PRIx64 ":", Address);
669 if (!NoShowRawInsn) {
671 dumpBytes(Bytes.slice(0, 4), OS);
672 OS << format("\t%08" PRIx32, opcode);
675 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
676 object::SectionedAddress Address, raw_ostream &OS,
677 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
678 std::vector<RelocationRef> *Rels) override {
679 if (SP && (PrintSource || PrintLines))
680 SP->printSourceLine(OS, Address, "");
682 printLead(Bytes, Address.Address, OS);
688 raw_string_ostream TempStream(Buffer);
689 IP.printInst(MI, TempStream, "", STI);
691 StringRef Contents(Buffer);
692 // Split off bundle attributes
693 auto PacketBundle = Contents.rsplit('\n');
694 // Split off first instruction from the rest
695 auto HeadTail = PacketBundle.first.split('\n');
696 auto Preamble = " { ";
699 // Hexagon's packets require relocations to be inline rather than
700 // clustered at the end of the packet.
701 std::vector<RelocationRef>::const_iterator RelCur = Rels->begin();
702 std::vector<RelocationRef>::const_iterator RelEnd = Rels->end();
703 auto PrintReloc = [&]() -> void {
704 while ((RelCur != RelEnd) && (RelCur->getOffset() <= Address.Address)) {
705 if (RelCur->getOffset() == Address.Address) {
706 printRelocation(*RelCur, Address.Address, 4);
713 while (!HeadTail.first.empty()) {
716 if (SP && (PrintSource || PrintLines))
717 SP->printSourceLine(OS, Address, "");
718 printLead(Bytes, Address.Address, OS);
722 auto Duplex = HeadTail.first.split('\v');
723 if (!Duplex.second.empty()) {
726 Inst = Duplex.second;
729 Inst = HeadTail.first;
731 HeadTail = HeadTail.second.split('\n');
732 if (HeadTail.first.empty())
733 OS << " } " << PacketBundle.second;
735 Bytes = Bytes.slice(4);
736 Address.Address += 4;
740 HexagonPrettyPrinter HexagonPrettyPrinterInst;
742 class AMDGCNPrettyPrinter : public PrettyPrinter {
744 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
745 object::SectionedAddress Address, raw_ostream &OS,
746 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
747 std::vector<RelocationRef> *Rels) override {
748 if (SP && (PrintSource || PrintLines))
749 SP->printSourceLine(OS, Address);
751 typedef support::ulittle32_t U32;
754 SmallString<40> InstStr;
755 raw_svector_ostream IS(InstStr);
757 IP.printInst(MI, IS, "", STI);
759 OS << left_justify(IS.str(), 60);
761 // an unrecognized encoding - this is probably data so represent it
762 // using the .long directive, or .byte directive if fewer than 4 bytes
764 if (Bytes.size() >= 4) {
765 OS << format("\t.long 0x%08" PRIx32 " ",
766 static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data())));
769 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
770 for (unsigned int i = 1; i < Bytes.size(); i++)
771 OS << format(", 0x%02" PRIx8, Bytes[i]);
772 OS.indent(55 - (6 * Bytes.size()));
776 OS << format("// %012" PRIX64 ": ", Address.Address);
777 if (Bytes.size() >=4) {
778 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
779 Bytes.size() / sizeof(U32)))
780 // D should be explicitly casted to uint32_t here as it is passed
781 // by format to snprintf as vararg.
782 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
784 for (unsigned int i = 0; i < Bytes.size(); i++)
785 OS << format("%02" PRIX8 " ", Bytes[i]);
789 OS << "// " << Annot;
792 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
794 class BPFPrettyPrinter : public PrettyPrinter {
796 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
797 object::SectionedAddress Address, raw_ostream &OS,
798 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
799 std::vector<RelocationRef> *Rels) override {
800 if (SP && (PrintSource || PrintLines))
801 SP->printSourceLine(OS, Address);
803 OS << format("%8" PRId64 ":", Address.Address / 8);
804 if (!NoShowRawInsn) {
806 dumpBytes(Bytes, OS);
809 IP.printInst(MI, OS, "", STI);
814 BPFPrettyPrinter BPFPrettyPrinterInst;
816 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
817 switch(Triple.getArch()) {
819 return PrettyPrinterInst;
820 case Triple::hexagon:
821 return HexagonPrettyPrinterInst;
823 return AMDGCNPrettyPrinterInst;
826 return BPFPrettyPrinterInst;
831 static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
832 assert(Obj->isELF());
833 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
834 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
835 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
836 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
837 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
838 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
839 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
840 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
841 llvm_unreachable("Unsupported binary format");
844 template <class ELFT> static void
845 addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
846 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
847 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
848 uint8_t SymbolType = Symbol.getELFType();
849 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
852 uint64_t Address = unwrapOrError(Symbol.getAddress(), Obj->getFileName());
853 StringRef Name = unwrapOrError(Symbol.getName(), Obj->getFileName());
857 section_iterator SecI =
858 unwrapOrError(Symbol.getSection(), Obj->getFileName());
859 if (SecI == Obj->section_end())
862 AllSymbols[*SecI].emplace_back(Address, Name, SymbolType);
867 addDynamicElfSymbols(const ObjectFile *Obj,
868 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
869 assert(Obj->isELF());
870 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
871 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
872 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
873 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
874 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
875 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
876 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
877 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
879 llvm_unreachable("Unsupported binary format");
882 static void addPltEntries(const ObjectFile *Obj,
883 std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
884 StringSaver &Saver) {
885 Optional<SectionRef> Plt = None;
886 for (const SectionRef &Section : Obj->sections()) {
888 if (Section.getName(Name))
895 if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) {
896 for (auto PltEntry : ElfObj->getPltAddresses()) {
897 SymbolRef Symbol(PltEntry.first, ElfObj);
898 uint8_t SymbolType = getElfSymbolType(Obj, Symbol);
900 StringRef Name = unwrapOrError(Symbol.getName(), Obj->getFileName());
902 AllSymbols[*Plt].emplace_back(
903 PltEntry.second, Saver.save((Name + "@plt").str()), SymbolType);
908 // Normally the disassembly output will skip blocks of zeroes. This function
909 // returns the number of zero bytes that can be skipped when dumping the
910 // disassembly of the instructions in Buf.
911 static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) {
912 // Find the number of leading zeroes.
914 while (N < Buf.size() && !Buf[N])
917 // We may want to skip blocks of zero bytes, but unless we see
918 // at least 8 of them in a row.
922 // We skip zeroes in multiples of 4 because do not want to truncate an
923 // instruction if it starts with a zero byte.
927 // Returns a map from sections to their relocations.
928 static std::map<SectionRef, std::vector<RelocationRef>>
929 getRelocsMap(object::ObjectFile const &Obj) {
930 std::map<SectionRef, std::vector<RelocationRef>> Ret;
931 for (SectionRef Sec : Obj.sections()) {
932 section_iterator Relocated = Sec.getRelocatedSection();
933 if (Relocated == Obj.section_end() || !shouldKeep(*Relocated))
935 std::vector<RelocationRef> &V = Ret[*Relocated];
936 for (const RelocationRef &R : Sec.relocations())
938 // Sort relocations by address.
939 llvm::stable_sort(V, isRelocAddressLess);
944 // Used for --adjust-vma to check if address should be adjusted by the
945 // specified value for a given section.
946 // For ELF we do not adjust non-allocatable sections like debug ones,
947 // because they are not loadable.
948 // TODO: implement for other file formats.
949 static bool shouldAdjustVA(const SectionRef &Section) {
950 const ObjectFile *Obj = Section.getObject();
951 if (isa<object::ELFObjectFileBase>(Obj))
952 return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
957 dumpARMELFData(uint64_t SectionAddr, uint64_t Index, uint64_t End,
958 const ObjectFile *Obj, ArrayRef<uint8_t> Bytes,
959 const std::vector<uint64_t> &TextMappingSymsAddr) {
960 support::endianness Endian =
961 Obj->isLittleEndian() ? support::little : support::big;
962 while (Index < End) {
963 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
965 if (Index + 4 <= End) {
966 dumpBytes(Bytes.slice(Index, 4), outs());
967 outs() << "\t.word\t"
969 support::endian::read32(Bytes.data() + Index, Endian), 10);
971 } else if (Index + 2 <= End) {
972 dumpBytes(Bytes.slice(Index, 2), outs());
973 outs() << "\t\t.short\t"
975 support::endian::read16(Bytes.data() + Index, Endian), 6);
978 dumpBytes(Bytes.slice(Index, 1), outs());
979 outs() << "\t\t.byte\t" << format_hex(Bytes[0], 4);
983 if (std::binary_search(TextMappingSymsAddr.begin(),
984 TextMappingSymsAddr.end(), Index))
990 static void dumpELFData(uint64_t SectionAddr, uint64_t Index, uint64_t End,
991 ArrayRef<uint8_t> Bytes) {
992 // print out data up to 8 bytes at a time in hex and ascii
993 uint8_t AsciiData[9] = {'\0'};
997 for (; Index < End; ++Index) {
999 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1002 Byte = Bytes.slice(Index)[0];
1003 outs() << format(" %02x", Byte);
1004 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
1006 uint8_t IndentOffset = 0;
1008 if (Index == End - 1 || NumBytes > 8) {
1009 // Indent the space for less than 8 bytes data.
1010 // 2 spaces for byte and one for space between bytes
1011 IndentOffset = 3 * (8 - NumBytes);
1012 for (int Excess = NumBytes; Excess < 8; Excess++)
1013 AsciiData[Excess] = '\0';
1016 if (NumBytes == 8) {
1017 AsciiData[8] = '\0';
1018 outs() << std::string(IndentOffset, ' ') << " ";
1019 outs() << reinterpret_cast<char *>(AsciiData);
1026 static void disassembleObject(const Target *TheTarget, const ObjectFile *Obj,
1027 MCContext &Ctx, MCDisassembler *DisAsm,
1028 const MCInstrAnalysis *MIA, MCInstPrinter *IP,
1029 const MCSubtargetInfo *STI, PrettyPrinter &PIP,
1030 SourcePrinter &SP, bool InlineRelocs) {
1031 std::map<SectionRef, std::vector<RelocationRef>> RelocMap;
1033 RelocMap = getRelocsMap(*Obj);
1035 // Create a mapping from virtual address to symbol name. This is used to
1036 // pretty print the symbols while disassembling.
1037 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1038 SectionSymbolsTy AbsoluteSymbols;
1039 const StringRef FileName = Obj->getFileName();
1040 for (const SymbolRef &Symbol : Obj->symbols()) {
1041 uint64_t Address = unwrapOrError(Symbol.getAddress(), FileName);
1043 StringRef Name = unwrapOrError(Symbol.getName(), FileName);
1047 uint8_t SymbolType = ELF::STT_NOTYPE;
1049 SymbolType = getElfSymbolType(Obj, Symbol);
1050 if (SymbolType == ELF::STT_SECTION)
1054 section_iterator SecI = unwrapOrError(Symbol.getSection(), FileName);
1055 if (SecI != Obj->section_end())
1056 AllSymbols[*SecI].emplace_back(Address, Name, SymbolType);
1058 AbsoluteSymbols.emplace_back(Address, Name, SymbolType);
1060 if (AllSymbols.empty() && Obj->isELF())
1061 addDynamicElfSymbols(Obj, AllSymbols);
1064 StringSaver Saver(A);
1065 addPltEntries(Obj, AllSymbols, Saver);
1067 // Create a mapping from virtual address to section.
1068 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1069 for (SectionRef Sec : Obj->sections())
1070 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1071 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1073 // Linked executables (.exe and .dll files) typically don't include a real
1074 // symbol table but they might contain an export table.
1075 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1076 for (const auto &ExportEntry : COFFObj->export_directories()) {
1078 error(ExportEntry.getSymbolName(Name));
1082 error(ExportEntry.getExportRVA(RVA));
1084 uint64_t VA = COFFObj->getImageBase() + RVA;
1085 auto Sec = llvm::bsearch(
1086 SectionAddresses, [VA](const std::pair<uint64_t, SectionRef> &RHS) {
1087 return VA < RHS.first;
1089 if (Sec != SectionAddresses.begin()) {
1091 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
1093 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
1097 // Sort all the symbols, this allows us to use a simple binary search to find
1098 // a symbol near an address.
1099 StringSet<> FoundDisasmFuncsSet;
1100 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1101 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1102 array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
1104 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1105 if (FilterSections.empty() && !DisassembleAll &&
1106 (!Section.isText() || Section.isVirtual()))
1109 uint64_t SectionAddr = Section.getAddress();
1110 uint64_t SectSize = Section.getSize();
1114 // Get the list of all the symbols in this section.
1115 SectionSymbolsTy &Symbols = AllSymbols[Section];
1116 std::vector<uint64_t> DataMappingSymsAddr;
1117 std::vector<uint64_t> TextMappingSymsAddr;
1118 if (isArmElf(Obj)) {
1119 for (const auto &Symb : Symbols) {
1120 uint64_t Address = std::get<0>(Symb);
1121 StringRef Name = std::get<1>(Symb);
1122 if (Name.startswith("$d"))
1123 DataMappingSymsAddr.push_back(Address - SectionAddr);
1124 if (Name.startswith("$x"))
1125 TextMappingSymsAddr.push_back(Address - SectionAddr);
1126 if (Name.startswith("$a"))
1127 TextMappingSymsAddr.push_back(Address - SectionAddr);
1128 if (Name.startswith("$t"))
1129 TextMappingSymsAddr.push_back(Address - SectionAddr);
1133 llvm::sort(DataMappingSymsAddr);
1134 llvm::sort(TextMappingSymsAddr);
1136 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1137 // AMDGPU disassembler uses symbolizer for printing labels
1138 std::unique_ptr<MCRelocationInfo> RelInfo(
1139 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1141 std::unique_ptr<MCSymbolizer> Symbolizer(
1142 TheTarget->createMCSymbolizer(
1143 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1144 DisAsm->setSymbolizer(std::move(Symbolizer));
1148 StringRef SegmentName = "";
1149 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
1150 DataRefImpl DR = Section.getRawDataRefImpl();
1151 SegmentName = MachO->getSectionFinalSegmentName(DR);
1153 StringRef SectionName;
1154 error(Section.getName(SectionName));
1156 // If the section has no symbol at the start, just insert a dummy one.
1157 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
1160 std::make_tuple(SectionAddr, SectionName,
1161 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
1164 SmallString<40> Comments;
1165 raw_svector_ostream CommentStream(Comments);
1167 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(
1168 unwrapOrError(Section.getContents(), Obj->getFileName()));
1170 uint64_t VMAAdjustment = 0;
1171 if (shouldAdjustVA(Section))
1172 VMAAdjustment = AdjustVMA;
1176 bool PrintedSection = false;
1177 std::vector<RelocationRef> Rels = RelocMap[Section];
1178 std::vector<RelocationRef>::const_iterator RelCur = Rels.begin();
1179 std::vector<RelocationRef>::const_iterator RelEnd = Rels.end();
1180 // Disassemble symbol by symbol.
1181 for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) {
1182 // Skip if --disassemble-functions is not empty and the symbol is not in
1184 if (!DisasmFuncsSet.empty() &&
1185 !DisasmFuncsSet.count(std::get<1>(Symbols[SI])))
1188 uint64_t Start = std::get<0>(Symbols[SI]);
1189 if (Start < SectionAddr || StopAddress <= Start)
1192 FoundDisasmFuncsSet.insert(std::get<1>(Symbols[SI]));
1194 // The end is the section end, the beginning of the next symbol, or
1196 uint64_t End = std::min<uint64_t>(SectionAddr + SectSize, StopAddress);
1198 End = std::min(End, std::get<0>(Symbols[SI + 1]));
1199 if (Start >= End || End <= StartAddress)
1201 Start -= SectionAddr;
1204 if (!PrintedSection) {
1205 PrintedSection = true;
1206 outs() << "\nDisassembly of section ";
1207 if (!SegmentName.empty())
1208 outs() << SegmentName << ",";
1209 outs() << SectionName << ":\n";
1212 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1213 if (std::get<2>(Symbols[SI]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1214 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1218 std::get<2>(Symbols[SI + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1219 // cut trailing zeroes at the end of kernel
1220 // cut up to 256 bytes
1221 const uint64_t EndAlign = 256;
1222 const auto Limit = End - (std::min)(EndAlign, End - Start);
1223 while (End > Limit &&
1224 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1231 outs() << format("%016" PRIx64 " ",
1232 SectionAddr + Start + VMAAdjustment);
1234 StringRef SymbolName = std::get<1>(Symbols[SI]);
1236 outs() << demangle(SymbolName) << ":\n";
1238 outs() << SymbolName << ":\n";
1240 // Don't print raw contents of a virtual section. A virtual section
1241 // doesn't have any contents in the file.
1242 if (Section.isVirtual()) {
1248 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1250 raw_ostream &DebugOut = nulls();
1253 // Some targets (like WebAssembly) have a special prelude at the start
1255 DisAsm->onSymbolStart(SymbolName, Size, Bytes.slice(Start, End - Start),
1256 SectionAddr + Start, DebugOut, CommentStream);
1260 if (SectionAddr < StartAddress)
1261 Index = std::max<uint64_t>(Index, StartAddress - SectionAddr);
1263 // If there is a data symbol inside an ELF text section and we are
1264 // only disassembling text (applicable all architectures), we are in a
1265 // situation where we must print the data and not disassemble it.
1266 if (Obj->isELF() && std::get<2>(Symbols[SI]) == ELF::STT_OBJECT &&
1267 !DisassembleAll && Section.isText()) {
1268 dumpELFData(SectionAddr, Index, End, Bytes);
1272 bool CheckARMELFData = isArmElf(Obj) &&
1273 std::get<2>(Symbols[SI]) != ELF::STT_OBJECT &&
1275 while (Index < End) {
1276 // AArch64 ELF binaries can interleave data and text in the same
1277 // section. We rely on the markers introduced to understand what we
1278 // need to dump. If the data marker is within a function, it is
1279 // denoted as a word/short etc.
1280 if (CheckARMELFData &&
1281 std::binary_search(DataMappingSymsAddr.begin(),
1282 DataMappingSymsAddr.end(), Index)) {
1283 Index = dumpARMELFData(SectionAddr, Index, End, Obj, Bytes,
1284 TextMappingSymsAddr);
1288 // When -z or --disassemble-zeroes are given we always dissasemble
1289 // them. Otherwise we might want to skip zero bytes we see.
1290 if (!DisassembleZeroes) {
1291 uint64_t MaxOffset = End - Index;
1292 // For -reloc: print zero blocks patched by relocations, so that
1293 // relocations can be shown in the dump.
1294 if (RelCur != RelEnd)
1295 MaxOffset = RelCur->getOffset() - Index;
1298 countSkippableZeroBytes(Bytes.slice(Index, MaxOffset))) {
1299 outs() << "\t\t..." << '\n';
1305 // Disassemble a real instruction or a data when disassemble all is
1308 bool Disassembled = DisAsm->getInstruction(
1309 Inst, Size, Bytes.slice(Index), SectionAddr + Index, DebugOut,
1315 *IP, Disassembled ? &Inst : nullptr, Bytes.slice(Index, Size),
1316 {SectionAddr + Index + VMAAdjustment, Section.getIndex()}, outs(),
1317 "", *STI, &SP, &Rels);
1318 outs() << CommentStream.str();
1321 // Try to resolve the target of a call, tail call, etc. to a specific
1323 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1324 MIA->isConditionalBranch(Inst))) {
1326 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1327 // In a relocatable object, the target's section must reside in
1328 // the same section as the call instruction or it is accessed
1329 // through a relocation.
1331 // In a non-relocatable object, the target may be in any section.
1333 // N.B. We don't walk the relocations in the relocatable case yet.
1334 auto *TargetSectionSymbols = &Symbols;
1335 if (!Obj->isRelocatableObject()) {
1336 auto It = llvm::bsearch(
1338 [=](const std::pair<uint64_t, SectionRef> &RHS) {
1339 return Target < RHS.first;
1341 if (It != SectionAddresses.begin()) {
1343 TargetSectionSymbols = &AllSymbols[It->second];
1345 TargetSectionSymbols = &AbsoluteSymbols;
1349 // Find the last symbol in the section whose offset is less than
1350 // or equal to the target. If there isn't a section that contains
1351 // the target, find the nearest preceding absolute symbol.
1352 auto TargetSym = llvm::bsearch(
1353 *TargetSectionSymbols,
1354 [=](const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1355 return Target < std::get<0>(RHS);
1357 if (TargetSym == TargetSectionSymbols->begin()) {
1358 TargetSectionSymbols = &AbsoluteSymbols;
1359 TargetSym = llvm::bsearch(
1361 [=](const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1362 return Target < std::get<0>(RHS);
1365 if (TargetSym != TargetSectionSymbols->begin()) {
1367 uint64_t TargetAddress = std::get<0>(*TargetSym);
1368 StringRef TargetName = std::get<1>(*TargetSym);
1369 outs() << " <" << TargetName;
1370 uint64_t Disp = Target - TargetAddress;
1372 outs() << "+0x" << Twine::utohexstr(Disp);
1379 // Hexagon does this in pretty printer
1380 if (Obj->getArch() != Triple::hexagon) {
1381 // Print relocation for instruction.
1382 while (RelCur != RelEnd) {
1383 uint64_t Offset = RelCur->getOffset();
1384 // If this relocation is hidden, skip it.
1385 if (getHidden(*RelCur) || SectionAddr + Offset < StartAddress) {
1390 // Stop when RelCur's offset is past the current instruction.
1391 if (Offset >= Index + Size)
1394 // When --adjust-vma is used, update the address printed.
1395 if (RelCur->getSymbol() != Obj->symbol_end()) {
1396 Expected<section_iterator> SymSI =
1397 RelCur->getSymbol()->getSection();
1398 if (SymSI && *SymSI != Obj->section_end() &&
1399 shouldAdjustVA(**SymSI))
1400 Offset += AdjustVMA;
1403 printRelocation(*RelCur, SectionAddr + Offset,
1404 Obj->getBytesInAddress());
1413 StringSet<> MissingDisasmFuncsSet =
1414 set_difference(DisasmFuncsSet, FoundDisasmFuncsSet);
1415 for (StringRef MissingDisasmFunc : MissingDisasmFuncsSet.keys())
1416 warn("failed to disassemble missing function " + MissingDisasmFunc);
1419 static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
1420 if (StartAddress > StopAddress)
1421 error("Start address should be less than stop address");
1423 const Target *TheTarget = getTarget(Obj);
1425 // Package up features to be passed to target/subtarget
1426 SubtargetFeatures Features = Obj->getFeatures();
1427 if (!MAttrs.empty())
1428 for (unsigned I = 0; I != MAttrs.size(); ++I)
1429 Features.AddFeature(MAttrs[I]);
1431 std::unique_ptr<const MCRegisterInfo> MRI(
1432 TheTarget->createMCRegInfo(TripleName));
1434 report_error(Obj->getFileName(),
1435 "no register info for target " + TripleName);
1437 // Set up disassembler.
1438 std::unique_ptr<const MCAsmInfo> AsmInfo(
1439 TheTarget->createMCAsmInfo(*MRI, TripleName));
1441 report_error(Obj->getFileName(),
1442 "no assembly info for target " + TripleName);
1443 std::unique_ptr<const MCSubtargetInfo> STI(
1444 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1446 report_error(Obj->getFileName(),
1447 "no subtarget info for target " + TripleName);
1448 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1450 report_error(Obj->getFileName(),
1451 "no instruction info for target " + TripleName);
1452 MCObjectFileInfo MOFI;
1453 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1454 // FIXME: for now initialize MCObjectFileInfo with default values
1455 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
1457 std::unique_ptr<MCDisassembler> DisAsm(
1458 TheTarget->createMCDisassembler(*STI, Ctx));
1460 report_error(Obj->getFileName(),
1461 "no disassembler for target " + TripleName);
1463 std::unique_ptr<const MCInstrAnalysis> MIA(
1464 TheTarget->createMCInstrAnalysis(MII.get()));
1466 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1467 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1468 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
1470 report_error(Obj->getFileName(),
1471 "no instruction printer for target " + TripleName);
1472 IP->setPrintImmHex(PrintImmHex);
1474 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
1475 SourcePrinter SP(Obj, TheTarget->getName());
1477 for (StringRef Opt : DisassemblerOptions)
1478 if (!IP->applyTargetSpecificCLOption(Opt))
1479 error("Unrecognized disassembler option: " + Opt);
1481 disassembleObject(TheTarget, Obj, Ctx, DisAsm.get(), MIA.get(), IP.get(),
1482 STI.get(), PIP, SP, InlineRelocs);
1485 void printRelocations(const ObjectFile *Obj) {
1486 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1488 // Regular objdump doesn't print relocations in non-relocatable object
1490 if (!Obj->isRelocatableObject())
1493 // Build a mapping from relocation target to a vector of relocation
1494 // sections. Usually, there is an only one relocation section for
1495 // each relocated section.
1496 MapVector<SectionRef, std::vector<SectionRef>> SecToRelSec;
1497 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1498 if (Section.relocation_begin() == Section.relocation_end())
1500 const SectionRef TargetSec = *Section.getRelocatedSection();
1501 SecToRelSec[TargetSec].push_back(Section);
1504 for (std::pair<SectionRef, std::vector<SectionRef>> &P : SecToRelSec) {
1506 error(P.first.getName(SecName));
1507 outs() << "RELOCATION RECORDS FOR [" << SecName << "]:\n";
1509 for (SectionRef Section : P.second) {
1510 for (const RelocationRef &Reloc : Section.relocations()) {
1511 uint64_t Address = Reloc.getOffset();
1512 SmallString<32> RelocName;
1513 SmallString<32> ValueStr;
1514 if (Address < StartAddress || Address > StopAddress || getHidden(Reloc))
1516 Reloc.getTypeName(RelocName);
1517 error(getRelocationValueString(Reloc, ValueStr));
1518 outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1519 << ValueStr << "\n";
1526 void printDynamicRelocations(const ObjectFile *Obj) {
1527 // For the moment, this option is for ELF only
1531 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
1532 if (!Elf || Elf->getEType() != ELF::ET_DYN) {
1533 error("not a dynamic object");
1537 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1538 if (DynRelSec.empty())
1541 outs() << "DYNAMIC RELOCATION RECORDS\n";
1542 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1543 for (const SectionRef &Section : DynRelSec)
1544 for (const RelocationRef &Reloc : Section.relocations()) {
1545 uint64_t Address = Reloc.getOffset();
1546 SmallString<32> RelocName;
1547 SmallString<32> ValueStr;
1548 Reloc.getTypeName(RelocName);
1549 error(getRelocationValueString(Reloc, ValueStr));
1550 outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1551 << ValueStr << "\n";
1555 // Returns true if we need to show LMA column when dumping section headers. We
1556 // show it only when the platform is ELF and either we have at least one section
1557 // whose VMA and LMA are different and/or when --show-lma flag is used.
1558 static bool shouldDisplayLMA(const ObjectFile *Obj) {
1561 for (const SectionRef &S : ToolSectionFilter(*Obj))
1562 if (S.getAddress() != getELFSectionLMA(S))
1567 void printSectionHeaders(const ObjectFile *Obj) {
1568 bool HasLMAColumn = shouldDisplayLMA(Obj);
1570 outs() << "Sections:\n"
1571 "Idx Name Size VMA LMA "
1574 outs() << "Sections:\n"
1575 "Idx Name Size VMA Type\n";
1577 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1579 error(Section.getName(Name));
1580 uint64_t VMA = Section.getAddress();
1581 if (shouldAdjustVA(Section))
1584 uint64_t Size = Section.getSize();
1585 bool Text = Section.isText();
1586 bool Data = Section.isData();
1587 bool BSS = Section.isBSS();
1588 std::string Type = (std::string(Text ? "TEXT " : "") +
1589 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1592 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %016" PRIx64
1594 (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1595 VMA, getELFSectionLMA(Section), Type.c_str());
1597 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
1598 (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1604 void printSectionContents(const ObjectFile *Obj) {
1605 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1607 error(Section.getName(Name));
1608 uint64_t BaseAddr = Section.getAddress();
1609 uint64_t Size = Section.getSize();
1613 outs() << "Contents of section " << Name << ":\n";
1614 if (Section.isBSS()) {
1615 outs() << format("<skipping contents of bss section at [%04" PRIx64
1616 ", %04" PRIx64 ")>\n",
1617 BaseAddr, BaseAddr + Size);
1621 StringRef Contents = unwrapOrError(Section.getContents(), Obj->getFileName());
1623 // Dump out the content as hex and printable ascii characters.
1624 for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) {
1625 outs() << format(" %04" PRIx64 " ", BaseAddr + Addr);
1626 // Dump line of hex.
1627 for (std::size_t I = 0; I < 16; ++I) {
1628 if (I != 0 && I % 4 == 0)
1631 outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true)
1632 << hexdigit(Contents[Addr + I] & 0xF, true);
1638 for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) {
1639 if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF))
1640 outs() << Contents[Addr + I];
1649 void printSymbolTable(const ObjectFile *O, StringRef ArchiveName,
1650 StringRef ArchitectureName) {
1651 outs() << "SYMBOL TABLE:\n";
1653 if (const COFFObjectFile *Coff = dyn_cast<const COFFObjectFile>(O)) {
1654 printCOFFSymbolTable(Coff);
1658 const StringRef FileName = O->getFileName();
1659 for (auto I = O->symbol_begin(), E = O->symbol_end(); I != E; ++I) {
1660 const SymbolRef &Symbol = *I;
1661 uint64_t Address = unwrapOrError(Symbol.getAddress(), ArchiveName, FileName,
1663 if ((Address < StartAddress) || (Address > StopAddress))
1665 SymbolRef::Type Type = unwrapOrError(Symbol.getType(), ArchiveName,
1666 FileName, ArchitectureName);
1667 uint32_t Flags = Symbol.getFlags();
1668 section_iterator Section = unwrapOrError(Symbol.getSection(), ArchiveName,
1669 FileName, ArchitectureName);
1671 if (Type == SymbolRef::ST_Debug && Section != O->section_end())
1672 Section->getName(Name);
1674 Name = unwrapOrError(Symbol.getName(), ArchiveName, FileName,
1677 bool Global = Flags & SymbolRef::SF_Global;
1678 bool Weak = Flags & SymbolRef::SF_Weak;
1679 bool Absolute = Flags & SymbolRef::SF_Absolute;
1680 bool Common = Flags & SymbolRef::SF_Common;
1681 bool Hidden = Flags & SymbolRef::SF_Hidden;
1684 if (Type != SymbolRef::ST_Unknown)
1685 GlobLoc = Global ? 'g' : 'l';
1686 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1688 char FileFunc = ' ';
1689 if (Type == SymbolRef::ST_File)
1691 else if (Type == SymbolRef::ST_Function)
1693 else if (Type == SymbolRef::ST_Data)
1696 const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 :
1699 outs() << format(Fmt, Address) << " "
1700 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1701 << (Weak ? 'w' : ' ') // Weak?
1702 << ' ' // Constructor. Not supported yet.
1703 << ' ' // Warning. Not supported yet.
1704 << ' ' // Indirect reference to another symbol.
1705 << Debug // Debugging (d) or dynamic (D) symbol.
1706 << FileFunc // Name of function (F), file (f) or object (O).
1710 } else if (Common) {
1712 } else if (Section == O->section_end()) {
1715 if (const MachOObjectFile *MachO =
1716 dyn_cast<const MachOObjectFile>(O)) {
1717 DataRefImpl DR = Section->getRawDataRefImpl();
1718 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1719 outs() << SegmentName << ",";
1721 StringRef SectionName;
1722 error(Section->getName(SectionName));
1723 outs() << SectionName;
1726 if (Common || isa<ELFObjectFileBase>(O)) {
1728 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1729 outs() << format("\t%08" PRIx64, Val);
1732 if (isa<ELFObjectFileBase>(O)) {
1733 uint8_t Other = ELFSymbolRef(Symbol).getOther();
1735 case ELF::STV_DEFAULT:
1737 case ELF::STV_INTERNAL:
1738 outs() << " .internal";
1740 case ELF::STV_HIDDEN:
1741 outs() << " .hidden";
1743 case ELF::STV_PROTECTED:
1744 outs() << " .protected";
1747 outs() << format(" 0x%02x", Other);
1750 } else if (Hidden) {
1751 outs() << " .hidden";
1755 outs() << ' ' << demangle(Name) << '\n';
1757 outs() << ' ' << Name << '\n';
1761 static void printUnwindInfo(const ObjectFile *O) {
1762 outs() << "Unwind info:\n\n";
1764 if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O))
1765 printCOFFUnwindInfo(Coff);
1766 else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O))
1767 printMachOUnwindInfo(MachO);
1769 // TODO: Extract DWARF dump tool to objdump.
1770 WithColor::error(errs(), ToolName)
1771 << "This operation is only currently supported "
1772 "for COFF and MachO object files.\n";
1775 /// Dump the raw contents of the __clangast section so the output can be piped
1776 /// into llvm-bcanalyzer.
1777 void printRawClangAST(const ObjectFile *Obj) {
1778 if (outs().is_displayed()) {
1779 WithColor::error(errs(), ToolName)
1780 << "The -raw-clang-ast option will dump the raw binary contents of "
1781 "the clang ast section.\n"
1782 "Please redirect the output to a file or another program such as "
1783 "llvm-bcanalyzer.\n";
1787 StringRef ClangASTSectionName("__clangast");
1788 if (isa<COFFObjectFile>(Obj)) {
1789 ClangASTSectionName = "clangast";
1792 Optional<object::SectionRef> ClangASTSection;
1793 for (auto Sec : ToolSectionFilter(*Obj)) {
1796 if (Name == ClangASTSectionName) {
1797 ClangASTSection = Sec;
1801 if (!ClangASTSection)
1804 StringRef ClangASTContents = unwrapOrError(
1805 ClangASTSection.getValue().getContents(), Obj->getFileName());
1806 outs().write(ClangASTContents.data(), ClangASTContents.size());
1809 static void printFaultMaps(const ObjectFile *Obj) {
1810 StringRef FaultMapSectionName;
1812 if (isa<ELFObjectFileBase>(Obj)) {
1813 FaultMapSectionName = ".llvm_faultmaps";
1814 } else if (isa<MachOObjectFile>(Obj)) {
1815 FaultMapSectionName = "__llvm_faultmaps";
1817 WithColor::error(errs(), ToolName)
1818 << "This operation is only currently supported "
1819 "for ELF and Mach-O executable files.\n";
1823 Optional<object::SectionRef> FaultMapSection;
1825 for (auto Sec : ToolSectionFilter(*Obj)) {
1828 if (Name == FaultMapSectionName) {
1829 FaultMapSection = Sec;
1834 outs() << "FaultMap table:\n";
1836 if (!FaultMapSection.hasValue()) {
1837 outs() << "<not found>\n";
1841 StringRef FaultMapContents =
1842 unwrapOrError(FaultMapSection.getValue().getContents(), Obj->getFileName());
1843 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1844 FaultMapContents.bytes_end());
1849 static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) {
1851 printELFFileHeader(O);
1852 printELFDynamicSection(O);
1853 printELFSymbolVersionInfo(O);
1857 return printCOFFFileHeader(O);
1859 return printWasmFileHeader(O);
1861 printMachOFileHeader(O);
1863 printMachOLoadCommands(O);
1866 report_error(O->getFileName(), "Invalid/Unsupported object file format");
1869 static void printFileHeaders(const ObjectFile *O) {
1870 if (!O->isELF() && !O->isCOFF())
1871 report_error(O->getFileName(), "Invalid/Unsupported object file format");
1873 Triple::ArchType AT = O->getArch();
1874 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
1875 uint64_t Address = unwrapOrError(O->getStartAddress(), O->getFileName());
1877 StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1878 outs() << "start address: "
1879 << "0x" << format(Fmt.data(), Address) << "\n\n";
1882 static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
1883 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
1885 WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n";
1886 consumeError(ModeOrErr.takeError());
1889 sys::fs::perms Mode = ModeOrErr.get();
1890 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1891 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1892 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1893 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1894 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1895 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1896 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1897 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1898 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
1902 outs() << format("%d/%d %6" PRId64 " ", unwrapOrError(C.getUID(), Filename),
1903 unwrapOrError(C.getGID(), Filename),
1904 unwrapOrError(C.getRawSize(), Filename));
1906 StringRef RawLastModified = C.getRawLastModified();
1908 if (RawLastModified.getAsInteger(10, Seconds))
1909 outs() << "(date: \"" << RawLastModified
1910 << "\" contains non-decimal chars) ";
1912 // Since ctime(3) returns a 26 character string of the form:
1913 // "Sun Sep 16 01:03:52 1973\n\0"
1914 // just print 24 characters.
1916 outs() << format("%.24s ", ctime(&t));
1919 StringRef Name = "";
1920 Expected<StringRef> NameOrErr = C.getName();
1922 consumeError(NameOrErr.takeError());
1923 Name = unwrapOrError(C.getRawName(), Filename);
1925 Name = NameOrErr.get();
1927 outs() << Name << "\n";
1930 static void dumpObject(ObjectFile *O, const Archive *A = nullptr,
1931 const Archive::Child *C = nullptr) {
1932 // Avoid other output when using a raw option.
1936 outs() << A->getFileName() << "(" << O->getFileName() << ")";
1938 outs() << O->getFileName();
1939 outs() << ":\tfile format " << O->getFileFormatName() << "\n\n";
1942 StringRef ArchiveName = A ? A->getFileName() : "";
1944 printFileHeaders(O);
1945 if (ArchiveHeaders && !MachOOpt && C)
1946 printArchiveChild(ArchiveName, *C);
1948 disassembleObject(O, Relocations);
1949 if (Relocations && !Disassemble)
1950 printRelocations(O);
1951 if (DynamicRelocations)
1952 printDynamicRelocations(O);
1954 printSectionHeaders(O);
1955 if (SectionContents)
1956 printSectionContents(O);
1958 printSymbolTable(O, ArchiveName);
1961 if (PrivateHeaders || FirstPrivateHeader)
1962 printPrivateFileHeaders(O, FirstPrivateHeader);
1964 printExportsTrie(O);
1966 printRebaseTable(O);
1970 printLazyBindTable(O);
1972 printWeakBindTable(O);
1974 printRawClangAST(O);
1975 if (FaultMapSection)
1977 if (DwarfDumpType != DIDT_Null) {
1978 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O);
1979 // Dump the complete DWARF structure.
1980 DIDumpOptions DumpOpts;
1981 DumpOpts.DumpType = DwarfDumpType;
1982 DICtx->dump(outs(), DumpOpts);
1986 static void dumpObject(const COFFImportFile *I, const Archive *A,
1987 const Archive::Child *C = nullptr) {
1988 StringRef ArchiveName = A ? A->getFileName() : "";
1990 // Avoid other output when using a raw option.
1993 << ArchiveName << "(" << I->getFileName() << ")"
1994 << ":\tfile format COFF-import-file"
1997 if (ArchiveHeaders && !MachOOpt && C)
1998 printArchiveChild(ArchiveName, *C);
2000 printCOFFSymbolTable(I);
2003 /// Dump each object file in \a a;
2004 static void dumpArchive(const Archive *A) {
2005 Error Err = Error::success();
2006 for (auto &C : A->children(Err)) {
2007 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2009 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2010 report_error(std::move(E), A->getFileName(), C);
2013 if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2014 dumpObject(O, A, &C);
2015 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2016 dumpObject(I, A, &C);
2018 report_error(errorCodeToError(object_error::invalid_file_type),
2022 report_error(std::move(Err), A->getFileName());
2025 /// Open file and figure out how to dump it.
2026 static void dumpInput(StringRef file) {
2027 // If we are using the Mach-O specific object file parser, then let it parse
2028 // the file and process the command line options. So the -arch flags can
2029 // be used to select specific slices, etc.
2031 parseInputMachO(file);
2035 // Attempt to open the binary.
2036 OwningBinary<Binary> OBinary = unwrapOrError(createBinary(file), file);
2037 Binary &Binary = *OBinary.getBinary();
2039 if (Archive *A = dyn_cast<Archive>(&Binary))
2041 else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary))
2043 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
2044 parseInputMachO(UB);
2046 report_error(errorCodeToError(object_error::invalid_file_type), file);
2050 int main(int argc, char **argv) {
2051 using namespace llvm;
2052 InitLLVM X(argc, argv);
2053 const cl::OptionCategory *OptionFilters[] = {&ObjdumpCat, &MachOCat};
2054 cl::HideUnrelatedOptions(OptionFilters);
2056 // Initialize targets and assembly printers/parsers.
2057 InitializeAllTargetInfos();
2058 InitializeAllTargetMCs();
2059 InitializeAllDisassemblers();
2061 // Register the target printer for --version.
2062 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2064 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2068 // Defaults to a.out if no filenames specified.
2069 if (InputFilenames.empty())
2070 InputFilenames.push_back("a.out");
2073 ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations =
2074 SectionHeaders = SymbolTable = true;
2076 if (DisassembleAll || PrintSource || PrintLines ||
2077 (!DisassembleFunctions.empty()))
2080 if (!ArchiveHeaders && !Disassemble && DwarfDumpType == DIDT_Null &&
2081 !DynamicRelocations && !FileHeaders && !PrivateHeaders && !RawClangAST &&
2082 !Relocations && !SectionHeaders && !SectionContents && !SymbolTable &&
2083 !UnwindInfo && !FaultMapSection &&
2085 (Bind || DataInCode || DylibId || DylibsUsed || ExportsTrie ||
2086 FirstPrivateHeader || IndirectSymbols || InfoPlist || LazyBind ||
2087 LinkOptHints || ObjcMetaData || Rebase || UniversalHeaders ||
2088 WeakBind || !FilterSections.empty()))) {
2089 cl::PrintHelpMessage();
2093 DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2094 DisassembleFunctions.end());
2096 llvm::for_each(InputFilenames, dumpInput);
2098 return EXIT_SUCCESS;