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