1 //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This program is a utility that works like binutils "objdump", that is, it
10 // dumps out a plethora of information about an object file depending on the
13 // The flags and output of this program should be near identical to those of
16 //===----------------------------------------------------------------------===//
18 #include "llvm-objdump.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SetOperations.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringSet.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/CodeGen/FaultMaps.h"
26 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
27 #include "llvm/DebugInfo/Symbolize/Symbolize.h"
28 #include "llvm/Demangle/Demangle.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/MC/MCContext.h"
31 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
32 #include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
33 #include "llvm/MC/MCInst.h"
34 #include "llvm/MC/MCInstPrinter.h"
35 #include "llvm/MC/MCInstrAnalysis.h"
36 #include "llvm/MC/MCInstrInfo.h"
37 #include "llvm/MC/MCObjectFileInfo.h"
38 #include "llvm/MC/MCRegisterInfo.h"
39 #include "llvm/MC/MCSubtargetInfo.h"
40 #include "llvm/Object/Archive.h"
41 #include "llvm/Object/COFF.h"
42 #include "llvm/Object/COFFImportFile.h"
43 #include "llvm/Object/ELFObjectFile.h"
44 #include "llvm/Object/MachO.h"
45 #include "llvm/Object/MachOUniversal.h"
46 #include "llvm/Object/ObjectFile.h"
47 #include "llvm/Object/Wasm.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/Errc.h"
52 #include "llvm/Support/FileSystem.h"
53 #include "llvm/Support/Format.h"
54 #include "llvm/Support/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"
68 #include <system_error>
69 #include <unordered_map>
72 using namespace llvm::object
;
76 cl::OptionCategory
ObjdumpCat("llvm-objdump Options");
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(
97 cl::desc("Increase the displayed address by the specified offset"),
98 cl::value_desc("offset"), cl::init(0), cl::cat(ObjdumpCat
));
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(
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(
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
));
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
));
167 DisassemblerOptionsShort("M", cl::desc("Alias for --disassembler-options"),
168 cl::NotHidden
, cl::Grouping
, cl::Prefix
,
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(
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
));
187 FaultMapSection("fault-map-section",
188 cl::desc("Display contents of faultmap section"),
189 cl::cat(ObjdumpCat
));
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>"),
210 cl::cat(ObjdumpCat
));
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
));
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(
248 cl::desc("Dump the raw binary contents of the clang AST section"),
249 cl::cat(ObjdumpCat
));
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"),
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
));
294 cl::desc("Display LMA column when dumping ELF section headers"),
295 cl::cat(ObjdumpCat
));
297 static cl::opt
<bool> PrintSource(
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
));
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
));
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
;
346 struct FilterResult
{
347 // True if the section should not be skipped.
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
358 static FilterResult
checkSectionFilter(object::SectionRef S
) {
359 if (FilterSections
.empty())
360 return {/*Keep=*/true, /*IncrementIndex=*/true};
362 Expected
<StringRef
> SecNameOrErr
= S
.getName();
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).
385 return SectionFilter(
386 [Idx
](object::SectionRef S
) {
387 FilterResult Result
= checkSectionFilter(S
);
388 if (Idx
!= nullptr && Result
.IncrementIndex
)
395 std::string
getFileNameForError(const object::Archive::Child
&C
,
397 Expected
<StringRef
> NameOrErr
= C
.getName();
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.
410 WithColor::warning(errs(), ToolName
)
411 << "'" << File
<< "': " << Message
<< "\n";
415 LLVM_ATTRIBUTE_NORETURN
void reportError(StringRef File
, Twine Message
) {
416 WithColor::error(errs(), ToolName
) << "'" << File
<< "': " << Message
<< "\n";
420 LLVM_ATTRIBUTE_NORETURN
void reportError(Error E
, StringRef FileName
,
421 StringRef ArchiveName
,
422 StringRef ArchitectureName
) {
424 WithColor::error(errs(), ToolName
);
425 if (ArchiveName
!= "")
426 errs() << ArchiveName
<< "(" << FileName
<< ")";
428 errs() << "'" << FileName
<< "'";
429 if (!ArchitectureName
.empty())
430 errs() << " (for architecture " << ArchitectureName
<< ")";
432 raw_string_ostream
OS(Buf
);
433 logAllUnhandledErrors(std::move(E
), OS
);
435 errs() << ": " << Buf
;
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";
448 static void warnOnNoMatchForSections() {
449 SetVector
<StringRef
> MissingSections
;
450 for (StringRef S
: FilterSections
) {
451 if (FoundSectionSet
.count(S
))
453 // User may specify a unnamed section. Don't warn for it.
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();
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.
479 const Target
*TheTarget
= TargetRegistry::lookupTarget(ArchName
, TheTriple
,
482 reportError(Obj
->getFileName(), "can't find target: " + Error
);
484 // Update the triple name and return the found target.
485 TripleName
= TheTriple
.getTriple();
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());
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
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
;
530 uint64_t PrevType
= MachO
->getRelocationType(RelPrev
);
531 if (PrevType
== MachO::X86_64_RELOC_SUBTRACTOR
)
540 class SourcePrinter
{
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
;
555 bool cacheSource(const DILineInfo
& LineInfoFile
);
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
);
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
,
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
)
595 Lines
.emplace_back(Start
, I
- Start
- (BufferStart
< I
&& I
[-1] == '\r'));
598 if (Start
< BufferEnd
)
599 Lines
.emplace_back(Start
, BufferEnd
- Start
);
600 SourceCache
[LineInfo
.FileName
] = std::move(Buffer
);
604 void SourcePrinter::printSourceLine(raw_ostream
&OS
,
605 object::SectionedAddress Address
,
606 StringRef ObjectFilename
,
607 StringRef Delimiter
) {
611 DILineInfo LineInfo
= DILineInfo();
612 auto ExpectedLineInfo
= Symbolizer
->symbolizeCode(*Obj
, Address
);
613 std::string ErrorMessage
;
614 if (!ExpectedLineInfo
)
615 ErrorMessage
= toString(ExpectedLineInfo
.takeError());
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;
631 if (LineInfo
.Line
== 0 || ((OldLineInfo
.Line
== LineInfo
.Line
) &&
632 (OldLineInfo
.FileName
== LineInfo
.FileName
)))
636 OS
<< Delimiter
<< LineInfo
.FileName
<< ":" << LineInfo
.Line
<< "\n";
638 if (SourceCache
.find(LineInfo
.FileName
) == SourceCache
.end())
639 if (!cacheSource(LineInfo
))
641 auto LineBuffer
= LineCache
.find(LineInfo
.FileName
);
642 if (LineBuffer
!= LineCache
.end()) {
643 if (LineInfo
.Line
> LineBuffer
->second
.size()) {
646 "debug info line number {0} exceeds the number of lines in {1}",
647 LineInfo
.Line
, LineInfo
.FileName
),
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
;
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
{
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();
697 OS
<< format("%8" PRIx64
":", Address
.Address
);
698 if (!NoShowRawInsn
) {
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);
710 IP
.printInst(MI
, OS
, "", STI
);
715 PrettyPrinter PrettyPrinterInst
;
717 class HexagonPrettyPrinter
: public PrettyPrinter
{
719 void printLead(ArrayRef
<uint8_t> Bytes
, uint64_t Address
,
722 (Bytes
[3] << 24) | (Bytes
[2] << 16) | (Bytes
[1] << 8) | Bytes
[0];
724 OS
<< format("%8" PRIx64
":", Address
);
725 if (!NoShowRawInsn
) {
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
, "");
739 printLead(Bytes
, Address
.Address
, OS
);
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
= " { ";
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);
770 while (!HeadTail
.first
.empty()) {
773 if (SP
&& (PrintSource
|| PrintLines
))
774 SP
->printSourceLine(OS
, Address
, ObjectFilename
, "");
775 printLead(Bytes
, Address
.Address
, OS
);
779 auto Duplex
= HeadTail
.first
.split('\v');
780 if (!Duplex
.second
.empty()) {
783 Inst
= Duplex
.second
;
786 Inst
= HeadTail
.first
;
788 HeadTail
= HeadTail
.second
.split('\n');
789 if (HeadTail
.first
.empty())
790 OS
<< " } " << PacketBundle
.second
;
792 Bytes
= Bytes
.slice(4);
793 Address
.Address
+= 4;
797 HexagonPrettyPrinter HexagonPrettyPrinterInst
;
799 class AMDGCNPrettyPrinter
: public PrettyPrinter
{
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
);
810 SmallString
<40> InstStr
;
811 raw_svector_ostream
IS(InstStr
);
813 IP
.printInst(MI
, IS
, "", STI
);
815 OS
<< left_justify(IS
.str(), 60);
817 // an unrecognized encoding - this is probably data so represent it
818 // using the .long directive, or .byte directive if fewer than 4 bytes
820 if (Bytes
.size() >= 4) {
821 OS
<< format("\t.long 0x%08" PRIx32
" ",
822 support::endian::read32
<support::little
>(Bytes
.data()));
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()),
839 OS
<< format(" %08" PRIX32
, D
);
841 for (unsigned char B
: Bytes
)
842 OS
<< format(" %02" PRIX8
, B
);
846 OS
<< " // " << Annot
;
849 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst
;
851 class BPFPrettyPrinter
: public PrettyPrinter
{
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
);
861 OS
<< format("%8" PRId64
":", Address
.Address
/ 8);
862 if (!NoShowRawInsn
) {
864 dumpBytes(Bytes
, OS
);
867 IP
.printInst(MI
, OS
, "", STI
);
872 BPFPrettyPrinter BPFPrettyPrinterInst
;
874 PrettyPrinter
&selectPrettyPrinter(Triple
const &Triple
) {
875 switch(Triple
.getArch()) {
877 return PrettyPrinterInst
;
878 case Triple::hexagon
:
879 return HexagonPrettyPrinterInst
;
881 return AMDGCNPrettyPrinterInst
;
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
)
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());
920 section_iterator SecI
=
921 unwrapOrError(Symbol
.getSection(), Obj
->getFileName());
922 if (SecI
== Obj
->section_end())
925 AllSymbols
[*SecI
].emplace_back(Address
, Name
, SymbolType
);
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
);
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();
952 consumeError(SecNameOrErr
.takeError());
955 if (*SecNameOrErr
== ".plt")
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());
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.
979 while (N
< Buf
.size() && !Buf
[N
])
982 // We may want to skip blocks of zero bytes, but unless we see
983 // at least 8 of them in a row.
987 // We skip zeroes in multiples of 4 because do not want to truncate an
988 // instruction if it starts with a zero byte.
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()) {
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
)
1009 std::vector
<RelocationRef
> &V
= Ret
[*Relocated
];
1010 for (const RelocationRef
&R
: Sec
.relocations())
1012 // Sort relocations by address.
1013 llvm::stable_sort(V
, isRelocAddressLess
);
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
;
1031 typedef std::pair
<uint64_t, char> MappingSymbolPair
;
1032 static char getMappingSymbolKind(ArrayRef
<MappingSymbolPair
> MappingSymbols
,
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())
1042 return (It
- 1)->second
;
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
);
1054 if (Index
+ 4 <= End
) {
1055 dumpBytes(Bytes
.slice(Index
, 4), outs());
1056 outs() << "\t.word\t"
1058 support::endian::read32(Bytes
.data() + Index
, Endian
), 10);
1060 } else if (Index
+ 2 <= End
) {
1061 dumpBytes(Bytes
.slice(Index
, 2), outs());
1062 outs() << "\t\t.short\t"
1064 support::endian::read16(Bytes
.data() + Index
, Endian
), 6);
1067 dumpBytes(Bytes
.slice(Index
, 1), outs());
1068 outs() << "\t\t.byte\t" << format_hex(Bytes
[0], 4);
1072 if (getMappingSymbolKind(MappingSymbols
, Index
) != 'd')
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'};
1085 for (; Index
< End
; ++Index
) {
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;
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';
1102 if (NumBytes
== 8) {
1103 AsciiData
[8] = '\0';
1104 outs() << std::string(IndentOffset
, ' ') << " ";
1105 outs() << reinterpret_cast<char *>(AsciiData
);
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
,
1119 SourcePrinter
&SP
, bool InlineRelocs
) {
1120 const MCSubtargetInfo
*STI
= PrimarySTI
;
1121 MCDisassembler
*DisAsm
= PrimaryDisAsm
;
1122 bool PrimaryIsThumb
= false;
1124 PrimaryIsThumb
= STI
->checkFeatures("+thumb-mode");
1126 std::map
<SectionRef
, std::vector
<RelocationRef
>> RelocMap
;
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
);
1143 uint8_t SymbolType
= ELF::STT_NOTYPE
;
1145 SymbolType
= getElfSymbolType(Obj
, Symbol
);
1146 if (SymbolType
== ELF::STT_SECTION
)
1150 section_iterator SecI
= unwrapOrError(Symbol
.getSection(), FileName
);
1151 if (SecI
!= Obj
->section_end())
1152 AllSymbols
[*SecI
].emplace_back(Address
, Name
, SymbolType
);
1154 AbsoluteSymbols
.emplace_back(Address
, Name
, SymbolType
);
1156 if (AllSymbols
.empty() && Obj
->isELF())
1157 addDynamicElfSymbols(Obj
, AllSymbols
);
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()) {
1174 if (std::error_code EC
= ExportEntry
.getSymbolName(Name
))
1175 reportError(errorCodeToError(EC
), Obj
->getFileName());
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()) {
1190 AllSymbols
[Sec
->second
].emplace_back(VA
, Name
, ELF::STT_NOTYPE
);
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()))
1208 uint64_t SectionAddr
= Section
.getAddress();
1209 uint64_t SectSize
= Section
.getSize();
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
));
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) {
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
;
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();
1280 SymbolName
= demangle(SymbolName
);
1282 // Skip if --disassemble-functions is not empty and the symbol is not in
1284 if (!DisasmFuncsSet
.empty() && !DisasmFuncsSet
.count(SymbolName
))
1287 uint64_t Start
= std::get
<0>(Symbols
[SI
]);
1288 if (Start
< SectionAddr
|| StopAddress
<= Start
)
1291 FoundDisasmFuncsSet
.insert(SymbolName
);
1293 // The end is the section end, the beginning of the next symbol, or
1295 uint64_t End
= std::min
<uint64_t>(SectionAddr
+ SectSize
, StopAddress
);
1297 End
= std::min(End
, std::get
<0>(Symbols
[SI
+ 1]));
1298 if (Start
>= End
|| End
<= StartAddress
)
1300 Start
-= 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)
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)
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()) {
1343 raw_ostream
&DebugOut
= DebugFlag
? dbgs() : nulls();
1345 raw_ostream
&DebugOut
= nulls();
1348 // Some targets (like WebAssembly) have a special prelude at the start
1350 DisAsm
->onSymbolStart(SymbolName
, Size
, Bytes
.slice(Start
, End
- Start
),
1351 SectionAddr
+ Start
, DebugOut
, CommentStream
);
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
);
1369 bool CheckARMELFData
= hasMappingSymbols(Obj
) &&
1370 std::get
<2>(Symbols
[SI
]) != ELF::STT_OBJECT
&&
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
,
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
;
1394 countSkippableZeroBytes(Bytes
.slice(Index
, MaxOffset
))) {
1395 outs() << "\t\t..." << '\n';
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
1414 bool Disassembled
= DisAsm
->getInstruction(
1415 Inst
, Size
, Bytes
.slice(Index
), SectionAddr
+ Index
, DebugOut
,
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();
1427 // Try to resolve the target of a call, tail call, etc. to a specific
1429 if (MIA
&& (MIA
->isCall(Inst
) || MIA
->isUnconditionalBranch(Inst
) ||
1430 MIA
->isConditionalBranch(Inst
))) {
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(
1444 [=](const std::pair
<uint64_t, SectionRef
> &O
) {
1445 return O
.first
<= Target
;
1447 if (It
!= SectionAddresses
.begin()) {
1449 TargetSectionSymbols
= &AllSymbols
[It
->second
];
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(
1467 [=](const std::tuple
<uint64_t, StringRef
, uint8_t> &O
) {
1468 return std::get
<0>(O
) <= Target
;
1471 if (TargetSym
!= TargetSectionSymbols
->begin()) {
1473 uint64_t TargetAddress
= std::get
<0>(*TargetSym
);
1474 StringRef TargetName
= std::get
<1>(*TargetSym
);
1475 outs() << " <" << TargetName
;
1476 uint64_t Disp
= Target
- TargetAddress
;
1478 outs() << "+0x" << Twine::utohexstr(Disp
);
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
) {
1496 // Stop when RelCur's offset is past the current instruction.
1497 if (Offset
>= Index
+ Size
)
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
,
1519 StringSet
<> MissingDisasmFuncsSet
=
1520 set_difference(DisasmFuncsSet
, FoundDisasmFuncsSet
);
1521 for (StringRef MissingDisasmFunc
: MissingDisasmFuncsSet
.keys())
1522 reportWarning("failed to disassemble missing function " + MissingDisasmFunc
,
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
));
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
));
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()));
1550 reportError(Obj
->getFileName(),
1551 "no subtarget info for target " + TripleName
);
1552 std::unique_ptr
<const MCInstrInfo
> MII(TheTarget
->createMCInstrInfo());
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
));
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
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");
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
));
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
,
1606 void printRelocations(const ObjectFile
*Obj
) {
1607 StringRef Fmt
= Obj
->getBytesInAddress() > 4 ? "%016" PRIx64
:
1609 // Regular objdump doesn't print relocations in non-relocatable object
1611 if (!Obj
->isRelocatableObject())
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
;
1619 for (const SectionRef
&Section
: ToolSectionFilter(*Obj
, &Ndx
)) {
1620 if (Section
.relocation_begin() == Section
.relocation_end())
1622 Expected
<section_iterator
> SecOrErr
= Section
.getRelocatedSection();
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
))
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";
1654 void printDynamicRelocations(const ObjectFile
*Obj
) {
1655 // For the moment, this option is for ELF only
1659 const auto *Elf
= dyn_cast
<ELFObjectFileBase
>(Obj
);
1660 if (!Elf
|| Elf
->getEType() != ELF::ET_DYN
) {
1661 reportError(Obj
->getFileName(), "not a dynamic object");
1665 std::vector
<SectionRef
> DynRelSec
= Obj
->dynamic_relocation_sections();
1666 if (DynRelSec
.empty())
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
) {
1690 for (const SectionRef
&S
: ToolSectionFilter(*Obj
))
1691 if (S
.getAddress() != getELFSectionLMA(S
))
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());
1706 void printSectionHeaders(const ObjectFile
*Obj
) {
1707 size_t NameWidth
= getMaxSectionNameWidth(Obj
);
1708 size_t AddressWidth
= 2 * Obj
->getBytesInAddress();
1709 bool HasLMAColumn
= shouldDisplayLMA(Obj
);
1711 outs() << "Sections:\n"
1713 << left_justify("Name", NameWidth
) << " Size "
1714 << left_justify("VMA", AddressWidth
) << " "
1715 << left_justify("LMA", AddressWidth
) << " Type\n";
1717 outs() << "Sections:\n"
1719 << left_justify("Name", NameWidth
) << " Size "
1720 << left_justify("VMA", AddressWidth
) << " Type\n";
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
))
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";
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";
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";
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();
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
);
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)
1777 outs() << hexdigit((Contents
[Addr
+ I
] >> 4) & 0xF, true)
1778 << hexdigit(Contents
[Addr
+ I
] & 0xF, true);
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
];
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
);
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
,
1809 if ((Address
< StartAddress
) || (Address
> StopAddress
))
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
);
1817 if (Type
== SymbolRef::ST_Debug
&& Section
!= O
->section_end()) {
1818 if (Expected
<StringRef
> NameOrErr
= Section
->getName())
1821 consumeError(NameOrErr
.takeError());
1824 Name
= unwrapOrError(Symbol
.getName(), FileName
, ArchiveName
,
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
;
1835 if (Type
!= SymbolRef::ST_Unknown
)
1836 GlobLoc
= Global
? 'g' : 'l';
1837 char Debug
= (Type
== SymbolRef::ST_Debug
|| Type
== SymbolRef::ST_File
)
1839 char FileFunc
= ' ';
1840 if (Type
== SymbolRef::ST_File
)
1842 else if (Type
== SymbolRef::ST_Function
)
1844 else if (Type
== SymbolRef::ST_Data
)
1847 const char *Fmt
= O
->getBytesInAddress() > 4 ? "%016" 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).
1861 } else if (Common
) {
1863 } else if (Section
== O
->section_end()) {
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
)) {
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();
1886 case ELF::STV_DEFAULT
:
1888 case ELF::STV_INTERNAL
:
1889 outs() << " .internal";
1891 case ELF::STV_HIDDEN
:
1892 outs() << " .hidden";
1894 case ELF::STV_PROTECTED
:
1895 outs() << " .protected";
1898 outs() << format(" 0x%02x", Other
);
1901 } else if (Hidden
) {
1902 outs() << " .hidden";
1906 outs() << ' ' << demangle(Name
) << '\n';
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
);
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";
1938 StringRef
ClangASTSectionName("__clangast");
1939 if (isa
<COFFObjectFile
>(Obj
)) {
1940 ClangASTSectionName
= "clangast";
1943 Optional
<object::SectionRef
> ClangASTSection
;
1944 for (auto Sec
: ToolSectionFilter(*Obj
)) {
1946 if (Expected
<StringRef
> NameOrErr
= Sec
.getName())
1949 consumeError(NameOrErr
.takeError());
1951 if (Name
== ClangASTSectionName
) {
1952 ClangASTSection
= Sec
;
1956 if (!ClangASTSection
)
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";
1972 WithColor::error(errs(), ToolName
)
1973 << "This operation is only currently supported "
1974 "for ELF and Mach-O executable files.\n";
1978 Optional
<object::SectionRef
> FaultMapSection
;
1980 for (auto Sec
: ToolSectionFilter(*Obj
)) {
1982 if (Expected
<StringRef
> NameOrErr
= Sec
.getName())
1985 consumeError(NameOrErr
.takeError());
1987 if (Name
== FaultMapSectionName
) {
1988 FaultMapSection
= Sec
;
1993 outs() << "FaultMap table:\n";
1995 if (!FaultMapSection
.hasValue()) {
1996 outs() << "<not found>\n";
2000 StringRef FaultMapContents
=
2001 unwrapOrError(FaultMapSection
.getValue().getContents(), Obj
->getFileName());
2002 FaultMapParser
FMP(FaultMapContents
.bytes_begin(),
2003 FaultMapContents
.bytes_end());
2008 static void printPrivateFileHeaders(const ObjectFile
*O
, bool OnlyFirst
) {
2010 printELFFileHeader(O
);
2011 printELFDynamicSection(O
);
2012 printELFSymbolVersionInfo(O
);
2016 return printCOFFFileHeader(O
);
2018 return printWasmFileHeader(O
);
2020 printMachOFileHeader(O
);
2022 printMachOLoadCommands(O
);
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();
2044 WithColor::error(errs(), ToolName
) << "ill-formed archive entry.\n";
2045 consumeError(ModeOrErr
.takeError());
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" : "-");
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();
2067 if (RawLastModified
.getAsInteger(10, Seconds
))
2068 outs() << "(date: \"" << RawLastModified
2069 << "\" contains non-decimal chars) ";
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.
2075 outs() << format("%.24s ", ctime(&t
));
2078 StringRef Name
= "";
2079 Expected
<StringRef
> NameOrErr
= C
.getName();
2081 consumeError(NameOrErr
.takeError());
2082 Name
= unwrapOrError(C
.getRawName(), Filename
);
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
)
2098 static void checkForInvalidStartStopAddress(ObjectFile
*Obj
,
2099 uint64_t Start
, uint64_t Stop
) {
2100 if (!shouldWarnForInvalidStartStopAddress(Obj
))
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
)
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());
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.
2132 outs() << A
->getFileName() << "(" << O
->getFileName() << ")";
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
);
2146 printFileHeaders(O
);
2147 if (PrivateHeaders
|| FirstPrivateHeader
)
2148 printPrivateFileHeaders(O
, FirstPrivateHeader
);
2150 printSectionHeaders(O
);
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
);
2167 disassembleObject(O
, Relocations
);
2171 // Mach-O specific options:
2173 printExportsTrie(O
);
2175 printRebaseTable(O
);
2179 printLazyBindTable(O
);
2181 printWeakBindTable(O
);
2183 // Other special sections:
2185 printRawClangAST(O
);
2186 if (FaultMapSection
)
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.
2197 << ArchiveName
<< "(" << I
->getFileName() << ")"
2198 << ":\tfile format COFF-import-file"
2201 if (ArchiveHeaders
&& !MachOOpt
&& C
)
2202 printArchiveChild(ArchiveName
, *C
);
2204 printCOFFSymbolTable(I
);
2207 /// Dump each object file in \a a;
2208 static void dumpArchive(const Archive
*A
) {
2209 Error Err
= Error::success();
2211 for (auto &C
: A
->children(Err
)) {
2213 Expected
<std::unique_ptr
<Binary
>> ChildOrErr
= C
.getAsBinary();
2215 if (auto E
= isNotObjectErrorInvalidFileType(ChildOrErr
.takeError()))
2216 reportError(std::move(E
), getFileNameForError(C
, I
), A
->getFileName());
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
);
2224 reportError(errorCodeToError(object_error::invalid_file_type
),
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.
2237 parseInputMachO(file
);
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
))
2247 else if (ObjectFile
*O
= dyn_cast
<ObjectFile
>(&Binary
))
2249 else if (MachOUniversalBinary
*UB
= dyn_cast
<MachOUniversalBinary
>(&Binary
))
2250 parseInputMachO(UB
);
2252 reportError(errorCodeToError(object_error::invalid_file_type
), file
);
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");
2277 // Defaults to a.out if no filenames specified.
2278 if (InputFilenames
.empty())
2279 InputFilenames
.push_back("a.out");
2282 ArchiveHeaders
= FileHeaders
= PrivateHeaders
= Relocations
=
2283 SectionHeaders
= SymbolTable
= true;
2285 if (DisassembleAll
|| PrintSource
|| PrintLines
||
2286 (!DisassembleFunctions
.empty()))
2289 if (!ArchiveHeaders
&& !Disassemble
&& DwarfDumpType
== DIDT_Null
&&
2290 !DynamicRelocations
&& !FileHeaders
&& !PrivateHeaders
&& !RawClangAST
&&
2291 !Relocations
&& !SectionHeaders
&& !SectionContents
&& !SymbolTable
&&
2292 !UnwindInfo
&& !FaultMapSection
&&
2294 (Bind
|| DataInCode
|| DylibId
|| DylibsUsed
|| ExportsTrie
||
2295 FirstPrivateHeader
|| IndirectSymbols
|| InfoPlist
|| LazyBind
||
2296 LinkOptHints
|| ObjcMetaData
|| Rebase
|| UniversalHeaders
||
2297 WeakBind
|| !FilterSections
.empty()))) {
2298 cl::PrintHelpMessage();
2302 DisasmFuncsSet
.insert(DisassembleFunctions
.begin(),
2303 DisassembleFunctions
.end());
2305 llvm::for_each(InputFilenames
, dumpInput
);
2307 warnOnNoMatchForSections();
2309 return EXIT_SUCCESS
;