[MIParser] Set RegClassOrRegBank during instruction parsing
[llvm-complete.git] / tools / llvm-objdump / llvm-objdump.cpp
blob34a44b3b7fa947c9c43954a1e9ae31c2a25579cf
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/FormatVariadic.h"
55 #include "llvm/Support/GraphWriter.h"
56 #include "llvm/Support/Host.h"
57 #include "llvm/Support/InitLLVM.h"
58 #include "llvm/Support/MemoryBuffer.h"
59 #include "llvm/Support/SourceMgr.h"
60 #include "llvm/Support/StringSaver.h"
61 #include "llvm/Support/TargetRegistry.h"
62 #include "llvm/Support/TargetSelect.h"
63 #include "llvm/Support/WithColor.h"
64 #include "llvm/Support/raw_ostream.h"
65 #include <algorithm>
66 #include <cctype>
67 #include <cstring>
68 #include <system_error>
69 #include <unordered_map>
70 #include <utility>
72 using namespace llvm::object;
74 namespace llvm {
76 cl::OptionCategory ObjdumpCat("llvm-objdump Options");
78 // MachO specific
79 extern cl::OptionCategory MachOCat;
80 extern cl::opt<bool> Bind;
81 extern cl::opt<bool> DataInCode;
82 extern cl::opt<bool> DylibsUsed;
83 extern cl::opt<bool> DylibId;
84 extern cl::opt<bool> ExportsTrie;
85 extern cl::opt<bool> FirstPrivateHeader;
86 extern cl::opt<bool> IndirectSymbols;
87 extern cl::opt<bool> InfoPlist;
88 extern cl::opt<bool> LazyBind;
89 extern cl::opt<bool> LinkOptHints;
90 extern cl::opt<bool> ObjcMetaData;
91 extern cl::opt<bool> Rebase;
92 extern cl::opt<bool> UniversalHeaders;
93 extern cl::opt<bool> WeakBind;
95 static cl::opt<uint64_t> AdjustVMA(
96 "adjust-vma",
97 cl::desc("Increase the displayed address by the specified offset"),
98 cl::value_desc("offset"), cl::init(0), cl::cat(ObjdumpCat));
100 static cl::opt<bool>
101 AllHeaders("all-headers",
102 cl::desc("Display all available header information"),
103 cl::cat(ObjdumpCat));
104 static cl::alias AllHeadersShort("x", cl::desc("Alias for --all-headers"),
105 cl::NotHidden, cl::Grouping,
106 cl::aliasopt(AllHeaders));
108 static cl::opt<std::string>
109 ArchName("arch-name",
110 cl::desc("Target arch to disassemble for, "
111 "see -version for available targets"),
112 cl::cat(ObjdumpCat));
114 cl::opt<bool> ArchiveHeaders("archive-headers",
115 cl::desc("Display archive header information"),
116 cl::cat(ObjdumpCat));
117 static cl::alias ArchiveHeadersShort("a",
118 cl::desc("Alias for --archive-headers"),
119 cl::NotHidden, cl::Grouping,
120 cl::aliasopt(ArchiveHeaders));
122 cl::opt<bool> Demangle("demangle", cl::desc("Demangle symbols names"),
123 cl::init(false), cl::cat(ObjdumpCat));
124 static cl::alias DemangleShort("C", cl::desc("Alias for --demangle"),
125 cl::NotHidden, cl::Grouping,
126 cl::aliasopt(Demangle));
128 cl::opt<bool> Disassemble(
129 "disassemble",
130 cl::desc("Display assembler mnemonics for the machine instructions"),
131 cl::cat(ObjdumpCat));
132 static cl::alias DisassembleShort("d", cl::desc("Alias for --disassemble"),
133 cl::NotHidden, cl::Grouping,
134 cl::aliasopt(Disassemble));
136 cl::opt<bool> DisassembleAll(
137 "disassemble-all",
138 cl::desc("Display assembler mnemonics for the machine instructions"),
139 cl::cat(ObjdumpCat));
140 static cl::alias DisassembleAllShort("D",
141 cl::desc("Alias for --disassemble-all"),
142 cl::NotHidden, cl::Grouping,
143 cl::aliasopt(DisassembleAll));
145 static cl::list<std::string>
146 DisassembleFunctions("disassemble-functions", cl::CommaSeparated,
147 cl::desc("List of functions to disassemble. "
148 "Accept demangled names when --demangle is "
149 "specified, otherwise accept mangled names"),
150 cl::cat(ObjdumpCat));
152 static cl::opt<bool> DisassembleZeroes(
153 "disassemble-zeroes",
154 cl::desc("Do not skip blocks of zeroes when disassembling"),
155 cl::cat(ObjdumpCat));
156 static cl::alias
157 DisassembleZeroesShort("z", cl::desc("Alias for --disassemble-zeroes"),
158 cl::NotHidden, cl::Grouping,
159 cl::aliasopt(DisassembleZeroes));
161 static cl::list<std::string>
162 DisassemblerOptions("disassembler-options",
163 cl::desc("Pass target specific disassembler options"),
164 cl::value_desc("options"), cl::CommaSeparated,
165 cl::cat(ObjdumpCat));
166 static cl::alias
167 DisassemblerOptionsShort("M", cl::desc("Alias for --disassembler-options"),
168 cl::NotHidden, cl::Grouping, cl::Prefix,
169 cl::CommaSeparated,
170 cl::aliasopt(DisassemblerOptions));
172 cl::opt<DIDumpType> DwarfDumpType(
173 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
174 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")),
175 cl::cat(ObjdumpCat));
177 static cl::opt<bool> DynamicRelocations(
178 "dynamic-reloc",
179 cl::desc("Display the dynamic relocation entries in the file"),
180 cl::cat(ObjdumpCat));
181 static cl::alias DynamicRelocationShort("R",
182 cl::desc("Alias for --dynamic-reloc"),
183 cl::NotHidden, cl::Grouping,
184 cl::aliasopt(DynamicRelocations));
186 static cl::opt<bool>
187 FaultMapSection("fault-map-section",
188 cl::desc("Display contents of faultmap section"),
189 cl::cat(ObjdumpCat));
191 static cl::opt<bool>
192 FileHeaders("file-headers",
193 cl::desc("Display the contents of the overall file header"),
194 cl::cat(ObjdumpCat));
195 static cl::alias FileHeadersShort("f", cl::desc("Alias for --file-headers"),
196 cl::NotHidden, cl::Grouping,
197 cl::aliasopt(FileHeaders));
199 cl::opt<bool> SectionContents("full-contents",
200 cl::desc("Display the content of each section"),
201 cl::cat(ObjdumpCat));
202 static cl::alias SectionContentsShort("s",
203 cl::desc("Alias for --full-contents"),
204 cl::NotHidden, cl::Grouping,
205 cl::aliasopt(SectionContents));
207 static cl::list<std::string> InputFilenames(cl::Positional,
208 cl::desc("<input object files>"),
209 cl::ZeroOrMore,
210 cl::cat(ObjdumpCat));
212 static cl::opt<bool>
213 PrintLines("line-numbers",
214 cl::desc("Display source line numbers with "
215 "disassembly. Implies disassemble object"),
216 cl::cat(ObjdumpCat));
217 static cl::alias PrintLinesShort("l", cl::desc("Alias for --line-numbers"),
218 cl::NotHidden, cl::Grouping,
219 cl::aliasopt(PrintLines));
221 static cl::opt<bool> MachOOpt("macho",
222 cl::desc("Use MachO specific object file parser"),
223 cl::cat(ObjdumpCat));
224 static cl::alias MachOm("m", cl::desc("Alias for --macho"), cl::NotHidden,
225 cl::Grouping, cl::aliasopt(MachOOpt));
227 cl::opt<std::string>
228 MCPU("mcpu",
229 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
230 cl::value_desc("cpu-name"), cl::init(""), cl::cat(ObjdumpCat));
232 cl::list<std::string> MAttrs("mattr", cl::CommaSeparated,
233 cl::desc("Target specific attributes"),
234 cl::value_desc("a1,+a2,-a3,..."),
235 cl::cat(ObjdumpCat));
237 cl::opt<bool> NoShowRawInsn("no-show-raw-insn",
238 cl::desc("When disassembling "
239 "instructions, do not print "
240 "the instruction bytes."),
241 cl::cat(ObjdumpCat));
242 cl::opt<bool> NoLeadingAddr("no-leading-addr",
243 cl::desc("Print no leading address"),
244 cl::cat(ObjdumpCat));
246 static cl::opt<bool> RawClangAST(
247 "raw-clang-ast",
248 cl::desc("Dump the raw binary contents of the clang AST section"),
249 cl::cat(ObjdumpCat));
251 cl::opt<bool>
252 Relocations("reloc", cl::desc("Display the relocation entries in the file"),
253 cl::cat(ObjdumpCat));
254 static cl::alias RelocationsShort("r", cl::desc("Alias for --reloc"),
255 cl::NotHidden, cl::Grouping,
256 cl::aliasopt(Relocations));
258 cl::opt<bool> PrintImmHex("print-imm-hex",
259 cl::desc("Use hex format for immediate values"),
260 cl::cat(ObjdumpCat));
262 cl::opt<bool> PrivateHeaders("private-headers",
263 cl::desc("Display format specific file headers"),
264 cl::cat(ObjdumpCat));
265 static cl::alias PrivateHeadersShort("p",
266 cl::desc("Alias for --private-headers"),
267 cl::NotHidden, cl::Grouping,
268 cl::aliasopt(PrivateHeaders));
270 cl::list<std::string>
271 FilterSections("section",
272 cl::desc("Operate on the specified sections only. "
273 "With -macho dump segment,section"),
274 cl::cat(ObjdumpCat));
275 static cl::alias FilterSectionsj("j", cl::desc("Alias for --section"),
276 cl::NotHidden, cl::Grouping, cl::Prefix,
277 cl::aliasopt(FilterSections));
279 cl::opt<bool> SectionHeaders("section-headers",
280 cl::desc("Display summaries of the "
281 "headers for each section."),
282 cl::cat(ObjdumpCat));
283 static cl::alias SectionHeadersShort("headers",
284 cl::desc("Alias for --section-headers"),
285 cl::NotHidden,
286 cl::aliasopt(SectionHeaders));
287 static cl::alias SectionHeadersShorter("h",
288 cl::desc("Alias for --section-headers"),
289 cl::NotHidden, cl::Grouping,
290 cl::aliasopt(SectionHeaders));
292 static cl::opt<bool>
293 ShowLMA("show-lma",
294 cl::desc("Display LMA column when dumping ELF section headers"),
295 cl::cat(ObjdumpCat));
297 static cl::opt<bool> PrintSource(
298 "source",
299 cl::desc(
300 "Display source inlined with disassembly. Implies disassemble object"),
301 cl::cat(ObjdumpCat));
302 static cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
303 cl::NotHidden, cl::Grouping,
304 cl::aliasopt(PrintSource));
306 static cl::opt<uint64_t>
307 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
308 cl::value_desc("address"), cl::init(0), cl::cat(ObjdumpCat));
309 static cl::opt<uint64_t> StopAddress("stop-address",
310 cl::desc("Stop disassembly at address"),
311 cl::value_desc("address"),
312 cl::init(UINT64_MAX), cl::cat(ObjdumpCat));
314 cl::opt<bool> SymbolTable("syms", cl::desc("Display the symbol table"),
315 cl::cat(ObjdumpCat));
316 static cl::alias SymbolTableShort("t", cl::desc("Alias for --syms"),
317 cl::NotHidden, cl::Grouping,
318 cl::aliasopt(SymbolTable));
320 cl::opt<std::string> TripleName("triple",
321 cl::desc("Target triple to disassemble for, "
322 "see -version for available targets"),
323 cl::cat(ObjdumpCat));
325 cl::opt<bool> UnwindInfo("unwind-info", cl::desc("Display unwind information"),
326 cl::cat(ObjdumpCat));
327 static cl::alias UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
328 cl::NotHidden, cl::Grouping,
329 cl::aliasopt(UnwindInfo));
331 static cl::opt<bool>
332 Wide("wide", cl::desc("Ignored for compatibility with GNU objdump"),
333 cl::cat(ObjdumpCat));
334 static cl::alias WideShort("w", cl::Grouping, cl::aliasopt(Wide));
336 static cl::extrahelp
337 HelpResponse("\nPass @FILE as argument to read options from FILE.\n");
339 static StringSet<> DisasmFuncsSet;
340 static StringSet<> FoundSectionSet;
341 static StringRef ToolName;
343 typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
345 namespace {
346 struct FilterResult {
347 // True if the section should not be skipped.
348 bool Keep;
350 // True if the index counter should be incremented, even if the section should
351 // be skipped. For example, sections may be skipped if they are not included
352 // in the --section flag, but we still want those to count toward the section
353 // count.
354 bool IncrementIndex;
356 } // namespace
358 static FilterResult checkSectionFilter(object::SectionRef S) {
359 if (FilterSections.empty())
360 return {/*Keep=*/true, /*IncrementIndex=*/true};
362 Expected<StringRef> SecNameOrErr = S.getName();
363 if (!SecNameOrErr) {
364 consumeError(SecNameOrErr.takeError());
365 return {/*Keep=*/false, /*IncrementIndex=*/false};
367 StringRef SecName = *SecNameOrErr;
369 // StringSet does not allow empty key so avoid adding sections with
370 // no name (such as the section with index 0) here.
371 if (!SecName.empty())
372 FoundSectionSet.insert(SecName);
374 // Only show the section if it's in the FilterSections list, but always
375 // increment so the indexing is stable.
376 return {/*Keep=*/is_contained(FilterSections, SecName),
377 /*IncrementIndex=*/true};
380 SectionFilter ToolSectionFilter(object::ObjectFile const &O, uint64_t *Idx) {
381 // Start at UINT64_MAX so that the first index returned after an increment is
382 // zero (after the unsigned wrap).
383 if (Idx)
384 *Idx = UINT64_MAX;
385 return SectionFilter(
386 [Idx](object::SectionRef S) {
387 FilterResult Result = checkSectionFilter(S);
388 if (Idx != nullptr && Result.IncrementIndex)
389 *Idx += 1;
390 return Result.Keep;
395 std::string getFileNameForError(const object::Archive::Child &C,
396 unsigned Index) {
397 Expected<StringRef> NameOrErr = C.getName();
398 if (NameOrErr)
399 return NameOrErr.get();
400 // If we have an error getting the name then we print the index of the archive
401 // member. Since we are already in an error state, we just ignore this error.
402 consumeError(NameOrErr.takeError());
403 return "<file index: " + std::to_string(Index) + ">";
406 void reportWarning(Twine Message, StringRef File) {
407 // Output order between errs() and outs() matters especially for archive
408 // files where the output is per member object.
409 outs().flush();
410 WithColor::warning(errs(), ToolName)
411 << "'" << File << "': " << Message << "\n";
412 errs().flush();
415 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Twine Message) {
416 WithColor::error(errs(), ToolName) << "'" << File << "': " << Message << "\n";
417 exit(1);
420 LLVM_ATTRIBUTE_NORETURN void reportError(Error E, StringRef FileName,
421 StringRef ArchiveName,
422 StringRef ArchitectureName) {
423 assert(E);
424 WithColor::error(errs(), ToolName);
425 if (ArchiveName != "")
426 errs() << ArchiveName << "(" << FileName << ")";
427 else
428 errs() << "'" << FileName << "'";
429 if (!ArchitectureName.empty())
430 errs() << " (for architecture " << ArchitectureName << ")";
431 std::string Buf;
432 raw_string_ostream OS(Buf);
433 logAllUnhandledErrors(std::move(E), OS);
434 OS.flush();
435 errs() << ": " << Buf;
436 exit(1);
439 static void reportCmdLineWarning(Twine Message) {
440 WithColor::warning(errs(), ToolName) << Message << "\n";
443 LLVM_ATTRIBUTE_NORETURN static void reportCmdLineError(Twine Message) {
444 WithColor::error(errs(), ToolName) << Message << "\n";
445 exit(1);
448 static void warnOnNoMatchForSections() {
449 SetVector<StringRef> MissingSections;
450 for (StringRef S : FilterSections) {
451 if (FoundSectionSet.count(S))
452 return;
453 // User may specify a unnamed section. Don't warn for it.
454 if (!S.empty())
455 MissingSections.insert(S);
458 // Warn only if no section in FilterSections is matched.
459 for (StringRef S : MissingSections)
460 reportCmdLineWarning("section '" + S +
461 "' mentioned in a -j/--section option, but not "
462 "found in any input file");
465 static const Target *getTarget(const ObjectFile *Obj) {
466 // Figure out the target triple.
467 Triple TheTriple("unknown-unknown-unknown");
468 if (TripleName.empty()) {
469 TheTriple = Obj->makeTriple();
470 } else {
471 TheTriple.setTriple(Triple::normalize(TripleName));
472 auto Arch = Obj->getArch();
473 if (Arch == Triple::arm || Arch == Triple::armeb)
474 Obj->setARMSubArch(TheTriple);
477 // Get the target specific parser.
478 std::string Error;
479 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
480 Error);
481 if (!TheTarget)
482 reportError(Obj->getFileName(), "can't find target: " + Error);
484 // Update the triple name and return the found target.
485 TripleName = TheTriple.getTriple();
486 return TheTarget;
489 bool isRelocAddressLess(RelocationRef A, RelocationRef B) {
490 return A.getOffset() < B.getOffset();
493 static Error getRelocationValueString(const RelocationRef &Rel,
494 SmallVectorImpl<char> &Result) {
495 const ObjectFile *Obj = Rel.getObject();
496 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
497 return getELFRelocationValueString(ELF, Rel, Result);
498 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
499 return getCOFFRelocationValueString(COFF, Rel, Result);
500 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
501 return getWasmRelocationValueString(Wasm, Rel, Result);
502 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
503 return getMachORelocationValueString(MachO, Rel, Result);
504 llvm_unreachable("unknown object file format");
507 /// Indicates whether this relocation should hidden when listing
508 /// relocations, usually because it is the trailing part of a multipart
509 /// relocation that will be printed as part of the leading relocation.
510 static bool getHidden(RelocationRef RelRef) {
511 auto *MachO = dyn_cast<MachOObjectFile>(RelRef.getObject());
512 if (!MachO)
513 return false;
515 unsigned Arch = MachO->getArch();
516 DataRefImpl Rel = RelRef.getRawDataRefImpl();
517 uint64_t Type = MachO->getRelocationType(Rel);
519 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
520 // is always hidden.
521 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc)
522 return Type == MachO::GENERIC_RELOC_PAIR;
524 if (Arch == Triple::x86_64) {
525 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
526 // an X86_64_RELOC_SUBTRACTOR.
527 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
528 DataRefImpl RelPrev = Rel;
529 RelPrev.d.a--;
530 uint64_t PrevType = MachO->getRelocationType(RelPrev);
531 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
532 return true;
536 return false;
539 namespace {
540 class SourcePrinter {
541 protected:
542 DILineInfo OldLineInfo;
543 const ObjectFile *Obj = nullptr;
544 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
545 // File name to file contents of source.
546 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
547 // Mark the line endings of the cached source.
548 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
549 // Keep track of missing sources.
550 StringSet<> MissingSources;
551 // Only emit 'no debug info' warning once.
552 bool WarnedNoDebugInfo;
554 private:
555 bool cacheSource(const DILineInfo& LineInfoFile);
557 public:
558 SourcePrinter() = default;
559 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch)
560 : Obj(Obj), WarnedNoDebugInfo(false) {
561 symbolize::LLVMSymbolizer::Options SymbolizerOpts;
562 SymbolizerOpts.PrintFunctions = DILineInfoSpecifier::FunctionNameKind::None;
563 SymbolizerOpts.Demangle = false;
564 SymbolizerOpts.DefaultArch = DefaultArch;
565 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
567 virtual ~SourcePrinter() = default;
568 virtual void printSourceLine(raw_ostream &OS,
569 object::SectionedAddress Address,
570 StringRef ObjectFilename,
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 if (MissingSources.insert(LineInfo.FileName).second)
582 reportWarning("failed to find source " + LineInfo.FileName,
583 Obj->getFileName());
584 return false;
586 Buffer = std::move(*BufferOrError);
588 // Chomp the file to get lines
589 const char *BufferStart = Buffer->getBufferStart(),
590 *BufferEnd = Buffer->getBufferEnd();
591 std::vector<StringRef> &Lines = LineCache[LineInfo.FileName];
592 const char *Start = BufferStart;
593 for (const char *I = BufferStart; I != BufferEnd; ++I)
594 if (*I == '\n') {
595 Lines.emplace_back(Start, I - Start - (BufferStart < I && I[-1] == '\r'));
596 Start = I + 1;
598 if (Start < BufferEnd)
599 Lines.emplace_back(Start, BufferEnd - Start);
600 SourceCache[LineInfo.FileName] = std::move(Buffer);
601 return true;
604 void SourcePrinter::printSourceLine(raw_ostream &OS,
605 object::SectionedAddress Address,
606 StringRef ObjectFilename,
607 StringRef Delimiter) {
608 if (!Symbolizer)
609 return;
611 DILineInfo LineInfo = DILineInfo();
612 auto ExpectedLineInfo = Symbolizer->symbolizeCode(*Obj, Address);
613 std::string ErrorMessage;
614 if (!ExpectedLineInfo)
615 ErrorMessage = toString(ExpectedLineInfo.takeError());
616 else
617 LineInfo = *ExpectedLineInfo;
619 if (LineInfo.FileName == DILineInfo::BadString) {
620 if (!WarnedNoDebugInfo) {
621 std::string Warning =
622 "failed to parse debug information for " + ObjectFilename.str();
623 if (!ErrorMessage.empty())
624 Warning += ": " + ErrorMessage;
625 reportWarning(Warning, ObjectFilename);
626 WarnedNoDebugInfo = true;
628 return;
631 if (LineInfo.Line == 0 || ((OldLineInfo.Line == LineInfo.Line) &&
632 (OldLineInfo.FileName == LineInfo.FileName)))
633 return;
635 if (PrintLines)
636 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
637 if (PrintSource) {
638 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
639 if (!cacheSource(LineInfo))
640 return;
641 auto LineBuffer = LineCache.find(LineInfo.FileName);
642 if (LineBuffer != LineCache.end()) {
643 if (LineInfo.Line > LineBuffer->second.size()) {
644 reportWarning(
645 formatv(
646 "debug info line number {0} exceeds the number of lines in {1}",
647 LineInfo.Line, LineInfo.FileName),
648 ObjectFilename);
649 return;
651 // Vector begins at 0, line numbers are non-zero
652 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1] << '\n';
655 OldLineInfo = LineInfo;
658 static bool isAArch64Elf(const ObjectFile *Obj) {
659 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
660 return Elf && Elf->getEMachine() == ELF::EM_AARCH64;
663 static bool isArmElf(const ObjectFile *Obj) {
664 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
665 return Elf && Elf->getEMachine() == ELF::EM_ARM;
668 static bool hasMappingSymbols(const ObjectFile *Obj) {
669 return isArmElf(Obj) || isAArch64Elf(Obj);
672 static void printRelocation(StringRef FileName, const RelocationRef &Rel,
673 uint64_t Address, bool Is64Bits) {
674 StringRef Fmt = Is64Bits ? "\t\t%016" PRIx64 ": " : "\t\t\t%08" PRIx64 ": ";
675 SmallString<16> Name;
676 SmallString<32> Val;
677 Rel.getTypeName(Name);
678 if (Error E = getRelocationValueString(Rel, Val))
679 reportError(std::move(E), FileName);
680 outs() << format(Fmt.data(), Address) << Name << "\t" << Val << "\n";
683 class PrettyPrinter {
684 public:
685 virtual ~PrettyPrinter() = default;
686 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
687 ArrayRef<uint8_t> Bytes,
688 object::SectionedAddress Address, raw_ostream &OS,
689 StringRef Annot, MCSubtargetInfo const &STI,
690 SourcePrinter *SP, StringRef ObjectFilename,
691 std::vector<RelocationRef> *Rels = nullptr) {
692 if (SP && (PrintSource || PrintLines))
693 SP->printSourceLine(OS, Address, ObjectFilename);
695 size_t Start = OS.tell();
696 if (!NoLeadingAddr)
697 OS << format("%8" PRIx64 ":", Address.Address);
698 if (!NoShowRawInsn) {
699 OS << ' ';
700 dumpBytes(Bytes, OS);
703 // The output of printInst starts with a tab. Print some spaces so that
704 // the tab has 1 column and advances to the target tab stop.
705 unsigned TabStop = NoShowRawInsn ? 16 : 40;
706 unsigned Column = OS.tell() - Start;
707 OS.indent(Column < TabStop - 1 ? TabStop - 1 - Column : 7 - Column % 8);
709 if (MI)
710 IP.printInst(MI, OS, "", STI);
711 else
712 OS << "\t<unknown>";
715 PrettyPrinter PrettyPrinterInst;
717 class HexagonPrettyPrinter : public PrettyPrinter {
718 public:
719 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
720 raw_ostream &OS) {
721 uint32_t opcode =
722 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
723 if (!NoLeadingAddr)
724 OS << format("%8" PRIx64 ":", Address);
725 if (!NoShowRawInsn) {
726 OS << "\t";
727 dumpBytes(Bytes.slice(0, 4), OS);
728 OS << format("\t%08" PRIx32, opcode);
731 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
732 object::SectionedAddress Address, raw_ostream &OS,
733 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
734 StringRef ObjectFilename,
735 std::vector<RelocationRef> *Rels) override {
736 if (SP && (PrintSource || PrintLines))
737 SP->printSourceLine(OS, Address, ObjectFilename, "");
738 if (!MI) {
739 printLead(Bytes, Address.Address, OS);
740 OS << " <unknown>";
741 return;
743 std::string Buffer;
745 raw_string_ostream TempStream(Buffer);
746 IP.printInst(MI, TempStream, "", STI);
748 StringRef Contents(Buffer);
749 // Split off bundle attributes
750 auto PacketBundle = Contents.rsplit('\n');
751 // Split off first instruction from the rest
752 auto HeadTail = PacketBundle.first.split('\n');
753 auto Preamble = " { ";
754 auto Separator = "";
756 // Hexagon's packets require relocations to be inline rather than
757 // clustered at the end of the packet.
758 std::vector<RelocationRef>::const_iterator RelCur = Rels->begin();
759 std::vector<RelocationRef>::const_iterator RelEnd = Rels->end();
760 auto PrintReloc = [&]() -> void {
761 while ((RelCur != RelEnd) && (RelCur->getOffset() <= Address.Address)) {
762 if (RelCur->getOffset() == Address.Address) {
763 printRelocation(ObjectFilename, *RelCur, Address.Address, false);
764 return;
766 ++RelCur;
770 while (!HeadTail.first.empty()) {
771 OS << Separator;
772 Separator = "\n";
773 if (SP && (PrintSource || PrintLines))
774 SP->printSourceLine(OS, Address, ObjectFilename, "");
775 printLead(Bytes, Address.Address, OS);
776 OS << Preamble;
777 Preamble = " ";
778 StringRef Inst;
779 auto Duplex = HeadTail.first.split('\v');
780 if (!Duplex.second.empty()) {
781 OS << Duplex.first;
782 OS << "; ";
783 Inst = Duplex.second;
785 else
786 Inst = HeadTail.first;
787 OS << Inst;
788 HeadTail = HeadTail.second.split('\n');
789 if (HeadTail.first.empty())
790 OS << " } " << PacketBundle.second;
791 PrintReloc();
792 Bytes = Bytes.slice(4);
793 Address.Address += 4;
797 HexagonPrettyPrinter HexagonPrettyPrinterInst;
799 class AMDGCNPrettyPrinter : public PrettyPrinter {
800 public:
801 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
802 object::SectionedAddress Address, raw_ostream &OS,
803 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
804 StringRef ObjectFilename,
805 std::vector<RelocationRef> *Rels) override {
806 if (SP && (PrintSource || PrintLines))
807 SP->printSourceLine(OS, Address, ObjectFilename);
809 if (MI) {
810 SmallString<40> InstStr;
811 raw_svector_ostream IS(InstStr);
813 IP.printInst(MI, IS, "", STI);
815 OS << left_justify(IS.str(), 60);
816 } else {
817 // an unrecognized encoding - this is probably data so represent it
818 // using the .long directive, or .byte directive if fewer than 4 bytes
819 // remaining
820 if (Bytes.size() >= 4) {
821 OS << format("\t.long 0x%08" PRIx32 " ",
822 support::endian::read32<support::little>(Bytes.data()));
823 OS.indent(42);
824 } else {
825 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
826 for (unsigned int i = 1; i < Bytes.size(); i++)
827 OS << format(", 0x%02" PRIx8, Bytes[i]);
828 OS.indent(55 - (6 * Bytes.size()));
832 OS << format("// %012" PRIX64 ":", Address.Address);
833 if (Bytes.size() >= 4) {
834 // D should be casted to uint32_t here as it is passed by format to
835 // snprintf as vararg.
836 for (uint32_t D : makeArrayRef(
837 reinterpret_cast<const support::little32_t *>(Bytes.data()),
838 Bytes.size() / 4))
839 OS << format(" %08" PRIX32, D);
840 } else {
841 for (unsigned char B : Bytes)
842 OS << format(" %02" PRIX8, B);
845 if (!Annot.empty())
846 OS << " // " << Annot;
849 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
851 class BPFPrettyPrinter : public PrettyPrinter {
852 public:
853 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
854 object::SectionedAddress Address, raw_ostream &OS,
855 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
856 StringRef ObjectFilename,
857 std::vector<RelocationRef> *Rels) override {
858 if (SP && (PrintSource || PrintLines))
859 SP->printSourceLine(OS, Address, ObjectFilename);
860 if (!NoLeadingAddr)
861 OS << format("%8" PRId64 ":", Address.Address / 8);
862 if (!NoShowRawInsn) {
863 OS << "\t";
864 dumpBytes(Bytes, OS);
866 if (MI)
867 IP.printInst(MI, OS, "", STI);
868 else
869 OS << "\t<unknown>";
872 BPFPrettyPrinter BPFPrettyPrinterInst;
874 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
875 switch(Triple.getArch()) {
876 default:
877 return PrettyPrinterInst;
878 case Triple::hexagon:
879 return HexagonPrettyPrinterInst;
880 case Triple::amdgcn:
881 return AMDGCNPrettyPrinterInst;
882 case Triple::bpfel:
883 case Triple::bpfeb:
884 return BPFPrettyPrinterInst;
889 static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
890 assert(Obj->isELF());
891 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
892 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
893 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
894 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
895 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
896 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
897 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
898 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
899 llvm_unreachable("Unsupported binary format");
902 template <class ELFT> static void
903 addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
904 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
905 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
906 uint8_t SymbolType = Symbol.getELFType();
907 if (SymbolType == ELF::STT_SECTION)
908 continue;
910 uint64_t Address = unwrapOrError(Symbol.getAddress(), Obj->getFileName());
911 // ELFSymbolRef::getAddress() returns size instead of value for common
912 // symbols which is not desirable for disassembly output. Overriding.
913 if (SymbolType == ELF::STT_COMMON)
914 Address = Obj->getSymbol(Symbol.getRawDataRefImpl())->st_value;
916 StringRef Name = unwrapOrError(Symbol.getName(), Obj->getFileName());
917 if (Name.empty())
918 continue;
920 section_iterator SecI =
921 unwrapOrError(Symbol.getSection(), Obj->getFileName());
922 if (SecI == Obj->section_end())
923 continue;
925 AllSymbols[*SecI].emplace_back(Address, Name, SymbolType);
929 static void
930 addDynamicElfSymbols(const ObjectFile *Obj,
931 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
932 assert(Obj->isELF());
933 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
934 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
935 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
936 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
937 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
938 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
939 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
940 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
941 else
942 llvm_unreachable("Unsupported binary format");
945 static void addPltEntries(const ObjectFile *Obj,
946 std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
947 StringSaver &Saver) {
948 Optional<SectionRef> Plt = None;
949 for (const SectionRef &Section : Obj->sections()) {
950 Expected<StringRef> SecNameOrErr = Section.getName();
951 if (!SecNameOrErr) {
952 consumeError(SecNameOrErr.takeError());
953 continue;
955 if (*SecNameOrErr == ".plt")
956 Plt = Section;
958 if (!Plt)
959 return;
960 if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) {
961 for (auto PltEntry : ElfObj->getPltAddresses()) {
962 SymbolRef Symbol(PltEntry.first, ElfObj);
963 uint8_t SymbolType = getElfSymbolType(Obj, Symbol);
965 StringRef Name = unwrapOrError(Symbol.getName(), Obj->getFileName());
966 if (!Name.empty())
967 AllSymbols[*Plt].emplace_back(
968 PltEntry.second, Saver.save((Name + "@plt").str()), SymbolType);
973 // Normally the disassembly output will skip blocks of zeroes. This function
974 // returns the number of zero bytes that can be skipped when dumping the
975 // disassembly of the instructions in Buf.
976 static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) {
977 // Find the number of leading zeroes.
978 size_t N = 0;
979 while (N < Buf.size() && !Buf[N])
980 ++N;
982 // We may want to skip blocks of zero bytes, but unless we see
983 // at least 8 of them in a row.
984 if (N < 8)
985 return 0;
987 // We skip zeroes in multiples of 4 because do not want to truncate an
988 // instruction if it starts with a zero byte.
989 return N & ~0x3;
992 // Returns a map from sections to their relocations.
993 static std::map<SectionRef, std::vector<RelocationRef>>
994 getRelocsMap(object::ObjectFile const &Obj) {
995 std::map<SectionRef, std::vector<RelocationRef>> Ret;
996 uint64_t I = (uint64_t)-1;
997 for (SectionRef Sec : Obj.sections()) {
998 ++I;
999 Expected<section_iterator> RelocatedOrErr = Sec.getRelocatedSection();
1000 if (!RelocatedOrErr)
1001 reportError(Obj.getFileName(),
1002 "section (" + Twine(I) +
1003 "): failed to get a relocated section: " +
1004 toString(RelocatedOrErr.takeError()));
1006 section_iterator Relocated = *RelocatedOrErr;
1007 if (Relocated == Obj.section_end() || !checkSectionFilter(*Relocated).Keep)
1008 continue;
1009 std::vector<RelocationRef> &V = Ret[*Relocated];
1010 for (const RelocationRef &R : Sec.relocations())
1011 V.push_back(R);
1012 // Sort relocations by address.
1013 llvm::stable_sort(V, isRelocAddressLess);
1015 return Ret;
1018 // Used for --adjust-vma to check if address should be adjusted by the
1019 // specified value for a given section.
1020 // For ELF we do not adjust non-allocatable sections like debug ones,
1021 // because they are not loadable.
1022 // TODO: implement for other file formats.
1023 static bool shouldAdjustVA(const SectionRef &Section) {
1024 const ObjectFile *Obj = Section.getObject();
1025 if (isa<object::ELFObjectFileBase>(Obj))
1026 return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
1027 return false;
1031 typedef std::pair<uint64_t, char> MappingSymbolPair;
1032 static char getMappingSymbolKind(ArrayRef<MappingSymbolPair> MappingSymbols,
1033 uint64_t Address) {
1034 auto It =
1035 partition_point(MappingSymbols, [Address](const MappingSymbolPair &Val) {
1036 return Val.first <= Address;
1038 // Return zero for any address before the first mapping symbol; this means
1039 // we should use the default disassembly mode, depending on the target.
1040 if (It == MappingSymbols.begin())
1041 return '\x00';
1042 return (It - 1)->second;
1045 static uint64_t
1046 dumpARMELFData(uint64_t SectionAddr, uint64_t Index, uint64_t End,
1047 const ObjectFile *Obj, ArrayRef<uint8_t> Bytes,
1048 ArrayRef<MappingSymbolPair> MappingSymbols) {
1049 support::endianness Endian =
1050 Obj->isLittleEndian() ? support::little : support::big;
1051 while (Index < End) {
1052 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1053 outs() << "\t";
1054 if (Index + 4 <= End) {
1055 dumpBytes(Bytes.slice(Index, 4), outs());
1056 outs() << "\t.word\t"
1057 << format_hex(
1058 support::endian::read32(Bytes.data() + Index, Endian), 10);
1059 Index += 4;
1060 } else if (Index + 2 <= End) {
1061 dumpBytes(Bytes.slice(Index, 2), outs());
1062 outs() << "\t\t.short\t"
1063 << format_hex(
1064 support::endian::read16(Bytes.data() + Index, Endian), 6);
1065 Index += 2;
1066 } else {
1067 dumpBytes(Bytes.slice(Index, 1), outs());
1068 outs() << "\t\t.byte\t" << format_hex(Bytes[0], 4);
1069 ++Index;
1071 outs() << "\n";
1072 if (getMappingSymbolKind(MappingSymbols, Index) != 'd')
1073 break;
1075 return Index;
1078 static void dumpELFData(uint64_t SectionAddr, uint64_t Index, uint64_t End,
1079 ArrayRef<uint8_t> Bytes) {
1080 // print out data up to 8 bytes at a time in hex and ascii
1081 uint8_t AsciiData[9] = {'\0'};
1082 uint8_t Byte;
1083 int NumBytes = 0;
1085 for (; Index < End; ++Index) {
1086 if (NumBytes == 0)
1087 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1088 Byte = Bytes.slice(Index)[0];
1089 outs() << format(" %02x", Byte);
1090 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
1092 uint8_t IndentOffset = 0;
1093 NumBytes++;
1094 if (Index == End - 1 || NumBytes > 8) {
1095 // Indent the space for less than 8 bytes data.
1096 // 2 spaces for byte and one for space between bytes
1097 IndentOffset = 3 * (8 - NumBytes);
1098 for (int Excess = NumBytes; Excess < 8; Excess++)
1099 AsciiData[Excess] = '\0';
1100 NumBytes = 8;
1102 if (NumBytes == 8) {
1103 AsciiData[8] = '\0';
1104 outs() << std::string(IndentOffset, ' ') << " ";
1105 outs() << reinterpret_cast<char *>(AsciiData);
1106 outs() << '\n';
1107 NumBytes = 0;
1112 static void disassembleObject(const Target *TheTarget, const ObjectFile *Obj,
1113 MCContext &Ctx, MCDisassembler *PrimaryDisAsm,
1114 MCDisassembler *SecondaryDisAsm,
1115 const MCInstrAnalysis *MIA, MCInstPrinter *IP,
1116 const MCSubtargetInfo *PrimarySTI,
1117 const MCSubtargetInfo *SecondarySTI,
1118 PrettyPrinter &PIP,
1119 SourcePrinter &SP, bool InlineRelocs) {
1120 const MCSubtargetInfo *STI = PrimarySTI;
1121 MCDisassembler *DisAsm = PrimaryDisAsm;
1122 bool PrimaryIsThumb = false;
1123 if (isArmElf(Obj))
1124 PrimaryIsThumb = STI->checkFeatures("+thumb-mode");
1126 std::map<SectionRef, std::vector<RelocationRef>> RelocMap;
1127 if (InlineRelocs)
1128 RelocMap = getRelocsMap(*Obj);
1129 bool Is64Bits = Obj->getBytesInAddress() > 4;
1131 // Create a mapping from virtual address to symbol name. This is used to
1132 // pretty print the symbols while disassembling.
1133 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1134 SectionSymbolsTy AbsoluteSymbols;
1135 const StringRef FileName = Obj->getFileName();
1136 for (const SymbolRef &Symbol : Obj->symbols()) {
1137 uint64_t Address = unwrapOrError(Symbol.getAddress(), FileName);
1139 StringRef Name = unwrapOrError(Symbol.getName(), FileName);
1140 if (Name.empty())
1141 continue;
1143 uint8_t SymbolType = ELF::STT_NOTYPE;
1144 if (Obj->isELF()) {
1145 SymbolType = getElfSymbolType(Obj, Symbol);
1146 if (SymbolType == ELF::STT_SECTION)
1147 continue;
1150 section_iterator SecI = unwrapOrError(Symbol.getSection(), FileName);
1151 if (SecI != Obj->section_end())
1152 AllSymbols[*SecI].emplace_back(Address, Name, SymbolType);
1153 else
1154 AbsoluteSymbols.emplace_back(Address, Name, SymbolType);
1156 if (AllSymbols.empty() && Obj->isELF())
1157 addDynamicElfSymbols(Obj, AllSymbols);
1159 BumpPtrAllocator A;
1160 StringSaver Saver(A);
1161 addPltEntries(Obj, AllSymbols, Saver);
1163 // Create a mapping from virtual address to section.
1164 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1165 for (SectionRef Sec : Obj->sections())
1166 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1167 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1169 // Linked executables (.exe and .dll files) typically don't include a real
1170 // symbol table but they might contain an export table.
1171 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1172 for (const auto &ExportEntry : COFFObj->export_directories()) {
1173 StringRef Name;
1174 if (std::error_code EC = ExportEntry.getSymbolName(Name))
1175 reportError(errorCodeToError(EC), Obj->getFileName());
1176 if (Name.empty())
1177 continue;
1179 uint32_t RVA;
1180 if (std::error_code EC = ExportEntry.getExportRVA(RVA))
1181 reportError(errorCodeToError(EC), Obj->getFileName());
1183 uint64_t VA = COFFObj->getImageBase() + RVA;
1184 auto Sec = partition_point(
1185 SectionAddresses, [VA](const std::pair<uint64_t, SectionRef> &O) {
1186 return O.first <= VA;
1188 if (Sec != SectionAddresses.begin()) {
1189 --Sec;
1190 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
1191 } else
1192 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
1196 // Sort all the symbols, this allows us to use a simple binary search to find
1197 // a symbol near an address.
1198 StringSet<> FoundDisasmFuncsSet;
1199 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1200 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1201 array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
1203 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1204 if (FilterSections.empty() && !DisassembleAll &&
1205 (!Section.isText() || Section.isVirtual()))
1206 continue;
1208 uint64_t SectionAddr = Section.getAddress();
1209 uint64_t SectSize = Section.getSize();
1210 if (!SectSize)
1211 continue;
1213 // Get the list of all the symbols in this section.
1214 SectionSymbolsTy &Symbols = AllSymbols[Section];
1215 std::vector<MappingSymbolPair> MappingSymbols;
1216 if (hasMappingSymbols(Obj)) {
1217 for (const auto &Symb : Symbols) {
1218 uint64_t Address = std::get<0>(Symb);
1219 StringRef Name = std::get<1>(Symb);
1220 if (Name.startswith("$d"))
1221 MappingSymbols.emplace_back(Address - SectionAddr, 'd');
1222 if (Name.startswith("$x"))
1223 MappingSymbols.emplace_back(Address - SectionAddr, 'x');
1224 if (Name.startswith("$a"))
1225 MappingSymbols.emplace_back(Address - SectionAddr, 'a');
1226 if (Name.startswith("$t"))
1227 MappingSymbols.emplace_back(Address - SectionAddr, 't');
1231 llvm::sort(MappingSymbols);
1233 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1234 // AMDGPU disassembler uses symbolizer for printing labels
1235 std::unique_ptr<MCRelocationInfo> RelInfo(
1236 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1237 if (RelInfo) {
1238 std::unique_ptr<MCSymbolizer> Symbolizer(
1239 TheTarget->createMCSymbolizer(
1240 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1241 DisAsm->setSymbolizer(std::move(Symbolizer));
1245 StringRef SegmentName = "";
1246 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
1247 DataRefImpl DR = Section.getRawDataRefImpl();
1248 SegmentName = MachO->getSectionFinalSegmentName(DR);
1251 StringRef SectionName = unwrapOrError(Section.getName(), Obj->getFileName());
1252 // If the section has no symbol at the start, just insert a dummy one.
1253 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
1254 Symbols.insert(
1255 Symbols.begin(),
1256 std::make_tuple(SectionAddr, SectionName,
1257 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
1260 SmallString<40> Comments;
1261 raw_svector_ostream CommentStream(Comments);
1263 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(
1264 unwrapOrError(Section.getContents(), Obj->getFileName()));
1266 uint64_t VMAAdjustment = 0;
1267 if (shouldAdjustVA(Section))
1268 VMAAdjustment = AdjustVMA;
1270 uint64_t Size;
1271 uint64_t Index;
1272 bool PrintedSection = false;
1273 std::vector<RelocationRef> Rels = RelocMap[Section];
1274 std::vector<RelocationRef>::const_iterator RelCur = Rels.begin();
1275 std::vector<RelocationRef>::const_iterator RelEnd = Rels.end();
1276 // Disassemble symbol by symbol.
1277 for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) {
1278 std::string SymbolName = std::get<1>(Symbols[SI]).str();
1279 if (Demangle)
1280 SymbolName = demangle(SymbolName);
1282 // Skip if --disassemble-functions is not empty and the symbol is not in
1283 // the list.
1284 if (!DisasmFuncsSet.empty() && !DisasmFuncsSet.count(SymbolName))
1285 continue;
1287 uint64_t Start = std::get<0>(Symbols[SI]);
1288 if (Start < SectionAddr || StopAddress <= Start)
1289 continue;
1290 else
1291 FoundDisasmFuncsSet.insert(SymbolName);
1293 // The end is the section end, the beginning of the next symbol, or
1294 // --stop-address.
1295 uint64_t End = std::min<uint64_t>(SectionAddr + SectSize, StopAddress);
1296 if (SI + 1 < SE)
1297 End = std::min(End, std::get<0>(Symbols[SI + 1]));
1298 if (Start >= End || End <= StartAddress)
1299 continue;
1300 Start -= SectionAddr;
1301 End -= SectionAddr;
1303 if (!PrintedSection) {
1304 PrintedSection = true;
1305 outs() << "\nDisassembly of section ";
1306 if (!SegmentName.empty())
1307 outs() << SegmentName << ",";
1308 outs() << SectionName << ":\n";
1311 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1312 if (std::get<2>(Symbols[SI]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1313 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1314 Start += 256;
1316 if (SI == SE - 1 ||
1317 std::get<2>(Symbols[SI + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1318 // cut trailing zeroes at the end of kernel
1319 // cut up to 256 bytes
1320 const uint64_t EndAlign = 256;
1321 const auto Limit = End - (std::min)(EndAlign, End - Start);
1322 while (End > Limit &&
1323 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1324 End -= 4;
1328 outs() << '\n';
1329 if (!NoLeadingAddr)
1330 outs() << format(Is64Bits ? "%016" PRIx64 " " : "%08" PRIx64 " ",
1331 SectionAddr + Start + VMAAdjustment);
1333 outs() << SymbolName << ":\n";
1335 // Don't print raw contents of a virtual section. A virtual section
1336 // doesn't have any contents in the file.
1337 if (Section.isVirtual()) {
1338 outs() << "...\n";
1339 continue;
1342 #ifndef NDEBUG
1343 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1344 #else
1345 raw_ostream &DebugOut = nulls();
1346 #endif
1348 // Some targets (like WebAssembly) have a special prelude at the start
1349 // of each symbol.
1350 DisAsm->onSymbolStart(SymbolName, Size, Bytes.slice(Start, End - Start),
1351 SectionAddr + Start, DebugOut, CommentStream);
1352 Start += Size;
1354 Index = Start;
1355 if (SectionAddr < StartAddress)
1356 Index = std::max<uint64_t>(Index, StartAddress - SectionAddr);
1358 // If there is a data/common symbol inside an ELF text section and we are
1359 // only disassembling text (applicable all architectures), we are in a
1360 // situation where we must print the data and not disassemble it.
1361 if (Obj->isELF() && !DisassembleAll && Section.isText()) {
1362 uint8_t SymTy = std::get<2>(Symbols[SI]);
1363 if (SymTy == ELF::STT_OBJECT || SymTy == ELF::STT_COMMON) {
1364 dumpELFData(SectionAddr, Index, End, Bytes);
1365 Index = End;
1369 bool CheckARMELFData = hasMappingSymbols(Obj) &&
1370 std::get<2>(Symbols[SI]) != ELF::STT_OBJECT &&
1371 !DisassembleAll;
1372 while (Index < End) {
1373 // ARM and AArch64 ELF binaries can interleave data and text in the
1374 // same section. We rely on the markers introduced to understand what
1375 // we need to dump. If the data marker is within a function, it is
1376 // denoted as a word/short etc.
1377 if (CheckARMELFData &&
1378 getMappingSymbolKind(MappingSymbols, Index) == 'd') {
1379 Index = dumpARMELFData(SectionAddr, Index, End, Obj, Bytes,
1380 MappingSymbols);
1381 continue;
1384 // When -z or --disassemble-zeroes are given we always dissasemble
1385 // them. Otherwise we might want to skip zero bytes we see.
1386 if (!DisassembleZeroes) {
1387 uint64_t MaxOffset = End - Index;
1388 // For -reloc: print zero blocks patched by relocations, so that
1389 // relocations can be shown in the dump.
1390 if (RelCur != RelEnd)
1391 MaxOffset = RelCur->getOffset() - Index;
1393 if (size_t N =
1394 countSkippableZeroBytes(Bytes.slice(Index, MaxOffset))) {
1395 outs() << "\t\t..." << '\n';
1396 Index += N;
1397 continue;
1401 if (SecondarySTI) {
1402 if (getMappingSymbolKind(MappingSymbols, Index) == 'a') {
1403 STI = PrimaryIsThumb ? SecondarySTI : PrimarySTI;
1404 DisAsm = PrimaryIsThumb ? SecondaryDisAsm : PrimaryDisAsm;
1405 } else if (getMappingSymbolKind(MappingSymbols, Index) == 't') {
1406 STI = PrimaryIsThumb ? PrimarySTI : SecondarySTI;
1407 DisAsm = PrimaryIsThumb ? PrimaryDisAsm : SecondaryDisAsm;
1411 // Disassemble a real instruction or a data when disassemble all is
1412 // provided
1413 MCInst Inst;
1414 bool Disassembled = DisAsm->getInstruction(
1415 Inst, Size, Bytes.slice(Index), SectionAddr + Index, DebugOut,
1416 CommentStream);
1417 if (Size == 0)
1418 Size = 1;
1420 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
1421 Bytes.slice(Index, Size),
1422 {SectionAddr + Index + VMAAdjustment, Section.getIndex()},
1423 outs(), "", *STI, &SP, Obj->getFileName(), &Rels);
1424 outs() << CommentStream.str();
1425 Comments.clear();
1427 // Try to resolve the target of a call, tail call, etc. to a specific
1428 // symbol.
1429 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1430 MIA->isConditionalBranch(Inst))) {
1431 uint64_t Target;
1432 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1433 // In a relocatable object, the target's section must reside in
1434 // the same section as the call instruction or it is accessed
1435 // through a relocation.
1437 // In a non-relocatable object, the target may be in any section.
1439 // N.B. We don't walk the relocations in the relocatable case yet.
1440 auto *TargetSectionSymbols = &Symbols;
1441 if (!Obj->isRelocatableObject()) {
1442 auto It = partition_point(
1443 SectionAddresses,
1444 [=](const std::pair<uint64_t, SectionRef> &O) {
1445 return O.first <= Target;
1447 if (It != SectionAddresses.begin()) {
1448 --It;
1449 TargetSectionSymbols = &AllSymbols[It->second];
1450 } else {
1451 TargetSectionSymbols = &AbsoluteSymbols;
1455 // Find the last symbol in the section whose offset is less than
1456 // or equal to the target. If there isn't a section that contains
1457 // the target, find the nearest preceding absolute symbol.
1458 auto TargetSym = partition_point(
1459 *TargetSectionSymbols,
1460 [=](const std::tuple<uint64_t, StringRef, uint8_t> &O) {
1461 return std::get<0>(O) <= Target;
1463 if (TargetSym == TargetSectionSymbols->begin()) {
1464 TargetSectionSymbols = &AbsoluteSymbols;
1465 TargetSym = partition_point(
1466 AbsoluteSymbols,
1467 [=](const std::tuple<uint64_t, StringRef, uint8_t> &O) {
1468 return std::get<0>(O) <= Target;
1471 if (TargetSym != TargetSectionSymbols->begin()) {
1472 --TargetSym;
1473 uint64_t TargetAddress = std::get<0>(*TargetSym);
1474 StringRef TargetName = std::get<1>(*TargetSym);
1475 outs() << " <" << TargetName;
1476 uint64_t Disp = Target - TargetAddress;
1477 if (Disp)
1478 outs() << "+0x" << Twine::utohexstr(Disp);
1479 outs() << '>';
1483 outs() << "\n";
1485 // Hexagon does this in pretty printer
1486 if (Obj->getArch() != Triple::hexagon) {
1487 // Print relocation for instruction.
1488 while (RelCur != RelEnd) {
1489 uint64_t Offset = RelCur->getOffset();
1490 // If this relocation is hidden, skip it.
1491 if (getHidden(*RelCur) || SectionAddr + Offset < StartAddress) {
1492 ++RelCur;
1493 continue;
1496 // Stop when RelCur's offset is past the current instruction.
1497 if (Offset >= Index + Size)
1498 break;
1500 // When --adjust-vma is used, update the address printed.
1501 if (RelCur->getSymbol() != Obj->symbol_end()) {
1502 Expected<section_iterator> SymSI =
1503 RelCur->getSymbol()->getSection();
1504 if (SymSI && *SymSI != Obj->section_end() &&
1505 shouldAdjustVA(**SymSI))
1506 Offset += AdjustVMA;
1509 printRelocation(Obj->getFileName(), *RelCur, SectionAddr + Offset,
1510 Is64Bits);
1511 ++RelCur;
1515 Index += Size;
1519 StringSet<> MissingDisasmFuncsSet =
1520 set_difference(DisasmFuncsSet, FoundDisasmFuncsSet);
1521 for (StringRef MissingDisasmFunc : MissingDisasmFuncsSet.keys())
1522 reportWarning("failed to disassemble missing function " + MissingDisasmFunc,
1523 FileName);
1526 static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
1527 const Target *TheTarget = getTarget(Obj);
1529 // Package up features to be passed to target/subtarget
1530 SubtargetFeatures Features = Obj->getFeatures();
1531 if (!MAttrs.empty())
1532 for (unsigned I = 0; I != MAttrs.size(); ++I)
1533 Features.AddFeature(MAttrs[I]);
1535 std::unique_ptr<const MCRegisterInfo> MRI(
1536 TheTarget->createMCRegInfo(TripleName));
1537 if (!MRI)
1538 reportError(Obj->getFileName(),
1539 "no register info for target " + TripleName);
1541 // Set up disassembler.
1542 std::unique_ptr<const MCAsmInfo> AsmInfo(
1543 TheTarget->createMCAsmInfo(*MRI, TripleName));
1544 if (!AsmInfo)
1545 reportError(Obj->getFileName(),
1546 "no assembly info for target " + TripleName);
1547 std::unique_ptr<const MCSubtargetInfo> STI(
1548 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1549 if (!STI)
1550 reportError(Obj->getFileName(),
1551 "no subtarget info for target " + TripleName);
1552 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1553 if (!MII)
1554 reportError(Obj->getFileName(),
1555 "no instruction info for target " + TripleName);
1556 MCObjectFileInfo MOFI;
1557 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1558 // FIXME: for now initialize MCObjectFileInfo with default values
1559 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
1561 std::unique_ptr<MCDisassembler> DisAsm(
1562 TheTarget->createMCDisassembler(*STI, Ctx));
1563 if (!DisAsm)
1564 reportError(Obj->getFileName(), "no disassembler for target " + TripleName);
1566 // If we have an ARM object file, we need a second disassembler, because
1567 // ARM CPUs have two different instruction sets: ARM mode, and Thumb mode.
1568 // We use mapping symbols to switch between the two assemblers, where
1569 // appropriate.
1570 std::unique_ptr<MCDisassembler> SecondaryDisAsm;
1571 std::unique_ptr<const MCSubtargetInfo> SecondarySTI;
1572 if (isArmElf(Obj) && !STI->checkFeatures("+mclass")) {
1573 if (STI->checkFeatures("+thumb-mode"))
1574 Features.AddFeature("-thumb-mode");
1575 else
1576 Features.AddFeature("+thumb-mode");
1577 SecondarySTI.reset(TheTarget->createMCSubtargetInfo(TripleName, MCPU,
1578 Features.getString()));
1579 SecondaryDisAsm.reset(TheTarget->createMCDisassembler(*SecondarySTI, Ctx));
1582 std::unique_ptr<const MCInstrAnalysis> MIA(
1583 TheTarget->createMCInstrAnalysis(MII.get()));
1585 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1586 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1587 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
1588 if (!IP)
1589 reportError(Obj->getFileName(),
1590 "no instruction printer for target " + TripleName);
1591 IP->setPrintImmHex(PrintImmHex);
1593 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
1594 SourcePrinter SP(Obj, TheTarget->getName());
1596 for (StringRef Opt : DisassemblerOptions)
1597 if (!IP->applyTargetSpecificCLOption(Opt))
1598 reportError(Obj->getFileName(),
1599 "Unrecognized disassembler option: " + Opt);
1601 disassembleObject(TheTarget, Obj, Ctx, DisAsm.get(), SecondaryDisAsm.get(),
1602 MIA.get(), IP.get(), STI.get(), SecondarySTI.get(), PIP,
1603 SP, InlineRelocs);
1606 void printRelocations(const ObjectFile *Obj) {
1607 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1608 "%08" PRIx64;
1609 // Regular objdump doesn't print relocations in non-relocatable object
1610 // files.
1611 if (!Obj->isRelocatableObject())
1612 return;
1614 // Build a mapping from relocation target to a vector of relocation
1615 // sections. Usually, there is an only one relocation section for
1616 // each relocated section.
1617 MapVector<SectionRef, std::vector<SectionRef>> SecToRelSec;
1618 uint64_t Ndx;
1619 for (const SectionRef &Section : ToolSectionFilter(*Obj, &Ndx)) {
1620 if (Section.relocation_begin() == Section.relocation_end())
1621 continue;
1622 Expected<section_iterator> SecOrErr = Section.getRelocatedSection();
1623 if (!SecOrErr)
1624 reportError(Obj->getFileName(),
1625 "section (" + Twine(Ndx) +
1626 "): unable to get a relocation target: " +
1627 toString(SecOrErr.takeError()));
1628 SecToRelSec[**SecOrErr].push_back(Section);
1631 for (std::pair<SectionRef, std::vector<SectionRef>> &P : SecToRelSec) {
1632 StringRef SecName = unwrapOrError(P.first.getName(), Obj->getFileName());
1633 outs() << "RELOCATION RECORDS FOR [" << SecName << "]:\n";
1635 for (SectionRef Section : P.second) {
1636 for (const RelocationRef &Reloc : Section.relocations()) {
1637 uint64_t Address = Reloc.getOffset();
1638 SmallString<32> RelocName;
1639 SmallString<32> ValueStr;
1640 if (Address < StartAddress || Address > StopAddress || getHidden(Reloc))
1641 continue;
1642 Reloc.getTypeName(RelocName);
1643 if (Error E = getRelocationValueString(Reloc, ValueStr))
1644 reportError(std::move(E), Obj->getFileName());
1646 outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1647 << ValueStr << "\n";
1650 outs() << "\n";
1654 void printDynamicRelocations(const ObjectFile *Obj) {
1655 // For the moment, this option is for ELF only
1656 if (!Obj->isELF())
1657 return;
1659 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
1660 if (!Elf || Elf->getEType() != ELF::ET_DYN) {
1661 reportError(Obj->getFileName(), "not a dynamic object");
1662 return;
1665 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1666 if (DynRelSec.empty())
1667 return;
1669 outs() << "DYNAMIC RELOCATION RECORDS\n";
1670 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1671 for (const SectionRef &Section : DynRelSec)
1672 for (const RelocationRef &Reloc : Section.relocations()) {
1673 uint64_t Address = Reloc.getOffset();
1674 SmallString<32> RelocName;
1675 SmallString<32> ValueStr;
1676 Reloc.getTypeName(RelocName);
1677 if (Error E = getRelocationValueString(Reloc, ValueStr))
1678 reportError(std::move(E), Obj->getFileName());
1679 outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1680 << ValueStr << "\n";
1684 // Returns true if we need to show LMA column when dumping section headers. We
1685 // show it only when the platform is ELF and either we have at least one section
1686 // whose VMA and LMA are different and/or when --show-lma flag is used.
1687 static bool shouldDisplayLMA(const ObjectFile *Obj) {
1688 if (!Obj->isELF())
1689 return false;
1690 for (const SectionRef &S : ToolSectionFilter(*Obj))
1691 if (S.getAddress() != getELFSectionLMA(S))
1692 return true;
1693 return ShowLMA;
1696 static size_t getMaxSectionNameWidth(const ObjectFile *Obj) {
1697 // Default column width for names is 13 even if no names are that long.
1698 size_t MaxWidth = 13;
1699 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1700 StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName());
1701 MaxWidth = std::max(MaxWidth, Name.size());
1703 return MaxWidth;
1706 void printSectionHeaders(const ObjectFile *Obj) {
1707 size_t NameWidth = getMaxSectionNameWidth(Obj);
1708 size_t AddressWidth = 2 * Obj->getBytesInAddress();
1709 bool HasLMAColumn = shouldDisplayLMA(Obj);
1710 if (HasLMAColumn)
1711 outs() << "Sections:\n"
1712 "Idx "
1713 << left_justify("Name", NameWidth) << " Size "
1714 << left_justify("VMA", AddressWidth) << " "
1715 << left_justify("LMA", AddressWidth) << " Type\n";
1716 else
1717 outs() << "Sections:\n"
1718 "Idx "
1719 << left_justify("Name", NameWidth) << " Size "
1720 << left_justify("VMA", AddressWidth) << " Type\n";
1722 uint64_t Idx;
1723 for (const SectionRef &Section : ToolSectionFilter(*Obj, &Idx)) {
1724 StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName());
1725 uint64_t VMA = Section.getAddress();
1726 if (shouldAdjustVA(Section))
1727 VMA += AdjustVMA;
1729 uint64_t Size = Section.getSize();
1731 std::string Type = Section.isText() ? "TEXT" : "";
1732 if (Section.isData())
1733 Type += Type.empty() ? "DATA" : " DATA";
1734 if (Section.isBSS())
1735 Type += Type.empty() ? "BSS" : " BSS";
1737 if (HasLMAColumn)
1738 outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth,
1739 Name.str().c_str(), Size)
1740 << format_hex_no_prefix(VMA, AddressWidth) << " "
1741 << format_hex_no_prefix(getELFSectionLMA(Section), AddressWidth)
1742 << " " << Type << "\n";
1743 else
1744 outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth,
1745 Name.str().c_str(), Size)
1746 << format_hex_no_prefix(VMA, AddressWidth) << " " << Type << "\n";
1748 outs() << "\n";
1751 void printSectionContents(const ObjectFile *Obj) {
1752 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1753 StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName());
1754 uint64_t BaseAddr = Section.getAddress();
1755 uint64_t Size = Section.getSize();
1756 if (!Size)
1757 continue;
1759 outs() << "Contents of section " << Name << ":\n";
1760 if (Section.isBSS()) {
1761 outs() << format("<skipping contents of bss section at [%04" PRIx64
1762 ", %04" PRIx64 ")>\n",
1763 BaseAddr, BaseAddr + Size);
1764 continue;
1767 StringRef Contents = unwrapOrError(Section.getContents(), Obj->getFileName());
1769 // Dump out the content as hex and printable ascii characters.
1770 for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) {
1771 outs() << format(" %04" PRIx64 " ", BaseAddr + Addr);
1772 // Dump line of hex.
1773 for (std::size_t I = 0; I < 16; ++I) {
1774 if (I != 0 && I % 4 == 0)
1775 outs() << ' ';
1776 if (Addr + I < End)
1777 outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true)
1778 << hexdigit(Contents[Addr + I] & 0xF, true);
1779 else
1780 outs() << " ";
1782 // Print ascii.
1783 outs() << " ";
1784 for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) {
1785 if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF))
1786 outs() << Contents[Addr + I];
1787 else
1788 outs() << ".";
1790 outs() << "\n";
1795 void printSymbolTable(const ObjectFile *O, StringRef ArchiveName,
1796 StringRef ArchitectureName) {
1797 outs() << "SYMBOL TABLE:\n";
1799 if (const COFFObjectFile *Coff = dyn_cast<const COFFObjectFile>(O)) {
1800 printCOFFSymbolTable(Coff);
1801 return;
1804 const StringRef FileName = O->getFileName();
1805 for (auto I = O->symbol_begin(), E = O->symbol_end(); I != E; ++I) {
1806 const SymbolRef &Symbol = *I;
1807 uint64_t Address = unwrapOrError(Symbol.getAddress(), FileName, ArchiveName,
1808 ArchitectureName);
1809 if ((Address < StartAddress) || (Address > StopAddress))
1810 continue;
1811 SymbolRef::Type Type = unwrapOrError(Symbol.getType(), FileName,
1812 ArchiveName, ArchitectureName);
1813 uint32_t Flags = Symbol.getFlags();
1814 section_iterator Section = unwrapOrError(Symbol.getSection(), FileName,
1815 ArchiveName, ArchitectureName);
1816 StringRef Name;
1817 if (Type == SymbolRef::ST_Debug && Section != O->section_end()) {
1818 if (Expected<StringRef> NameOrErr = Section->getName())
1819 Name = *NameOrErr;
1820 else
1821 consumeError(NameOrErr.takeError());
1823 } else {
1824 Name = unwrapOrError(Symbol.getName(), FileName, ArchiveName,
1825 ArchitectureName);
1828 bool Global = Flags & SymbolRef::SF_Global;
1829 bool Weak = Flags & SymbolRef::SF_Weak;
1830 bool Absolute = Flags & SymbolRef::SF_Absolute;
1831 bool Common = Flags & SymbolRef::SF_Common;
1832 bool Hidden = Flags & SymbolRef::SF_Hidden;
1834 char GlobLoc = ' ';
1835 if (Type != SymbolRef::ST_Unknown)
1836 GlobLoc = Global ? 'g' : 'l';
1837 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1838 ? 'd' : ' ';
1839 char FileFunc = ' ';
1840 if (Type == SymbolRef::ST_File)
1841 FileFunc = 'f';
1842 else if (Type == SymbolRef::ST_Function)
1843 FileFunc = 'F';
1844 else if (Type == SymbolRef::ST_Data)
1845 FileFunc = 'O';
1847 const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 :
1848 "%08" PRIx64;
1850 outs() << format(Fmt, Address) << " "
1851 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1852 << (Weak ? 'w' : ' ') // Weak?
1853 << ' ' // Constructor. Not supported yet.
1854 << ' ' // Warning. Not supported yet.
1855 << ' ' // Indirect reference to another symbol.
1856 << Debug // Debugging (d) or dynamic (D) symbol.
1857 << FileFunc // Name of function (F), file (f) or object (O).
1858 << ' ';
1859 if (Absolute) {
1860 outs() << "*ABS*";
1861 } else if (Common) {
1862 outs() << "*COM*";
1863 } else if (Section == O->section_end()) {
1864 outs() << "*UND*";
1865 } else {
1866 if (const MachOObjectFile *MachO =
1867 dyn_cast<const MachOObjectFile>(O)) {
1868 DataRefImpl DR = Section->getRawDataRefImpl();
1869 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1870 outs() << SegmentName << ",";
1872 StringRef SectionName =
1873 unwrapOrError(Section->getName(), O->getFileName());
1874 outs() << SectionName;
1877 if (Common || isa<ELFObjectFileBase>(O)) {
1878 uint64_t Val =
1879 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1880 outs() << format("\t%08" PRIx64, Val);
1883 if (isa<ELFObjectFileBase>(O)) {
1884 uint8_t Other = ELFSymbolRef(Symbol).getOther();
1885 switch (Other) {
1886 case ELF::STV_DEFAULT:
1887 break;
1888 case ELF::STV_INTERNAL:
1889 outs() << " .internal";
1890 break;
1891 case ELF::STV_HIDDEN:
1892 outs() << " .hidden";
1893 break;
1894 case ELF::STV_PROTECTED:
1895 outs() << " .protected";
1896 break;
1897 default:
1898 outs() << format(" 0x%02x", Other);
1899 break;
1901 } else if (Hidden) {
1902 outs() << " .hidden";
1905 if (Demangle)
1906 outs() << ' ' << demangle(Name) << '\n';
1907 else
1908 outs() << ' ' << Name << '\n';
1912 static void printUnwindInfo(const ObjectFile *O) {
1913 outs() << "Unwind info:\n\n";
1915 if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O))
1916 printCOFFUnwindInfo(Coff);
1917 else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O))
1918 printMachOUnwindInfo(MachO);
1919 else
1920 // TODO: Extract DWARF dump tool to objdump.
1921 WithColor::error(errs(), ToolName)
1922 << "This operation is only currently supported "
1923 "for COFF and MachO object files.\n";
1926 /// Dump the raw contents of the __clangast section so the output can be piped
1927 /// into llvm-bcanalyzer.
1928 void printRawClangAST(const ObjectFile *Obj) {
1929 if (outs().is_displayed()) {
1930 WithColor::error(errs(), ToolName)
1931 << "The -raw-clang-ast option will dump the raw binary contents of "
1932 "the clang ast section.\n"
1933 "Please redirect the output to a file or another program such as "
1934 "llvm-bcanalyzer.\n";
1935 return;
1938 StringRef ClangASTSectionName("__clangast");
1939 if (isa<COFFObjectFile>(Obj)) {
1940 ClangASTSectionName = "clangast";
1943 Optional<object::SectionRef> ClangASTSection;
1944 for (auto Sec : ToolSectionFilter(*Obj)) {
1945 StringRef Name;
1946 if (Expected<StringRef> NameOrErr = Sec.getName())
1947 Name = *NameOrErr;
1948 else
1949 consumeError(NameOrErr.takeError());
1951 if (Name == ClangASTSectionName) {
1952 ClangASTSection = Sec;
1953 break;
1956 if (!ClangASTSection)
1957 return;
1959 StringRef ClangASTContents = unwrapOrError(
1960 ClangASTSection.getValue().getContents(), Obj->getFileName());
1961 outs().write(ClangASTContents.data(), ClangASTContents.size());
1964 static void printFaultMaps(const ObjectFile *Obj) {
1965 StringRef FaultMapSectionName;
1967 if (isa<ELFObjectFileBase>(Obj)) {
1968 FaultMapSectionName = ".llvm_faultmaps";
1969 } else if (isa<MachOObjectFile>(Obj)) {
1970 FaultMapSectionName = "__llvm_faultmaps";
1971 } else {
1972 WithColor::error(errs(), ToolName)
1973 << "This operation is only currently supported "
1974 "for ELF and Mach-O executable files.\n";
1975 return;
1978 Optional<object::SectionRef> FaultMapSection;
1980 for (auto Sec : ToolSectionFilter(*Obj)) {
1981 StringRef Name;
1982 if (Expected<StringRef> NameOrErr = Sec.getName())
1983 Name = *NameOrErr;
1984 else
1985 consumeError(NameOrErr.takeError());
1987 if (Name == FaultMapSectionName) {
1988 FaultMapSection = Sec;
1989 break;
1993 outs() << "FaultMap table:\n";
1995 if (!FaultMapSection.hasValue()) {
1996 outs() << "<not found>\n";
1997 return;
2000 StringRef FaultMapContents =
2001 unwrapOrError(FaultMapSection.getValue().getContents(), Obj->getFileName());
2002 FaultMapParser FMP(FaultMapContents.bytes_begin(),
2003 FaultMapContents.bytes_end());
2005 outs() << FMP;
2008 static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) {
2009 if (O->isELF()) {
2010 printELFFileHeader(O);
2011 printELFDynamicSection(O);
2012 printELFSymbolVersionInfo(O);
2013 return;
2015 if (O->isCOFF())
2016 return printCOFFFileHeader(O);
2017 if (O->isWasm())
2018 return printWasmFileHeader(O);
2019 if (O->isMachO()) {
2020 printMachOFileHeader(O);
2021 if (!OnlyFirst)
2022 printMachOLoadCommands(O);
2023 return;
2025 reportError(O->getFileName(), "Invalid/Unsupported object file format");
2028 static void printFileHeaders(const ObjectFile *O) {
2029 if (!O->isELF() && !O->isCOFF())
2030 reportError(O->getFileName(), "Invalid/Unsupported object file format");
2032 Triple::ArchType AT = O->getArch();
2033 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
2034 uint64_t Address = unwrapOrError(O->getStartAddress(), O->getFileName());
2036 StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
2037 outs() << "start address: "
2038 << "0x" << format(Fmt.data(), Address) << "\n\n";
2041 static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
2042 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
2043 if (!ModeOrErr) {
2044 WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n";
2045 consumeError(ModeOrErr.takeError());
2046 return;
2048 sys::fs::perms Mode = ModeOrErr.get();
2049 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2050 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2051 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2052 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2053 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2054 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2055 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2056 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2057 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2059 outs() << " ";
2061 outs() << format("%d/%d %6" PRId64 " ", unwrapOrError(C.getUID(), Filename),
2062 unwrapOrError(C.getGID(), Filename),
2063 unwrapOrError(C.getRawSize(), Filename));
2065 StringRef RawLastModified = C.getRawLastModified();
2066 unsigned Seconds;
2067 if (RawLastModified.getAsInteger(10, Seconds))
2068 outs() << "(date: \"" << RawLastModified
2069 << "\" contains non-decimal chars) ";
2070 else {
2071 // Since ctime(3) returns a 26 character string of the form:
2072 // "Sun Sep 16 01:03:52 1973\n\0"
2073 // just print 24 characters.
2074 time_t t = Seconds;
2075 outs() << format("%.24s ", ctime(&t));
2078 StringRef Name = "";
2079 Expected<StringRef> NameOrErr = C.getName();
2080 if (!NameOrErr) {
2081 consumeError(NameOrErr.takeError());
2082 Name = unwrapOrError(C.getRawName(), Filename);
2083 } else {
2084 Name = NameOrErr.get();
2086 outs() << Name << "\n";
2089 // For ELF only now.
2090 static bool shouldWarnForInvalidStartStopAddress(ObjectFile *Obj) {
2091 if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj)) {
2092 if (Elf->getEType() != ELF::ET_REL)
2093 return true;
2095 return false;
2098 static void checkForInvalidStartStopAddress(ObjectFile *Obj,
2099 uint64_t Start, uint64_t Stop) {
2100 if (!shouldWarnForInvalidStartStopAddress(Obj))
2101 return;
2103 for (const SectionRef &Section : Obj->sections())
2104 if (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC) {
2105 uint64_t BaseAddr = Section.getAddress();
2106 uint64_t Size = Section.getSize();
2107 if ((Start < BaseAddr + Size) && Stop > BaseAddr)
2108 return;
2111 if (StartAddress.getNumOccurrences() == 0)
2112 reportWarning("no section has address less than 0x" +
2113 Twine::utohexstr(Stop) + " specified by --stop-address",
2114 Obj->getFileName());
2115 else if (StopAddress.getNumOccurrences() == 0)
2116 reportWarning("no section has address greater than or equal to 0x" +
2117 Twine::utohexstr(Start) + " specified by --start-address",
2118 Obj->getFileName());
2119 else
2120 reportWarning("no section overlaps the range [0x" +
2121 Twine::utohexstr(Start) + ",0x" + Twine::utohexstr(Stop) +
2122 ") specified by --start-address/--stop-address",
2123 Obj->getFileName());
2126 static void dumpObject(ObjectFile *O, const Archive *A = nullptr,
2127 const Archive::Child *C = nullptr) {
2128 // Avoid other output when using a raw option.
2129 if (!RawClangAST) {
2130 outs() << '\n';
2131 if (A)
2132 outs() << A->getFileName() << "(" << O->getFileName() << ")";
2133 else
2134 outs() << O->getFileName();
2135 outs() << ":\tfile format " << O->getFileFormatName() << "\n\n";
2138 if (StartAddress.getNumOccurrences() || StopAddress.getNumOccurrences())
2139 checkForInvalidStartStopAddress(O, StartAddress, StopAddress);
2141 // Note: the order here matches GNU objdump for compatability.
2142 StringRef ArchiveName = A ? A->getFileName() : "";
2143 if (ArchiveHeaders && !MachOOpt && C)
2144 printArchiveChild(ArchiveName, *C);
2145 if (FileHeaders)
2146 printFileHeaders(O);
2147 if (PrivateHeaders || FirstPrivateHeader)
2148 printPrivateFileHeaders(O, FirstPrivateHeader);
2149 if (SectionHeaders)
2150 printSectionHeaders(O);
2151 if (SymbolTable)
2152 printSymbolTable(O, ArchiveName);
2153 if (DwarfDumpType != DIDT_Null) {
2154 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O);
2155 // Dump the complete DWARF structure.
2156 DIDumpOptions DumpOpts;
2157 DumpOpts.DumpType = DwarfDumpType;
2158 DICtx->dump(outs(), DumpOpts);
2160 if (Relocations && !Disassemble)
2161 printRelocations(O);
2162 if (DynamicRelocations)
2163 printDynamicRelocations(O);
2164 if (SectionContents)
2165 printSectionContents(O);
2166 if (Disassemble)
2167 disassembleObject(O, Relocations);
2168 if (UnwindInfo)
2169 printUnwindInfo(O);
2171 // Mach-O specific options:
2172 if (ExportsTrie)
2173 printExportsTrie(O);
2174 if (Rebase)
2175 printRebaseTable(O);
2176 if (Bind)
2177 printBindTable(O);
2178 if (LazyBind)
2179 printLazyBindTable(O);
2180 if (WeakBind)
2181 printWeakBindTable(O);
2183 // Other special sections:
2184 if (RawClangAST)
2185 printRawClangAST(O);
2186 if (FaultMapSection)
2187 printFaultMaps(O);
2190 static void dumpObject(const COFFImportFile *I, const Archive *A,
2191 const Archive::Child *C = nullptr) {
2192 StringRef ArchiveName = A ? A->getFileName() : "";
2194 // Avoid other output when using a raw option.
2195 if (!RawClangAST)
2196 outs() << '\n'
2197 << ArchiveName << "(" << I->getFileName() << ")"
2198 << ":\tfile format COFF-import-file"
2199 << "\n\n";
2201 if (ArchiveHeaders && !MachOOpt && C)
2202 printArchiveChild(ArchiveName, *C);
2203 if (SymbolTable)
2204 printCOFFSymbolTable(I);
2207 /// Dump each object file in \a a;
2208 static void dumpArchive(const Archive *A) {
2209 Error Err = Error::success();
2210 unsigned I = -1;
2211 for (auto &C : A->children(Err)) {
2212 ++I;
2213 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2214 if (!ChildOrErr) {
2215 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2216 reportError(std::move(E), getFileNameForError(C, I), A->getFileName());
2217 continue;
2219 if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2220 dumpObject(O, A, &C);
2221 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2222 dumpObject(I, A, &C);
2223 else
2224 reportError(errorCodeToError(object_error::invalid_file_type),
2225 A->getFileName());
2227 if (Err)
2228 reportError(std::move(Err), A->getFileName());
2231 /// Open file and figure out how to dump it.
2232 static void dumpInput(StringRef file) {
2233 // If we are using the Mach-O specific object file parser, then let it parse
2234 // the file and process the command line options. So the -arch flags can
2235 // be used to select specific slices, etc.
2236 if (MachOOpt) {
2237 parseInputMachO(file);
2238 return;
2241 // Attempt to open the binary.
2242 OwningBinary<Binary> OBinary = unwrapOrError(createBinary(file), file);
2243 Binary &Binary = *OBinary.getBinary();
2245 if (Archive *A = dyn_cast<Archive>(&Binary))
2246 dumpArchive(A);
2247 else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary))
2248 dumpObject(O);
2249 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
2250 parseInputMachO(UB);
2251 else
2252 reportError(errorCodeToError(object_error::invalid_file_type), file);
2254 } // namespace llvm
2256 int main(int argc, char **argv) {
2257 using namespace llvm;
2258 InitLLVM X(argc, argv);
2259 const cl::OptionCategory *OptionFilters[] = {&ObjdumpCat, &MachOCat};
2260 cl::HideUnrelatedOptions(OptionFilters);
2262 // Initialize targets and assembly printers/parsers.
2263 InitializeAllTargetInfos();
2264 InitializeAllTargetMCs();
2265 InitializeAllDisassemblers();
2267 // Register the target printer for --version.
2268 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2270 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2272 if (StartAddress >= StopAddress)
2273 reportCmdLineError("start address should be less than stop address");
2275 ToolName = argv[0];
2277 // Defaults to a.out if no filenames specified.
2278 if (InputFilenames.empty())
2279 InputFilenames.push_back("a.out");
2281 if (AllHeaders)
2282 ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations =
2283 SectionHeaders = SymbolTable = true;
2285 if (DisassembleAll || PrintSource || PrintLines ||
2286 (!DisassembleFunctions.empty()))
2287 Disassemble = true;
2289 if (!ArchiveHeaders && !Disassemble && DwarfDumpType == DIDT_Null &&
2290 !DynamicRelocations && !FileHeaders && !PrivateHeaders && !RawClangAST &&
2291 !Relocations && !SectionHeaders && !SectionContents && !SymbolTable &&
2292 !UnwindInfo && !FaultMapSection &&
2293 !(MachOOpt &&
2294 (Bind || DataInCode || DylibId || DylibsUsed || ExportsTrie ||
2295 FirstPrivateHeader || IndirectSymbols || InfoPlist || LazyBind ||
2296 LinkOptHints || ObjcMetaData || Rebase || UniversalHeaders ||
2297 WeakBind || !FilterSections.empty()))) {
2298 cl::PrintHelpMessage();
2299 return 2;
2302 DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2303 DisassembleFunctions.end());
2305 llvm::for_each(InputFilenames, dumpInput);
2307 warnOnNoMatchForSections();
2309 return EXIT_SUCCESS;