Revert r368812 "[llvm/Object] - Convert SectionRef::getName() to return Expected<>"
[llvm-complete.git] / tools / llvm-objdump / llvm-objdump.cpp
blob93833858282a3f26735d0f0f1c54952064d88629
1 //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
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
11 // flags.
13 // The flags and output of this program should be near identical to those of
14 // binutils objdump.
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"
64 #include <algorithm>
65 #include <cctype>
66 #include <cstring>
67 #include <system_error>
68 #include <unordered_map>
69 #include <utility>
71 using namespace llvm::object;
73 namespace llvm {
75 cl::OptionCategory ObjdumpCat("llvm-objdump Options");
77 // MachO specific
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(
95 "adjust-vma",
96 cl::desc("Increase the displayed address by the specified offset"),
97 cl::value_desc("offset"), cl::init(0), cl::cat(ObjdumpCat));
99 static cl::opt<bool>
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(
128 "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(
136 "disassemble-all",
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 "Accept demangled names when --demangle is "
148 "specified, otherwise accept mangled names"),
149 cl::cat(ObjdumpCat));
151 static cl::opt<bool> DisassembleZeroes(
152 "disassemble-zeroes",
153 cl::desc("Do not skip blocks of zeroes when disassembling"),
154 cl::cat(ObjdumpCat));
155 static cl::alias
156 DisassembleZeroesShort("z", cl::desc("Alias for --disassemble-zeroes"),
157 cl::NotHidden, cl::Grouping,
158 cl::aliasopt(DisassembleZeroes));
160 static cl::list<std::string>
161 DisassemblerOptions("disassembler-options",
162 cl::desc("Pass target specific disassembler options"),
163 cl::value_desc("options"), cl::CommaSeparated,
164 cl::cat(ObjdumpCat));
165 static cl::alias
166 DisassemblerOptionsShort("M", cl::desc("Alias for --disassembler-options"),
167 cl::NotHidden, cl::Grouping, cl::Prefix,
168 cl::CommaSeparated,
169 cl::aliasopt(DisassemblerOptions));
171 cl::opt<DIDumpType> DwarfDumpType(
172 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
173 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")),
174 cl::cat(ObjdumpCat));
176 static cl::opt<bool> DynamicRelocations(
177 "dynamic-reloc",
178 cl::desc("Display the dynamic relocation entries in the file"),
179 cl::cat(ObjdumpCat));
180 static cl::alias DynamicRelocationShort("R",
181 cl::desc("Alias for --dynamic-reloc"),
182 cl::NotHidden, cl::Grouping,
183 cl::aliasopt(DynamicRelocations));
185 static cl::opt<bool>
186 FaultMapSection("fault-map-section",
187 cl::desc("Display contents of faultmap section"),
188 cl::cat(ObjdumpCat));
190 static cl::opt<bool>
191 FileHeaders("file-headers",
192 cl::desc("Display the contents of the overall file header"),
193 cl::cat(ObjdumpCat));
194 static cl::alias FileHeadersShort("f", cl::desc("Alias for --file-headers"),
195 cl::NotHidden, cl::Grouping,
196 cl::aliasopt(FileHeaders));
198 cl::opt<bool> SectionContents("full-contents",
199 cl::desc("Display the content of each section"),
200 cl::cat(ObjdumpCat));
201 static cl::alias SectionContentsShort("s",
202 cl::desc("Alias for --full-contents"),
203 cl::NotHidden, cl::Grouping,
204 cl::aliasopt(SectionContents));
206 static cl::list<std::string> InputFilenames(cl::Positional,
207 cl::desc("<input object files>"),
208 cl::ZeroOrMore,
209 cl::cat(ObjdumpCat));
211 static cl::opt<bool>
212 PrintLines("line-numbers",
213 cl::desc("Display source line numbers with "
214 "disassembly. Implies disassemble object"),
215 cl::cat(ObjdumpCat));
216 static cl::alias PrintLinesShort("l", cl::desc("Alias for --line-numbers"),
217 cl::NotHidden, cl::Grouping,
218 cl::aliasopt(PrintLines));
220 static cl::opt<bool> MachOOpt("macho",
221 cl::desc("Use MachO specific object file parser"),
222 cl::cat(ObjdumpCat));
223 static cl::alias MachOm("m", cl::desc("Alias for --macho"), cl::NotHidden,
224 cl::Grouping, cl::aliasopt(MachOOpt));
226 cl::opt<std::string>
227 MCPU("mcpu",
228 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
229 cl::value_desc("cpu-name"), cl::init(""), cl::cat(ObjdumpCat));
231 cl::list<std::string> MAttrs("mattr", cl::CommaSeparated,
232 cl::desc("Target specific attributes"),
233 cl::value_desc("a1,+a2,-a3,..."),
234 cl::cat(ObjdumpCat));
236 cl::opt<bool> NoShowRawInsn("no-show-raw-insn",
237 cl::desc("When disassembling "
238 "instructions, do not print "
239 "the instruction bytes."),
240 cl::cat(ObjdumpCat));
241 cl::opt<bool> NoLeadingAddr("no-leading-addr",
242 cl::desc("Print no leading address"),
243 cl::cat(ObjdumpCat));
245 static cl::opt<bool> RawClangAST(
246 "raw-clang-ast",
247 cl::desc("Dump the raw binary contents of the clang AST section"),
248 cl::cat(ObjdumpCat));
250 cl::opt<bool>
251 Relocations("reloc", cl::desc("Display the relocation entries in the file"),
252 cl::cat(ObjdumpCat));
253 static cl::alias RelocationsShort("r", cl::desc("Alias for --reloc"),
254 cl::NotHidden, cl::Grouping,
255 cl::aliasopt(Relocations));
257 cl::opt<bool> PrintImmHex("print-imm-hex",
258 cl::desc("Use hex format for immediate values"),
259 cl::cat(ObjdumpCat));
261 cl::opt<bool> PrivateHeaders("private-headers",
262 cl::desc("Display format specific file headers"),
263 cl::cat(ObjdumpCat));
264 static cl::alias PrivateHeadersShort("p",
265 cl::desc("Alias for --private-headers"),
266 cl::NotHidden, cl::Grouping,
267 cl::aliasopt(PrivateHeaders));
269 cl::list<std::string>
270 FilterSections("section",
271 cl::desc("Operate on the specified sections only. "
272 "With -macho dump segment,section"),
273 cl::cat(ObjdumpCat));
274 static cl::alias FilterSectionsj("j", cl::desc("Alias for --section"),
275 cl::NotHidden, cl::Grouping, cl::Prefix,
276 cl::aliasopt(FilterSections));
278 cl::opt<bool> SectionHeaders("section-headers",
279 cl::desc("Display summaries of the "
280 "headers for each section."),
281 cl::cat(ObjdumpCat));
282 static cl::alias SectionHeadersShort("headers",
283 cl::desc("Alias for --section-headers"),
284 cl::NotHidden,
285 cl::aliasopt(SectionHeaders));
286 static cl::alias SectionHeadersShorter("h",
287 cl::desc("Alias for --section-headers"),
288 cl::NotHidden, cl::Grouping,
289 cl::aliasopt(SectionHeaders));
291 static cl::opt<bool>
292 ShowLMA("show-lma",
293 cl::desc("Display LMA column when dumping ELF section headers"),
294 cl::cat(ObjdumpCat));
296 static cl::opt<bool> PrintSource(
297 "source",
298 cl::desc(
299 "Display source inlined with disassembly. Implies disassemble object"),
300 cl::cat(ObjdumpCat));
301 static cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
302 cl::NotHidden, cl::Grouping,
303 cl::aliasopt(PrintSource));
305 static cl::opt<uint64_t>
306 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
307 cl::value_desc("address"), cl::init(0), cl::cat(ObjdumpCat));
308 static cl::opt<uint64_t> StopAddress("stop-address",
309 cl::desc("Stop disassembly at address"),
310 cl::value_desc("address"),
311 cl::init(UINT64_MAX), cl::cat(ObjdumpCat));
313 cl::opt<bool> SymbolTable("syms", cl::desc("Display the symbol table"),
314 cl::cat(ObjdumpCat));
315 static cl::alias SymbolTableShort("t", cl::desc("Alias for --syms"),
316 cl::NotHidden, cl::Grouping,
317 cl::aliasopt(SymbolTable));
319 cl::opt<std::string> TripleName("triple",
320 cl::desc("Target triple to disassemble for, "
321 "see -version for available targets"),
322 cl::cat(ObjdumpCat));
324 cl::opt<bool> UnwindInfo("unwind-info", cl::desc("Display unwind information"),
325 cl::cat(ObjdumpCat));
326 static cl::alias UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
327 cl::NotHidden, cl::Grouping,
328 cl::aliasopt(UnwindInfo));
330 static cl::opt<bool>
331 Wide("wide", cl::desc("Ignored for compatibility with GNU objdump"),
332 cl::cat(ObjdumpCat));
333 static cl::alias WideShort("w", cl::Grouping, cl::aliasopt(Wide));
335 static cl::extrahelp
336 HelpResponse("\nPass @FILE as argument to read options from FILE.\n");
338 static StringSet<> DisasmFuncsSet;
339 static StringSet<> FoundSectionSet;
340 static StringRef ToolName;
342 typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
344 static bool shouldKeep(object::SectionRef S) {
345 if (FilterSections.empty())
346 return true;
347 StringRef SecName;
348 std::error_code error = S.getName(SecName);
349 if (error)
350 return false;
351 // StringSet does not allow empty key so avoid adding sections with
352 // no name (such as the section with index 0) here.
353 if (!SecName.empty())
354 FoundSectionSet.insert(SecName);
355 return is_contained(FilterSections, SecName);
358 SectionFilter ToolSectionFilter(object::ObjectFile const &O) {
359 return SectionFilter([](object::SectionRef S) { return shouldKeep(S); }, O);
362 void error(std::error_code EC) {
363 if (!EC)
364 return;
365 WithColor::error(errs(), ToolName)
366 << "reading file: " << EC.message() << ".\n";
367 errs().flush();
368 exit(1);
371 void error(Error E) {
372 if (!E)
373 return;
374 WithColor::error(errs(), ToolName) << toString(std::move(E));
375 exit(1);
378 LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
379 WithColor::error(errs(), ToolName) << Message << ".\n";
380 errs().flush();
381 exit(1);
384 void warn(StringRef Message) {
385 WithColor::warning(errs(), ToolName) << Message << ".\n";
386 errs().flush();
389 static void warn(Twine Message) {
390 // Output order between errs() and outs() matters especially for archive
391 // files where the output is per member object.
392 outs().flush();
393 WithColor::warning(errs(), ToolName) << Message << "\n";
394 errs().flush();
397 LLVM_ATTRIBUTE_NORETURN void report_error(StringRef File, Twine Message) {
398 WithColor::error(errs(), ToolName)
399 << "'" << File << "': " << Message << ".\n";
400 exit(1);
403 LLVM_ATTRIBUTE_NORETURN void report_error(Error E, StringRef File) {
404 assert(E);
405 std::string Buf;
406 raw_string_ostream OS(Buf);
407 logAllUnhandledErrors(std::move(E), OS);
408 OS.flush();
409 WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf;
410 exit(1);
413 LLVM_ATTRIBUTE_NORETURN void report_error(Error E, StringRef ArchiveName,
414 StringRef FileName,
415 StringRef ArchitectureName) {
416 assert(E);
417 WithColor::error(errs(), ToolName);
418 if (ArchiveName != "")
419 errs() << ArchiveName << "(" << FileName << ")";
420 else
421 errs() << "'" << FileName << "'";
422 if (!ArchitectureName.empty())
423 errs() << " (for architecture " << ArchitectureName << ")";
424 std::string Buf;
425 raw_string_ostream OS(Buf);
426 logAllUnhandledErrors(std::move(E), OS);
427 OS.flush();
428 errs() << ": " << Buf;
429 exit(1);
432 LLVM_ATTRIBUTE_NORETURN void report_error(Error E, StringRef ArchiveName,
433 const object::Archive::Child &C,
434 StringRef ArchitectureName) {
435 Expected<StringRef> NameOrErr = C.getName();
436 // TODO: if we have a error getting the name then it would be nice to print
437 // the index of which archive member this is and or its offset in the
438 // archive instead of "???" as the name.
439 if (!NameOrErr) {
440 consumeError(NameOrErr.takeError());
441 report_error(std::move(E), ArchiveName, "???", ArchitectureName);
442 } else
443 report_error(std::move(E), ArchiveName, NameOrErr.get(), ArchitectureName);
446 static void warnOnNoMatchForSections() {
447 SetVector<StringRef> MissingSections;
448 for (StringRef S : FilterSections) {
449 if (FoundSectionSet.count(S))
450 return;
451 // User may specify a unnamed section. Don't warn for it.
452 if (!S.empty())
453 MissingSections.insert(S);
456 // Warn only if no section in FilterSections is matched.
457 for (StringRef S : MissingSections)
458 warn("section '" + S + "' mentioned in a -j/--section option, but not "
459 "found in any input file");
462 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
463 // Figure out the target triple.
464 Triple TheTriple("unknown-unknown-unknown");
465 if (TripleName.empty()) {
466 if (Obj)
467 TheTriple = Obj->makeTriple();
468 } else {
469 TheTriple.setTriple(Triple::normalize(TripleName));
471 // Use the triple, but also try to combine with ARM build attributes.
472 if (Obj) {
473 auto Arch = Obj->getArch();
474 if (Arch == Triple::arm || Arch == Triple::armeb)
475 Obj->setARMSubArch(TheTriple);
479 // Get the target specific parser.
480 std::string Error;
481 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
482 Error);
483 if (!TheTarget) {
484 if (Obj)
485 report_error(Obj->getFileName(), "can't find target: " + Error);
486 else
487 error("can't find target: " + Error);
490 // Update the triple name and return the found target.
491 TripleName = TheTriple.getTriple();
492 return TheTarget;
495 bool isRelocAddressLess(RelocationRef A, RelocationRef B) {
496 return A.getOffset() < B.getOffset();
499 static Error getRelocationValueString(const RelocationRef &Rel,
500 SmallVectorImpl<char> &Result) {
501 const ObjectFile *Obj = Rel.getObject();
502 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
503 return getELFRelocationValueString(ELF, Rel, Result);
504 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
505 return getCOFFRelocationValueString(COFF, Rel, Result);
506 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
507 return getWasmRelocationValueString(Wasm, Rel, Result);
508 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
509 return getMachORelocationValueString(MachO, Rel, Result);
510 llvm_unreachable("unknown object file format");
513 /// Indicates whether this relocation should hidden when listing
514 /// relocations, usually because it is the trailing part of a multipart
515 /// relocation that will be printed as part of the leading relocation.
516 static bool getHidden(RelocationRef RelRef) {
517 auto *MachO = dyn_cast<MachOObjectFile>(RelRef.getObject());
518 if (!MachO)
519 return false;
521 unsigned Arch = MachO->getArch();
522 DataRefImpl Rel = RelRef.getRawDataRefImpl();
523 uint64_t Type = MachO->getRelocationType(Rel);
525 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
526 // is always hidden.
527 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc)
528 return Type == MachO::GENERIC_RELOC_PAIR;
530 if (Arch == Triple::x86_64) {
531 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
532 // an X86_64_RELOC_SUBTRACTOR.
533 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
534 DataRefImpl RelPrev = Rel;
535 RelPrev.d.a--;
536 uint64_t PrevType = MachO->getRelocationType(RelPrev);
537 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
538 return true;
542 return false;
545 namespace {
546 class SourcePrinter {
547 protected:
548 DILineInfo OldLineInfo;
549 const ObjectFile *Obj = nullptr;
550 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
551 // File name to file contents of source
552 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
553 // Mark the line endings of the cached source
554 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
556 private:
557 bool cacheSource(const DILineInfo& LineInfoFile);
559 public:
560 SourcePrinter() = default;
561 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
562 symbolize::LLVMSymbolizer::Options SymbolizerOpts;
563 SymbolizerOpts.PrintFunctions = DILineInfoSpecifier::FunctionNameKind::None;
564 SymbolizerOpts.Demangle = false;
565 SymbolizerOpts.DefaultArch = DefaultArch;
566 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
568 virtual ~SourcePrinter() = default;
569 virtual void printSourceLine(raw_ostream &OS,
570 object::SectionedAddress Address,
571 StringRef Delimiter = "; ");
574 bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
575 std::unique_ptr<MemoryBuffer> Buffer;
576 if (LineInfo.Source) {
577 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);
578 } else {
579 auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName);
580 if (!BufferOrError)
581 return false;
582 Buffer = std::move(*BufferOrError);
584 // Chomp the file to get lines
585 const char *BufferStart = Buffer->getBufferStart(),
586 *BufferEnd = Buffer->getBufferEnd();
587 std::vector<StringRef> &Lines = LineCache[LineInfo.FileName];
588 const char *Start = BufferStart;
589 for (const char *I = BufferStart; I != BufferEnd; ++I)
590 if (*I == '\n') {
591 Lines.emplace_back(Start, I - Start - (BufferStart < I && I[-1] == '\r'));
592 Start = I + 1;
594 if (Start < BufferEnd)
595 Lines.emplace_back(Start, BufferEnd - Start);
596 SourceCache[LineInfo.FileName] = std::move(Buffer);
597 return true;
600 void SourcePrinter::printSourceLine(raw_ostream &OS,
601 object::SectionedAddress Address,
602 StringRef Delimiter) {
603 if (!Symbolizer)
604 return;
606 DILineInfo LineInfo = DILineInfo();
607 auto ExpectedLineInfo = Symbolizer->symbolizeCode(*Obj, Address);
608 if (!ExpectedLineInfo)
609 consumeError(ExpectedLineInfo.takeError());
610 else
611 LineInfo = *ExpectedLineInfo;
613 if ((LineInfo.FileName == "<invalid>") || LineInfo.Line == 0 ||
614 ((OldLineInfo.Line == LineInfo.Line) &&
615 (OldLineInfo.FileName == LineInfo.FileName)))
616 return;
618 if (PrintLines)
619 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
620 if (PrintSource) {
621 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
622 if (!cacheSource(LineInfo))
623 return;
624 auto LineBuffer = LineCache.find(LineInfo.FileName);
625 if (LineBuffer != LineCache.end()) {
626 if (LineInfo.Line > LineBuffer->second.size())
627 return;
628 // Vector begins at 0, line numbers are non-zero
629 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1] << '\n';
632 OldLineInfo = LineInfo;
635 static bool isAArch64Elf(const ObjectFile *Obj) {
636 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
637 return Elf && Elf->getEMachine() == ELF::EM_AARCH64;
640 static bool isArmElf(const ObjectFile *Obj) {
641 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
642 return Elf && Elf->getEMachine() == ELF::EM_ARM;
645 static bool hasMappingSymbols(const ObjectFile *Obj) {
646 return isArmElf(Obj) || isAArch64Elf(Obj);
649 static void printRelocation(const RelocationRef &Rel, uint64_t Address,
650 bool Is64Bits) {
651 StringRef Fmt = Is64Bits ? "\t\t%016" PRIx64 ": " : "\t\t\t%08" PRIx64 ": ";
652 SmallString<16> Name;
653 SmallString<32> Val;
654 Rel.getTypeName(Name);
655 error(getRelocationValueString(Rel, Val));
656 outs() << format(Fmt.data(), Address) << Name << "\t" << Val << "\n";
659 class PrettyPrinter {
660 public:
661 virtual ~PrettyPrinter() = default;
662 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
663 ArrayRef<uint8_t> Bytes,
664 object::SectionedAddress Address, raw_ostream &OS,
665 StringRef Annot, MCSubtargetInfo const &STI,
666 SourcePrinter *SP,
667 std::vector<RelocationRef> *Rels = nullptr) {
668 if (SP && (PrintSource || PrintLines))
669 SP->printSourceLine(OS, Address);
671 size_t Start = OS.tell();
672 if (!NoLeadingAddr)
673 OS << format("%8" PRIx64 ":", Address.Address);
674 if (!NoShowRawInsn) {
675 OS << ' ';
676 dumpBytes(Bytes, OS);
679 // The output of printInst starts with a tab. Print some spaces so that
680 // the tab has 1 column and advances to the target tab stop.
681 unsigned TabStop = NoShowRawInsn ? 16 : 40;
682 unsigned Column = OS.tell() - Start;
683 OS.indent(Column < TabStop - 1 ? TabStop - 1 - Column : 7 - Column % 8);
685 if (MI)
686 IP.printInst(MI, OS, "", STI);
687 else
688 OS << "\t<unknown>";
691 PrettyPrinter PrettyPrinterInst;
693 class HexagonPrettyPrinter : public PrettyPrinter {
694 public:
695 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
696 raw_ostream &OS) {
697 uint32_t opcode =
698 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
699 if (!NoLeadingAddr)
700 OS << format("%8" PRIx64 ":", Address);
701 if (!NoShowRawInsn) {
702 OS << "\t";
703 dumpBytes(Bytes.slice(0, 4), OS);
704 OS << format("\t%08" PRIx32, opcode);
707 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
708 object::SectionedAddress Address, raw_ostream &OS,
709 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
710 std::vector<RelocationRef> *Rels) override {
711 if (SP && (PrintSource || PrintLines))
712 SP->printSourceLine(OS, Address, "");
713 if (!MI) {
714 printLead(Bytes, Address.Address, OS);
715 OS << " <unknown>";
716 return;
718 std::string Buffer;
720 raw_string_ostream TempStream(Buffer);
721 IP.printInst(MI, TempStream, "", STI);
723 StringRef Contents(Buffer);
724 // Split off bundle attributes
725 auto PacketBundle = Contents.rsplit('\n');
726 // Split off first instruction from the rest
727 auto HeadTail = PacketBundle.first.split('\n');
728 auto Preamble = " { ";
729 auto Separator = "";
731 // Hexagon's packets require relocations to be inline rather than
732 // clustered at the end of the packet.
733 std::vector<RelocationRef>::const_iterator RelCur = Rels->begin();
734 std::vector<RelocationRef>::const_iterator RelEnd = Rels->end();
735 auto PrintReloc = [&]() -> void {
736 while ((RelCur != RelEnd) && (RelCur->getOffset() <= Address.Address)) {
737 if (RelCur->getOffset() == Address.Address) {
738 printRelocation(*RelCur, Address.Address, false);
739 return;
741 ++RelCur;
745 while (!HeadTail.first.empty()) {
746 OS << Separator;
747 Separator = "\n";
748 if (SP && (PrintSource || PrintLines))
749 SP->printSourceLine(OS, Address, "");
750 printLead(Bytes, Address.Address, OS);
751 OS << Preamble;
752 Preamble = " ";
753 StringRef Inst;
754 auto Duplex = HeadTail.first.split('\v');
755 if (!Duplex.second.empty()) {
756 OS << Duplex.first;
757 OS << "; ";
758 Inst = Duplex.second;
760 else
761 Inst = HeadTail.first;
762 OS << Inst;
763 HeadTail = HeadTail.second.split('\n');
764 if (HeadTail.first.empty())
765 OS << " } " << PacketBundle.second;
766 PrintReloc();
767 Bytes = Bytes.slice(4);
768 Address.Address += 4;
772 HexagonPrettyPrinter HexagonPrettyPrinterInst;
774 class AMDGCNPrettyPrinter : public PrettyPrinter {
775 public:
776 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
777 object::SectionedAddress Address, raw_ostream &OS,
778 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
779 std::vector<RelocationRef> *Rels) override {
780 if (SP && (PrintSource || PrintLines))
781 SP->printSourceLine(OS, Address);
783 if (MI) {
784 SmallString<40> InstStr;
785 raw_svector_ostream IS(InstStr);
787 IP.printInst(MI, IS, "", STI);
789 OS << left_justify(IS.str(), 60);
790 } else {
791 // an unrecognized encoding - this is probably data so represent it
792 // using the .long directive, or .byte directive if fewer than 4 bytes
793 // remaining
794 if (Bytes.size() >= 4) {
795 OS << format("\t.long 0x%08" PRIx32 " ",
796 support::endian::read32<support::little>(Bytes.data()));
797 OS.indent(42);
798 } else {
799 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
800 for (unsigned int i = 1; i < Bytes.size(); i++)
801 OS << format(", 0x%02" PRIx8, Bytes[i]);
802 OS.indent(55 - (6 * Bytes.size()));
806 OS << format("// %012" PRIX64 ":", Address.Address);
807 if (Bytes.size() >= 4) {
808 // D should be casted to uint32_t here as it is passed by format to
809 // snprintf as vararg.
810 for (uint32_t D : makeArrayRef(
811 reinterpret_cast<const support::little32_t *>(Bytes.data()),
812 Bytes.size() / 4))
813 OS << format(" %08" PRIX32, D);
814 } else {
815 for (unsigned char B : Bytes)
816 OS << format(" %02" PRIX8, B);
819 if (!Annot.empty())
820 OS << " // " << Annot;
823 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
825 class BPFPrettyPrinter : public PrettyPrinter {
826 public:
827 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
828 object::SectionedAddress Address, raw_ostream &OS,
829 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
830 std::vector<RelocationRef> *Rels) override {
831 if (SP && (PrintSource || PrintLines))
832 SP->printSourceLine(OS, Address);
833 if (!NoLeadingAddr)
834 OS << format("%8" PRId64 ":", Address.Address / 8);
835 if (!NoShowRawInsn) {
836 OS << "\t";
837 dumpBytes(Bytes, OS);
839 if (MI)
840 IP.printInst(MI, OS, "", STI);
841 else
842 OS << "\t<unknown>";
845 BPFPrettyPrinter BPFPrettyPrinterInst;
847 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
848 switch(Triple.getArch()) {
849 default:
850 return PrettyPrinterInst;
851 case Triple::hexagon:
852 return HexagonPrettyPrinterInst;
853 case Triple::amdgcn:
854 return AMDGCNPrettyPrinterInst;
855 case Triple::bpfel:
856 case Triple::bpfeb:
857 return BPFPrettyPrinterInst;
862 static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
863 assert(Obj->isELF());
864 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
865 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
866 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
867 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
868 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
869 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
870 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
871 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
872 llvm_unreachable("Unsupported binary format");
875 template <class ELFT> static void
876 addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
877 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
878 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
879 uint8_t SymbolType = Symbol.getELFType();
880 if (SymbolType == ELF::STT_SECTION)
881 continue;
883 uint64_t Address = unwrapOrError(Symbol.getAddress(), Obj->getFileName());
884 // ELFSymbolRef::getAddress() returns size instead of value for common
885 // symbols which is not desirable for disassembly output. Overriding.
886 if (SymbolType == ELF::STT_COMMON)
887 Address = Obj->getSymbol(Symbol.getRawDataRefImpl())->st_value;
889 StringRef Name = unwrapOrError(Symbol.getName(), Obj->getFileName());
890 if (Name.empty())
891 continue;
893 section_iterator SecI =
894 unwrapOrError(Symbol.getSection(), Obj->getFileName());
895 if (SecI == Obj->section_end())
896 continue;
898 AllSymbols[*SecI].emplace_back(Address, Name, SymbolType);
902 static void
903 addDynamicElfSymbols(const ObjectFile *Obj,
904 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
905 assert(Obj->isELF());
906 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
907 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
908 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
909 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
910 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
911 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
912 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
913 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
914 else
915 llvm_unreachable("Unsupported binary format");
918 static void addPltEntries(const ObjectFile *Obj,
919 std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
920 StringSaver &Saver) {
921 Optional<SectionRef> Plt = None;
922 for (const SectionRef &Section : Obj->sections()) {
923 StringRef Name;
924 if (Section.getName(Name))
925 continue;
926 if (Name == ".plt")
927 Plt = Section;
929 if (!Plt)
930 return;
931 if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) {
932 for (auto PltEntry : ElfObj->getPltAddresses()) {
933 SymbolRef Symbol(PltEntry.first, ElfObj);
934 uint8_t SymbolType = getElfSymbolType(Obj, Symbol);
936 StringRef Name = unwrapOrError(Symbol.getName(), Obj->getFileName());
937 if (!Name.empty())
938 AllSymbols[*Plt].emplace_back(
939 PltEntry.second, Saver.save((Name + "@plt").str()), SymbolType);
944 // Normally the disassembly output will skip blocks of zeroes. This function
945 // returns the number of zero bytes that can be skipped when dumping the
946 // disassembly of the instructions in Buf.
947 static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) {
948 // Find the number of leading zeroes.
949 size_t N = 0;
950 while (N < Buf.size() && !Buf[N])
951 ++N;
953 // We may want to skip blocks of zero bytes, but unless we see
954 // at least 8 of them in a row.
955 if (N < 8)
956 return 0;
958 // We skip zeroes in multiples of 4 because do not want to truncate an
959 // instruction if it starts with a zero byte.
960 return N & ~0x3;
963 // Returns a map from sections to their relocations.
964 static std::map<SectionRef, std::vector<RelocationRef>>
965 getRelocsMap(object::ObjectFile const &Obj) {
966 std::map<SectionRef, std::vector<RelocationRef>> Ret;
967 for (SectionRef Sec : Obj.sections()) {
968 section_iterator Relocated = Sec.getRelocatedSection();
969 if (Relocated == Obj.section_end() || !shouldKeep(*Relocated))
970 continue;
971 std::vector<RelocationRef> &V = Ret[*Relocated];
972 for (const RelocationRef &R : Sec.relocations())
973 V.push_back(R);
974 // Sort relocations by address.
975 llvm::stable_sort(V, isRelocAddressLess);
977 return Ret;
980 // Used for --adjust-vma to check if address should be adjusted by the
981 // specified value for a given section.
982 // For ELF we do not adjust non-allocatable sections like debug ones,
983 // because they are not loadable.
984 // TODO: implement for other file formats.
985 static bool shouldAdjustVA(const SectionRef &Section) {
986 const ObjectFile *Obj = Section.getObject();
987 if (isa<object::ELFObjectFileBase>(Obj))
988 return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
989 return false;
993 typedef std::pair<uint64_t, char> MappingSymbolPair;
994 static char getMappingSymbolKind(ArrayRef<MappingSymbolPair> MappingSymbols,
995 uint64_t Address) {
996 auto It =
997 partition_point(MappingSymbols, [Address](const MappingSymbolPair &Val) {
998 return Val.first <= Address;
1000 // Return zero for any address before the first mapping symbol; this means
1001 // we should use the default disassembly mode, depending on the target.
1002 if (It == MappingSymbols.begin())
1003 return '\x00';
1004 return (It - 1)->second;
1007 static uint64_t
1008 dumpARMELFData(uint64_t SectionAddr, uint64_t Index, uint64_t End,
1009 const ObjectFile *Obj, ArrayRef<uint8_t> Bytes,
1010 ArrayRef<MappingSymbolPair> MappingSymbols) {
1011 support::endianness Endian =
1012 Obj->isLittleEndian() ? support::little : support::big;
1013 while (Index < End) {
1014 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1015 outs() << "\t";
1016 if (Index + 4 <= End) {
1017 dumpBytes(Bytes.slice(Index, 4), outs());
1018 outs() << "\t.word\t"
1019 << format_hex(
1020 support::endian::read32(Bytes.data() + Index, Endian), 10);
1021 Index += 4;
1022 } else if (Index + 2 <= End) {
1023 dumpBytes(Bytes.slice(Index, 2), outs());
1024 outs() << "\t\t.short\t"
1025 << format_hex(
1026 support::endian::read16(Bytes.data() + Index, Endian), 6);
1027 Index += 2;
1028 } else {
1029 dumpBytes(Bytes.slice(Index, 1), outs());
1030 outs() << "\t\t.byte\t" << format_hex(Bytes[0], 4);
1031 ++Index;
1033 outs() << "\n";
1034 if (getMappingSymbolKind(MappingSymbols, Index) != 'd')
1035 break;
1037 return Index;
1040 static void dumpELFData(uint64_t SectionAddr, uint64_t Index, uint64_t End,
1041 ArrayRef<uint8_t> Bytes) {
1042 // print out data up to 8 bytes at a time in hex and ascii
1043 uint8_t AsciiData[9] = {'\0'};
1044 uint8_t Byte;
1045 int NumBytes = 0;
1047 for (; Index < End; ++Index) {
1048 if (NumBytes == 0)
1049 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1050 Byte = Bytes.slice(Index)[0];
1051 outs() << format(" %02x", Byte);
1052 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
1054 uint8_t IndentOffset = 0;
1055 NumBytes++;
1056 if (Index == End - 1 || NumBytes > 8) {
1057 // Indent the space for less than 8 bytes data.
1058 // 2 spaces for byte and one for space between bytes
1059 IndentOffset = 3 * (8 - NumBytes);
1060 for (int Excess = NumBytes; Excess < 8; Excess++)
1061 AsciiData[Excess] = '\0';
1062 NumBytes = 8;
1064 if (NumBytes == 8) {
1065 AsciiData[8] = '\0';
1066 outs() << std::string(IndentOffset, ' ') << " ";
1067 outs() << reinterpret_cast<char *>(AsciiData);
1068 outs() << '\n';
1069 NumBytes = 0;
1074 static void disassembleObject(const Target *TheTarget, const ObjectFile *Obj,
1075 MCContext &Ctx, MCDisassembler *PrimaryDisAsm,
1076 MCDisassembler *SecondaryDisAsm,
1077 const MCInstrAnalysis *MIA, MCInstPrinter *IP,
1078 const MCSubtargetInfo *PrimarySTI,
1079 const MCSubtargetInfo *SecondarySTI,
1080 PrettyPrinter &PIP,
1081 SourcePrinter &SP, bool InlineRelocs) {
1082 const MCSubtargetInfo *STI = PrimarySTI;
1083 MCDisassembler *DisAsm = PrimaryDisAsm;
1084 bool PrimaryIsThumb = false;
1085 if (isArmElf(Obj))
1086 PrimaryIsThumb = STI->checkFeatures("+thumb-mode");
1088 std::map<SectionRef, std::vector<RelocationRef>> RelocMap;
1089 if (InlineRelocs)
1090 RelocMap = getRelocsMap(*Obj);
1091 bool Is64Bits = Obj->getBytesInAddress() > 4;
1093 // Create a mapping from virtual address to symbol name. This is used to
1094 // pretty print the symbols while disassembling.
1095 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1096 SectionSymbolsTy AbsoluteSymbols;
1097 const StringRef FileName = Obj->getFileName();
1098 for (const SymbolRef &Symbol : Obj->symbols()) {
1099 uint64_t Address = unwrapOrError(Symbol.getAddress(), FileName);
1101 StringRef Name = unwrapOrError(Symbol.getName(), FileName);
1102 if (Name.empty())
1103 continue;
1105 uint8_t SymbolType = ELF::STT_NOTYPE;
1106 if (Obj->isELF()) {
1107 SymbolType = getElfSymbolType(Obj, Symbol);
1108 if (SymbolType == ELF::STT_SECTION)
1109 continue;
1112 section_iterator SecI = unwrapOrError(Symbol.getSection(), FileName);
1113 if (SecI != Obj->section_end())
1114 AllSymbols[*SecI].emplace_back(Address, Name, SymbolType);
1115 else
1116 AbsoluteSymbols.emplace_back(Address, Name, SymbolType);
1118 if (AllSymbols.empty() && Obj->isELF())
1119 addDynamicElfSymbols(Obj, AllSymbols);
1121 BumpPtrAllocator A;
1122 StringSaver Saver(A);
1123 addPltEntries(Obj, AllSymbols, Saver);
1125 // Create a mapping from virtual address to section.
1126 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1127 for (SectionRef Sec : Obj->sections())
1128 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1129 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1131 // Linked executables (.exe and .dll files) typically don't include a real
1132 // symbol table but they might contain an export table.
1133 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1134 for (const auto &ExportEntry : COFFObj->export_directories()) {
1135 StringRef Name;
1136 error(ExportEntry.getSymbolName(Name));
1137 if (Name.empty())
1138 continue;
1139 uint32_t RVA;
1140 error(ExportEntry.getExportRVA(RVA));
1142 uint64_t VA = COFFObj->getImageBase() + RVA;
1143 auto Sec = partition_point(
1144 SectionAddresses, [VA](const std::pair<uint64_t, SectionRef> &O) {
1145 return O.first <= VA;
1147 if (Sec != SectionAddresses.begin()) {
1148 --Sec;
1149 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
1150 } else
1151 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
1155 // Sort all the symbols, this allows us to use a simple binary search to find
1156 // a symbol near an address.
1157 StringSet<> FoundDisasmFuncsSet;
1158 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1159 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1160 array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
1162 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1163 if (FilterSections.empty() && !DisassembleAll &&
1164 (!Section.isText() || Section.isVirtual()))
1165 continue;
1167 uint64_t SectionAddr = Section.getAddress();
1168 uint64_t SectSize = Section.getSize();
1169 if (!SectSize)
1170 continue;
1172 // Get the list of all the symbols in this section.
1173 SectionSymbolsTy &Symbols = AllSymbols[Section];
1174 std::vector<MappingSymbolPair> MappingSymbols;
1175 if (hasMappingSymbols(Obj)) {
1176 for (const auto &Symb : Symbols) {
1177 uint64_t Address = std::get<0>(Symb);
1178 StringRef Name = std::get<1>(Symb);
1179 if (Name.startswith("$d"))
1180 MappingSymbols.emplace_back(Address - SectionAddr, 'd');
1181 if (Name.startswith("$x"))
1182 MappingSymbols.emplace_back(Address - SectionAddr, 'x');
1183 if (Name.startswith("$a"))
1184 MappingSymbols.emplace_back(Address - SectionAddr, 'a');
1185 if (Name.startswith("$t"))
1186 MappingSymbols.emplace_back(Address - SectionAddr, 't');
1190 llvm::sort(MappingSymbols);
1192 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1193 // AMDGPU disassembler uses symbolizer for printing labels
1194 std::unique_ptr<MCRelocationInfo> RelInfo(
1195 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1196 if (RelInfo) {
1197 std::unique_ptr<MCSymbolizer> Symbolizer(
1198 TheTarget->createMCSymbolizer(
1199 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1200 DisAsm->setSymbolizer(std::move(Symbolizer));
1204 StringRef SegmentName = "";
1205 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
1206 DataRefImpl DR = Section.getRawDataRefImpl();
1207 SegmentName = MachO->getSectionFinalSegmentName(DR);
1209 StringRef SectionName;
1210 error(Section.getName(SectionName));
1212 // If the section has no symbol at the start, just insert a dummy one.
1213 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
1214 Symbols.insert(
1215 Symbols.begin(),
1216 std::make_tuple(SectionAddr, SectionName,
1217 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
1220 SmallString<40> Comments;
1221 raw_svector_ostream CommentStream(Comments);
1223 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(
1224 unwrapOrError(Section.getContents(), Obj->getFileName()));
1226 uint64_t VMAAdjustment = 0;
1227 if (shouldAdjustVA(Section))
1228 VMAAdjustment = AdjustVMA;
1230 uint64_t Size;
1231 uint64_t Index;
1232 bool PrintedSection = false;
1233 std::vector<RelocationRef> Rels = RelocMap[Section];
1234 std::vector<RelocationRef>::const_iterator RelCur = Rels.begin();
1235 std::vector<RelocationRef>::const_iterator RelEnd = Rels.end();
1236 // Disassemble symbol by symbol.
1237 for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) {
1238 std::string SymbolName = std::get<1>(Symbols[SI]).str();
1239 if (Demangle)
1240 SymbolName = demangle(SymbolName);
1242 // Skip if --disassemble-functions is not empty and the symbol is not in
1243 // the list.
1244 if (!DisasmFuncsSet.empty() && !DisasmFuncsSet.count(SymbolName))
1245 continue;
1247 uint64_t Start = std::get<0>(Symbols[SI]);
1248 if (Start < SectionAddr || StopAddress <= Start)
1249 continue;
1250 else
1251 FoundDisasmFuncsSet.insert(SymbolName);
1253 // The end is the section end, the beginning of the next symbol, or
1254 // --stop-address.
1255 uint64_t End = std::min<uint64_t>(SectionAddr + SectSize, StopAddress);
1256 if (SI + 1 < SE)
1257 End = std::min(End, std::get<0>(Symbols[SI + 1]));
1258 if (Start >= End || End <= StartAddress)
1259 continue;
1260 Start -= SectionAddr;
1261 End -= SectionAddr;
1263 if (!PrintedSection) {
1264 PrintedSection = true;
1265 outs() << "\nDisassembly of section ";
1266 if (!SegmentName.empty())
1267 outs() << SegmentName << ",";
1268 outs() << SectionName << ":\n";
1271 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1272 if (std::get<2>(Symbols[SI]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1273 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1274 Start += 256;
1276 if (SI == SE - 1 ||
1277 std::get<2>(Symbols[SI + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1278 // cut trailing zeroes at the end of kernel
1279 // cut up to 256 bytes
1280 const uint64_t EndAlign = 256;
1281 const auto Limit = End - (std::min)(EndAlign, End - Start);
1282 while (End > Limit &&
1283 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1284 End -= 4;
1288 outs() << '\n';
1289 if (!NoLeadingAddr)
1290 outs() << format(Is64Bits ? "%016" PRIx64 " " : "%08" PRIx64 " ",
1291 SectionAddr + Start + VMAAdjustment);
1293 outs() << SymbolName << ":\n";
1295 // Don't print raw contents of a virtual section. A virtual section
1296 // doesn't have any contents in the file.
1297 if (Section.isVirtual()) {
1298 outs() << "...\n";
1299 continue;
1302 #ifndef NDEBUG
1303 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1304 #else
1305 raw_ostream &DebugOut = nulls();
1306 #endif
1308 // Some targets (like WebAssembly) have a special prelude at the start
1309 // of each symbol.
1310 DisAsm->onSymbolStart(SymbolName, Size, Bytes.slice(Start, End - Start),
1311 SectionAddr + Start, DebugOut, CommentStream);
1312 Start += Size;
1314 Index = Start;
1315 if (SectionAddr < StartAddress)
1316 Index = std::max<uint64_t>(Index, StartAddress - SectionAddr);
1318 // If there is a data/common symbol inside an ELF text section and we are
1319 // only disassembling text (applicable all architectures), we are in a
1320 // situation where we must print the data and not disassemble it.
1321 if (Obj->isELF() && !DisassembleAll && Section.isText()) {
1322 uint8_t SymTy = std::get<2>(Symbols[SI]);
1323 if (SymTy == ELF::STT_OBJECT || SymTy == ELF::STT_COMMON) {
1324 dumpELFData(SectionAddr, Index, End, Bytes);
1325 Index = End;
1329 bool CheckARMELFData = hasMappingSymbols(Obj) &&
1330 std::get<2>(Symbols[SI]) != ELF::STT_OBJECT &&
1331 !DisassembleAll;
1332 while (Index < End) {
1333 // ARM and AArch64 ELF binaries can interleave data and text in the
1334 // same section. We rely on the markers introduced to understand what
1335 // we need to dump. If the data marker is within a function, it is
1336 // denoted as a word/short etc.
1337 if (CheckARMELFData &&
1338 getMappingSymbolKind(MappingSymbols, Index) == 'd') {
1339 Index = dumpARMELFData(SectionAddr, Index, End, Obj, Bytes,
1340 MappingSymbols);
1341 continue;
1344 // When -z or --disassemble-zeroes are given we always dissasemble
1345 // them. Otherwise we might want to skip zero bytes we see.
1346 if (!DisassembleZeroes) {
1347 uint64_t MaxOffset = End - Index;
1348 // For -reloc: print zero blocks patched by relocations, so that
1349 // relocations can be shown in the dump.
1350 if (RelCur != RelEnd)
1351 MaxOffset = RelCur->getOffset() - Index;
1353 if (size_t N =
1354 countSkippableZeroBytes(Bytes.slice(Index, MaxOffset))) {
1355 outs() << "\t\t..." << '\n';
1356 Index += N;
1357 continue;
1361 if (SecondarySTI) {
1362 if (getMappingSymbolKind(MappingSymbols, Index) == 'a') {
1363 STI = PrimaryIsThumb ? SecondarySTI : PrimarySTI;
1364 DisAsm = PrimaryIsThumb ? SecondaryDisAsm : PrimaryDisAsm;
1365 } else if (getMappingSymbolKind(MappingSymbols, Index) == 't') {
1366 STI = PrimaryIsThumb ? PrimarySTI : SecondarySTI;
1367 DisAsm = PrimaryIsThumb ? PrimaryDisAsm : SecondaryDisAsm;
1371 // Disassemble a real instruction or a data when disassemble all is
1372 // provided
1373 MCInst Inst;
1374 bool Disassembled = DisAsm->getInstruction(
1375 Inst, Size, Bytes.slice(Index), SectionAddr + Index, DebugOut,
1376 CommentStream);
1377 if (Size == 0)
1378 Size = 1;
1380 PIP.printInst(
1381 *IP, Disassembled ? &Inst : nullptr, Bytes.slice(Index, Size),
1382 {SectionAddr + Index + VMAAdjustment, Section.getIndex()}, outs(),
1383 "", *STI, &SP, &Rels);
1384 outs() << CommentStream.str();
1385 Comments.clear();
1387 // Try to resolve the target of a call, tail call, etc. to a specific
1388 // symbol.
1389 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1390 MIA->isConditionalBranch(Inst))) {
1391 uint64_t Target;
1392 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1393 // In a relocatable object, the target's section must reside in
1394 // the same section as the call instruction or it is accessed
1395 // through a relocation.
1397 // In a non-relocatable object, the target may be in any section.
1399 // N.B. We don't walk the relocations in the relocatable case yet.
1400 auto *TargetSectionSymbols = &Symbols;
1401 if (!Obj->isRelocatableObject()) {
1402 auto It = partition_point(
1403 SectionAddresses,
1404 [=](const std::pair<uint64_t, SectionRef> &O) {
1405 return O.first <= Target;
1407 if (It != SectionAddresses.begin()) {
1408 --It;
1409 TargetSectionSymbols = &AllSymbols[It->second];
1410 } else {
1411 TargetSectionSymbols = &AbsoluteSymbols;
1415 // Find the last symbol in the section whose offset is less than
1416 // or equal to the target. If there isn't a section that contains
1417 // the target, find the nearest preceding absolute symbol.
1418 auto TargetSym = partition_point(
1419 *TargetSectionSymbols,
1420 [=](const std::tuple<uint64_t, StringRef, uint8_t> &O) {
1421 return std::get<0>(O) <= Target;
1423 if (TargetSym == TargetSectionSymbols->begin()) {
1424 TargetSectionSymbols = &AbsoluteSymbols;
1425 TargetSym = partition_point(
1426 AbsoluteSymbols,
1427 [=](const std::tuple<uint64_t, StringRef, uint8_t> &O) {
1428 return std::get<0>(O) <= Target;
1431 if (TargetSym != TargetSectionSymbols->begin()) {
1432 --TargetSym;
1433 uint64_t TargetAddress = std::get<0>(*TargetSym);
1434 StringRef TargetName = std::get<1>(*TargetSym);
1435 outs() << " <" << TargetName;
1436 uint64_t Disp = Target - TargetAddress;
1437 if (Disp)
1438 outs() << "+0x" << Twine::utohexstr(Disp);
1439 outs() << '>';
1443 outs() << "\n";
1445 // Hexagon does this in pretty printer
1446 if (Obj->getArch() != Triple::hexagon) {
1447 // Print relocation for instruction.
1448 while (RelCur != RelEnd) {
1449 uint64_t Offset = RelCur->getOffset();
1450 // If this relocation is hidden, skip it.
1451 if (getHidden(*RelCur) || SectionAddr + Offset < StartAddress) {
1452 ++RelCur;
1453 continue;
1456 // Stop when RelCur's offset is past the current instruction.
1457 if (Offset >= Index + Size)
1458 break;
1460 // When --adjust-vma is used, update the address printed.
1461 if (RelCur->getSymbol() != Obj->symbol_end()) {
1462 Expected<section_iterator> SymSI =
1463 RelCur->getSymbol()->getSection();
1464 if (SymSI && *SymSI != Obj->section_end() &&
1465 shouldAdjustVA(**SymSI))
1466 Offset += AdjustVMA;
1469 printRelocation(*RelCur, SectionAddr + Offset, Is64Bits);
1470 ++RelCur;
1474 Index += Size;
1478 StringSet<> MissingDisasmFuncsSet =
1479 set_difference(DisasmFuncsSet, FoundDisasmFuncsSet);
1480 for (StringRef MissingDisasmFunc : MissingDisasmFuncsSet.keys())
1481 warn("failed to disassemble missing function " + MissingDisasmFunc);
1484 static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
1485 const Target *TheTarget = getTarget(Obj);
1487 // Package up features to be passed to target/subtarget
1488 SubtargetFeatures Features = Obj->getFeatures();
1489 if (!MAttrs.empty())
1490 for (unsigned I = 0; I != MAttrs.size(); ++I)
1491 Features.AddFeature(MAttrs[I]);
1493 std::unique_ptr<const MCRegisterInfo> MRI(
1494 TheTarget->createMCRegInfo(TripleName));
1495 if (!MRI)
1496 report_error(Obj->getFileName(),
1497 "no register info for target " + TripleName);
1499 // Set up disassembler.
1500 std::unique_ptr<const MCAsmInfo> AsmInfo(
1501 TheTarget->createMCAsmInfo(*MRI, TripleName));
1502 if (!AsmInfo)
1503 report_error(Obj->getFileName(),
1504 "no assembly info for target " + TripleName);
1505 std::unique_ptr<const MCSubtargetInfo> STI(
1506 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1507 if (!STI)
1508 report_error(Obj->getFileName(),
1509 "no subtarget info for target " + TripleName);
1510 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1511 if (!MII)
1512 report_error(Obj->getFileName(),
1513 "no instruction info for target " + TripleName);
1514 MCObjectFileInfo MOFI;
1515 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1516 // FIXME: for now initialize MCObjectFileInfo with default values
1517 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
1519 std::unique_ptr<MCDisassembler> DisAsm(
1520 TheTarget->createMCDisassembler(*STI, Ctx));
1521 if (!DisAsm)
1522 report_error(Obj->getFileName(),
1523 "no disassembler for target " + TripleName);
1525 // If we have an ARM object file, we need a second disassembler, because
1526 // ARM CPUs have two different instruction sets: ARM mode, and Thumb mode.
1527 // We use mapping symbols to switch between the two assemblers, where
1528 // appropriate.
1529 std::unique_ptr<MCDisassembler> SecondaryDisAsm;
1530 std::unique_ptr<const MCSubtargetInfo> SecondarySTI;
1531 if (isArmElf(Obj) && !STI->checkFeatures("+mclass")) {
1532 if (STI->checkFeatures("+thumb-mode"))
1533 Features.AddFeature("-thumb-mode");
1534 else
1535 Features.AddFeature("+thumb-mode");
1536 SecondarySTI.reset(TheTarget->createMCSubtargetInfo(TripleName, MCPU,
1537 Features.getString()));
1538 SecondaryDisAsm.reset(TheTarget->createMCDisassembler(*SecondarySTI, Ctx));
1541 std::unique_ptr<const MCInstrAnalysis> MIA(
1542 TheTarget->createMCInstrAnalysis(MII.get()));
1544 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1545 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1546 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
1547 if (!IP)
1548 report_error(Obj->getFileName(),
1549 "no instruction printer for target " + TripleName);
1550 IP->setPrintImmHex(PrintImmHex);
1552 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
1553 SourcePrinter SP(Obj, TheTarget->getName());
1555 for (StringRef Opt : DisassemblerOptions)
1556 if (!IP->applyTargetSpecificCLOption(Opt))
1557 error("Unrecognized disassembler option: " + Opt);
1559 disassembleObject(TheTarget, Obj, Ctx, DisAsm.get(), SecondaryDisAsm.get(),
1560 MIA.get(), IP.get(), STI.get(), SecondarySTI.get(), PIP,
1561 SP, InlineRelocs);
1564 void printRelocations(const ObjectFile *Obj) {
1565 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1566 "%08" PRIx64;
1567 // Regular objdump doesn't print relocations in non-relocatable object
1568 // files.
1569 if (!Obj->isRelocatableObject())
1570 return;
1572 // Build a mapping from relocation target to a vector of relocation
1573 // sections. Usually, there is an only one relocation section for
1574 // each relocated section.
1575 MapVector<SectionRef, std::vector<SectionRef>> SecToRelSec;
1576 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1577 if (Section.relocation_begin() == Section.relocation_end())
1578 continue;
1579 const SectionRef TargetSec = *Section.getRelocatedSection();
1580 SecToRelSec[TargetSec].push_back(Section);
1583 for (std::pair<SectionRef, std::vector<SectionRef>> &P : SecToRelSec) {
1584 StringRef SecName;
1585 error(P.first.getName(SecName));
1586 outs() << "RELOCATION RECORDS FOR [" << SecName << "]:\n";
1588 for (SectionRef Section : P.second) {
1589 for (const RelocationRef &Reloc : Section.relocations()) {
1590 uint64_t Address = Reloc.getOffset();
1591 SmallString<32> RelocName;
1592 SmallString<32> ValueStr;
1593 if (Address < StartAddress || Address > StopAddress || getHidden(Reloc))
1594 continue;
1595 Reloc.getTypeName(RelocName);
1596 error(getRelocationValueString(Reloc, ValueStr));
1597 outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1598 << ValueStr << "\n";
1601 outs() << "\n";
1605 void printDynamicRelocations(const ObjectFile *Obj) {
1606 // For the moment, this option is for ELF only
1607 if (!Obj->isELF())
1608 return;
1610 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
1611 if (!Elf || Elf->getEType() != ELF::ET_DYN) {
1612 error("not a dynamic object");
1613 return;
1616 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1617 if (DynRelSec.empty())
1618 return;
1620 outs() << "DYNAMIC RELOCATION RECORDS\n";
1621 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1622 for (const SectionRef &Section : DynRelSec)
1623 for (const RelocationRef &Reloc : Section.relocations()) {
1624 uint64_t Address = Reloc.getOffset();
1625 SmallString<32> RelocName;
1626 SmallString<32> ValueStr;
1627 Reloc.getTypeName(RelocName);
1628 error(getRelocationValueString(Reloc, ValueStr));
1629 outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1630 << ValueStr << "\n";
1634 // Returns true if we need to show LMA column when dumping section headers. We
1635 // show it only when the platform is ELF and either we have at least one section
1636 // whose VMA and LMA are different and/or when --show-lma flag is used.
1637 static bool shouldDisplayLMA(const ObjectFile *Obj) {
1638 if (!Obj->isELF())
1639 return false;
1640 for (const SectionRef &S : ToolSectionFilter(*Obj))
1641 if (S.getAddress() != getELFSectionLMA(S))
1642 return true;
1643 return ShowLMA;
1646 void printSectionHeaders(const ObjectFile *Obj) {
1647 bool HasLMAColumn = shouldDisplayLMA(Obj);
1648 if (HasLMAColumn)
1649 outs() << "Sections:\n"
1650 "Idx Name Size VMA LMA "
1651 "Type\n";
1652 else
1653 outs() << "Sections:\n"
1654 "Idx Name Size VMA Type\n";
1656 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1657 StringRef Name;
1658 error(Section.getName(Name));
1659 uint64_t VMA = Section.getAddress();
1660 if (shouldAdjustVA(Section))
1661 VMA += AdjustVMA;
1663 uint64_t Size = Section.getSize();
1664 bool Text = Section.isText();
1665 bool Data = Section.isData();
1666 bool BSS = Section.isBSS();
1667 std::string Type = (std::string(Text ? "TEXT " : "") +
1668 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1670 if (HasLMAColumn)
1671 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %016" PRIx64
1672 " %s\n",
1673 (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1674 VMA, getELFSectionLMA(Section), Type.c_str());
1675 else
1676 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
1677 (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1678 VMA, Type.c_str());
1680 outs() << "\n";
1683 void printSectionContents(const ObjectFile *Obj) {
1684 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1685 StringRef Name;
1686 error(Section.getName(Name));
1687 uint64_t BaseAddr = Section.getAddress();
1688 uint64_t Size = Section.getSize();
1689 if (!Size)
1690 continue;
1692 outs() << "Contents of section " << Name << ":\n";
1693 if (Section.isBSS()) {
1694 outs() << format("<skipping contents of bss section at [%04" PRIx64
1695 ", %04" PRIx64 ")>\n",
1696 BaseAddr, BaseAddr + Size);
1697 continue;
1700 StringRef Contents = unwrapOrError(Section.getContents(), Obj->getFileName());
1702 // Dump out the content as hex and printable ascii characters.
1703 for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) {
1704 outs() << format(" %04" PRIx64 " ", BaseAddr + Addr);
1705 // Dump line of hex.
1706 for (std::size_t I = 0; I < 16; ++I) {
1707 if (I != 0 && I % 4 == 0)
1708 outs() << ' ';
1709 if (Addr + I < End)
1710 outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true)
1711 << hexdigit(Contents[Addr + I] & 0xF, true);
1712 else
1713 outs() << " ";
1715 // Print ascii.
1716 outs() << " ";
1717 for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) {
1718 if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF))
1719 outs() << Contents[Addr + I];
1720 else
1721 outs() << ".";
1723 outs() << "\n";
1728 void printSymbolTable(const ObjectFile *O, StringRef ArchiveName,
1729 StringRef ArchitectureName) {
1730 outs() << "SYMBOL TABLE:\n";
1732 if (const COFFObjectFile *Coff = dyn_cast<const COFFObjectFile>(O)) {
1733 printCOFFSymbolTable(Coff);
1734 return;
1737 const StringRef FileName = O->getFileName();
1738 for (auto I = O->symbol_begin(), E = O->symbol_end(); I != E; ++I) {
1739 const SymbolRef &Symbol = *I;
1740 uint64_t Address = unwrapOrError(Symbol.getAddress(), ArchiveName, FileName,
1741 ArchitectureName);
1742 if ((Address < StartAddress) || (Address > StopAddress))
1743 continue;
1744 SymbolRef::Type Type = unwrapOrError(Symbol.getType(), ArchiveName,
1745 FileName, ArchitectureName);
1746 uint32_t Flags = Symbol.getFlags();
1747 section_iterator Section = unwrapOrError(Symbol.getSection(), ArchiveName,
1748 FileName, ArchitectureName);
1749 StringRef Name;
1750 if (Type == SymbolRef::ST_Debug && Section != O->section_end())
1751 Section->getName(Name);
1752 else
1753 Name = unwrapOrError(Symbol.getName(), ArchiveName, FileName,
1754 ArchitectureName);
1756 bool Global = Flags & SymbolRef::SF_Global;
1757 bool Weak = Flags & SymbolRef::SF_Weak;
1758 bool Absolute = Flags & SymbolRef::SF_Absolute;
1759 bool Common = Flags & SymbolRef::SF_Common;
1760 bool Hidden = Flags & SymbolRef::SF_Hidden;
1762 char GlobLoc = ' ';
1763 if (Type != SymbolRef::ST_Unknown)
1764 GlobLoc = Global ? 'g' : 'l';
1765 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1766 ? 'd' : ' ';
1767 char FileFunc = ' ';
1768 if (Type == SymbolRef::ST_File)
1769 FileFunc = 'f';
1770 else if (Type == SymbolRef::ST_Function)
1771 FileFunc = 'F';
1772 else if (Type == SymbolRef::ST_Data)
1773 FileFunc = 'O';
1775 const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 :
1776 "%08" PRIx64;
1778 outs() << format(Fmt, Address) << " "
1779 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1780 << (Weak ? 'w' : ' ') // Weak?
1781 << ' ' // Constructor. Not supported yet.
1782 << ' ' // Warning. Not supported yet.
1783 << ' ' // Indirect reference to another symbol.
1784 << Debug // Debugging (d) or dynamic (D) symbol.
1785 << FileFunc // Name of function (F), file (f) or object (O).
1786 << ' ';
1787 if (Absolute) {
1788 outs() << "*ABS*";
1789 } else if (Common) {
1790 outs() << "*COM*";
1791 } else if (Section == O->section_end()) {
1792 outs() << "*UND*";
1793 } else {
1794 if (const MachOObjectFile *MachO =
1795 dyn_cast<const MachOObjectFile>(O)) {
1796 DataRefImpl DR = Section->getRawDataRefImpl();
1797 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1798 outs() << SegmentName << ",";
1800 StringRef SectionName;
1801 error(Section->getName(SectionName));
1802 outs() << SectionName;
1805 if (Common || isa<ELFObjectFileBase>(O)) {
1806 uint64_t Val =
1807 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1808 outs() << format("\t%08" PRIx64, Val);
1811 if (isa<ELFObjectFileBase>(O)) {
1812 uint8_t Other = ELFSymbolRef(Symbol).getOther();
1813 switch (Other) {
1814 case ELF::STV_DEFAULT:
1815 break;
1816 case ELF::STV_INTERNAL:
1817 outs() << " .internal";
1818 break;
1819 case ELF::STV_HIDDEN:
1820 outs() << " .hidden";
1821 break;
1822 case ELF::STV_PROTECTED:
1823 outs() << " .protected";
1824 break;
1825 default:
1826 outs() << format(" 0x%02x", Other);
1827 break;
1829 } else if (Hidden) {
1830 outs() << " .hidden";
1833 if (Demangle)
1834 outs() << ' ' << demangle(Name) << '\n';
1835 else
1836 outs() << ' ' << Name << '\n';
1840 static void printUnwindInfo(const ObjectFile *O) {
1841 outs() << "Unwind info:\n\n";
1843 if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O))
1844 printCOFFUnwindInfo(Coff);
1845 else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O))
1846 printMachOUnwindInfo(MachO);
1847 else
1848 // TODO: Extract DWARF dump tool to objdump.
1849 WithColor::error(errs(), ToolName)
1850 << "This operation is only currently supported "
1851 "for COFF and MachO object files.\n";
1854 /// Dump the raw contents of the __clangast section so the output can be piped
1855 /// into llvm-bcanalyzer.
1856 void printRawClangAST(const ObjectFile *Obj) {
1857 if (outs().is_displayed()) {
1858 WithColor::error(errs(), ToolName)
1859 << "The -raw-clang-ast option will dump the raw binary contents of "
1860 "the clang ast section.\n"
1861 "Please redirect the output to a file or another program such as "
1862 "llvm-bcanalyzer.\n";
1863 return;
1866 StringRef ClangASTSectionName("__clangast");
1867 if (isa<COFFObjectFile>(Obj)) {
1868 ClangASTSectionName = "clangast";
1871 Optional<object::SectionRef> ClangASTSection;
1872 for (auto Sec : ToolSectionFilter(*Obj)) {
1873 StringRef Name;
1874 Sec.getName(Name);
1875 if (Name == ClangASTSectionName) {
1876 ClangASTSection = Sec;
1877 break;
1880 if (!ClangASTSection)
1881 return;
1883 StringRef ClangASTContents = unwrapOrError(
1884 ClangASTSection.getValue().getContents(), Obj->getFileName());
1885 outs().write(ClangASTContents.data(), ClangASTContents.size());
1888 static void printFaultMaps(const ObjectFile *Obj) {
1889 StringRef FaultMapSectionName;
1891 if (isa<ELFObjectFileBase>(Obj)) {
1892 FaultMapSectionName = ".llvm_faultmaps";
1893 } else if (isa<MachOObjectFile>(Obj)) {
1894 FaultMapSectionName = "__llvm_faultmaps";
1895 } else {
1896 WithColor::error(errs(), ToolName)
1897 << "This operation is only currently supported "
1898 "for ELF and Mach-O executable files.\n";
1899 return;
1902 Optional<object::SectionRef> FaultMapSection;
1904 for (auto Sec : ToolSectionFilter(*Obj)) {
1905 StringRef Name;
1906 Sec.getName(Name);
1907 if (Name == FaultMapSectionName) {
1908 FaultMapSection = Sec;
1909 break;
1913 outs() << "FaultMap table:\n";
1915 if (!FaultMapSection.hasValue()) {
1916 outs() << "<not found>\n";
1917 return;
1920 StringRef FaultMapContents =
1921 unwrapOrError(FaultMapSection.getValue().getContents(), Obj->getFileName());
1922 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1923 FaultMapContents.bytes_end());
1925 outs() << FMP;
1928 static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) {
1929 if (O->isELF()) {
1930 printELFFileHeader(O);
1931 printELFDynamicSection(O);
1932 printELFSymbolVersionInfo(O);
1933 return;
1935 if (O->isCOFF())
1936 return printCOFFFileHeader(O);
1937 if (O->isWasm())
1938 return printWasmFileHeader(O);
1939 if (O->isMachO()) {
1940 printMachOFileHeader(O);
1941 if (!OnlyFirst)
1942 printMachOLoadCommands(O);
1943 return;
1945 report_error(O->getFileName(), "Invalid/Unsupported object file format");
1948 static void printFileHeaders(const ObjectFile *O) {
1949 if (!O->isELF() && !O->isCOFF())
1950 report_error(O->getFileName(), "Invalid/Unsupported object file format");
1952 Triple::ArchType AT = O->getArch();
1953 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
1954 uint64_t Address = unwrapOrError(O->getStartAddress(), O->getFileName());
1956 StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1957 outs() << "start address: "
1958 << "0x" << format(Fmt.data(), Address) << "\n\n";
1961 static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
1962 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
1963 if (!ModeOrErr) {
1964 WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n";
1965 consumeError(ModeOrErr.takeError());
1966 return;
1968 sys::fs::perms Mode = ModeOrErr.get();
1969 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1970 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1971 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1972 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1973 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1974 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1975 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1976 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1977 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
1979 outs() << " ";
1981 outs() << format("%d/%d %6" PRId64 " ", unwrapOrError(C.getUID(), Filename),
1982 unwrapOrError(C.getGID(), Filename),
1983 unwrapOrError(C.getRawSize(), Filename));
1985 StringRef RawLastModified = C.getRawLastModified();
1986 unsigned Seconds;
1987 if (RawLastModified.getAsInteger(10, Seconds))
1988 outs() << "(date: \"" << RawLastModified
1989 << "\" contains non-decimal chars) ";
1990 else {
1991 // Since ctime(3) returns a 26 character string of the form:
1992 // "Sun Sep 16 01:03:52 1973\n\0"
1993 // just print 24 characters.
1994 time_t t = Seconds;
1995 outs() << format("%.24s ", ctime(&t));
1998 StringRef Name = "";
1999 Expected<StringRef> NameOrErr = C.getName();
2000 if (!NameOrErr) {
2001 consumeError(NameOrErr.takeError());
2002 Name = unwrapOrError(C.getRawName(), Filename);
2003 } else {
2004 Name = NameOrErr.get();
2006 outs() << Name << "\n";
2009 // For ELF only now.
2010 static bool shouldWarnForInvalidStartStopAddress(ObjectFile *Obj) {
2011 if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj)) {
2012 if (Elf->getEType() != ELF::ET_REL)
2013 return true;
2015 return false;
2018 static void checkForInvalidStartStopAddress(ObjectFile *Obj,
2019 uint64_t Start, uint64_t Stop) {
2020 if (!shouldWarnForInvalidStartStopAddress(Obj))
2021 return;
2023 for (const SectionRef &Section : Obj->sections())
2024 if (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC) {
2025 uint64_t BaseAddr = Section.getAddress();
2026 uint64_t Size = Section.getSize();
2027 if ((Start < BaseAddr + Size) && Stop > BaseAddr)
2028 return;
2031 if (StartAddress.getNumOccurrences() == 0)
2032 warn("no section has address less than 0x" +
2033 Twine::utohexstr(Stop) + " specified by --stop-address");
2034 else if (StopAddress.getNumOccurrences() == 0)
2035 warn("no section has address greater than or equal to 0x" +
2036 Twine::utohexstr(Start) + " specified by --start-address");
2037 else
2038 warn("no section overlaps the range [0x" +
2039 Twine::utohexstr(Start) + ",0x" + Twine::utohexstr(Stop) +
2040 ") specified by --start-address/--stop-address");
2043 static void dumpObject(ObjectFile *O, const Archive *A = nullptr,
2044 const Archive::Child *C = nullptr) {
2045 // Avoid other output when using a raw option.
2046 if (!RawClangAST) {
2047 outs() << '\n';
2048 if (A)
2049 outs() << A->getFileName() << "(" << O->getFileName() << ")";
2050 else
2051 outs() << O->getFileName();
2052 outs() << ":\tfile format " << O->getFileFormatName() << "\n\n";
2055 if (StartAddress.getNumOccurrences() || StopAddress.getNumOccurrences())
2056 checkForInvalidStartStopAddress(O, StartAddress, StopAddress);
2058 StringRef ArchiveName = A ? A->getFileName() : "";
2059 if (FileHeaders)
2060 printFileHeaders(O);
2061 if (ArchiveHeaders && !MachOOpt && C)
2062 printArchiveChild(ArchiveName, *C);
2063 if (Disassemble)
2064 disassembleObject(O, Relocations);
2065 if (Relocations && !Disassemble)
2066 printRelocations(O);
2067 if (DynamicRelocations)
2068 printDynamicRelocations(O);
2069 if (SectionHeaders)
2070 printSectionHeaders(O);
2071 if (SectionContents)
2072 printSectionContents(O);
2073 if (SymbolTable)
2074 printSymbolTable(O, ArchiveName);
2075 if (UnwindInfo)
2076 printUnwindInfo(O);
2077 if (PrivateHeaders || FirstPrivateHeader)
2078 printPrivateFileHeaders(O, FirstPrivateHeader);
2079 if (ExportsTrie)
2080 printExportsTrie(O);
2081 if (Rebase)
2082 printRebaseTable(O);
2083 if (Bind)
2084 printBindTable(O);
2085 if (LazyBind)
2086 printLazyBindTable(O);
2087 if (WeakBind)
2088 printWeakBindTable(O);
2089 if (RawClangAST)
2090 printRawClangAST(O);
2091 if (FaultMapSection)
2092 printFaultMaps(O);
2093 if (DwarfDumpType != DIDT_Null) {
2094 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O);
2095 // Dump the complete DWARF structure.
2096 DIDumpOptions DumpOpts;
2097 DumpOpts.DumpType = DwarfDumpType;
2098 DICtx->dump(outs(), DumpOpts);
2102 static void dumpObject(const COFFImportFile *I, const Archive *A,
2103 const Archive::Child *C = nullptr) {
2104 StringRef ArchiveName = A ? A->getFileName() : "";
2106 // Avoid other output when using a raw option.
2107 if (!RawClangAST)
2108 outs() << '\n'
2109 << ArchiveName << "(" << I->getFileName() << ")"
2110 << ":\tfile format COFF-import-file"
2111 << "\n\n";
2113 if (ArchiveHeaders && !MachOOpt && C)
2114 printArchiveChild(ArchiveName, *C);
2115 if (SymbolTable)
2116 printCOFFSymbolTable(I);
2119 /// Dump each object file in \a a;
2120 static void dumpArchive(const Archive *A) {
2121 Error Err = Error::success();
2122 for (auto &C : A->children(Err)) {
2123 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2124 if (!ChildOrErr) {
2125 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2126 report_error(std::move(E), A->getFileName(), C);
2127 continue;
2129 if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2130 dumpObject(O, A, &C);
2131 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2132 dumpObject(I, A, &C);
2133 else
2134 report_error(errorCodeToError(object_error::invalid_file_type),
2135 A->getFileName());
2137 if (Err)
2138 report_error(std::move(Err), A->getFileName());
2141 /// Open file and figure out how to dump it.
2142 static void dumpInput(StringRef file) {
2143 // If we are using the Mach-O specific object file parser, then let it parse
2144 // the file and process the command line options. So the -arch flags can
2145 // be used to select specific slices, etc.
2146 if (MachOOpt) {
2147 parseInputMachO(file);
2148 return;
2151 // Attempt to open the binary.
2152 OwningBinary<Binary> OBinary = unwrapOrError(createBinary(file), file);
2153 Binary &Binary = *OBinary.getBinary();
2155 if (Archive *A = dyn_cast<Archive>(&Binary))
2156 dumpArchive(A);
2157 else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary))
2158 dumpObject(O);
2159 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
2160 parseInputMachO(UB);
2161 else
2162 report_error(errorCodeToError(object_error::invalid_file_type), file);
2164 } // namespace llvm
2166 int main(int argc, char **argv) {
2167 using namespace llvm;
2168 InitLLVM X(argc, argv);
2169 const cl::OptionCategory *OptionFilters[] = {&ObjdumpCat, &MachOCat};
2170 cl::HideUnrelatedOptions(OptionFilters);
2172 // Initialize targets and assembly printers/parsers.
2173 InitializeAllTargetInfos();
2174 InitializeAllTargetMCs();
2175 InitializeAllDisassemblers();
2177 // Register the target printer for --version.
2178 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2180 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2182 if (StartAddress >= StopAddress)
2183 error("start address should be less than stop address");
2185 ToolName = argv[0];
2187 // Defaults to a.out if no filenames specified.
2188 if (InputFilenames.empty())
2189 InputFilenames.push_back("a.out");
2191 if (AllHeaders)
2192 ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations =
2193 SectionHeaders = SymbolTable = true;
2195 if (DisassembleAll || PrintSource || PrintLines ||
2196 (!DisassembleFunctions.empty()))
2197 Disassemble = true;
2199 if (!ArchiveHeaders && !Disassemble && DwarfDumpType == DIDT_Null &&
2200 !DynamicRelocations && !FileHeaders && !PrivateHeaders && !RawClangAST &&
2201 !Relocations && !SectionHeaders && !SectionContents && !SymbolTable &&
2202 !UnwindInfo && !FaultMapSection &&
2203 !(MachOOpt &&
2204 (Bind || DataInCode || DylibId || DylibsUsed || ExportsTrie ||
2205 FirstPrivateHeader || IndirectSymbols || InfoPlist || LazyBind ||
2206 LinkOptHints || ObjcMetaData || Rebase || UniversalHeaders ||
2207 WeakBind || !FilterSections.empty()))) {
2208 cl::PrintHelpMessage();
2209 return 2;
2212 DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2213 DisassembleFunctions.end());
2215 llvm::for_each(InputFilenames, dumpInput);
2217 warnOnNoMatchForSections();
2219 return EXIT_SUCCESS;