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
;
345 static bool shouldKeep(object::SectionRef S
) {
346 if (FilterSections
.empty())
349 Expected
<StringRef
> SecNameOrErr
= S
.getName();
351 consumeError(SecNameOrErr
.takeError());
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
,
369 Expected
<StringRef
> NameOrErr
= C
.getName();
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.
382 WithColor::warning(errs(), ToolName
)
383 << "'" << File
<< "': " << Message
<< "\n";
387 LLVM_ATTRIBUTE_NORETURN
void reportError(StringRef File
, Twine Message
) {
388 WithColor::error(errs(), ToolName
) << "'" << File
<< "': " << Message
<< "\n";
392 LLVM_ATTRIBUTE_NORETURN
void reportError(Error E
, StringRef FileName
,
393 StringRef ArchiveName
,
394 StringRef ArchitectureName
) {
396 WithColor::error(errs(), ToolName
);
397 if (ArchiveName
!= "")
398 errs() << ArchiveName
<< "(" << FileName
<< ")";
400 errs() << "'" << FileName
<< "'";
401 if (!ArchitectureName
.empty())
402 errs() << " (for architecture " << ArchitectureName
<< ")";
404 raw_string_ostream
OS(Buf
);
405 logAllUnhandledErrors(std::move(E
), OS
);
407 errs() << ": " << Buf
;
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";
420 static void warnOnNoMatchForSections() {
421 SetVector
<StringRef
> MissingSections
;
422 for (StringRef S
: FilterSections
) {
423 if (FoundSectionSet
.count(S
))
425 // User may specify a unnamed section. Don't warn for it.
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();
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.
451 const Target
*TheTarget
= TargetRegistry::lookupTarget(ArchName
, TheTriple
,
454 reportError(Obj
->getFileName(), "can't find target: " + Error
);
456 // Update the triple name and return the found target.
457 TripleName
= TheTriple
.getTriple();
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());
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
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
;
502 uint64_t PrevType
= MachO
->getRelocationType(RelPrev
);
503 if (PrevType
== MachO::X86_64_RELOC_SUBTRACTOR
)
512 class SourcePrinter
{
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
;
527 bool cacheSource(const DILineInfo
& LineInfoFile
);
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
);
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
,
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
)
567 Lines
.emplace_back(Start
, I
- Start
- (BufferStart
< I
&& I
[-1] == '\r'));
570 if (Start
< BufferEnd
)
571 Lines
.emplace_back(Start
, BufferEnd
- Start
);
572 SourceCache
[LineInfo
.FileName
] = std::move(Buffer
);
576 void SourcePrinter::printSourceLine(raw_ostream
&OS
,
577 object::SectionedAddress Address
,
578 StringRef ObjectFilename
,
579 StringRef Delimiter
) {
583 DILineInfo LineInfo
= DILineInfo();
584 auto ExpectedLineInfo
= Symbolizer
->symbolizeCode(*Obj
, Address
);
585 std::string ErrorMessage
;
586 if (!ExpectedLineInfo
)
587 ErrorMessage
= toString(ExpectedLineInfo
.takeError());
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;
603 if (LineInfo
.Line
== 0 || ((OldLineInfo
.Line
== LineInfo
.Line
) &&
604 (OldLineInfo
.FileName
== LineInfo
.FileName
)))
608 OS
<< Delimiter
<< LineInfo
.FileName
<< ":" << LineInfo
.Line
<< "\n";
610 if (SourceCache
.find(LineInfo
.FileName
) == SourceCache
.end())
611 if (!cacheSource(LineInfo
))
613 auto LineBuffer
= LineCache
.find(LineInfo
.FileName
);
614 if (LineBuffer
!= LineCache
.end()) {
615 if (LineInfo
.Line
> LineBuffer
->second
.size()) {
618 "debug info line number {0} exceeds the number of lines in {1}",
619 LineInfo
.Line
, LineInfo
.FileName
),
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
;
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
{
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();
669 OS
<< format("%8" PRIx64
":", Address
.Address
);
670 if (!NoShowRawInsn
) {
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);
682 IP
.printInst(MI
, OS
, "", STI
);
687 PrettyPrinter PrettyPrinterInst
;
689 class HexagonPrettyPrinter
: public PrettyPrinter
{
691 void printLead(ArrayRef
<uint8_t> Bytes
, uint64_t Address
,
694 (Bytes
[3] << 24) | (Bytes
[2] << 16) | (Bytes
[1] << 8) | Bytes
[0];
696 OS
<< format("%8" PRIx64
":", Address
);
697 if (!NoShowRawInsn
) {
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
, "");
711 printLead(Bytes
, Address
.Address
, OS
);
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
= " { ";
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);
742 while (!HeadTail
.first
.empty()) {
745 if (SP
&& (PrintSource
|| PrintLines
))
746 SP
->printSourceLine(OS
, Address
, ObjectFilename
, "");
747 printLead(Bytes
, Address
.Address
, OS
);
751 auto Duplex
= HeadTail
.first
.split('\v');
752 if (!Duplex
.second
.empty()) {
755 Inst
= Duplex
.second
;
758 Inst
= HeadTail
.first
;
760 HeadTail
= HeadTail
.second
.split('\n');
761 if (HeadTail
.first
.empty())
762 OS
<< " } " << PacketBundle
.second
;
764 Bytes
= Bytes
.slice(4);
765 Address
.Address
+= 4;
769 HexagonPrettyPrinter HexagonPrettyPrinterInst
;
771 class AMDGCNPrettyPrinter
: public PrettyPrinter
{
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
);
782 SmallString
<40> InstStr
;
783 raw_svector_ostream
IS(InstStr
);
785 IP
.printInst(MI
, IS
, "", STI
);
787 OS
<< left_justify(IS
.str(), 60);
789 // an unrecognized encoding - this is probably data so represent it
790 // using the .long directive, or .byte directive if fewer than 4 bytes
792 if (Bytes
.size() >= 4) {
793 OS
<< format("\t.long 0x%08" PRIx32
" ",
794 support::endian::read32
<support::little
>(Bytes
.data()));
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()),
811 OS
<< format(" %08" PRIX32
, D
);
813 for (unsigned char B
: Bytes
)
814 OS
<< format(" %02" PRIX8
, B
);
818 OS
<< " // " << Annot
;
821 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst
;
823 class BPFPrettyPrinter
: public PrettyPrinter
{
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
);
833 OS
<< format("%8" PRId64
":", Address
.Address
/ 8);
834 if (!NoShowRawInsn
) {
836 dumpBytes(Bytes
, OS
);
839 IP
.printInst(MI
, OS
, "", STI
);
844 BPFPrettyPrinter BPFPrettyPrinterInst
;
846 PrettyPrinter
&selectPrettyPrinter(Triple
const &Triple
) {
847 switch(Triple
.getArch()) {
849 return PrettyPrinterInst
;
850 case Triple::hexagon
:
851 return HexagonPrettyPrinterInst
;
853 return AMDGCNPrettyPrinterInst
;
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
)
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());
892 section_iterator SecI
=
893 unwrapOrError(Symbol
.getSection(), Obj
->getFileName());
894 if (SecI
== Obj
->section_end())
897 AllSymbols
[*SecI
].emplace_back(Address
, Name
, SymbolType
);
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
);
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();
924 consumeError(SecNameOrErr
.takeError());
927 if (*SecNameOrErr
== ".plt")
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());
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.
951 while (N
< Buf
.size() && !Buf
[N
])
954 // We may want to skip blocks of zero bytes, but unless we see
955 // at least 8 of them in a row.
959 // We skip zeroes in multiples of 4 because do not want to truncate an
960 // instruction if it starts with a zero byte.
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
))
972 std::vector
<RelocationRef
> &V
= Ret
[*Relocated
];
973 for (const RelocationRef
&R
: Sec
.relocations())
975 // Sort relocations by address.
976 llvm::stable_sort(V
, isRelocAddressLess
);
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
;
994 typedef std::pair
<uint64_t, char> MappingSymbolPair
;
995 static char getMappingSymbolKind(ArrayRef
<MappingSymbolPair
> MappingSymbols
,
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())
1005 return (It
- 1)->second
;
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
);
1017 if (Index
+ 4 <= End
) {
1018 dumpBytes(Bytes
.slice(Index
, 4), outs());
1019 outs() << "\t.word\t"
1021 support::endian::read32(Bytes
.data() + Index
, Endian
), 10);
1023 } else if (Index
+ 2 <= End
) {
1024 dumpBytes(Bytes
.slice(Index
, 2), outs());
1025 outs() << "\t\t.short\t"
1027 support::endian::read16(Bytes
.data() + Index
, Endian
), 6);
1030 dumpBytes(Bytes
.slice(Index
, 1), outs());
1031 outs() << "\t\t.byte\t" << format_hex(Bytes
[0], 4);
1035 if (getMappingSymbolKind(MappingSymbols
, Index
) != 'd')
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'};
1048 for (; Index
< End
; ++Index
) {
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;
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';
1065 if (NumBytes
== 8) {
1066 AsciiData
[8] = '\0';
1067 outs() << std::string(IndentOffset
, ' ') << " ";
1068 outs() << reinterpret_cast<char *>(AsciiData
);
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
,
1082 SourcePrinter
&SP
, bool InlineRelocs
) {
1083 const MCSubtargetInfo
*STI
= PrimarySTI
;
1084 MCDisassembler
*DisAsm
= PrimaryDisAsm
;
1085 bool PrimaryIsThumb
= false;
1087 PrimaryIsThumb
= STI
->checkFeatures("+thumb-mode");
1089 std::map
<SectionRef
, std::vector
<RelocationRef
>> RelocMap
;
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
);
1106 uint8_t SymbolType
= ELF::STT_NOTYPE
;
1108 SymbolType
= getElfSymbolType(Obj
, Symbol
);
1109 if (SymbolType
== ELF::STT_SECTION
)
1113 section_iterator SecI
= unwrapOrError(Symbol
.getSection(), FileName
);
1114 if (SecI
!= Obj
->section_end())
1115 AllSymbols
[*SecI
].emplace_back(Address
, Name
, SymbolType
);
1117 AbsoluteSymbols
.emplace_back(Address
, Name
, SymbolType
);
1119 if (AllSymbols
.empty() && Obj
->isELF())
1120 addDynamicElfSymbols(Obj
, AllSymbols
);
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()) {
1137 if (std::error_code EC
= ExportEntry
.getSymbolName(Name
))
1138 reportError(errorCodeToError(EC
), Obj
->getFileName());
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()) {
1153 AllSymbols
[Sec
->second
].emplace_back(VA
, Name
, ELF::STT_NOTYPE
);
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()))
1171 uint64_t SectionAddr
= Section
.getAddress();
1172 uint64_t SectSize
= Section
.getSize();
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
));
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) {
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
;
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();
1243 SymbolName
= demangle(SymbolName
);
1245 // Skip if --disassemble-functions is not empty and the symbol is not in
1247 if (!DisasmFuncsSet
.empty() && !DisasmFuncsSet
.count(SymbolName
))
1250 uint64_t Start
= std::get
<0>(Symbols
[SI
]);
1251 if (Start
< SectionAddr
|| StopAddress
<= Start
)
1254 FoundDisasmFuncsSet
.insert(SymbolName
);
1256 // The end is the section end, the beginning of the next symbol, or
1258 uint64_t End
= std::min
<uint64_t>(SectionAddr
+ SectSize
, StopAddress
);
1260 End
= std::min(End
, std::get
<0>(Symbols
[SI
+ 1]));
1261 if (Start
>= End
|| End
<= StartAddress
)
1263 Start
-= 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)
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)
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()) {
1306 raw_ostream
&DebugOut
= DebugFlag
? dbgs() : nulls();
1308 raw_ostream
&DebugOut
= nulls();
1311 // Some targets (like WebAssembly) have a special prelude at the start
1313 DisAsm
->onSymbolStart(SymbolName
, Size
, Bytes
.slice(Start
, End
- Start
),
1314 SectionAddr
+ Start
, DebugOut
, CommentStream
);
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
);
1332 bool CheckARMELFData
= hasMappingSymbols(Obj
) &&
1333 std::get
<2>(Symbols
[SI
]) != ELF::STT_OBJECT
&&
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
,
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
;
1357 countSkippableZeroBytes(Bytes
.slice(Index
, MaxOffset
))) {
1358 outs() << "\t\t..." << '\n';
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
1377 bool Disassembled
= DisAsm
->getInstruction(
1378 Inst
, Size
, Bytes
.slice(Index
), SectionAddr
+ Index
, DebugOut
,
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();
1390 // Try to resolve the target of a call, tail call, etc. to a specific
1392 if (MIA
&& (MIA
->isCall(Inst
) || MIA
->isUnconditionalBranch(Inst
) ||
1393 MIA
->isConditionalBranch(Inst
))) {
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(
1407 [=](const std::pair
<uint64_t, SectionRef
> &O
) {
1408 return O
.first
<= Target
;
1410 if (It
!= SectionAddresses
.begin()) {
1412 TargetSectionSymbols
= &AllSymbols
[It
->second
];
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(
1430 [=](const std::tuple
<uint64_t, StringRef
, uint8_t> &O
) {
1431 return std::get
<0>(O
) <= Target
;
1434 if (TargetSym
!= TargetSectionSymbols
->begin()) {
1436 uint64_t TargetAddress
= std::get
<0>(*TargetSym
);
1437 StringRef TargetName
= std::get
<1>(*TargetSym
);
1438 outs() << " <" << TargetName
;
1439 uint64_t Disp
= Target
- TargetAddress
;
1441 outs() << "+0x" << Twine::utohexstr(Disp
);
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
) {
1459 // Stop when RelCur's offset is past the current instruction.
1460 if (Offset
>= Index
+ Size
)
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
,
1482 StringSet
<> MissingDisasmFuncsSet
=
1483 set_difference(DisasmFuncsSet
, FoundDisasmFuncsSet
);
1484 for (StringRef MissingDisasmFunc
: MissingDisasmFuncsSet
.keys())
1485 reportWarning("failed to disassemble missing function " + MissingDisasmFunc
,
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
));
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
));
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()));
1513 reportError(Obj
->getFileName(),
1514 "no subtarget info for target " + TripleName
);
1515 std::unique_ptr
<const MCInstrInfo
> MII(TheTarget
->createMCInstrInfo());
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
));
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
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");
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
));
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
,
1569 void printRelocations(const ObjectFile
*Obj
) {
1570 StringRef Fmt
= Obj
->getBytesInAddress() > 4 ? "%016" PRIx64
:
1572 // Regular objdump doesn't print relocations in non-relocatable object
1574 if (!Obj
->isRelocatableObject())
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())
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
))
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";
1611 void printDynamicRelocations(const ObjectFile
*Obj
) {
1612 // For the moment, this option is for ELF only
1616 const auto *Elf
= dyn_cast
<ELFObjectFileBase
>(Obj
);
1617 if (!Elf
|| Elf
->getEType() != ELF::ET_DYN
) {
1618 reportError(Obj
->getFileName(), "not a dynamic object");
1622 std::vector
<SectionRef
> DynRelSec
= Obj
->dynamic_relocation_sections();
1623 if (DynRelSec
.empty())
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
) {
1647 for (const SectionRef
&S
: ToolSectionFilter(*Obj
))
1648 if (S
.getAddress() != getELFSectionLMA(S
))
1653 void printSectionHeaders(const ObjectFile
*Obj
) {
1654 bool HasLMAColumn
= shouldDisplayLMA(Obj
);
1656 outs() << "Sections:\n"
1657 "Idx Name Size VMA LMA "
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
))
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" : ""));
1677 outs() << format("%3d %-13s %08" PRIx64
" %016" PRIx64
" %016" PRIx64
1679 (unsigned)Section
.getIndex(), Name
.str().c_str(), Size
,
1680 VMA
, getELFSectionLMA(Section
), Type
.c_str());
1682 outs() << format("%3d %-13s %08" PRIx64
" %016" PRIx64
" %s\n",
1683 (unsigned)Section
.getIndex(), Name
.str().c_str(), Size
,
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();
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
);
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)
1715 outs() << hexdigit((Contents
[Addr
+ I
] >> 4) & 0xF, true)
1716 << hexdigit(Contents
[Addr
+ I
] & 0xF, true);
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
];
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
);
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
,
1747 if ((Address
< StartAddress
) || (Address
> StopAddress
))
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
);
1755 if (Type
== SymbolRef::ST_Debug
&& Section
!= O
->section_end()) {
1756 if (Expected
<StringRef
> NameOrErr
= Section
->getName())
1759 consumeError(NameOrErr
.takeError());
1762 Name
= unwrapOrError(Symbol
.getName(), FileName
, ArchiveName
,
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
;
1773 if (Type
!= SymbolRef::ST_Unknown
)
1774 GlobLoc
= Global
? 'g' : 'l';
1775 char Debug
= (Type
== SymbolRef::ST_Debug
|| Type
== SymbolRef::ST_File
)
1777 char FileFunc
= ' ';
1778 if (Type
== SymbolRef::ST_File
)
1780 else if (Type
== SymbolRef::ST_Function
)
1782 else if (Type
== SymbolRef::ST_Data
)
1785 const char *Fmt
= O
->getBytesInAddress() > 4 ? "%016" 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).
1799 } else if (Common
) {
1801 } else if (Section
== O
->section_end()) {
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
)) {
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();
1824 case ELF::STV_DEFAULT
:
1826 case ELF::STV_INTERNAL
:
1827 outs() << " .internal";
1829 case ELF::STV_HIDDEN
:
1830 outs() << " .hidden";
1832 case ELF::STV_PROTECTED
:
1833 outs() << " .protected";
1836 outs() << format(" 0x%02x", Other
);
1839 } else if (Hidden
) {
1840 outs() << " .hidden";
1844 outs() << ' ' << demangle(Name
) << '\n';
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
);
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";
1876 StringRef
ClangASTSectionName("__clangast");
1877 if (isa
<COFFObjectFile
>(Obj
)) {
1878 ClangASTSectionName
= "clangast";
1881 Optional
<object::SectionRef
> ClangASTSection
;
1882 for (auto Sec
: ToolSectionFilter(*Obj
)) {
1884 if (Expected
<StringRef
> NameOrErr
= Sec
.getName())
1887 consumeError(NameOrErr
.takeError());
1889 if (Name
== ClangASTSectionName
) {
1890 ClangASTSection
= Sec
;
1894 if (!ClangASTSection
)
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";
1910 WithColor::error(errs(), ToolName
)
1911 << "This operation is only currently supported "
1912 "for ELF and Mach-O executable files.\n";
1916 Optional
<object::SectionRef
> FaultMapSection
;
1918 for (auto Sec
: ToolSectionFilter(*Obj
)) {
1920 if (Expected
<StringRef
> NameOrErr
= Sec
.getName())
1923 consumeError(NameOrErr
.takeError());
1925 if (Name
== FaultMapSectionName
) {
1926 FaultMapSection
= Sec
;
1931 outs() << "FaultMap table:\n";
1933 if (!FaultMapSection
.hasValue()) {
1934 outs() << "<not found>\n";
1938 StringRef FaultMapContents
=
1939 unwrapOrError(FaultMapSection
.getValue().getContents(), Obj
->getFileName());
1940 FaultMapParser
FMP(FaultMapContents
.bytes_begin(),
1941 FaultMapContents
.bytes_end());
1946 static void printPrivateFileHeaders(const ObjectFile
*O
, bool OnlyFirst
) {
1948 printELFFileHeader(O
);
1949 printELFDynamicSection(O
);
1950 printELFSymbolVersionInfo(O
);
1954 return printCOFFFileHeader(O
);
1956 return printWasmFileHeader(O
);
1958 printMachOFileHeader(O
);
1960 printMachOLoadCommands(O
);
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();
1982 WithColor::error(errs(), ToolName
) << "ill-formed archive entry.\n";
1983 consumeError(ModeOrErr
.takeError());
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" : "-");
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();
2005 if (RawLastModified
.getAsInteger(10, Seconds
))
2006 outs() << "(date: \"" << RawLastModified
2007 << "\" contains non-decimal chars) ";
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.
2013 outs() << format("%.24s ", ctime(&t
));
2016 StringRef Name
= "";
2017 Expected
<StringRef
> NameOrErr
= C
.getName();
2019 consumeError(NameOrErr
.takeError());
2020 Name
= unwrapOrError(C
.getRawName(), Filename
);
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
)
2036 static void checkForInvalidStartStopAddress(ObjectFile
*Obj
,
2037 uint64_t Start
, uint64_t Stop
) {
2038 if (!shouldWarnForInvalidStartStopAddress(Obj
))
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
)
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());
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.
2070 outs() << A
->getFileName() << "(" << O
->getFileName() << ")";
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
);
2084 printFileHeaders(O
);
2085 if (PrivateHeaders
|| FirstPrivateHeader
)
2086 printPrivateFileHeaders(O
, FirstPrivateHeader
);
2088 printSectionHeaders(O
);
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
);
2105 disassembleObject(O
, Relocations
);
2109 // Mach-O specific options:
2111 printExportsTrie(O
);
2113 printRebaseTable(O
);
2117 printLazyBindTable(O
);
2119 printWeakBindTable(O
);
2121 // Other special sections:
2123 printRawClangAST(O
);
2124 if (FaultMapSection
)
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.
2135 << ArchiveName
<< "(" << I
->getFileName() << ")"
2136 << ":\tfile format COFF-import-file"
2139 if (ArchiveHeaders
&& !MachOOpt
&& C
)
2140 printArchiveChild(ArchiveName
, *C
);
2142 printCOFFSymbolTable(I
);
2145 /// Dump each object file in \a a;
2146 static void dumpArchive(const Archive
*A
) {
2147 Error Err
= Error::success();
2149 for (auto &C
: A
->children(Err
)) {
2151 Expected
<std::unique_ptr
<Binary
>> ChildOrErr
= C
.getAsBinary();
2153 if (auto E
= isNotObjectErrorInvalidFileType(ChildOrErr
.takeError()))
2154 reportError(std::move(E
), getFileNameForError(C
, I
), A
->getFileName());
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
);
2162 reportError(errorCodeToError(object_error::invalid_file_type
),
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.
2175 parseInputMachO(file
);
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
))
2185 else if (ObjectFile
*O
= dyn_cast
<ObjectFile
>(&Binary
))
2187 else if (MachOUniversalBinary
*UB
= dyn_cast
<MachOUniversalBinary
>(&Binary
))
2188 parseInputMachO(UB
);
2190 reportError(errorCodeToError(object_error::invalid_file_type
), file
);
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");
2215 // Defaults to a.out if no filenames specified.
2216 if (InputFilenames
.empty())
2217 InputFilenames
.push_back("a.out");
2220 ArchiveHeaders
= FileHeaders
= PrivateHeaders
= Relocations
=
2221 SectionHeaders
= SymbolTable
= true;
2223 if (DisassembleAll
|| PrintSource
|| PrintLines
||
2224 (!DisassembleFunctions
.empty()))
2227 if (!ArchiveHeaders
&& !Disassemble
&& DwarfDumpType
== DIDT_Null
&&
2228 !DynamicRelocations
&& !FileHeaders
&& !PrivateHeaders
&& !RawClangAST
&&
2229 !Relocations
&& !SectionHeaders
&& !SectionContents
&& !SymbolTable
&&
2230 !UnwindInfo
&& !FaultMapSection
&&
2232 (Bind
|| DataInCode
|| DylibId
|| DylibsUsed
|| ExportsTrie
||
2233 FirstPrivateHeader
|| IndirectSymbols
|| InfoPlist
|| LazyBind
||
2234 LinkOptHints
|| ObjcMetaData
|| Rebase
|| UniversalHeaders
||
2235 WeakBind
|| !FilterSections
.empty()))) {
2236 cl::PrintHelpMessage();
2240 DisasmFuncsSet
.insert(DisassembleFunctions
.begin(),
2241 DisassembleFunctions
.end());
2243 llvm::for_each(InputFilenames
, dumpInput
);
2245 warnOnNoMatchForSections();
2247 return EXIT_SUCCESS
;