[UpdateCCTestChecks] Detect function mangled name on separate line
[llvm-core.git] / tools / llvm-objdump / llvm-objdump.cpp
blob8b0a04c61049de199b17580a1f3f0630232fdb56
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 static bool shouldKeep(object::SectionRef S) {
346 if (FilterSections.empty())
347 return true;
349 Expected<StringRef> SecNameOrErr = S.getName();
350 if (!SecNameOrErr) {
351 consumeError(SecNameOrErr.takeError());
352 return false;
354 StringRef SecName = *SecNameOrErr;
356 // StringSet does not allow empty key so avoid adding sections with
357 // no name (such as the section with index 0) here.
358 if (!SecName.empty())
359 FoundSectionSet.insert(SecName);
360 return is_contained(FilterSections, SecName);
363 SectionFilter ToolSectionFilter(object::ObjectFile const &O) {
364 return SectionFilter([](object::SectionRef S) { return shouldKeep(S); }, O);
367 std::string getFileNameForError(const object::Archive::Child &C,
368 unsigned Index) {
369 Expected<StringRef> NameOrErr = C.getName();
370 if (NameOrErr)
371 return NameOrErr.get();
372 // If we have an error getting the name then we print the index of the archive
373 // member. Since we are already in an error state, we just ignore this error.
374 consumeError(NameOrErr.takeError());
375 return "<file index: " + std::to_string(Index) + ">";
378 void reportWarning(Twine Message, StringRef File) {
379 // Output order between errs() and outs() matters especially for archive
380 // files where the output is per member object.
381 outs().flush();
382 WithColor::warning(errs(), ToolName)
383 << "'" << File << "': " << Message << "\n";
384 errs().flush();
387 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Twine Message) {
388 WithColor::error(errs(), ToolName) << "'" << File << "': " << Message << "\n";
389 exit(1);
392 LLVM_ATTRIBUTE_NORETURN void reportError(Error E, StringRef FileName,
393 StringRef ArchiveName,
394 StringRef ArchitectureName) {
395 assert(E);
396 WithColor::error(errs(), ToolName);
397 if (ArchiveName != "")
398 errs() << ArchiveName << "(" << FileName << ")";
399 else
400 errs() << "'" << FileName << "'";
401 if (!ArchitectureName.empty())
402 errs() << " (for architecture " << ArchitectureName << ")";
403 std::string Buf;
404 raw_string_ostream OS(Buf);
405 logAllUnhandledErrors(std::move(E), OS);
406 OS.flush();
407 errs() << ": " << Buf;
408 exit(1);
411 static void reportCmdLineWarning(Twine Message) {
412 WithColor::warning(errs(), ToolName) << Message << "\n";
415 LLVM_ATTRIBUTE_NORETURN static void reportCmdLineError(Twine Message) {
416 WithColor::error(errs(), ToolName) << Message << "\n";
417 exit(1);
420 static void warnOnNoMatchForSections() {
421 SetVector<StringRef> MissingSections;
422 for (StringRef S : FilterSections) {
423 if (FoundSectionSet.count(S))
424 return;
425 // User may specify a unnamed section. Don't warn for it.
426 if (!S.empty())
427 MissingSections.insert(S);
430 // Warn only if no section in FilterSections is matched.
431 for (StringRef S : MissingSections)
432 reportCmdLineWarning("section '" + S +
433 "' mentioned in a -j/--section option, but not "
434 "found in any input file");
437 static const Target *getTarget(const ObjectFile *Obj) {
438 // Figure out the target triple.
439 Triple TheTriple("unknown-unknown-unknown");
440 if (TripleName.empty()) {
441 TheTriple = Obj->makeTriple();
442 } else {
443 TheTriple.setTriple(Triple::normalize(TripleName));
444 auto Arch = Obj->getArch();
445 if (Arch == Triple::arm || Arch == Triple::armeb)
446 Obj->setARMSubArch(TheTriple);
449 // Get the target specific parser.
450 std::string Error;
451 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
452 Error);
453 if (!TheTarget)
454 reportError(Obj->getFileName(), "can't find target: " + Error);
456 // Update the triple name and return the found target.
457 TripleName = TheTriple.getTriple();
458 return TheTarget;
461 bool isRelocAddressLess(RelocationRef A, RelocationRef B) {
462 return A.getOffset() < B.getOffset();
465 static Error getRelocationValueString(const RelocationRef &Rel,
466 SmallVectorImpl<char> &Result) {
467 const ObjectFile *Obj = Rel.getObject();
468 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
469 return getELFRelocationValueString(ELF, Rel, Result);
470 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
471 return getCOFFRelocationValueString(COFF, Rel, Result);
472 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
473 return getWasmRelocationValueString(Wasm, Rel, Result);
474 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
475 return getMachORelocationValueString(MachO, Rel, Result);
476 llvm_unreachable("unknown object file format");
479 /// Indicates whether this relocation should hidden when listing
480 /// relocations, usually because it is the trailing part of a multipart
481 /// relocation that will be printed as part of the leading relocation.
482 static bool getHidden(RelocationRef RelRef) {
483 auto *MachO = dyn_cast<MachOObjectFile>(RelRef.getObject());
484 if (!MachO)
485 return false;
487 unsigned Arch = MachO->getArch();
488 DataRefImpl Rel = RelRef.getRawDataRefImpl();
489 uint64_t Type = MachO->getRelocationType(Rel);
491 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
492 // is always hidden.
493 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc)
494 return Type == MachO::GENERIC_RELOC_PAIR;
496 if (Arch == Triple::x86_64) {
497 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
498 // an X86_64_RELOC_SUBTRACTOR.
499 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
500 DataRefImpl RelPrev = Rel;
501 RelPrev.d.a--;
502 uint64_t PrevType = MachO->getRelocationType(RelPrev);
503 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
504 return true;
508 return false;
511 namespace {
512 class SourcePrinter {
513 protected:
514 DILineInfo OldLineInfo;
515 const ObjectFile *Obj = nullptr;
516 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
517 // File name to file contents of source.
518 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
519 // Mark the line endings of the cached source.
520 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
521 // Keep track of missing sources.
522 StringSet<> MissingSources;
523 // Only emit 'no debug info' warning once.
524 bool WarnedNoDebugInfo;
526 private:
527 bool cacheSource(const DILineInfo& LineInfoFile);
529 public:
530 SourcePrinter() = default;
531 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch)
532 : Obj(Obj), WarnedNoDebugInfo(false) {
533 symbolize::LLVMSymbolizer::Options SymbolizerOpts;
534 SymbolizerOpts.PrintFunctions = DILineInfoSpecifier::FunctionNameKind::None;
535 SymbolizerOpts.Demangle = false;
536 SymbolizerOpts.DefaultArch = DefaultArch;
537 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
539 virtual ~SourcePrinter() = default;
540 virtual void printSourceLine(raw_ostream &OS,
541 object::SectionedAddress Address,
542 StringRef ObjectFilename,
543 StringRef Delimiter = "; ");
546 bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
547 std::unique_ptr<MemoryBuffer> Buffer;
548 if (LineInfo.Source) {
549 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);
550 } else {
551 auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName);
552 if (!BufferOrError) {
553 if (MissingSources.insert(LineInfo.FileName).second)
554 reportWarning("failed to find source " + LineInfo.FileName,
555 Obj->getFileName());
556 return false;
558 Buffer = std::move(*BufferOrError);
560 // Chomp the file to get lines
561 const char *BufferStart = Buffer->getBufferStart(),
562 *BufferEnd = Buffer->getBufferEnd();
563 std::vector<StringRef> &Lines = LineCache[LineInfo.FileName];
564 const char *Start = BufferStart;
565 for (const char *I = BufferStart; I != BufferEnd; ++I)
566 if (*I == '\n') {
567 Lines.emplace_back(Start, I - Start - (BufferStart < I && I[-1] == '\r'));
568 Start = I + 1;
570 if (Start < BufferEnd)
571 Lines.emplace_back(Start, BufferEnd - Start);
572 SourceCache[LineInfo.FileName] = std::move(Buffer);
573 return true;
576 void SourcePrinter::printSourceLine(raw_ostream &OS,
577 object::SectionedAddress Address,
578 StringRef ObjectFilename,
579 StringRef Delimiter) {
580 if (!Symbolizer)
581 return;
583 DILineInfo LineInfo = DILineInfo();
584 auto ExpectedLineInfo = Symbolizer->symbolizeCode(*Obj, Address);
585 std::string ErrorMessage;
586 if (!ExpectedLineInfo)
587 ErrorMessage = toString(ExpectedLineInfo.takeError());
588 else
589 LineInfo = *ExpectedLineInfo;
591 if (LineInfo.FileName == DILineInfo::BadString) {
592 if (!WarnedNoDebugInfo) {
593 std::string Warning =
594 "failed to parse debug information for " + ObjectFilename.str();
595 if (!ErrorMessage.empty())
596 Warning += ": " + ErrorMessage;
597 reportWarning(Warning, ObjectFilename);
598 WarnedNoDebugInfo = true;
600 return;
603 if (LineInfo.Line == 0 || ((OldLineInfo.Line == LineInfo.Line) &&
604 (OldLineInfo.FileName == LineInfo.FileName)))
605 return;
607 if (PrintLines)
608 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
609 if (PrintSource) {
610 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
611 if (!cacheSource(LineInfo))
612 return;
613 auto LineBuffer = LineCache.find(LineInfo.FileName);
614 if (LineBuffer != LineCache.end()) {
615 if (LineInfo.Line > LineBuffer->second.size()) {
616 reportWarning(
617 formatv(
618 "debug info line number {0} exceeds the number of lines in {1}",
619 LineInfo.Line, LineInfo.FileName),
620 ObjectFilename);
621 return;
623 // Vector begins at 0, line numbers are non-zero
624 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1] << '\n';
627 OldLineInfo = LineInfo;
630 static bool isAArch64Elf(const ObjectFile *Obj) {
631 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
632 return Elf && Elf->getEMachine() == ELF::EM_AARCH64;
635 static bool isArmElf(const ObjectFile *Obj) {
636 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
637 return Elf && Elf->getEMachine() == ELF::EM_ARM;
640 static bool hasMappingSymbols(const ObjectFile *Obj) {
641 return isArmElf(Obj) || isAArch64Elf(Obj);
644 static void printRelocation(StringRef FileName, const RelocationRef &Rel,
645 uint64_t Address, bool Is64Bits) {
646 StringRef Fmt = Is64Bits ? "\t\t%016" PRIx64 ": " : "\t\t\t%08" PRIx64 ": ";
647 SmallString<16> Name;
648 SmallString<32> Val;
649 Rel.getTypeName(Name);
650 if (Error E = getRelocationValueString(Rel, Val))
651 reportError(std::move(E), FileName);
652 outs() << format(Fmt.data(), Address) << Name << "\t" << Val << "\n";
655 class PrettyPrinter {
656 public:
657 virtual ~PrettyPrinter() = default;
658 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
659 ArrayRef<uint8_t> Bytes,
660 object::SectionedAddress Address, raw_ostream &OS,
661 StringRef Annot, MCSubtargetInfo const &STI,
662 SourcePrinter *SP, StringRef ObjectFilename,
663 std::vector<RelocationRef> *Rels = nullptr) {
664 if (SP && (PrintSource || PrintLines))
665 SP->printSourceLine(OS, Address, ObjectFilename);
667 size_t Start = OS.tell();
668 if (!NoLeadingAddr)
669 OS << format("%8" PRIx64 ":", Address.Address);
670 if (!NoShowRawInsn) {
671 OS << ' ';
672 dumpBytes(Bytes, OS);
675 // The output of printInst starts with a tab. Print some spaces so that
676 // the tab has 1 column and advances to the target tab stop.
677 unsigned TabStop = NoShowRawInsn ? 16 : 40;
678 unsigned Column = OS.tell() - Start;
679 OS.indent(Column < TabStop - 1 ? TabStop - 1 - Column : 7 - Column % 8);
681 if (MI)
682 IP.printInst(MI, OS, "", STI);
683 else
684 OS << "\t<unknown>";
687 PrettyPrinter PrettyPrinterInst;
689 class HexagonPrettyPrinter : public PrettyPrinter {
690 public:
691 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
692 raw_ostream &OS) {
693 uint32_t opcode =
694 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
695 if (!NoLeadingAddr)
696 OS << format("%8" PRIx64 ":", Address);
697 if (!NoShowRawInsn) {
698 OS << "\t";
699 dumpBytes(Bytes.slice(0, 4), OS);
700 OS << format("\t%08" PRIx32, opcode);
703 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
704 object::SectionedAddress Address, raw_ostream &OS,
705 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
706 StringRef ObjectFilename,
707 std::vector<RelocationRef> *Rels) override {
708 if (SP && (PrintSource || PrintLines))
709 SP->printSourceLine(OS, Address, ObjectFilename, "");
710 if (!MI) {
711 printLead(Bytes, Address.Address, OS);
712 OS << " <unknown>";
713 return;
715 std::string Buffer;
717 raw_string_ostream TempStream(Buffer);
718 IP.printInst(MI, TempStream, "", STI);
720 StringRef Contents(Buffer);
721 // Split off bundle attributes
722 auto PacketBundle = Contents.rsplit('\n');
723 // Split off first instruction from the rest
724 auto HeadTail = PacketBundle.first.split('\n');
725 auto Preamble = " { ";
726 auto Separator = "";
728 // Hexagon's packets require relocations to be inline rather than
729 // clustered at the end of the packet.
730 std::vector<RelocationRef>::const_iterator RelCur = Rels->begin();
731 std::vector<RelocationRef>::const_iterator RelEnd = Rels->end();
732 auto PrintReloc = [&]() -> void {
733 while ((RelCur != RelEnd) && (RelCur->getOffset() <= Address.Address)) {
734 if (RelCur->getOffset() == Address.Address) {
735 printRelocation(ObjectFilename, *RelCur, Address.Address, false);
736 return;
738 ++RelCur;
742 while (!HeadTail.first.empty()) {
743 OS << Separator;
744 Separator = "\n";
745 if (SP && (PrintSource || PrintLines))
746 SP->printSourceLine(OS, Address, ObjectFilename, "");
747 printLead(Bytes, Address.Address, OS);
748 OS << Preamble;
749 Preamble = " ";
750 StringRef Inst;
751 auto Duplex = HeadTail.first.split('\v');
752 if (!Duplex.second.empty()) {
753 OS << Duplex.first;
754 OS << "; ";
755 Inst = Duplex.second;
757 else
758 Inst = HeadTail.first;
759 OS << Inst;
760 HeadTail = HeadTail.second.split('\n');
761 if (HeadTail.first.empty())
762 OS << " } " << PacketBundle.second;
763 PrintReloc();
764 Bytes = Bytes.slice(4);
765 Address.Address += 4;
769 HexagonPrettyPrinter HexagonPrettyPrinterInst;
771 class AMDGCNPrettyPrinter : public PrettyPrinter {
772 public:
773 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
774 object::SectionedAddress Address, raw_ostream &OS,
775 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
776 StringRef ObjectFilename,
777 std::vector<RelocationRef> *Rels) override {
778 if (SP && (PrintSource || PrintLines))
779 SP->printSourceLine(OS, Address, ObjectFilename);
781 if (MI) {
782 SmallString<40> InstStr;
783 raw_svector_ostream IS(InstStr);
785 IP.printInst(MI, IS, "", STI);
787 OS << left_justify(IS.str(), 60);
788 } else {
789 // an unrecognized encoding - this is probably data so represent it
790 // using the .long directive, or .byte directive if fewer than 4 bytes
791 // remaining
792 if (Bytes.size() >= 4) {
793 OS << format("\t.long 0x%08" PRIx32 " ",
794 support::endian::read32<support::little>(Bytes.data()));
795 OS.indent(42);
796 } else {
797 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
798 for (unsigned int i = 1; i < Bytes.size(); i++)
799 OS << format(", 0x%02" PRIx8, Bytes[i]);
800 OS.indent(55 - (6 * Bytes.size()));
804 OS << format("// %012" PRIX64 ":", Address.Address);
805 if (Bytes.size() >= 4) {
806 // D should be casted to uint32_t here as it is passed by format to
807 // snprintf as vararg.
808 for (uint32_t D : makeArrayRef(
809 reinterpret_cast<const support::little32_t *>(Bytes.data()),
810 Bytes.size() / 4))
811 OS << format(" %08" PRIX32, D);
812 } else {
813 for (unsigned char B : Bytes)
814 OS << format(" %02" PRIX8, B);
817 if (!Annot.empty())
818 OS << " // " << Annot;
821 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
823 class BPFPrettyPrinter : public PrettyPrinter {
824 public:
825 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
826 object::SectionedAddress Address, raw_ostream &OS,
827 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
828 StringRef ObjectFilename,
829 std::vector<RelocationRef> *Rels) override {
830 if (SP && (PrintSource || PrintLines))
831 SP->printSourceLine(OS, Address, ObjectFilename);
832 if (!NoLeadingAddr)
833 OS << format("%8" PRId64 ":", Address.Address / 8);
834 if (!NoShowRawInsn) {
835 OS << "\t";
836 dumpBytes(Bytes, OS);
838 if (MI)
839 IP.printInst(MI, OS, "", STI);
840 else
841 OS << "\t<unknown>";
844 BPFPrettyPrinter BPFPrettyPrinterInst;
846 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
847 switch(Triple.getArch()) {
848 default:
849 return PrettyPrinterInst;
850 case Triple::hexagon:
851 return HexagonPrettyPrinterInst;
852 case Triple::amdgcn:
853 return AMDGCNPrettyPrinterInst;
854 case Triple::bpfel:
855 case Triple::bpfeb:
856 return BPFPrettyPrinterInst;
861 static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
862 assert(Obj->isELF());
863 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
864 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
865 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
866 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
867 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
868 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
869 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
870 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
871 llvm_unreachable("Unsupported binary format");
874 template <class ELFT> static void
875 addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
876 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
877 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
878 uint8_t SymbolType = Symbol.getELFType();
879 if (SymbolType == ELF::STT_SECTION)
880 continue;
882 uint64_t Address = unwrapOrError(Symbol.getAddress(), Obj->getFileName());
883 // ELFSymbolRef::getAddress() returns size instead of value for common
884 // symbols which is not desirable for disassembly output. Overriding.
885 if (SymbolType == ELF::STT_COMMON)
886 Address = Obj->getSymbol(Symbol.getRawDataRefImpl())->st_value;
888 StringRef Name = unwrapOrError(Symbol.getName(), Obj->getFileName());
889 if (Name.empty())
890 continue;
892 section_iterator SecI =
893 unwrapOrError(Symbol.getSection(), Obj->getFileName());
894 if (SecI == Obj->section_end())
895 continue;
897 AllSymbols[*SecI].emplace_back(Address, Name, SymbolType);
901 static void
902 addDynamicElfSymbols(const ObjectFile *Obj,
903 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
904 assert(Obj->isELF());
905 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
906 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
907 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
908 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
909 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
910 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
911 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
912 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
913 else
914 llvm_unreachable("Unsupported binary format");
917 static void addPltEntries(const ObjectFile *Obj,
918 std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
919 StringSaver &Saver) {
920 Optional<SectionRef> Plt = None;
921 for (const SectionRef &Section : Obj->sections()) {
922 Expected<StringRef> SecNameOrErr = Section.getName();
923 if (!SecNameOrErr) {
924 consumeError(SecNameOrErr.takeError());
925 continue;
927 if (*SecNameOrErr == ".plt")
928 Plt = Section;
930 if (!Plt)
931 return;
932 if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) {
933 for (auto PltEntry : ElfObj->getPltAddresses()) {
934 SymbolRef Symbol(PltEntry.first, ElfObj);
935 uint8_t SymbolType = getElfSymbolType(Obj, Symbol);
937 StringRef Name = unwrapOrError(Symbol.getName(), Obj->getFileName());
938 if (!Name.empty())
939 AllSymbols[*Plt].emplace_back(
940 PltEntry.second, Saver.save((Name + "@plt").str()), SymbolType);
945 // Normally the disassembly output will skip blocks of zeroes. This function
946 // returns the number of zero bytes that can be skipped when dumping the
947 // disassembly of the instructions in Buf.
948 static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) {
949 // Find the number of leading zeroes.
950 size_t N = 0;
951 while (N < Buf.size() && !Buf[N])
952 ++N;
954 // We may want to skip blocks of zero bytes, but unless we see
955 // at least 8 of them in a row.
956 if (N < 8)
957 return 0;
959 // We skip zeroes in multiples of 4 because do not want to truncate an
960 // instruction if it starts with a zero byte.
961 return N & ~0x3;
964 // Returns a map from sections to their relocations.
965 static std::map<SectionRef, std::vector<RelocationRef>>
966 getRelocsMap(object::ObjectFile const &Obj) {
967 std::map<SectionRef, std::vector<RelocationRef>> Ret;
968 for (SectionRef Sec : Obj.sections()) {
969 section_iterator Relocated = Sec.getRelocatedSection();
970 if (Relocated == Obj.section_end() || !shouldKeep(*Relocated))
971 continue;
972 std::vector<RelocationRef> &V = Ret[*Relocated];
973 for (const RelocationRef &R : Sec.relocations())
974 V.push_back(R);
975 // Sort relocations by address.
976 llvm::stable_sort(V, isRelocAddressLess);
978 return Ret;
981 // Used for --adjust-vma to check if address should be adjusted by the
982 // specified value for a given section.
983 // For ELF we do not adjust non-allocatable sections like debug ones,
984 // because they are not loadable.
985 // TODO: implement for other file formats.
986 static bool shouldAdjustVA(const SectionRef &Section) {
987 const ObjectFile *Obj = Section.getObject();
988 if (isa<object::ELFObjectFileBase>(Obj))
989 return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
990 return false;
994 typedef std::pair<uint64_t, char> MappingSymbolPair;
995 static char getMappingSymbolKind(ArrayRef<MappingSymbolPair> MappingSymbols,
996 uint64_t Address) {
997 auto It =
998 partition_point(MappingSymbols, [Address](const MappingSymbolPair &Val) {
999 return Val.first <= Address;
1001 // Return zero for any address before the first mapping symbol; this means
1002 // we should use the default disassembly mode, depending on the target.
1003 if (It == MappingSymbols.begin())
1004 return '\x00';
1005 return (It - 1)->second;
1008 static uint64_t
1009 dumpARMELFData(uint64_t SectionAddr, uint64_t Index, uint64_t End,
1010 const ObjectFile *Obj, ArrayRef<uint8_t> Bytes,
1011 ArrayRef<MappingSymbolPair> MappingSymbols) {
1012 support::endianness Endian =
1013 Obj->isLittleEndian() ? support::little : support::big;
1014 while (Index < End) {
1015 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1016 outs() << "\t";
1017 if (Index + 4 <= End) {
1018 dumpBytes(Bytes.slice(Index, 4), outs());
1019 outs() << "\t.word\t"
1020 << format_hex(
1021 support::endian::read32(Bytes.data() + Index, Endian), 10);
1022 Index += 4;
1023 } else if (Index + 2 <= End) {
1024 dumpBytes(Bytes.slice(Index, 2), outs());
1025 outs() << "\t\t.short\t"
1026 << format_hex(
1027 support::endian::read16(Bytes.data() + Index, Endian), 6);
1028 Index += 2;
1029 } else {
1030 dumpBytes(Bytes.slice(Index, 1), outs());
1031 outs() << "\t\t.byte\t" << format_hex(Bytes[0], 4);
1032 ++Index;
1034 outs() << "\n";
1035 if (getMappingSymbolKind(MappingSymbols, Index) != 'd')
1036 break;
1038 return Index;
1041 static void dumpELFData(uint64_t SectionAddr, uint64_t Index, uint64_t End,
1042 ArrayRef<uint8_t> Bytes) {
1043 // print out data up to 8 bytes at a time in hex and ascii
1044 uint8_t AsciiData[9] = {'\0'};
1045 uint8_t Byte;
1046 int NumBytes = 0;
1048 for (; Index < End; ++Index) {
1049 if (NumBytes == 0)
1050 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1051 Byte = Bytes.slice(Index)[0];
1052 outs() << format(" %02x", Byte);
1053 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
1055 uint8_t IndentOffset = 0;
1056 NumBytes++;
1057 if (Index == End - 1 || NumBytes > 8) {
1058 // Indent the space for less than 8 bytes data.
1059 // 2 spaces for byte and one for space between bytes
1060 IndentOffset = 3 * (8 - NumBytes);
1061 for (int Excess = NumBytes; Excess < 8; Excess++)
1062 AsciiData[Excess] = '\0';
1063 NumBytes = 8;
1065 if (NumBytes == 8) {
1066 AsciiData[8] = '\0';
1067 outs() << std::string(IndentOffset, ' ') << " ";
1068 outs() << reinterpret_cast<char *>(AsciiData);
1069 outs() << '\n';
1070 NumBytes = 0;
1075 static void disassembleObject(const Target *TheTarget, const ObjectFile *Obj,
1076 MCContext &Ctx, MCDisassembler *PrimaryDisAsm,
1077 MCDisassembler *SecondaryDisAsm,
1078 const MCInstrAnalysis *MIA, MCInstPrinter *IP,
1079 const MCSubtargetInfo *PrimarySTI,
1080 const MCSubtargetInfo *SecondarySTI,
1081 PrettyPrinter &PIP,
1082 SourcePrinter &SP, bool InlineRelocs) {
1083 const MCSubtargetInfo *STI = PrimarySTI;
1084 MCDisassembler *DisAsm = PrimaryDisAsm;
1085 bool PrimaryIsThumb = false;
1086 if (isArmElf(Obj))
1087 PrimaryIsThumb = STI->checkFeatures("+thumb-mode");
1089 std::map<SectionRef, std::vector<RelocationRef>> RelocMap;
1090 if (InlineRelocs)
1091 RelocMap = getRelocsMap(*Obj);
1092 bool Is64Bits = Obj->getBytesInAddress() > 4;
1094 // Create a mapping from virtual address to symbol name. This is used to
1095 // pretty print the symbols while disassembling.
1096 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1097 SectionSymbolsTy AbsoluteSymbols;
1098 const StringRef FileName = Obj->getFileName();
1099 for (const SymbolRef &Symbol : Obj->symbols()) {
1100 uint64_t Address = unwrapOrError(Symbol.getAddress(), FileName);
1102 StringRef Name = unwrapOrError(Symbol.getName(), FileName);
1103 if (Name.empty())
1104 continue;
1106 uint8_t SymbolType = ELF::STT_NOTYPE;
1107 if (Obj->isELF()) {
1108 SymbolType = getElfSymbolType(Obj, Symbol);
1109 if (SymbolType == ELF::STT_SECTION)
1110 continue;
1113 section_iterator SecI = unwrapOrError(Symbol.getSection(), FileName);
1114 if (SecI != Obj->section_end())
1115 AllSymbols[*SecI].emplace_back(Address, Name, SymbolType);
1116 else
1117 AbsoluteSymbols.emplace_back(Address, Name, SymbolType);
1119 if (AllSymbols.empty() && Obj->isELF())
1120 addDynamicElfSymbols(Obj, AllSymbols);
1122 BumpPtrAllocator A;
1123 StringSaver Saver(A);
1124 addPltEntries(Obj, AllSymbols, Saver);
1126 // Create a mapping from virtual address to section.
1127 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1128 for (SectionRef Sec : Obj->sections())
1129 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1130 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1132 // Linked executables (.exe and .dll files) typically don't include a real
1133 // symbol table but they might contain an export table.
1134 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1135 for (const auto &ExportEntry : COFFObj->export_directories()) {
1136 StringRef Name;
1137 if (std::error_code EC = ExportEntry.getSymbolName(Name))
1138 reportError(errorCodeToError(EC), Obj->getFileName());
1139 if (Name.empty())
1140 continue;
1142 uint32_t RVA;
1143 if (std::error_code EC = ExportEntry.getExportRVA(RVA))
1144 reportError(errorCodeToError(EC), Obj->getFileName());
1146 uint64_t VA = COFFObj->getImageBase() + RVA;
1147 auto Sec = partition_point(
1148 SectionAddresses, [VA](const std::pair<uint64_t, SectionRef> &O) {
1149 return O.first <= VA;
1151 if (Sec != SectionAddresses.begin()) {
1152 --Sec;
1153 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
1154 } else
1155 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
1159 // Sort all the symbols, this allows us to use a simple binary search to find
1160 // a symbol near an address.
1161 StringSet<> FoundDisasmFuncsSet;
1162 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1163 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1164 array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
1166 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1167 if (FilterSections.empty() && !DisassembleAll &&
1168 (!Section.isText() || Section.isVirtual()))
1169 continue;
1171 uint64_t SectionAddr = Section.getAddress();
1172 uint64_t SectSize = Section.getSize();
1173 if (!SectSize)
1174 continue;
1176 // Get the list of all the symbols in this section.
1177 SectionSymbolsTy &Symbols = AllSymbols[Section];
1178 std::vector<MappingSymbolPair> MappingSymbols;
1179 if (hasMappingSymbols(Obj)) {
1180 for (const auto &Symb : Symbols) {
1181 uint64_t Address = std::get<0>(Symb);
1182 StringRef Name = std::get<1>(Symb);
1183 if (Name.startswith("$d"))
1184 MappingSymbols.emplace_back(Address - SectionAddr, 'd');
1185 if (Name.startswith("$x"))
1186 MappingSymbols.emplace_back(Address - SectionAddr, 'x');
1187 if (Name.startswith("$a"))
1188 MappingSymbols.emplace_back(Address - SectionAddr, 'a');
1189 if (Name.startswith("$t"))
1190 MappingSymbols.emplace_back(Address - SectionAddr, 't');
1194 llvm::sort(MappingSymbols);
1196 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1197 // AMDGPU disassembler uses symbolizer for printing labels
1198 std::unique_ptr<MCRelocationInfo> RelInfo(
1199 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1200 if (RelInfo) {
1201 std::unique_ptr<MCSymbolizer> Symbolizer(
1202 TheTarget->createMCSymbolizer(
1203 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1204 DisAsm->setSymbolizer(std::move(Symbolizer));
1208 StringRef SegmentName = "";
1209 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
1210 DataRefImpl DR = Section.getRawDataRefImpl();
1211 SegmentName = MachO->getSectionFinalSegmentName(DR);
1214 StringRef SectionName = unwrapOrError(Section.getName(), Obj->getFileName());
1215 // If the section has no symbol at the start, just insert a dummy one.
1216 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
1217 Symbols.insert(
1218 Symbols.begin(),
1219 std::make_tuple(SectionAddr, SectionName,
1220 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
1223 SmallString<40> Comments;
1224 raw_svector_ostream CommentStream(Comments);
1226 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(
1227 unwrapOrError(Section.getContents(), Obj->getFileName()));
1229 uint64_t VMAAdjustment = 0;
1230 if (shouldAdjustVA(Section))
1231 VMAAdjustment = AdjustVMA;
1233 uint64_t Size;
1234 uint64_t Index;
1235 bool PrintedSection = false;
1236 std::vector<RelocationRef> Rels = RelocMap[Section];
1237 std::vector<RelocationRef>::const_iterator RelCur = Rels.begin();
1238 std::vector<RelocationRef>::const_iterator RelEnd = Rels.end();
1239 // Disassemble symbol by symbol.
1240 for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) {
1241 std::string SymbolName = std::get<1>(Symbols[SI]).str();
1242 if (Demangle)
1243 SymbolName = demangle(SymbolName);
1245 // Skip if --disassemble-functions is not empty and the symbol is not in
1246 // the list.
1247 if (!DisasmFuncsSet.empty() && !DisasmFuncsSet.count(SymbolName))
1248 continue;
1250 uint64_t Start = std::get<0>(Symbols[SI]);
1251 if (Start < SectionAddr || StopAddress <= Start)
1252 continue;
1253 else
1254 FoundDisasmFuncsSet.insert(SymbolName);
1256 // The end is the section end, the beginning of the next symbol, or
1257 // --stop-address.
1258 uint64_t End = std::min<uint64_t>(SectionAddr + SectSize, StopAddress);
1259 if (SI + 1 < SE)
1260 End = std::min(End, std::get<0>(Symbols[SI + 1]));
1261 if (Start >= End || End <= StartAddress)
1262 continue;
1263 Start -= SectionAddr;
1264 End -= SectionAddr;
1266 if (!PrintedSection) {
1267 PrintedSection = true;
1268 outs() << "\nDisassembly of section ";
1269 if (!SegmentName.empty())
1270 outs() << SegmentName << ",";
1271 outs() << SectionName << ":\n";
1274 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1275 if (std::get<2>(Symbols[SI]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1276 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1277 Start += 256;
1279 if (SI == SE - 1 ||
1280 std::get<2>(Symbols[SI + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1281 // cut trailing zeroes at the end of kernel
1282 // cut up to 256 bytes
1283 const uint64_t EndAlign = 256;
1284 const auto Limit = End - (std::min)(EndAlign, End - Start);
1285 while (End > Limit &&
1286 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1287 End -= 4;
1291 outs() << '\n';
1292 if (!NoLeadingAddr)
1293 outs() << format(Is64Bits ? "%016" PRIx64 " " : "%08" PRIx64 " ",
1294 SectionAddr + Start + VMAAdjustment);
1296 outs() << SymbolName << ":\n";
1298 // Don't print raw contents of a virtual section. A virtual section
1299 // doesn't have any contents in the file.
1300 if (Section.isVirtual()) {
1301 outs() << "...\n";
1302 continue;
1305 #ifndef NDEBUG
1306 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1307 #else
1308 raw_ostream &DebugOut = nulls();
1309 #endif
1311 // Some targets (like WebAssembly) have a special prelude at the start
1312 // of each symbol.
1313 DisAsm->onSymbolStart(SymbolName, Size, Bytes.slice(Start, End - Start),
1314 SectionAddr + Start, DebugOut, CommentStream);
1315 Start += Size;
1317 Index = Start;
1318 if (SectionAddr < StartAddress)
1319 Index = std::max<uint64_t>(Index, StartAddress - SectionAddr);
1321 // If there is a data/common symbol inside an ELF text section and we are
1322 // only disassembling text (applicable all architectures), we are in a
1323 // situation where we must print the data and not disassemble it.
1324 if (Obj->isELF() && !DisassembleAll && Section.isText()) {
1325 uint8_t SymTy = std::get<2>(Symbols[SI]);
1326 if (SymTy == ELF::STT_OBJECT || SymTy == ELF::STT_COMMON) {
1327 dumpELFData(SectionAddr, Index, End, Bytes);
1328 Index = End;
1332 bool CheckARMELFData = hasMappingSymbols(Obj) &&
1333 std::get<2>(Symbols[SI]) != ELF::STT_OBJECT &&
1334 !DisassembleAll;
1335 while (Index < End) {
1336 // ARM and AArch64 ELF binaries can interleave data and text in the
1337 // same section. We rely on the markers introduced to understand what
1338 // we need to dump. If the data marker is within a function, it is
1339 // denoted as a word/short etc.
1340 if (CheckARMELFData &&
1341 getMappingSymbolKind(MappingSymbols, Index) == 'd') {
1342 Index = dumpARMELFData(SectionAddr, Index, End, Obj, Bytes,
1343 MappingSymbols);
1344 continue;
1347 // When -z or --disassemble-zeroes are given we always dissasemble
1348 // them. Otherwise we might want to skip zero bytes we see.
1349 if (!DisassembleZeroes) {
1350 uint64_t MaxOffset = End - Index;
1351 // For -reloc: print zero blocks patched by relocations, so that
1352 // relocations can be shown in the dump.
1353 if (RelCur != RelEnd)
1354 MaxOffset = RelCur->getOffset() - Index;
1356 if (size_t N =
1357 countSkippableZeroBytes(Bytes.slice(Index, MaxOffset))) {
1358 outs() << "\t\t..." << '\n';
1359 Index += N;
1360 continue;
1364 if (SecondarySTI) {
1365 if (getMappingSymbolKind(MappingSymbols, Index) == 'a') {
1366 STI = PrimaryIsThumb ? SecondarySTI : PrimarySTI;
1367 DisAsm = PrimaryIsThumb ? SecondaryDisAsm : PrimaryDisAsm;
1368 } else if (getMappingSymbolKind(MappingSymbols, Index) == 't') {
1369 STI = PrimaryIsThumb ? PrimarySTI : SecondarySTI;
1370 DisAsm = PrimaryIsThumb ? PrimaryDisAsm : SecondaryDisAsm;
1374 // Disassemble a real instruction or a data when disassemble all is
1375 // provided
1376 MCInst Inst;
1377 bool Disassembled = DisAsm->getInstruction(
1378 Inst, Size, Bytes.slice(Index), SectionAddr + Index, DebugOut,
1379 CommentStream);
1380 if (Size == 0)
1381 Size = 1;
1383 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
1384 Bytes.slice(Index, Size),
1385 {SectionAddr + Index + VMAAdjustment, Section.getIndex()},
1386 outs(), "", *STI, &SP, Obj->getFileName(), &Rels);
1387 outs() << CommentStream.str();
1388 Comments.clear();
1390 // Try to resolve the target of a call, tail call, etc. to a specific
1391 // symbol.
1392 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1393 MIA->isConditionalBranch(Inst))) {
1394 uint64_t Target;
1395 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1396 // In a relocatable object, the target's section must reside in
1397 // the same section as the call instruction or it is accessed
1398 // through a relocation.
1400 // In a non-relocatable object, the target may be in any section.
1402 // N.B. We don't walk the relocations in the relocatable case yet.
1403 auto *TargetSectionSymbols = &Symbols;
1404 if (!Obj->isRelocatableObject()) {
1405 auto It = partition_point(
1406 SectionAddresses,
1407 [=](const std::pair<uint64_t, SectionRef> &O) {
1408 return O.first <= Target;
1410 if (It != SectionAddresses.begin()) {
1411 --It;
1412 TargetSectionSymbols = &AllSymbols[It->second];
1413 } else {
1414 TargetSectionSymbols = &AbsoluteSymbols;
1418 // Find the last symbol in the section whose offset is less than
1419 // or equal to the target. If there isn't a section that contains
1420 // the target, find the nearest preceding absolute symbol.
1421 auto TargetSym = partition_point(
1422 *TargetSectionSymbols,
1423 [=](const std::tuple<uint64_t, StringRef, uint8_t> &O) {
1424 return std::get<0>(O) <= Target;
1426 if (TargetSym == TargetSectionSymbols->begin()) {
1427 TargetSectionSymbols = &AbsoluteSymbols;
1428 TargetSym = partition_point(
1429 AbsoluteSymbols,
1430 [=](const std::tuple<uint64_t, StringRef, uint8_t> &O) {
1431 return std::get<0>(O) <= Target;
1434 if (TargetSym != TargetSectionSymbols->begin()) {
1435 --TargetSym;
1436 uint64_t TargetAddress = std::get<0>(*TargetSym);
1437 StringRef TargetName = std::get<1>(*TargetSym);
1438 outs() << " <" << TargetName;
1439 uint64_t Disp = Target - TargetAddress;
1440 if (Disp)
1441 outs() << "+0x" << Twine::utohexstr(Disp);
1442 outs() << '>';
1446 outs() << "\n";
1448 // Hexagon does this in pretty printer
1449 if (Obj->getArch() != Triple::hexagon) {
1450 // Print relocation for instruction.
1451 while (RelCur != RelEnd) {
1452 uint64_t Offset = RelCur->getOffset();
1453 // If this relocation is hidden, skip it.
1454 if (getHidden(*RelCur) || SectionAddr + Offset < StartAddress) {
1455 ++RelCur;
1456 continue;
1459 // Stop when RelCur's offset is past the current instruction.
1460 if (Offset >= Index + Size)
1461 break;
1463 // When --adjust-vma is used, update the address printed.
1464 if (RelCur->getSymbol() != Obj->symbol_end()) {
1465 Expected<section_iterator> SymSI =
1466 RelCur->getSymbol()->getSection();
1467 if (SymSI && *SymSI != Obj->section_end() &&
1468 shouldAdjustVA(**SymSI))
1469 Offset += AdjustVMA;
1472 printRelocation(Obj->getFileName(), *RelCur, SectionAddr + Offset,
1473 Is64Bits);
1474 ++RelCur;
1478 Index += Size;
1482 StringSet<> MissingDisasmFuncsSet =
1483 set_difference(DisasmFuncsSet, FoundDisasmFuncsSet);
1484 for (StringRef MissingDisasmFunc : MissingDisasmFuncsSet.keys())
1485 reportWarning("failed to disassemble missing function " + MissingDisasmFunc,
1486 FileName);
1489 static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
1490 const Target *TheTarget = getTarget(Obj);
1492 // Package up features to be passed to target/subtarget
1493 SubtargetFeatures Features = Obj->getFeatures();
1494 if (!MAttrs.empty())
1495 for (unsigned I = 0; I != MAttrs.size(); ++I)
1496 Features.AddFeature(MAttrs[I]);
1498 std::unique_ptr<const MCRegisterInfo> MRI(
1499 TheTarget->createMCRegInfo(TripleName));
1500 if (!MRI)
1501 reportError(Obj->getFileName(),
1502 "no register info for target " + TripleName);
1504 // Set up disassembler.
1505 std::unique_ptr<const MCAsmInfo> AsmInfo(
1506 TheTarget->createMCAsmInfo(*MRI, TripleName));
1507 if (!AsmInfo)
1508 reportError(Obj->getFileName(),
1509 "no assembly info for target " + TripleName);
1510 std::unique_ptr<const MCSubtargetInfo> STI(
1511 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1512 if (!STI)
1513 reportError(Obj->getFileName(),
1514 "no subtarget info for target " + TripleName);
1515 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1516 if (!MII)
1517 reportError(Obj->getFileName(),
1518 "no instruction info for target " + TripleName);
1519 MCObjectFileInfo MOFI;
1520 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1521 // FIXME: for now initialize MCObjectFileInfo with default values
1522 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
1524 std::unique_ptr<MCDisassembler> DisAsm(
1525 TheTarget->createMCDisassembler(*STI, Ctx));
1526 if (!DisAsm)
1527 reportError(Obj->getFileName(), "no disassembler for target " + TripleName);
1529 // If we have an ARM object file, we need a second disassembler, because
1530 // ARM CPUs have two different instruction sets: ARM mode, and Thumb mode.
1531 // We use mapping symbols to switch between the two assemblers, where
1532 // appropriate.
1533 std::unique_ptr<MCDisassembler> SecondaryDisAsm;
1534 std::unique_ptr<const MCSubtargetInfo> SecondarySTI;
1535 if (isArmElf(Obj) && !STI->checkFeatures("+mclass")) {
1536 if (STI->checkFeatures("+thumb-mode"))
1537 Features.AddFeature("-thumb-mode");
1538 else
1539 Features.AddFeature("+thumb-mode");
1540 SecondarySTI.reset(TheTarget->createMCSubtargetInfo(TripleName, MCPU,
1541 Features.getString()));
1542 SecondaryDisAsm.reset(TheTarget->createMCDisassembler(*SecondarySTI, Ctx));
1545 std::unique_ptr<const MCInstrAnalysis> MIA(
1546 TheTarget->createMCInstrAnalysis(MII.get()));
1548 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1549 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1550 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
1551 if (!IP)
1552 reportError(Obj->getFileName(),
1553 "no instruction printer for target " + TripleName);
1554 IP->setPrintImmHex(PrintImmHex);
1556 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
1557 SourcePrinter SP(Obj, TheTarget->getName());
1559 for (StringRef Opt : DisassemblerOptions)
1560 if (!IP->applyTargetSpecificCLOption(Opt))
1561 reportError(Obj->getFileName(),
1562 "Unrecognized disassembler option: " + Opt);
1564 disassembleObject(TheTarget, Obj, Ctx, DisAsm.get(), SecondaryDisAsm.get(),
1565 MIA.get(), IP.get(), STI.get(), SecondarySTI.get(), PIP,
1566 SP, InlineRelocs);
1569 void printRelocations(const ObjectFile *Obj) {
1570 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1571 "%08" PRIx64;
1572 // Regular objdump doesn't print relocations in non-relocatable object
1573 // files.
1574 if (!Obj->isRelocatableObject())
1575 return;
1577 // Build a mapping from relocation target to a vector of relocation
1578 // sections. Usually, there is an only one relocation section for
1579 // each relocated section.
1580 MapVector<SectionRef, std::vector<SectionRef>> SecToRelSec;
1581 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1582 if (Section.relocation_begin() == Section.relocation_end())
1583 continue;
1584 const SectionRef TargetSec = *Section.getRelocatedSection();
1585 SecToRelSec[TargetSec].push_back(Section);
1588 for (std::pair<SectionRef, std::vector<SectionRef>> &P : SecToRelSec) {
1589 StringRef SecName = unwrapOrError(P.first.getName(), Obj->getFileName());
1590 outs() << "RELOCATION RECORDS FOR [" << SecName << "]:\n";
1592 for (SectionRef Section : P.second) {
1593 for (const RelocationRef &Reloc : Section.relocations()) {
1594 uint64_t Address = Reloc.getOffset();
1595 SmallString<32> RelocName;
1596 SmallString<32> ValueStr;
1597 if (Address < StartAddress || Address > StopAddress || getHidden(Reloc))
1598 continue;
1599 Reloc.getTypeName(RelocName);
1600 if (Error E = getRelocationValueString(Reloc, ValueStr))
1601 reportError(std::move(E), Obj->getFileName());
1603 outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1604 << ValueStr << "\n";
1607 outs() << "\n";
1611 void printDynamicRelocations(const ObjectFile *Obj) {
1612 // For the moment, this option is for ELF only
1613 if (!Obj->isELF())
1614 return;
1616 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
1617 if (!Elf || Elf->getEType() != ELF::ET_DYN) {
1618 reportError(Obj->getFileName(), "not a dynamic object");
1619 return;
1622 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1623 if (DynRelSec.empty())
1624 return;
1626 outs() << "DYNAMIC RELOCATION RECORDS\n";
1627 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1628 for (const SectionRef &Section : DynRelSec)
1629 for (const RelocationRef &Reloc : Section.relocations()) {
1630 uint64_t Address = Reloc.getOffset();
1631 SmallString<32> RelocName;
1632 SmallString<32> ValueStr;
1633 Reloc.getTypeName(RelocName);
1634 if (Error E = getRelocationValueString(Reloc, ValueStr))
1635 reportError(std::move(E), Obj->getFileName());
1636 outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1637 << ValueStr << "\n";
1641 // Returns true if we need to show LMA column when dumping section headers. We
1642 // show it only when the platform is ELF and either we have at least one section
1643 // whose VMA and LMA are different and/or when --show-lma flag is used.
1644 static bool shouldDisplayLMA(const ObjectFile *Obj) {
1645 if (!Obj->isELF())
1646 return false;
1647 for (const SectionRef &S : ToolSectionFilter(*Obj))
1648 if (S.getAddress() != getELFSectionLMA(S))
1649 return true;
1650 return ShowLMA;
1653 void printSectionHeaders(const ObjectFile *Obj) {
1654 bool HasLMAColumn = shouldDisplayLMA(Obj);
1655 if (HasLMAColumn)
1656 outs() << "Sections:\n"
1657 "Idx Name Size VMA LMA "
1658 "Type\n";
1659 else
1660 outs() << "Sections:\n"
1661 "Idx Name Size VMA Type\n";
1663 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1664 StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName());
1665 uint64_t VMA = Section.getAddress();
1666 if (shouldAdjustVA(Section))
1667 VMA += AdjustVMA;
1669 uint64_t Size = Section.getSize();
1670 bool Text = Section.isText();
1671 bool Data = Section.isData();
1672 bool BSS = Section.isBSS();
1673 std::string Type = (std::string(Text ? "TEXT " : "") +
1674 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1676 if (HasLMAColumn)
1677 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %016" PRIx64
1678 " %s\n",
1679 (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1680 VMA, getELFSectionLMA(Section), Type.c_str());
1681 else
1682 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
1683 (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1684 VMA, Type.c_str());
1686 outs() << "\n";
1689 void printSectionContents(const ObjectFile *Obj) {
1690 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1691 StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName());
1692 uint64_t BaseAddr = Section.getAddress();
1693 uint64_t Size = Section.getSize();
1694 if (!Size)
1695 continue;
1697 outs() << "Contents of section " << Name << ":\n";
1698 if (Section.isBSS()) {
1699 outs() << format("<skipping contents of bss section at [%04" PRIx64
1700 ", %04" PRIx64 ")>\n",
1701 BaseAddr, BaseAddr + Size);
1702 continue;
1705 StringRef Contents = unwrapOrError(Section.getContents(), Obj->getFileName());
1707 // Dump out the content as hex and printable ascii characters.
1708 for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) {
1709 outs() << format(" %04" PRIx64 " ", BaseAddr + Addr);
1710 // Dump line of hex.
1711 for (std::size_t I = 0; I < 16; ++I) {
1712 if (I != 0 && I % 4 == 0)
1713 outs() << ' ';
1714 if (Addr + I < End)
1715 outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true)
1716 << hexdigit(Contents[Addr + I] & 0xF, true);
1717 else
1718 outs() << " ";
1720 // Print ascii.
1721 outs() << " ";
1722 for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) {
1723 if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF))
1724 outs() << Contents[Addr + I];
1725 else
1726 outs() << ".";
1728 outs() << "\n";
1733 void printSymbolTable(const ObjectFile *O, StringRef ArchiveName,
1734 StringRef ArchitectureName) {
1735 outs() << "SYMBOL TABLE:\n";
1737 if (const COFFObjectFile *Coff = dyn_cast<const COFFObjectFile>(O)) {
1738 printCOFFSymbolTable(Coff);
1739 return;
1742 const StringRef FileName = O->getFileName();
1743 for (auto I = O->symbol_begin(), E = O->symbol_end(); I != E; ++I) {
1744 const SymbolRef &Symbol = *I;
1745 uint64_t Address = unwrapOrError(Symbol.getAddress(), FileName, ArchiveName,
1746 ArchitectureName);
1747 if ((Address < StartAddress) || (Address > StopAddress))
1748 continue;
1749 SymbolRef::Type Type = unwrapOrError(Symbol.getType(), FileName,
1750 ArchiveName, ArchitectureName);
1751 uint32_t Flags = Symbol.getFlags();
1752 section_iterator Section = unwrapOrError(Symbol.getSection(), FileName,
1753 ArchiveName, ArchitectureName);
1754 StringRef Name;
1755 if (Type == SymbolRef::ST_Debug && Section != O->section_end()) {
1756 if (Expected<StringRef> NameOrErr = Section->getName())
1757 Name = *NameOrErr;
1758 else
1759 consumeError(NameOrErr.takeError());
1761 } else {
1762 Name = unwrapOrError(Symbol.getName(), FileName, ArchiveName,
1763 ArchitectureName);
1766 bool Global = Flags & SymbolRef::SF_Global;
1767 bool Weak = Flags & SymbolRef::SF_Weak;
1768 bool Absolute = Flags & SymbolRef::SF_Absolute;
1769 bool Common = Flags & SymbolRef::SF_Common;
1770 bool Hidden = Flags & SymbolRef::SF_Hidden;
1772 char GlobLoc = ' ';
1773 if (Type != SymbolRef::ST_Unknown)
1774 GlobLoc = Global ? 'g' : 'l';
1775 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1776 ? 'd' : ' ';
1777 char FileFunc = ' ';
1778 if (Type == SymbolRef::ST_File)
1779 FileFunc = 'f';
1780 else if (Type == SymbolRef::ST_Function)
1781 FileFunc = 'F';
1782 else if (Type == SymbolRef::ST_Data)
1783 FileFunc = 'O';
1785 const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 :
1786 "%08" PRIx64;
1788 outs() << format(Fmt, Address) << " "
1789 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1790 << (Weak ? 'w' : ' ') // Weak?
1791 << ' ' // Constructor. Not supported yet.
1792 << ' ' // Warning. Not supported yet.
1793 << ' ' // Indirect reference to another symbol.
1794 << Debug // Debugging (d) or dynamic (D) symbol.
1795 << FileFunc // Name of function (F), file (f) or object (O).
1796 << ' ';
1797 if (Absolute) {
1798 outs() << "*ABS*";
1799 } else if (Common) {
1800 outs() << "*COM*";
1801 } else if (Section == O->section_end()) {
1802 outs() << "*UND*";
1803 } else {
1804 if (const MachOObjectFile *MachO =
1805 dyn_cast<const MachOObjectFile>(O)) {
1806 DataRefImpl DR = Section->getRawDataRefImpl();
1807 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1808 outs() << SegmentName << ",";
1810 StringRef SectionName =
1811 unwrapOrError(Section->getName(), O->getFileName());
1812 outs() << SectionName;
1815 if (Common || isa<ELFObjectFileBase>(O)) {
1816 uint64_t Val =
1817 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1818 outs() << format("\t%08" PRIx64, Val);
1821 if (isa<ELFObjectFileBase>(O)) {
1822 uint8_t Other = ELFSymbolRef(Symbol).getOther();
1823 switch (Other) {
1824 case ELF::STV_DEFAULT:
1825 break;
1826 case ELF::STV_INTERNAL:
1827 outs() << " .internal";
1828 break;
1829 case ELF::STV_HIDDEN:
1830 outs() << " .hidden";
1831 break;
1832 case ELF::STV_PROTECTED:
1833 outs() << " .protected";
1834 break;
1835 default:
1836 outs() << format(" 0x%02x", Other);
1837 break;
1839 } else if (Hidden) {
1840 outs() << " .hidden";
1843 if (Demangle)
1844 outs() << ' ' << demangle(Name) << '\n';
1845 else
1846 outs() << ' ' << Name << '\n';
1850 static void printUnwindInfo(const ObjectFile *O) {
1851 outs() << "Unwind info:\n\n";
1853 if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O))
1854 printCOFFUnwindInfo(Coff);
1855 else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O))
1856 printMachOUnwindInfo(MachO);
1857 else
1858 // TODO: Extract DWARF dump tool to objdump.
1859 WithColor::error(errs(), ToolName)
1860 << "This operation is only currently supported "
1861 "for COFF and MachO object files.\n";
1864 /// Dump the raw contents of the __clangast section so the output can be piped
1865 /// into llvm-bcanalyzer.
1866 void printRawClangAST(const ObjectFile *Obj) {
1867 if (outs().is_displayed()) {
1868 WithColor::error(errs(), ToolName)
1869 << "The -raw-clang-ast option will dump the raw binary contents of "
1870 "the clang ast section.\n"
1871 "Please redirect the output to a file or another program such as "
1872 "llvm-bcanalyzer.\n";
1873 return;
1876 StringRef ClangASTSectionName("__clangast");
1877 if (isa<COFFObjectFile>(Obj)) {
1878 ClangASTSectionName = "clangast";
1881 Optional<object::SectionRef> ClangASTSection;
1882 for (auto Sec : ToolSectionFilter(*Obj)) {
1883 StringRef Name;
1884 if (Expected<StringRef> NameOrErr = Sec.getName())
1885 Name = *NameOrErr;
1886 else
1887 consumeError(NameOrErr.takeError());
1889 if (Name == ClangASTSectionName) {
1890 ClangASTSection = Sec;
1891 break;
1894 if (!ClangASTSection)
1895 return;
1897 StringRef ClangASTContents = unwrapOrError(
1898 ClangASTSection.getValue().getContents(), Obj->getFileName());
1899 outs().write(ClangASTContents.data(), ClangASTContents.size());
1902 static void printFaultMaps(const ObjectFile *Obj) {
1903 StringRef FaultMapSectionName;
1905 if (isa<ELFObjectFileBase>(Obj)) {
1906 FaultMapSectionName = ".llvm_faultmaps";
1907 } else if (isa<MachOObjectFile>(Obj)) {
1908 FaultMapSectionName = "__llvm_faultmaps";
1909 } else {
1910 WithColor::error(errs(), ToolName)
1911 << "This operation is only currently supported "
1912 "for ELF and Mach-O executable files.\n";
1913 return;
1916 Optional<object::SectionRef> FaultMapSection;
1918 for (auto Sec : ToolSectionFilter(*Obj)) {
1919 StringRef Name;
1920 if (Expected<StringRef> NameOrErr = Sec.getName())
1921 Name = *NameOrErr;
1922 else
1923 consumeError(NameOrErr.takeError());
1925 if (Name == FaultMapSectionName) {
1926 FaultMapSection = Sec;
1927 break;
1931 outs() << "FaultMap table:\n";
1933 if (!FaultMapSection.hasValue()) {
1934 outs() << "<not found>\n";
1935 return;
1938 StringRef FaultMapContents =
1939 unwrapOrError(FaultMapSection.getValue().getContents(), Obj->getFileName());
1940 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1941 FaultMapContents.bytes_end());
1943 outs() << FMP;
1946 static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) {
1947 if (O->isELF()) {
1948 printELFFileHeader(O);
1949 printELFDynamicSection(O);
1950 printELFSymbolVersionInfo(O);
1951 return;
1953 if (O->isCOFF())
1954 return printCOFFFileHeader(O);
1955 if (O->isWasm())
1956 return printWasmFileHeader(O);
1957 if (O->isMachO()) {
1958 printMachOFileHeader(O);
1959 if (!OnlyFirst)
1960 printMachOLoadCommands(O);
1961 return;
1963 reportError(O->getFileName(), "Invalid/Unsupported object file format");
1966 static void printFileHeaders(const ObjectFile *O) {
1967 if (!O->isELF() && !O->isCOFF())
1968 reportError(O->getFileName(), "Invalid/Unsupported object file format");
1970 Triple::ArchType AT = O->getArch();
1971 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
1972 uint64_t Address = unwrapOrError(O->getStartAddress(), O->getFileName());
1974 StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1975 outs() << "start address: "
1976 << "0x" << format(Fmt.data(), Address) << "\n\n";
1979 static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
1980 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
1981 if (!ModeOrErr) {
1982 WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n";
1983 consumeError(ModeOrErr.takeError());
1984 return;
1986 sys::fs::perms Mode = ModeOrErr.get();
1987 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1988 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1989 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1990 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1991 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1992 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1993 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1994 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1995 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
1997 outs() << " ";
1999 outs() << format("%d/%d %6" PRId64 " ", unwrapOrError(C.getUID(), Filename),
2000 unwrapOrError(C.getGID(), Filename),
2001 unwrapOrError(C.getRawSize(), Filename));
2003 StringRef RawLastModified = C.getRawLastModified();
2004 unsigned Seconds;
2005 if (RawLastModified.getAsInteger(10, Seconds))
2006 outs() << "(date: \"" << RawLastModified
2007 << "\" contains non-decimal chars) ";
2008 else {
2009 // Since ctime(3) returns a 26 character string of the form:
2010 // "Sun Sep 16 01:03:52 1973\n\0"
2011 // just print 24 characters.
2012 time_t t = Seconds;
2013 outs() << format("%.24s ", ctime(&t));
2016 StringRef Name = "";
2017 Expected<StringRef> NameOrErr = C.getName();
2018 if (!NameOrErr) {
2019 consumeError(NameOrErr.takeError());
2020 Name = unwrapOrError(C.getRawName(), Filename);
2021 } else {
2022 Name = NameOrErr.get();
2024 outs() << Name << "\n";
2027 // For ELF only now.
2028 static bool shouldWarnForInvalidStartStopAddress(ObjectFile *Obj) {
2029 if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj)) {
2030 if (Elf->getEType() != ELF::ET_REL)
2031 return true;
2033 return false;
2036 static void checkForInvalidStartStopAddress(ObjectFile *Obj,
2037 uint64_t Start, uint64_t Stop) {
2038 if (!shouldWarnForInvalidStartStopAddress(Obj))
2039 return;
2041 for (const SectionRef &Section : Obj->sections())
2042 if (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC) {
2043 uint64_t BaseAddr = Section.getAddress();
2044 uint64_t Size = Section.getSize();
2045 if ((Start < BaseAddr + Size) && Stop > BaseAddr)
2046 return;
2049 if (StartAddress.getNumOccurrences() == 0)
2050 reportWarning("no section has address less than 0x" +
2051 Twine::utohexstr(Stop) + " specified by --stop-address",
2052 Obj->getFileName());
2053 else if (StopAddress.getNumOccurrences() == 0)
2054 reportWarning("no section has address greater than or equal to 0x" +
2055 Twine::utohexstr(Start) + " specified by --start-address",
2056 Obj->getFileName());
2057 else
2058 reportWarning("no section overlaps the range [0x" +
2059 Twine::utohexstr(Start) + ",0x" + Twine::utohexstr(Stop) +
2060 ") specified by --start-address/--stop-address",
2061 Obj->getFileName());
2064 static void dumpObject(ObjectFile *O, const Archive *A = nullptr,
2065 const Archive::Child *C = nullptr) {
2066 // Avoid other output when using a raw option.
2067 if (!RawClangAST) {
2068 outs() << '\n';
2069 if (A)
2070 outs() << A->getFileName() << "(" << O->getFileName() << ")";
2071 else
2072 outs() << O->getFileName();
2073 outs() << ":\tfile format " << O->getFileFormatName() << "\n\n";
2076 if (StartAddress.getNumOccurrences() || StopAddress.getNumOccurrences())
2077 checkForInvalidStartStopAddress(O, StartAddress, StopAddress);
2079 // Note: the order here matches GNU objdump for compatability.
2080 StringRef ArchiveName = A ? A->getFileName() : "";
2081 if (ArchiveHeaders && !MachOOpt && C)
2082 printArchiveChild(ArchiveName, *C);
2083 if (FileHeaders)
2084 printFileHeaders(O);
2085 if (PrivateHeaders || FirstPrivateHeader)
2086 printPrivateFileHeaders(O, FirstPrivateHeader);
2087 if (SectionHeaders)
2088 printSectionHeaders(O);
2089 if (SymbolTable)
2090 printSymbolTable(O, ArchiveName);
2091 if (DwarfDumpType != DIDT_Null) {
2092 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O);
2093 // Dump the complete DWARF structure.
2094 DIDumpOptions DumpOpts;
2095 DumpOpts.DumpType = DwarfDumpType;
2096 DICtx->dump(outs(), DumpOpts);
2098 if (Relocations && !Disassemble)
2099 printRelocations(O);
2100 if (DynamicRelocations)
2101 printDynamicRelocations(O);
2102 if (SectionContents)
2103 printSectionContents(O);
2104 if (Disassemble)
2105 disassembleObject(O, Relocations);
2106 if (UnwindInfo)
2107 printUnwindInfo(O);
2109 // Mach-O specific options:
2110 if (ExportsTrie)
2111 printExportsTrie(O);
2112 if (Rebase)
2113 printRebaseTable(O);
2114 if (Bind)
2115 printBindTable(O);
2116 if (LazyBind)
2117 printLazyBindTable(O);
2118 if (WeakBind)
2119 printWeakBindTable(O);
2121 // Other special sections:
2122 if (RawClangAST)
2123 printRawClangAST(O);
2124 if (FaultMapSection)
2125 printFaultMaps(O);
2128 static void dumpObject(const COFFImportFile *I, const Archive *A,
2129 const Archive::Child *C = nullptr) {
2130 StringRef ArchiveName = A ? A->getFileName() : "";
2132 // Avoid other output when using a raw option.
2133 if (!RawClangAST)
2134 outs() << '\n'
2135 << ArchiveName << "(" << I->getFileName() << ")"
2136 << ":\tfile format COFF-import-file"
2137 << "\n\n";
2139 if (ArchiveHeaders && !MachOOpt && C)
2140 printArchiveChild(ArchiveName, *C);
2141 if (SymbolTable)
2142 printCOFFSymbolTable(I);
2145 /// Dump each object file in \a a;
2146 static void dumpArchive(const Archive *A) {
2147 Error Err = Error::success();
2148 unsigned I = -1;
2149 for (auto &C : A->children(Err)) {
2150 ++I;
2151 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2152 if (!ChildOrErr) {
2153 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2154 reportError(std::move(E), getFileNameForError(C, I), A->getFileName());
2155 continue;
2157 if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2158 dumpObject(O, A, &C);
2159 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2160 dumpObject(I, A, &C);
2161 else
2162 reportError(errorCodeToError(object_error::invalid_file_type),
2163 A->getFileName());
2165 if (Err)
2166 reportError(std::move(Err), A->getFileName());
2169 /// Open file and figure out how to dump it.
2170 static void dumpInput(StringRef file) {
2171 // If we are using the Mach-O specific object file parser, then let it parse
2172 // the file and process the command line options. So the -arch flags can
2173 // be used to select specific slices, etc.
2174 if (MachOOpt) {
2175 parseInputMachO(file);
2176 return;
2179 // Attempt to open the binary.
2180 OwningBinary<Binary> OBinary = unwrapOrError(createBinary(file), file);
2181 Binary &Binary = *OBinary.getBinary();
2183 if (Archive *A = dyn_cast<Archive>(&Binary))
2184 dumpArchive(A);
2185 else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary))
2186 dumpObject(O);
2187 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
2188 parseInputMachO(UB);
2189 else
2190 reportError(errorCodeToError(object_error::invalid_file_type), file);
2192 } // namespace llvm
2194 int main(int argc, char **argv) {
2195 using namespace llvm;
2196 InitLLVM X(argc, argv);
2197 const cl::OptionCategory *OptionFilters[] = {&ObjdumpCat, &MachOCat};
2198 cl::HideUnrelatedOptions(OptionFilters);
2200 // Initialize targets and assembly printers/parsers.
2201 InitializeAllTargetInfos();
2202 InitializeAllTargetMCs();
2203 InitializeAllDisassemblers();
2205 // Register the target printer for --version.
2206 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2208 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2210 if (StartAddress >= StopAddress)
2211 reportCmdLineError("start address should be less than stop address");
2213 ToolName = argv[0];
2215 // Defaults to a.out if no filenames specified.
2216 if (InputFilenames.empty())
2217 InputFilenames.push_back("a.out");
2219 if (AllHeaders)
2220 ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations =
2221 SectionHeaders = SymbolTable = true;
2223 if (DisassembleAll || PrintSource || PrintLines ||
2224 (!DisassembleFunctions.empty()))
2225 Disassemble = true;
2227 if (!ArchiveHeaders && !Disassemble && DwarfDumpType == DIDT_Null &&
2228 !DynamicRelocations && !FileHeaders && !PrivateHeaders && !RawClangAST &&
2229 !Relocations && !SectionHeaders && !SectionContents && !SymbolTable &&
2230 !UnwindInfo && !FaultMapSection &&
2231 !(MachOOpt &&
2232 (Bind || DataInCode || DylibId || DylibsUsed || ExportsTrie ||
2233 FirstPrivateHeader || IndirectSymbols || InfoPlist || LazyBind ||
2234 LinkOptHints || ObjcMetaData || Rebase || UniversalHeaders ||
2235 WeakBind || !FilterSections.empty()))) {
2236 cl::PrintHelpMessage();
2237 return 2;
2240 DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2241 DisassembleFunctions.end());
2243 llvm::for_each(InputFilenames, dumpInput);
2245 warnOnNoMatchForSections();
2247 return EXIT_SUCCESS;