Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / llvm / tools / llvm-objdump / llvm-objdump.cpp
bloba112c50bf7f2715bca25d7cdfafe6f01c4291da3
1 //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This program is a utility that works like binutils "objdump", that is, it
10 // dumps out a plethora of information about an object file depending on the
11 // flags.
13 // The flags and output of this program should be near identical to those of
14 // binutils objdump.
16 //===----------------------------------------------------------------------===//
18 #include "llvm-objdump.h"
19 #include "COFFDump.h"
20 #include "ELFDump.h"
21 #include "MachODump.h"
22 #include "ObjdumpOptID.h"
23 #include "OffloadDump.h"
24 #include "SourcePrinter.h"
25 #include "WasmDump.h"
26 #include "XCOFFDump.h"
27 #include "llvm/ADT/IndexedMap.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SetOperations.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/ADT/StringSet.h"
33 #include "llvm/ADT/Twine.h"
34 #include "llvm/DebugInfo/BTF/BTFParser.h"
35 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
36 #include "llvm/DebugInfo/Symbolize/SymbolizableModule.h"
37 #include "llvm/DebugInfo/Symbolize/Symbolize.h"
38 #include "llvm/Debuginfod/BuildIDFetcher.h"
39 #include "llvm/Debuginfod/Debuginfod.h"
40 #include "llvm/Debuginfod/HTTPClient.h"
41 #include "llvm/Demangle/Demangle.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
45 #include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
46 #include "llvm/MC/MCInst.h"
47 #include "llvm/MC/MCInstPrinter.h"
48 #include "llvm/MC/MCInstrAnalysis.h"
49 #include "llvm/MC/MCInstrInfo.h"
50 #include "llvm/MC/MCObjectFileInfo.h"
51 #include "llvm/MC/MCRegisterInfo.h"
52 #include "llvm/MC/MCTargetOptions.h"
53 #include "llvm/MC/TargetRegistry.h"
54 #include "llvm/Object/Archive.h"
55 #include "llvm/Object/BuildID.h"
56 #include "llvm/Object/COFF.h"
57 #include "llvm/Object/COFFImportFile.h"
58 #include "llvm/Object/ELFObjectFile.h"
59 #include "llvm/Object/ELFTypes.h"
60 #include "llvm/Object/FaultMapParser.h"
61 #include "llvm/Object/MachO.h"
62 #include "llvm/Object/MachOUniversal.h"
63 #include "llvm/Object/ObjectFile.h"
64 #include "llvm/Object/OffloadBinary.h"
65 #include "llvm/Object/Wasm.h"
66 #include "llvm/Option/Arg.h"
67 #include "llvm/Option/ArgList.h"
68 #include "llvm/Option/Option.h"
69 #include "llvm/Support/Casting.h"
70 #include "llvm/Support/Debug.h"
71 #include "llvm/Support/Errc.h"
72 #include "llvm/Support/FileSystem.h"
73 #include "llvm/Support/Format.h"
74 #include "llvm/Support/FormatVariadic.h"
75 #include "llvm/Support/GraphWriter.h"
76 #include "llvm/Support/InitLLVM.h"
77 #include "llvm/Support/LLVMDriver.h"
78 #include "llvm/Support/MemoryBuffer.h"
79 #include "llvm/Support/SourceMgr.h"
80 #include "llvm/Support/StringSaver.h"
81 #include "llvm/Support/TargetSelect.h"
82 #include "llvm/Support/WithColor.h"
83 #include "llvm/Support/raw_ostream.h"
84 #include "llvm/TargetParser/Host.h"
85 #include "llvm/TargetParser/Triple.h"
86 #include <algorithm>
87 #include <cctype>
88 #include <cstring>
89 #include <optional>
90 #include <system_error>
91 #include <unordered_map>
92 #include <utility>
94 using namespace llvm;
95 using namespace llvm::object;
96 using namespace llvm::objdump;
97 using namespace llvm::opt;
99 namespace {
101 class CommonOptTable : public opt::GenericOptTable {
102 public:
103 CommonOptTable(ArrayRef<Info> OptionInfos, const char *Usage,
104 const char *Description)
105 : opt::GenericOptTable(OptionInfos), Usage(Usage),
106 Description(Description) {
107 setGroupedShortOptions(true);
110 void printHelp(StringRef Argv0, bool ShowHidden = false) const {
111 Argv0 = sys::path::filename(Argv0);
112 opt::GenericOptTable::printHelp(outs(), (Argv0 + Usage).str().c_str(),
113 Description, ShowHidden, ShowHidden);
114 // TODO Replace this with OptTable API once it adds extrahelp support.
115 outs() << "\nPass @FILE as argument to read options from FILE.\n";
118 private:
119 const char *Usage;
120 const char *Description;
123 // ObjdumpOptID is in ObjdumpOptID.h
124 namespace objdump_opt {
125 #define PREFIX(NAME, VALUE) \
126 static constexpr StringLiteral NAME##_init[] = VALUE; \
127 static constexpr ArrayRef<StringLiteral> NAME(NAME##_init, \
128 std::size(NAME##_init) - 1);
129 #include "ObjdumpOpts.inc"
130 #undef PREFIX
132 static constexpr opt::OptTable::Info ObjdumpInfoTable[] = {
133 #define OPTION(...) \
134 LLVM_CONSTRUCT_OPT_INFO_WITH_ID_PREFIX(OBJDUMP_, __VA_ARGS__),
135 #include "ObjdumpOpts.inc"
136 #undef OPTION
138 } // namespace objdump_opt
140 class ObjdumpOptTable : public CommonOptTable {
141 public:
142 ObjdumpOptTable()
143 : CommonOptTable(objdump_opt::ObjdumpInfoTable,
144 " [options] <input object files>",
145 "llvm object file dumper") {}
148 enum OtoolOptID {
149 OTOOL_INVALID = 0, // This is not an option ID.
150 #define OPTION(...) LLVM_MAKE_OPT_ID_WITH_ID_PREFIX(OTOOL_, __VA_ARGS__),
151 #include "OtoolOpts.inc"
152 #undef OPTION
155 namespace otool {
156 #define PREFIX(NAME, VALUE) \
157 static constexpr StringLiteral NAME##_init[] = VALUE; \
158 static constexpr ArrayRef<StringLiteral> NAME(NAME##_init, \
159 std::size(NAME##_init) - 1);
160 #include "OtoolOpts.inc"
161 #undef PREFIX
163 static constexpr opt::OptTable::Info OtoolInfoTable[] = {
164 #define OPTION(...) LLVM_CONSTRUCT_OPT_INFO_WITH_ID_PREFIX(OTOOL_, __VA_ARGS__),
165 #include "OtoolOpts.inc"
166 #undef OPTION
168 } // namespace otool
170 class OtoolOptTable : public CommonOptTable {
171 public:
172 OtoolOptTable()
173 : CommonOptTable(otool::OtoolInfoTable, " [option...] [file...]",
174 "Mach-O object file displaying tool") {}
177 } // namespace
179 #define DEBUG_TYPE "objdump"
181 enum class ColorOutput {
182 Auto,
183 Enable,
184 Disable,
185 Invalid,
188 static uint64_t AdjustVMA;
189 static bool AllHeaders;
190 static std::string ArchName;
191 bool objdump::ArchiveHeaders;
192 bool objdump::Demangle;
193 bool objdump::Disassemble;
194 bool objdump::DisassembleAll;
195 bool objdump::SymbolDescription;
196 bool objdump::TracebackTable;
197 static std::vector<std::string> DisassembleSymbols;
198 static bool DisassembleZeroes;
199 static std::vector<std::string> DisassemblerOptions;
200 static ColorOutput DisassemblyColor;
201 DIDumpType objdump::DwarfDumpType;
202 static bool DynamicRelocations;
203 static bool FaultMapSection;
204 static bool FileHeaders;
205 bool objdump::SectionContents;
206 static std::vector<std::string> InputFilenames;
207 bool objdump::PrintLines;
208 static bool MachOOpt;
209 std::string objdump::MCPU;
210 std::vector<std::string> objdump::MAttrs;
211 bool objdump::ShowRawInsn;
212 bool objdump::LeadingAddr;
213 static bool Offloading;
214 static bool RawClangAST;
215 bool objdump::Relocations;
216 bool objdump::PrintImmHex;
217 bool objdump::PrivateHeaders;
218 std::vector<std::string> objdump::FilterSections;
219 bool objdump::SectionHeaders;
220 static bool ShowAllSymbols;
221 static bool ShowLMA;
222 bool objdump::PrintSource;
224 static uint64_t StartAddress;
225 static bool HasStartAddressFlag;
226 static uint64_t StopAddress = UINT64_MAX;
227 static bool HasStopAddressFlag;
229 bool objdump::SymbolTable;
230 static bool SymbolizeOperands;
231 static bool DynamicSymbolTable;
232 std::string objdump::TripleName;
233 bool objdump::UnwindInfo;
234 static bool Wide;
235 std::string objdump::Prefix;
236 uint32_t objdump::PrefixStrip;
238 DebugVarsFormat objdump::DbgVariables = DVDisabled;
240 int objdump::DbgIndent = 52;
242 static StringSet<> DisasmSymbolSet;
243 StringSet<> objdump::FoundSectionSet;
244 static StringRef ToolName;
246 std::unique_ptr<BuildIDFetcher> BIDFetcher;
248 Dumper::Dumper(const object::ObjectFile &O) : O(O) {
249 WarningHandler = [this](const Twine &Msg) {
250 if (Warnings.insert(Msg.str()).second)
251 reportWarning(Msg, this->O.getFileName());
252 return Error::success();
256 void Dumper::reportUniqueWarning(Error Err) {
257 reportUniqueWarning(toString(std::move(Err)));
260 void Dumper::reportUniqueWarning(const Twine &Msg) {
261 cantFail(WarningHandler(Msg));
264 static Expected<std::unique_ptr<Dumper>> createDumper(const ObjectFile &Obj) {
265 if (const auto *O = dyn_cast<COFFObjectFile>(&Obj))
266 return createCOFFDumper(*O);
267 if (const auto *O = dyn_cast<ELFObjectFileBase>(&Obj))
268 return createELFDumper(*O);
269 if (const auto *O = dyn_cast<MachOObjectFile>(&Obj))
270 return createMachODumper(*O);
271 if (const auto *O = dyn_cast<WasmObjectFile>(&Obj))
272 return createWasmDumper(*O);
273 if (const auto *O = dyn_cast<XCOFFObjectFile>(&Obj))
274 return createXCOFFDumper(*O);
276 return createStringError(errc::invalid_argument,
277 "unsupported object file format");
280 namespace {
281 struct FilterResult {
282 // True if the section should not be skipped.
283 bool Keep;
285 // True if the index counter should be incremented, even if the section should
286 // be skipped. For example, sections may be skipped if they are not included
287 // in the --section flag, but we still want those to count toward the section
288 // count.
289 bool IncrementIndex;
291 } // namespace
293 static FilterResult checkSectionFilter(object::SectionRef S) {
294 if (FilterSections.empty())
295 return {/*Keep=*/true, /*IncrementIndex=*/true};
297 Expected<StringRef> SecNameOrErr = S.getName();
298 if (!SecNameOrErr) {
299 consumeError(SecNameOrErr.takeError());
300 return {/*Keep=*/false, /*IncrementIndex=*/false};
302 StringRef SecName = *SecNameOrErr;
304 // StringSet does not allow empty key so avoid adding sections with
305 // no name (such as the section with index 0) here.
306 if (!SecName.empty())
307 FoundSectionSet.insert(SecName);
309 // Only show the section if it's in the FilterSections list, but always
310 // increment so the indexing is stable.
311 return {/*Keep=*/is_contained(FilterSections, SecName),
312 /*IncrementIndex=*/true};
315 SectionFilter objdump::ToolSectionFilter(object::ObjectFile const &O,
316 uint64_t *Idx) {
317 // Start at UINT64_MAX so that the first index returned after an increment is
318 // zero (after the unsigned wrap).
319 if (Idx)
320 *Idx = UINT64_MAX;
321 return SectionFilter(
322 [Idx](object::SectionRef S) {
323 FilterResult Result = checkSectionFilter(S);
324 if (Idx != nullptr && Result.IncrementIndex)
325 *Idx += 1;
326 return Result.Keep;
331 std::string objdump::getFileNameForError(const object::Archive::Child &C,
332 unsigned Index) {
333 Expected<StringRef> NameOrErr = C.getName();
334 if (NameOrErr)
335 return std::string(NameOrErr.get());
336 // If we have an error getting the name then we print the index of the archive
337 // member. Since we are already in an error state, we just ignore this error.
338 consumeError(NameOrErr.takeError());
339 return "<file index: " + std::to_string(Index) + ">";
342 void objdump::reportWarning(const Twine &Message, StringRef File) {
343 // Output order between errs() and outs() matters especially for archive
344 // files where the output is per member object.
345 outs().flush();
346 WithColor::warning(errs(), ToolName)
347 << "'" << File << "': " << Message << "\n";
350 [[noreturn]] void objdump::reportError(StringRef File, const Twine &Message) {
351 outs().flush();
352 WithColor::error(errs(), ToolName) << "'" << File << "': " << Message << "\n";
353 exit(1);
356 [[noreturn]] void objdump::reportError(Error E, StringRef FileName,
357 StringRef ArchiveName,
358 StringRef ArchitectureName) {
359 assert(E);
360 outs().flush();
361 WithColor::error(errs(), ToolName);
362 if (ArchiveName != "")
363 errs() << ArchiveName << "(" << FileName << ")";
364 else
365 errs() << "'" << FileName << "'";
366 if (!ArchitectureName.empty())
367 errs() << " (for architecture " << ArchitectureName << ")";
368 errs() << ": ";
369 logAllUnhandledErrors(std::move(E), errs());
370 exit(1);
373 static void reportCmdLineWarning(const Twine &Message) {
374 WithColor::warning(errs(), ToolName) << Message << "\n";
377 [[noreturn]] static void reportCmdLineError(const Twine &Message) {
378 WithColor::error(errs(), ToolName) << Message << "\n";
379 exit(1);
382 static void warnOnNoMatchForSections() {
383 SetVector<StringRef> MissingSections;
384 for (StringRef S : FilterSections) {
385 if (FoundSectionSet.count(S))
386 return;
387 // User may specify a unnamed section. Don't warn for it.
388 if (!S.empty())
389 MissingSections.insert(S);
392 // Warn only if no section in FilterSections is matched.
393 for (StringRef S : MissingSections)
394 reportCmdLineWarning("section '" + S +
395 "' mentioned in a -j/--section option, but not "
396 "found in any input file");
399 static const Target *getTarget(const ObjectFile *Obj) {
400 // Figure out the target triple.
401 Triple TheTriple("unknown-unknown-unknown");
402 if (TripleName.empty()) {
403 TheTriple = Obj->makeTriple();
404 } else {
405 TheTriple.setTriple(Triple::normalize(TripleName));
406 auto Arch = Obj->getArch();
407 if (Arch == Triple::arm || Arch == Triple::armeb)
408 Obj->setARMSubArch(TheTriple);
411 // Get the target specific parser.
412 std::string Error;
413 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
414 Error);
415 if (!TheTarget)
416 reportError(Obj->getFileName(), "can't find target: " + Error);
418 // Update the triple name and return the found target.
419 TripleName = TheTriple.getTriple();
420 return TheTarget;
423 bool objdump::isRelocAddressLess(RelocationRef A, RelocationRef B) {
424 return A.getOffset() < B.getOffset();
427 static Error getRelocationValueString(const RelocationRef &Rel,
428 SmallVectorImpl<char> &Result) {
429 const ObjectFile *Obj = Rel.getObject();
430 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
431 return getELFRelocationValueString(ELF, Rel, Result);
432 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
433 return getCOFFRelocationValueString(COFF, Rel, Result);
434 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
435 return getWasmRelocationValueString(Wasm, Rel, Result);
436 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
437 return getMachORelocationValueString(MachO, Rel, Result);
438 if (auto *XCOFF = dyn_cast<XCOFFObjectFile>(Obj))
439 return getXCOFFRelocationValueString(*XCOFF, Rel, Result);
440 llvm_unreachable("unknown object file format");
443 /// Indicates whether this relocation should hidden when listing
444 /// relocations, usually because it is the trailing part of a multipart
445 /// relocation that will be printed as part of the leading relocation.
446 static bool getHidden(RelocationRef RelRef) {
447 auto *MachO = dyn_cast<MachOObjectFile>(RelRef.getObject());
448 if (!MachO)
449 return false;
451 unsigned Arch = MachO->getArch();
452 DataRefImpl Rel = RelRef.getRawDataRefImpl();
453 uint64_t Type = MachO->getRelocationType(Rel);
455 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
456 // is always hidden.
457 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc)
458 return Type == MachO::GENERIC_RELOC_PAIR;
460 if (Arch == Triple::x86_64) {
461 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
462 // an X86_64_RELOC_SUBTRACTOR.
463 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
464 DataRefImpl RelPrev = Rel;
465 RelPrev.d.a--;
466 uint64_t PrevType = MachO->getRelocationType(RelPrev);
467 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
468 return true;
472 return false;
475 /// Get the column at which we want to start printing the instruction
476 /// disassembly, taking into account anything which appears to the left of it.
477 unsigned objdump::getInstStartColumn(const MCSubtargetInfo &STI) {
478 return !ShowRawInsn ? 16 : STI.getTargetTriple().isX86() ? 40 : 24;
481 static void AlignToInstStartColumn(size_t Start, const MCSubtargetInfo &STI,
482 raw_ostream &OS) {
483 // The output of printInst starts with a tab. Print some spaces so that
484 // the tab has 1 column and advances to the target tab stop.
485 unsigned TabStop = getInstStartColumn(STI);
486 unsigned Column = OS.tell() - Start;
487 OS.indent(Column < TabStop - 1 ? TabStop - 1 - Column : 7 - Column % 8);
490 void objdump::printRawData(ArrayRef<uint8_t> Bytes, uint64_t Address,
491 formatted_raw_ostream &OS,
492 MCSubtargetInfo const &STI) {
493 size_t Start = OS.tell();
494 if (LeadingAddr)
495 OS << format("%8" PRIx64 ":", Address);
496 if (ShowRawInsn) {
497 OS << ' ';
498 dumpBytes(Bytes, OS);
500 AlignToInstStartColumn(Start, STI, OS);
503 namespace {
505 static bool isAArch64Elf(const ObjectFile &Obj) {
506 const auto *Elf = dyn_cast<ELFObjectFileBase>(&Obj);
507 return Elf && Elf->getEMachine() == ELF::EM_AARCH64;
510 static bool isArmElf(const ObjectFile &Obj) {
511 const auto *Elf = dyn_cast<ELFObjectFileBase>(&Obj);
512 return Elf && Elf->getEMachine() == ELF::EM_ARM;
515 static bool isCSKYElf(const ObjectFile &Obj) {
516 const auto *Elf = dyn_cast<ELFObjectFileBase>(&Obj);
517 return Elf && Elf->getEMachine() == ELF::EM_CSKY;
520 static bool hasMappingSymbols(const ObjectFile &Obj) {
521 return isArmElf(Obj) || isAArch64Elf(Obj) || isCSKYElf(Obj) ;
524 static void printRelocation(formatted_raw_ostream &OS, StringRef FileName,
525 const RelocationRef &Rel, uint64_t Address,
526 bool Is64Bits) {
527 StringRef Fmt = Is64Bits ? "%016" PRIx64 ": " : "%08" PRIx64 ": ";
528 SmallString<16> Name;
529 SmallString<32> Val;
530 Rel.getTypeName(Name);
531 if (Error E = getRelocationValueString(Rel, Val))
532 reportError(std::move(E), FileName);
533 OS << (Is64Bits || !LeadingAddr ? "\t\t" : "\t\t\t");
534 if (LeadingAddr)
535 OS << format(Fmt.data(), Address);
536 OS << Name << "\t" << Val;
539 static void printBTFRelocation(formatted_raw_ostream &FOS, llvm::BTFParser &BTF,
540 object::SectionedAddress Address,
541 LiveVariablePrinter &LVP) {
542 const llvm::BTF::BPFFieldReloc *Reloc = BTF.findFieldReloc(Address);
543 if (!Reloc)
544 return;
546 SmallString<64> Val;
547 BTF.symbolize(Reloc, Val);
548 FOS << "\t\t";
549 if (LeadingAddr)
550 FOS << format("%016" PRIx64 ": ", Address.Address + AdjustVMA);
551 FOS << "CO-RE " << Val;
552 LVP.printAfterOtherLine(FOS, true);
555 class PrettyPrinter {
556 public:
557 virtual ~PrettyPrinter() = default;
558 virtual void
559 printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
560 object::SectionedAddress Address, formatted_raw_ostream &OS,
561 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
562 StringRef ObjectFilename, std::vector<RelocationRef> *Rels,
563 LiveVariablePrinter &LVP) {
564 if (SP && (PrintSource || PrintLines))
565 SP->printSourceLine(OS, Address, ObjectFilename, LVP);
566 LVP.printBetweenInsts(OS, false);
568 printRawData(Bytes, Address.Address, OS, STI);
570 if (MI) {
571 // See MCInstPrinter::printInst. On targets where a PC relative immediate
572 // is relative to the next instruction and the length of a MCInst is
573 // difficult to measure (x86), this is the address of the next
574 // instruction.
575 uint64_t Addr =
576 Address.Address + (STI.getTargetTriple().isX86() ? Bytes.size() : 0);
577 IP.printInst(MI, Addr, "", STI, OS);
578 } else
579 OS << "\t<unknown>";
582 PrettyPrinter PrettyPrinterInst;
584 class HexagonPrettyPrinter : public PrettyPrinter {
585 public:
586 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
587 formatted_raw_ostream &OS) {
588 uint32_t opcode =
589 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
590 if (LeadingAddr)
591 OS << format("%8" PRIx64 ":", Address);
592 if (ShowRawInsn) {
593 OS << "\t";
594 dumpBytes(Bytes.slice(0, 4), OS);
595 OS << format("\t%08" PRIx32, opcode);
598 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
599 object::SectionedAddress Address, formatted_raw_ostream &OS,
600 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
601 StringRef ObjectFilename, std::vector<RelocationRef> *Rels,
602 LiveVariablePrinter &LVP) override {
603 if (SP && (PrintSource || PrintLines))
604 SP->printSourceLine(OS, Address, ObjectFilename, LVP, "");
605 if (!MI) {
606 printLead(Bytes, Address.Address, OS);
607 OS << " <unknown>";
608 return;
610 std::string Buffer;
612 raw_string_ostream TempStream(Buffer);
613 IP.printInst(MI, Address.Address, "", STI, TempStream);
615 StringRef Contents(Buffer);
616 // Split off bundle attributes
617 auto PacketBundle = Contents.rsplit('\n');
618 // Split off first instruction from the rest
619 auto HeadTail = PacketBundle.first.split('\n');
620 auto Preamble = " { ";
621 auto Separator = "";
623 // Hexagon's packets require relocations to be inline rather than
624 // clustered at the end of the packet.
625 std::vector<RelocationRef>::const_iterator RelCur = Rels->begin();
626 std::vector<RelocationRef>::const_iterator RelEnd = Rels->end();
627 auto PrintReloc = [&]() -> void {
628 while ((RelCur != RelEnd) && (RelCur->getOffset() <= Address.Address)) {
629 if (RelCur->getOffset() == Address.Address) {
630 printRelocation(OS, ObjectFilename, *RelCur, Address.Address, false);
631 return;
633 ++RelCur;
637 while (!HeadTail.first.empty()) {
638 OS << Separator;
639 Separator = "\n";
640 if (SP && (PrintSource || PrintLines))
641 SP->printSourceLine(OS, Address, ObjectFilename, LVP, "");
642 printLead(Bytes, Address.Address, OS);
643 OS << Preamble;
644 Preamble = " ";
645 StringRef Inst;
646 auto Duplex = HeadTail.first.split('\v');
647 if (!Duplex.second.empty()) {
648 OS << Duplex.first;
649 OS << "; ";
650 Inst = Duplex.second;
652 else
653 Inst = HeadTail.first;
654 OS << Inst;
655 HeadTail = HeadTail.second.split('\n');
656 if (HeadTail.first.empty())
657 OS << " } " << PacketBundle.second;
658 PrintReloc();
659 Bytes = Bytes.slice(4);
660 Address.Address += 4;
664 HexagonPrettyPrinter HexagonPrettyPrinterInst;
666 class AMDGCNPrettyPrinter : public PrettyPrinter {
667 public:
668 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
669 object::SectionedAddress Address, formatted_raw_ostream &OS,
670 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
671 StringRef ObjectFilename, std::vector<RelocationRef> *Rels,
672 LiveVariablePrinter &LVP) override {
673 if (SP && (PrintSource || PrintLines))
674 SP->printSourceLine(OS, Address, ObjectFilename, LVP);
676 if (MI) {
677 SmallString<40> InstStr;
678 raw_svector_ostream IS(InstStr);
680 IP.printInst(MI, Address.Address, "", STI, IS);
682 OS << left_justify(IS.str(), 60);
683 } else {
684 // an unrecognized encoding - this is probably data so represent it
685 // using the .long directive, or .byte directive if fewer than 4 bytes
686 // remaining
687 if (Bytes.size() >= 4) {
688 OS << format(
689 "\t.long 0x%08" PRIx32 " ",
690 support::endian::read32<llvm::endianness::little>(Bytes.data()));
691 OS.indent(42);
692 } else {
693 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
694 for (unsigned int i = 1; i < Bytes.size(); i++)
695 OS << format(", 0x%02" PRIx8, Bytes[i]);
696 OS.indent(55 - (6 * Bytes.size()));
700 OS << format("// %012" PRIX64 ":", Address.Address);
701 if (Bytes.size() >= 4) {
702 // D should be casted to uint32_t here as it is passed by format to
703 // snprintf as vararg.
704 for (uint32_t D :
705 ArrayRef(reinterpret_cast<const support::little32_t *>(Bytes.data()),
706 Bytes.size() / 4))
707 OS << format(" %08" PRIX32, D);
708 } else {
709 for (unsigned char B : Bytes)
710 OS << format(" %02" PRIX8, B);
713 if (!Annot.empty())
714 OS << " // " << Annot;
717 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
719 class BPFPrettyPrinter : public PrettyPrinter {
720 public:
721 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
722 object::SectionedAddress Address, formatted_raw_ostream &OS,
723 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
724 StringRef ObjectFilename, std::vector<RelocationRef> *Rels,
725 LiveVariablePrinter &LVP) override {
726 if (SP && (PrintSource || PrintLines))
727 SP->printSourceLine(OS, Address, ObjectFilename, LVP);
728 if (LeadingAddr)
729 OS << format("%8" PRId64 ":", Address.Address / 8);
730 if (ShowRawInsn) {
731 OS << "\t";
732 dumpBytes(Bytes, OS);
734 if (MI)
735 IP.printInst(MI, Address.Address, "", STI, OS);
736 else
737 OS << "\t<unknown>";
740 BPFPrettyPrinter BPFPrettyPrinterInst;
742 class ARMPrettyPrinter : public PrettyPrinter {
743 public:
744 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
745 object::SectionedAddress Address, formatted_raw_ostream &OS,
746 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
747 StringRef ObjectFilename, std::vector<RelocationRef> *Rels,
748 LiveVariablePrinter &LVP) override {
749 if (SP && (PrintSource || PrintLines))
750 SP->printSourceLine(OS, Address, ObjectFilename, LVP);
751 LVP.printBetweenInsts(OS, false);
753 size_t Start = OS.tell();
754 if (LeadingAddr)
755 OS << format("%8" PRIx64 ":", Address.Address);
756 if (ShowRawInsn) {
757 size_t Pos = 0, End = Bytes.size();
758 if (STI.checkFeatures("+thumb-mode")) {
759 for (; Pos + 2 <= End; Pos += 2)
760 OS << ' '
761 << format_hex_no_prefix(
762 llvm::support::endian::read<uint16_t>(
763 Bytes.data() + Pos, InstructionEndianness),
765 } else {
766 for (; Pos + 4 <= End; Pos += 4)
767 OS << ' '
768 << format_hex_no_prefix(
769 llvm::support::endian::read<uint32_t>(
770 Bytes.data() + Pos, InstructionEndianness),
773 if (Pos < End) {
774 OS << ' ';
775 dumpBytes(Bytes.slice(Pos), OS);
779 AlignToInstStartColumn(Start, STI, OS);
781 if (MI) {
782 IP.printInst(MI, Address.Address, "", STI, OS);
783 } else
784 OS << "\t<unknown>";
787 void setInstructionEndianness(llvm::endianness Endianness) {
788 InstructionEndianness = Endianness;
791 private:
792 llvm::endianness InstructionEndianness = llvm::endianness::little;
794 ARMPrettyPrinter ARMPrettyPrinterInst;
796 class AArch64PrettyPrinter : public PrettyPrinter {
797 public:
798 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
799 object::SectionedAddress Address, formatted_raw_ostream &OS,
800 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
801 StringRef ObjectFilename, std::vector<RelocationRef> *Rels,
802 LiveVariablePrinter &LVP) override {
803 if (SP && (PrintSource || PrintLines))
804 SP->printSourceLine(OS, Address, ObjectFilename, LVP);
805 LVP.printBetweenInsts(OS, false);
807 size_t Start = OS.tell();
808 if (LeadingAddr)
809 OS << format("%8" PRIx64 ":", Address.Address);
810 if (ShowRawInsn) {
811 size_t Pos = 0, End = Bytes.size();
812 for (; Pos + 4 <= End; Pos += 4)
813 OS << ' '
814 << format_hex_no_prefix(
815 llvm::support::endian::read<uint32_t>(
816 Bytes.data() + Pos, llvm::endianness::little),
818 if (Pos < End) {
819 OS << ' ';
820 dumpBytes(Bytes.slice(Pos), OS);
824 AlignToInstStartColumn(Start, STI, OS);
826 if (MI) {
827 IP.printInst(MI, Address.Address, "", STI, OS);
828 } else
829 OS << "\t<unknown>";
832 AArch64PrettyPrinter AArch64PrettyPrinterInst;
834 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
835 switch(Triple.getArch()) {
836 default:
837 return PrettyPrinterInst;
838 case Triple::hexagon:
839 return HexagonPrettyPrinterInst;
840 case Triple::amdgcn:
841 return AMDGCNPrettyPrinterInst;
842 case Triple::bpfel:
843 case Triple::bpfeb:
844 return BPFPrettyPrinterInst;
845 case Triple::arm:
846 case Triple::armeb:
847 case Triple::thumb:
848 case Triple::thumbeb:
849 return ARMPrettyPrinterInst;
850 case Triple::aarch64:
851 case Triple::aarch64_be:
852 case Triple::aarch64_32:
853 return AArch64PrettyPrinterInst;
857 class DisassemblerTarget {
858 public:
859 const Target *TheTarget;
860 std::unique_ptr<const MCSubtargetInfo> SubtargetInfo;
861 std::shared_ptr<MCContext> Context;
862 std::unique_ptr<MCDisassembler> DisAsm;
863 std::shared_ptr<MCInstrAnalysis> InstrAnalysis;
864 std::shared_ptr<MCInstPrinter> InstPrinter;
865 PrettyPrinter *Printer;
867 DisassemblerTarget(const Target *TheTarget, ObjectFile &Obj,
868 StringRef TripleName, StringRef MCPU,
869 SubtargetFeatures &Features);
870 DisassemblerTarget(DisassemblerTarget &Other, SubtargetFeatures &Features);
872 private:
873 MCTargetOptions Options;
874 std::shared_ptr<const MCRegisterInfo> RegisterInfo;
875 std::shared_ptr<const MCAsmInfo> AsmInfo;
876 std::shared_ptr<const MCInstrInfo> InstrInfo;
877 std::shared_ptr<MCObjectFileInfo> ObjectFileInfo;
880 DisassemblerTarget::DisassemblerTarget(const Target *TheTarget, ObjectFile &Obj,
881 StringRef TripleName, StringRef MCPU,
882 SubtargetFeatures &Features)
883 : TheTarget(TheTarget),
884 Printer(&selectPrettyPrinter(Triple(TripleName))),
885 RegisterInfo(TheTarget->createMCRegInfo(TripleName)) {
886 if (!RegisterInfo)
887 reportError(Obj.getFileName(), "no register info for target " + TripleName);
889 // Set up disassembler.
890 AsmInfo.reset(TheTarget->createMCAsmInfo(*RegisterInfo, TripleName, Options));
891 if (!AsmInfo)
892 reportError(Obj.getFileName(), "no assembly info for target " + TripleName);
894 SubtargetInfo.reset(
895 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
896 if (!SubtargetInfo)
897 reportError(Obj.getFileName(),
898 "no subtarget info for target " + TripleName);
899 InstrInfo.reset(TheTarget->createMCInstrInfo());
900 if (!InstrInfo)
901 reportError(Obj.getFileName(),
902 "no instruction info for target " + TripleName);
903 Context =
904 std::make_shared<MCContext>(Triple(TripleName), AsmInfo.get(),
905 RegisterInfo.get(), SubtargetInfo.get());
907 // FIXME: for now initialize MCObjectFileInfo with default values
908 ObjectFileInfo.reset(
909 TheTarget->createMCObjectFileInfo(*Context, /*PIC=*/false));
910 Context->setObjectFileInfo(ObjectFileInfo.get());
912 DisAsm.reset(TheTarget->createMCDisassembler(*SubtargetInfo, *Context));
913 if (!DisAsm)
914 reportError(Obj.getFileName(), "no disassembler for target " + TripleName);
916 InstrAnalysis.reset(TheTarget->createMCInstrAnalysis(InstrInfo.get()));
918 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
919 InstPrinter.reset(TheTarget->createMCInstPrinter(Triple(TripleName),
920 AsmPrinterVariant, *AsmInfo,
921 *InstrInfo, *RegisterInfo));
922 if (!InstPrinter)
923 reportError(Obj.getFileName(),
924 "no instruction printer for target " + TripleName);
925 InstPrinter->setPrintImmHex(PrintImmHex);
926 InstPrinter->setPrintBranchImmAsAddress(true);
927 InstPrinter->setSymbolizeOperands(SymbolizeOperands);
928 InstPrinter->setMCInstrAnalysis(InstrAnalysis.get());
930 switch (DisassemblyColor) {
931 case ColorOutput::Enable:
932 InstPrinter->setUseColor(true);
933 break;
934 case ColorOutput::Auto:
935 InstPrinter->setUseColor(outs().has_colors());
936 break;
937 case ColorOutput::Disable:
938 case ColorOutput::Invalid:
939 InstPrinter->setUseColor(false);
940 break;
944 DisassemblerTarget::DisassemblerTarget(DisassemblerTarget &Other,
945 SubtargetFeatures &Features)
946 : TheTarget(Other.TheTarget),
947 SubtargetInfo(TheTarget->createMCSubtargetInfo(TripleName, MCPU,
948 Features.getString())),
949 Context(Other.Context),
950 DisAsm(TheTarget->createMCDisassembler(*SubtargetInfo, *Context)),
951 InstrAnalysis(Other.InstrAnalysis), InstPrinter(Other.InstPrinter),
952 Printer(Other.Printer), RegisterInfo(Other.RegisterInfo),
953 AsmInfo(Other.AsmInfo), InstrInfo(Other.InstrInfo),
954 ObjectFileInfo(Other.ObjectFileInfo) {}
955 } // namespace
957 static uint8_t getElfSymbolType(const ObjectFile &Obj, const SymbolRef &Sym) {
958 assert(Obj.isELF());
959 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(&Obj))
960 return unwrapOrError(Elf32LEObj->getSymbol(Sym.getRawDataRefImpl()),
961 Obj.getFileName())
962 ->getType();
963 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(&Obj))
964 return unwrapOrError(Elf64LEObj->getSymbol(Sym.getRawDataRefImpl()),
965 Obj.getFileName())
966 ->getType();
967 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(&Obj))
968 return unwrapOrError(Elf32BEObj->getSymbol(Sym.getRawDataRefImpl()),
969 Obj.getFileName())
970 ->getType();
971 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(&Obj))
972 return unwrapOrError(Elf64BEObj->getSymbol(Sym.getRawDataRefImpl()),
973 Obj.getFileName())
974 ->getType();
975 llvm_unreachable("Unsupported binary format");
978 template <class ELFT>
979 static void
980 addDynamicElfSymbols(const ELFObjectFile<ELFT> &Obj,
981 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
982 for (auto Symbol : Obj.getDynamicSymbolIterators()) {
983 uint8_t SymbolType = Symbol.getELFType();
984 if (SymbolType == ELF::STT_SECTION)
985 continue;
987 uint64_t Address = unwrapOrError(Symbol.getAddress(), Obj.getFileName());
988 // ELFSymbolRef::getAddress() returns size instead of value for common
989 // symbols which is not desirable for disassembly output. Overriding.
990 if (SymbolType == ELF::STT_COMMON)
991 Address = unwrapOrError(Obj.getSymbol(Symbol.getRawDataRefImpl()),
992 Obj.getFileName())
993 ->st_value;
995 StringRef Name = unwrapOrError(Symbol.getName(), Obj.getFileName());
996 if (Name.empty())
997 continue;
999 section_iterator SecI =
1000 unwrapOrError(Symbol.getSection(), Obj.getFileName());
1001 if (SecI == Obj.section_end())
1002 continue;
1004 AllSymbols[*SecI].emplace_back(Address, Name, SymbolType);
1008 static void
1009 addDynamicElfSymbols(const ELFObjectFileBase &Obj,
1010 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1011 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(&Obj))
1012 addDynamicElfSymbols(*Elf32LEObj, AllSymbols);
1013 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(&Obj))
1014 addDynamicElfSymbols(*Elf64LEObj, AllSymbols);
1015 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(&Obj))
1016 addDynamicElfSymbols(*Elf32BEObj, AllSymbols);
1017 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(&Obj))
1018 addDynamicElfSymbols(*Elf64BEObj, AllSymbols);
1019 else
1020 llvm_unreachable("Unsupported binary format");
1023 static std::optional<SectionRef> getWasmCodeSection(const WasmObjectFile &Obj) {
1024 for (auto SecI : Obj.sections()) {
1025 const WasmSection &Section = Obj.getWasmSection(SecI);
1026 if (Section.Type == wasm::WASM_SEC_CODE)
1027 return SecI;
1029 return std::nullopt;
1032 static void
1033 addMissingWasmCodeSymbols(const WasmObjectFile &Obj,
1034 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1035 std::optional<SectionRef> Section = getWasmCodeSection(Obj);
1036 if (!Section)
1037 return;
1038 SectionSymbolsTy &Symbols = AllSymbols[*Section];
1040 std::set<uint64_t> SymbolAddresses;
1041 for (const auto &Sym : Symbols)
1042 SymbolAddresses.insert(Sym.Addr);
1044 for (const wasm::WasmFunction &Function : Obj.functions()) {
1045 uint64_t Address = Function.CodeSectionOffset;
1046 // Only add fallback symbols for functions not already present in the symbol
1047 // table.
1048 if (SymbolAddresses.count(Address))
1049 continue;
1050 // This function has no symbol, so it should have no SymbolName.
1051 assert(Function.SymbolName.empty());
1052 // We use DebugName for the name, though it may be empty if there is no
1053 // "name" custom section, or that section is missing a name for this
1054 // function.
1055 StringRef Name = Function.DebugName;
1056 Symbols.emplace_back(Address, Name, ELF::STT_NOTYPE);
1060 static void addPltEntries(const ObjectFile &Obj,
1061 std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
1062 StringSaver &Saver) {
1063 auto *ElfObj = dyn_cast<ELFObjectFileBase>(&Obj);
1064 if (!ElfObj)
1065 return;
1066 DenseMap<StringRef, SectionRef> Sections;
1067 for (SectionRef Section : Obj.sections()) {
1068 Expected<StringRef> SecNameOrErr = Section.getName();
1069 if (!SecNameOrErr) {
1070 consumeError(SecNameOrErr.takeError());
1071 continue;
1073 Sections[*SecNameOrErr] = Section;
1075 for (auto Plt : ElfObj->getPltEntries()) {
1076 if (Plt.Symbol) {
1077 SymbolRef Symbol(*Plt.Symbol, ElfObj);
1078 uint8_t SymbolType = getElfSymbolType(Obj, Symbol);
1079 if (Expected<StringRef> NameOrErr = Symbol.getName()) {
1080 if (!NameOrErr->empty())
1081 AllSymbols[Sections[Plt.Section]].emplace_back(
1082 Plt.Address, Saver.save((*NameOrErr + "@plt").str()), SymbolType);
1083 continue;
1084 } else {
1085 // The warning has been reported in disassembleObject().
1086 consumeError(NameOrErr.takeError());
1089 reportWarning("PLT entry at 0x" + Twine::utohexstr(Plt.Address) +
1090 " references an invalid symbol",
1091 Obj.getFileName());
1095 // Normally the disassembly output will skip blocks of zeroes. This function
1096 // returns the number of zero bytes that can be skipped when dumping the
1097 // disassembly of the instructions in Buf.
1098 static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) {
1099 // Find the number of leading zeroes.
1100 size_t N = 0;
1101 while (N < Buf.size() && !Buf[N])
1102 ++N;
1104 // We may want to skip blocks of zero bytes, but unless we see
1105 // at least 8 of them in a row.
1106 if (N < 8)
1107 return 0;
1109 // We skip zeroes in multiples of 4 because do not want to truncate an
1110 // instruction if it starts with a zero byte.
1111 return N & ~0x3;
1114 // Returns a map from sections to their relocations.
1115 static std::map<SectionRef, std::vector<RelocationRef>>
1116 getRelocsMap(object::ObjectFile const &Obj) {
1117 std::map<SectionRef, std::vector<RelocationRef>> Ret;
1118 uint64_t I = (uint64_t)-1;
1119 for (SectionRef Sec : Obj.sections()) {
1120 ++I;
1121 Expected<section_iterator> RelocatedOrErr = Sec.getRelocatedSection();
1122 if (!RelocatedOrErr)
1123 reportError(Obj.getFileName(),
1124 "section (" + Twine(I) +
1125 "): failed to get a relocated section: " +
1126 toString(RelocatedOrErr.takeError()));
1128 section_iterator Relocated = *RelocatedOrErr;
1129 if (Relocated == Obj.section_end() || !checkSectionFilter(*Relocated).Keep)
1130 continue;
1131 std::vector<RelocationRef> &V = Ret[*Relocated];
1132 append_range(V, Sec.relocations());
1133 // Sort relocations by address.
1134 llvm::stable_sort(V, isRelocAddressLess);
1136 return Ret;
1139 // Used for --adjust-vma to check if address should be adjusted by the
1140 // specified value for a given section.
1141 // For ELF we do not adjust non-allocatable sections like debug ones,
1142 // because they are not loadable.
1143 // TODO: implement for other file formats.
1144 static bool shouldAdjustVA(const SectionRef &Section) {
1145 const ObjectFile *Obj = Section.getObject();
1146 if (Obj->isELF())
1147 return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
1148 return false;
1152 typedef std::pair<uint64_t, char> MappingSymbolPair;
1153 static char getMappingSymbolKind(ArrayRef<MappingSymbolPair> MappingSymbols,
1154 uint64_t Address) {
1155 auto It =
1156 partition_point(MappingSymbols, [Address](const MappingSymbolPair &Val) {
1157 return Val.first <= Address;
1159 // Return zero for any address before the first mapping symbol; this means
1160 // we should use the default disassembly mode, depending on the target.
1161 if (It == MappingSymbols.begin())
1162 return '\x00';
1163 return (It - 1)->second;
1166 static uint64_t dumpARMELFData(uint64_t SectionAddr, uint64_t Index,
1167 uint64_t End, const ObjectFile &Obj,
1168 ArrayRef<uint8_t> Bytes,
1169 ArrayRef<MappingSymbolPair> MappingSymbols,
1170 const MCSubtargetInfo &STI, raw_ostream &OS) {
1171 llvm::endianness Endian =
1172 Obj.isLittleEndian() ? llvm::endianness::little : llvm::endianness::big;
1173 size_t Start = OS.tell();
1174 OS << format("%8" PRIx64 ": ", SectionAddr + Index);
1175 if (Index + 4 <= End) {
1176 dumpBytes(Bytes.slice(Index, 4), OS);
1177 AlignToInstStartColumn(Start, STI, OS);
1178 OS << "\t.word\t"
1179 << format_hex(support::endian::read32(Bytes.data() + Index, Endian),
1180 10);
1181 return 4;
1183 if (Index + 2 <= End) {
1184 dumpBytes(Bytes.slice(Index, 2), OS);
1185 AlignToInstStartColumn(Start, STI, OS);
1186 OS << "\t.short\t"
1187 << format_hex(support::endian::read16(Bytes.data() + Index, Endian), 6);
1188 return 2;
1190 dumpBytes(Bytes.slice(Index, 1), OS);
1191 AlignToInstStartColumn(Start, STI, OS);
1192 OS << "\t.byte\t" << format_hex(Bytes[Index], 4);
1193 return 1;
1196 static void dumpELFData(uint64_t SectionAddr, uint64_t Index, uint64_t End,
1197 ArrayRef<uint8_t> Bytes) {
1198 // print out data up to 8 bytes at a time in hex and ascii
1199 uint8_t AsciiData[9] = {'\0'};
1200 uint8_t Byte;
1201 int NumBytes = 0;
1203 for (; Index < End; ++Index) {
1204 if (NumBytes == 0)
1205 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1206 Byte = Bytes.slice(Index)[0];
1207 outs() << format(" %02x", Byte);
1208 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
1210 uint8_t IndentOffset = 0;
1211 NumBytes++;
1212 if (Index == End - 1 || NumBytes > 8) {
1213 // Indent the space for less than 8 bytes data.
1214 // 2 spaces for byte and one for space between bytes
1215 IndentOffset = 3 * (8 - NumBytes);
1216 for (int Excess = NumBytes; Excess < 8; Excess++)
1217 AsciiData[Excess] = '\0';
1218 NumBytes = 8;
1220 if (NumBytes == 8) {
1221 AsciiData[8] = '\0';
1222 outs() << std::string(IndentOffset, ' ') << " ";
1223 outs() << reinterpret_cast<char *>(AsciiData);
1224 outs() << '\n';
1225 NumBytes = 0;
1230 SymbolInfoTy objdump::createSymbolInfo(const ObjectFile &Obj,
1231 const SymbolRef &Symbol,
1232 bool IsMappingSymbol) {
1233 const StringRef FileName = Obj.getFileName();
1234 const uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
1235 const StringRef Name = unwrapOrError(Symbol.getName(), FileName);
1237 if (Obj.isXCOFF() && (SymbolDescription || TracebackTable)) {
1238 const auto &XCOFFObj = cast<XCOFFObjectFile>(Obj);
1239 DataRefImpl SymbolDRI = Symbol.getRawDataRefImpl();
1241 const uint32_t SymbolIndex = XCOFFObj.getSymbolIndex(SymbolDRI.p);
1242 std::optional<XCOFF::StorageMappingClass> Smc =
1243 getXCOFFSymbolCsectSMC(XCOFFObj, Symbol);
1244 return SymbolInfoTy(Smc, Addr, Name, SymbolIndex,
1245 isLabel(XCOFFObj, Symbol));
1246 } else if (Obj.isXCOFF()) {
1247 const SymbolRef::Type SymType = unwrapOrError(Symbol.getType(), FileName);
1248 return SymbolInfoTy(Addr, Name, SymType, /*IsMappingSymbol=*/false,
1249 /*IsXCOFF=*/true);
1250 } else {
1251 uint8_t Type =
1252 Obj.isELF() ? getElfSymbolType(Obj, Symbol) : (uint8_t)ELF::STT_NOTYPE;
1253 return SymbolInfoTy(Addr, Name, Type, IsMappingSymbol);
1257 static SymbolInfoTy createDummySymbolInfo(const ObjectFile &Obj,
1258 const uint64_t Addr, StringRef &Name,
1259 uint8_t Type) {
1260 if (Obj.isXCOFF() && (SymbolDescription || TracebackTable))
1261 return SymbolInfoTy(std::nullopt, Addr, Name, std::nullopt, false);
1262 else
1263 return SymbolInfoTy(Addr, Name, Type);
1266 static void
1267 collectBBAddrMapLabels(const std::unordered_map<uint64_t, BBAddrMap> &AddrToBBAddrMap,
1268 uint64_t SectionAddr, uint64_t Start, uint64_t End,
1269 std::unordered_map<uint64_t, std::vector<std::string>> &Labels) {
1270 if (AddrToBBAddrMap.empty())
1271 return;
1272 Labels.clear();
1273 uint64_t StartAddress = SectionAddr + Start;
1274 uint64_t EndAddress = SectionAddr + End;
1275 auto Iter = AddrToBBAddrMap.find(StartAddress);
1276 if (Iter == AddrToBBAddrMap.end())
1277 return;
1278 for (const BBAddrMap::BBEntry &BBEntry : Iter->second.BBEntries) {
1279 uint64_t BBAddress = BBEntry.Offset + Iter->second.Addr;
1280 if (BBAddress >= EndAddress)
1281 continue;
1282 Labels[BBAddress].push_back(("BB" + Twine(BBEntry.ID)).str());
1286 static void
1287 collectLocalBranchTargets(ArrayRef<uint8_t> Bytes, MCInstrAnalysis *MIA,
1288 MCDisassembler *DisAsm, MCInstPrinter *IP,
1289 const MCSubtargetInfo *STI, uint64_t SectionAddr,
1290 uint64_t Start, uint64_t End,
1291 std::unordered_map<uint64_t, std::string> &Labels) {
1292 // So far only supports PowerPC and X86.
1293 if (!STI->getTargetTriple().isPPC() && !STI->getTargetTriple().isX86())
1294 return;
1296 if (MIA)
1297 MIA->resetState();
1299 Labels.clear();
1300 unsigned LabelCount = 0;
1301 Start += SectionAddr;
1302 End += SectionAddr;
1303 uint64_t Index = Start;
1304 while (Index < End) {
1305 // Disassemble a real instruction and record function-local branch labels.
1306 MCInst Inst;
1307 uint64_t Size;
1308 ArrayRef<uint8_t> ThisBytes = Bytes.slice(Index - SectionAddr);
1309 bool Disassembled =
1310 DisAsm->getInstruction(Inst, Size, ThisBytes, Index, nulls());
1311 if (Size == 0)
1312 Size = std::min<uint64_t>(ThisBytes.size(),
1313 DisAsm->suggestBytesToSkip(ThisBytes, Index));
1315 if (Disassembled && MIA) {
1316 uint64_t Target;
1317 bool TargetKnown = MIA->evaluateBranch(Inst, Index, Size, Target);
1318 // On PowerPC, if the address of a branch is the same as the target, it
1319 // means that it's a function call. Do not mark the label for this case.
1320 if (TargetKnown && (Target >= Start && Target < End) &&
1321 !Labels.count(Target) &&
1322 !(STI->getTargetTriple().isPPC() && Target == Index))
1323 Labels[Target] = ("L" + Twine(LabelCount++)).str();
1324 MIA->updateState(Inst, Index);
1325 } else if (!Disassembled && MIA) {
1326 MIA->resetState();
1328 Index += Size;
1332 // Create an MCSymbolizer for the target and add it to the MCDisassembler.
1333 // This is currently only used on AMDGPU, and assumes the format of the
1334 // void * argument passed to AMDGPU's createMCSymbolizer.
1335 static void addSymbolizer(
1336 MCContext &Ctx, const Target *Target, StringRef TripleName,
1337 MCDisassembler *DisAsm, uint64_t SectionAddr, ArrayRef<uint8_t> Bytes,
1338 SectionSymbolsTy &Symbols,
1339 std::vector<std::unique_ptr<std::string>> &SynthesizedLabelNames) {
1341 std::unique_ptr<MCRelocationInfo> RelInfo(
1342 Target->createMCRelocationInfo(TripleName, Ctx));
1343 if (!RelInfo)
1344 return;
1345 std::unique_ptr<MCSymbolizer> Symbolizer(Target->createMCSymbolizer(
1346 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1347 MCSymbolizer *SymbolizerPtr = &*Symbolizer;
1348 DisAsm->setSymbolizer(std::move(Symbolizer));
1350 if (!SymbolizeOperands)
1351 return;
1353 // Synthesize labels referenced by branch instructions by
1354 // disassembling, discarding the output, and collecting the referenced
1355 // addresses from the symbolizer.
1356 for (size_t Index = 0; Index != Bytes.size();) {
1357 MCInst Inst;
1358 uint64_t Size;
1359 ArrayRef<uint8_t> ThisBytes = Bytes.slice(Index);
1360 const uint64_t ThisAddr = SectionAddr + Index;
1361 DisAsm->getInstruction(Inst, Size, ThisBytes, ThisAddr, nulls());
1362 if (Size == 0)
1363 Size = std::min<uint64_t>(ThisBytes.size(),
1364 DisAsm->suggestBytesToSkip(ThisBytes, Index));
1365 Index += Size;
1367 ArrayRef<uint64_t> LabelAddrsRef = SymbolizerPtr->getReferencedAddresses();
1368 // Copy and sort to remove duplicates.
1369 std::vector<uint64_t> LabelAddrs;
1370 LabelAddrs.insert(LabelAddrs.end(), LabelAddrsRef.begin(),
1371 LabelAddrsRef.end());
1372 llvm::sort(LabelAddrs);
1373 LabelAddrs.resize(std::unique(LabelAddrs.begin(), LabelAddrs.end()) -
1374 LabelAddrs.begin());
1375 // Add the labels.
1376 for (unsigned LabelNum = 0; LabelNum != LabelAddrs.size(); ++LabelNum) {
1377 auto Name = std::make_unique<std::string>();
1378 *Name = (Twine("L") + Twine(LabelNum)).str();
1379 SynthesizedLabelNames.push_back(std::move(Name));
1380 Symbols.push_back(SymbolInfoTy(
1381 LabelAddrs[LabelNum], *SynthesizedLabelNames.back(), ELF::STT_NOTYPE));
1383 llvm::stable_sort(Symbols);
1384 // Recreate the symbolizer with the new symbols list.
1385 RelInfo.reset(Target->createMCRelocationInfo(TripleName, Ctx));
1386 Symbolizer.reset(Target->createMCSymbolizer(
1387 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1388 DisAsm->setSymbolizer(std::move(Symbolizer));
1391 static StringRef getSegmentName(const MachOObjectFile *MachO,
1392 const SectionRef &Section) {
1393 if (MachO) {
1394 DataRefImpl DR = Section.getRawDataRefImpl();
1395 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1396 return SegmentName;
1398 return "";
1401 static void emitPostInstructionInfo(formatted_raw_ostream &FOS,
1402 const MCAsmInfo &MAI,
1403 const MCSubtargetInfo &STI,
1404 StringRef Comments,
1405 LiveVariablePrinter &LVP) {
1406 do {
1407 if (!Comments.empty()) {
1408 // Emit a line of comments.
1409 StringRef Comment;
1410 std::tie(Comment, Comments) = Comments.split('\n');
1411 // MAI.getCommentColumn() assumes that instructions are printed at the
1412 // position of 8, while getInstStartColumn() returns the actual position.
1413 unsigned CommentColumn =
1414 MAI.getCommentColumn() - 8 + getInstStartColumn(STI);
1415 FOS.PadToColumn(CommentColumn);
1416 FOS << MAI.getCommentString() << ' ' << Comment;
1418 LVP.printAfterInst(FOS);
1419 FOS << '\n';
1420 } while (!Comments.empty());
1421 FOS.flush();
1424 static void createFakeELFSections(ObjectFile &Obj) {
1425 assert(Obj.isELF());
1426 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(&Obj))
1427 Elf32LEObj->createFakeSections();
1428 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(&Obj))
1429 Elf64LEObj->createFakeSections();
1430 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(&Obj))
1431 Elf32BEObj->createFakeSections();
1432 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(&Obj))
1433 Elf64BEObj->createFakeSections();
1434 else
1435 llvm_unreachable("Unsupported binary format");
1438 // Tries to fetch a more complete version of the given object file using its
1439 // Build ID. Returns std::nullopt if nothing was found.
1440 static std::optional<OwningBinary<Binary>>
1441 fetchBinaryByBuildID(const ObjectFile &Obj) {
1442 object::BuildIDRef BuildID = getBuildID(&Obj);
1443 if (BuildID.empty())
1444 return std::nullopt;
1445 std::optional<std::string> Path = BIDFetcher->fetch(BuildID);
1446 if (!Path)
1447 return std::nullopt;
1448 Expected<OwningBinary<Binary>> DebugBinary = createBinary(*Path);
1449 if (!DebugBinary) {
1450 reportWarning(toString(DebugBinary.takeError()), *Path);
1451 return std::nullopt;
1453 return std::move(*DebugBinary);
1456 static void
1457 disassembleObject(ObjectFile &Obj, const ObjectFile &DbgObj,
1458 DisassemblerTarget &PrimaryTarget,
1459 std::optional<DisassemblerTarget> &SecondaryTarget,
1460 SourcePrinter &SP, bool InlineRelocs) {
1461 DisassemblerTarget *DT = &PrimaryTarget;
1462 bool PrimaryIsThumb = false;
1463 SmallVector<std::pair<uint64_t, uint64_t>, 0> CHPECodeMap;
1465 if (SecondaryTarget) {
1466 if (isArmElf(Obj)) {
1467 PrimaryIsThumb =
1468 PrimaryTarget.SubtargetInfo->checkFeatures("+thumb-mode");
1469 } else if (const auto *COFFObj = dyn_cast<COFFObjectFile>(&Obj)) {
1470 const chpe_metadata *CHPEMetadata = COFFObj->getCHPEMetadata();
1471 if (CHPEMetadata && CHPEMetadata->CodeMapCount) {
1472 uintptr_t CodeMapInt;
1473 cantFail(COFFObj->getRvaPtr(CHPEMetadata->CodeMap, CodeMapInt));
1474 auto CodeMap = reinterpret_cast<const chpe_range_entry *>(CodeMapInt);
1476 for (uint32_t i = 0; i < CHPEMetadata->CodeMapCount; ++i) {
1477 if (CodeMap[i].getType() == chpe_range_type::Amd64 &&
1478 CodeMap[i].Length) {
1479 // Store x86_64 CHPE code ranges.
1480 uint64_t Start = CodeMap[i].getStart() + COFFObj->getImageBase();
1481 CHPECodeMap.emplace_back(Start, Start + CodeMap[i].Length);
1484 llvm::sort(CHPECodeMap);
1489 std::map<SectionRef, std::vector<RelocationRef>> RelocMap;
1490 if (InlineRelocs)
1491 RelocMap = getRelocsMap(Obj);
1492 bool Is64Bits = Obj.getBytesInAddress() > 4;
1494 // Create a mapping from virtual address to symbol name. This is used to
1495 // pretty print the symbols while disassembling.
1496 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1497 std::map<SectionRef, SmallVector<MappingSymbolPair, 0>> AllMappingSymbols;
1498 SectionSymbolsTy AbsoluteSymbols;
1499 const StringRef FileName = Obj.getFileName();
1500 const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(&Obj);
1501 for (const SymbolRef &Symbol : Obj.symbols()) {
1502 Expected<StringRef> NameOrErr = Symbol.getName();
1503 if (!NameOrErr) {
1504 reportWarning(toString(NameOrErr.takeError()), FileName);
1505 continue;
1507 if (NameOrErr->empty() && !(Obj.isXCOFF() && SymbolDescription))
1508 continue;
1510 if (Obj.isELF() &&
1511 (cantFail(Symbol.getFlags()) & SymbolRef::SF_FormatSpecific)) {
1512 // Symbol is intended not to be displayed by default (STT_FILE,
1513 // STT_SECTION, or a mapping symbol). Ignore STT_SECTION symbols. We will
1514 // synthesize a section symbol if no symbol is defined at offset 0.
1516 // For a mapping symbol, store it within both AllSymbols and
1517 // AllMappingSymbols. If --show-all-symbols is unspecified, its label will
1518 // not be printed in disassembly listing.
1519 if (getElfSymbolType(Obj, Symbol) != ELF::STT_SECTION &&
1520 hasMappingSymbols(Obj)) {
1521 section_iterator SecI = unwrapOrError(Symbol.getSection(), FileName);
1522 if (SecI != Obj.section_end()) {
1523 uint64_t SectionAddr = SecI->getAddress();
1524 uint64_t Address = cantFail(Symbol.getAddress());
1525 StringRef Name = *NameOrErr;
1526 if (Name.consume_front("$") && Name.size() &&
1527 strchr("adtx", Name[0])) {
1528 AllMappingSymbols[*SecI].emplace_back(Address - SectionAddr,
1529 Name[0]);
1530 AllSymbols[*SecI].push_back(
1531 createSymbolInfo(Obj, Symbol, /*MappingSymbol=*/true));
1535 continue;
1538 if (MachO) {
1539 // __mh_(execute|dylib|dylinker|bundle|preload|object)_header are special
1540 // symbols that support MachO header introspection. They do not bind to
1541 // code locations and are irrelevant for disassembly.
1542 if (NameOrErr->startswith("__mh_") && NameOrErr->endswith("_header"))
1543 continue;
1544 // Don't ask a Mach-O STAB symbol for its section unless you know that
1545 // STAB symbol's section field refers to a valid section index. Otherwise
1546 // the symbol may error trying to load a section that does not exist.
1547 DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
1548 uint8_t NType = (MachO->is64Bit() ?
1549 MachO->getSymbol64TableEntry(SymDRI).n_type:
1550 MachO->getSymbolTableEntry(SymDRI).n_type);
1551 if (NType & MachO::N_STAB)
1552 continue;
1555 section_iterator SecI = unwrapOrError(Symbol.getSection(), FileName);
1556 if (SecI != Obj.section_end())
1557 AllSymbols[*SecI].push_back(createSymbolInfo(Obj, Symbol));
1558 else
1559 AbsoluteSymbols.push_back(createSymbolInfo(Obj, Symbol));
1562 if (AllSymbols.empty() && Obj.isELF())
1563 addDynamicElfSymbols(cast<ELFObjectFileBase>(Obj), AllSymbols);
1565 if (Obj.isWasm())
1566 addMissingWasmCodeSymbols(cast<WasmObjectFile>(Obj), AllSymbols);
1568 if (Obj.isELF() && Obj.sections().empty())
1569 createFakeELFSections(Obj);
1571 BumpPtrAllocator A;
1572 StringSaver Saver(A);
1573 addPltEntries(Obj, AllSymbols, Saver);
1575 // Create a mapping from virtual address to section. An empty section can
1576 // cause more than one section at the same address. Sort such sections to be
1577 // before same-addressed non-empty sections so that symbol lookups prefer the
1578 // non-empty section.
1579 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1580 for (SectionRef Sec : Obj.sections())
1581 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1582 llvm::stable_sort(SectionAddresses, [](const auto &LHS, const auto &RHS) {
1583 if (LHS.first != RHS.first)
1584 return LHS.first < RHS.first;
1585 return LHS.second.getSize() < RHS.second.getSize();
1588 // Linked executables (.exe and .dll files) typically don't include a real
1589 // symbol table but they might contain an export table.
1590 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(&Obj)) {
1591 for (const auto &ExportEntry : COFFObj->export_directories()) {
1592 StringRef Name;
1593 if (Error E = ExportEntry.getSymbolName(Name))
1594 reportError(std::move(E), Obj.getFileName());
1595 if (Name.empty())
1596 continue;
1598 uint32_t RVA;
1599 if (Error E = ExportEntry.getExportRVA(RVA))
1600 reportError(std::move(E), Obj.getFileName());
1602 uint64_t VA = COFFObj->getImageBase() + RVA;
1603 auto Sec = partition_point(
1604 SectionAddresses, [VA](const std::pair<uint64_t, SectionRef> &O) {
1605 return O.first <= VA;
1607 if (Sec != SectionAddresses.begin()) {
1608 --Sec;
1609 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
1610 } else
1611 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
1615 // Sort all the symbols, this allows us to use a simple binary search to find
1616 // Multiple symbols can have the same address. Use a stable sort to stabilize
1617 // the output.
1618 StringSet<> FoundDisasmSymbolSet;
1619 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1620 llvm::stable_sort(SecSyms.second);
1621 llvm::stable_sort(AbsoluteSymbols);
1623 std::unique_ptr<DWARFContext> DICtx;
1624 LiveVariablePrinter LVP(*DT->Context->getRegisterInfo(), *DT->SubtargetInfo);
1626 if (DbgVariables != DVDisabled) {
1627 DICtx = DWARFContext::create(DbgObj);
1628 for (const std::unique_ptr<DWARFUnit> &CU : DICtx->compile_units())
1629 LVP.addCompileUnit(CU->getUnitDIE(false));
1632 LLVM_DEBUG(LVP.dump());
1634 std::unordered_map<uint64_t, BBAddrMap> AddrToBBAddrMap;
1635 auto ReadBBAddrMap = [&](std::optional<unsigned> SectionIndex =
1636 std::nullopt) {
1637 AddrToBBAddrMap.clear();
1638 if (const auto *Elf = dyn_cast<ELFObjectFileBase>(&Obj)) {
1639 auto BBAddrMapsOrErr = Elf->readBBAddrMap(SectionIndex);
1640 if (!BBAddrMapsOrErr) {
1641 reportWarning(toString(BBAddrMapsOrErr.takeError()), Obj.getFileName());
1642 return;
1644 for (auto &FunctionBBAddrMap : *BBAddrMapsOrErr)
1645 AddrToBBAddrMap.emplace(FunctionBBAddrMap.Addr,
1646 std::move(FunctionBBAddrMap));
1650 // For non-relocatable objects, Read all LLVM_BB_ADDR_MAP sections into a
1651 // single mapping, since they don't have any conflicts.
1652 if (SymbolizeOperands && !Obj.isRelocatableObject())
1653 ReadBBAddrMap();
1655 std::optional<llvm::BTFParser> BTF;
1656 if (InlineRelocs && BTFParser::hasBTFSections(Obj)) {
1657 BTF.emplace();
1658 BTFParser::ParseOptions Opts = {};
1659 Opts.LoadTypes = true;
1660 Opts.LoadRelocs = true;
1661 if (Error E = BTF->parse(Obj, Opts))
1662 WithColor::defaultErrorHandler(std::move(E));
1665 for (const SectionRef &Section : ToolSectionFilter(Obj)) {
1666 if (FilterSections.empty() && !DisassembleAll &&
1667 (!Section.isText() || Section.isVirtual()))
1668 continue;
1670 uint64_t SectionAddr = Section.getAddress();
1671 uint64_t SectSize = Section.getSize();
1672 if (!SectSize)
1673 continue;
1675 // For relocatable object files, read the LLVM_BB_ADDR_MAP section
1676 // corresponding to this section, if present.
1677 if (SymbolizeOperands && Obj.isRelocatableObject())
1678 ReadBBAddrMap(Section.getIndex());
1680 // Get the list of all the symbols in this section.
1681 SectionSymbolsTy &Symbols = AllSymbols[Section];
1682 auto &MappingSymbols = AllMappingSymbols[Section];
1683 llvm::sort(MappingSymbols);
1685 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(
1686 unwrapOrError(Section.getContents(), Obj.getFileName()));
1688 std::vector<std::unique_ptr<std::string>> SynthesizedLabelNames;
1689 if (Obj.isELF() && Obj.getArch() == Triple::amdgcn) {
1690 // AMDGPU disassembler uses symbolizer for printing labels
1691 addSymbolizer(*DT->Context, DT->TheTarget, TripleName, DT->DisAsm.get(),
1692 SectionAddr, Bytes, Symbols, SynthesizedLabelNames);
1695 StringRef SegmentName = getSegmentName(MachO, Section);
1696 StringRef SectionName = unwrapOrError(Section.getName(), Obj.getFileName());
1697 // If the section has no symbol at the start, just insert a dummy one.
1698 // Without --show-all-symbols, also insert one if all symbols at the start
1699 // are mapping symbols.
1700 bool CreateDummy = Symbols.empty();
1701 if (!CreateDummy) {
1702 CreateDummy = true;
1703 for (auto &Sym : Symbols) {
1704 if (Sym.Addr != SectionAddr)
1705 break;
1706 if (!Sym.IsMappingSymbol || ShowAllSymbols)
1707 CreateDummy = false;
1710 if (CreateDummy) {
1711 SymbolInfoTy Sym = createDummySymbolInfo(
1712 Obj, SectionAddr, SectionName,
1713 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT);
1714 if (Obj.isXCOFF())
1715 Symbols.insert(Symbols.begin(), Sym);
1716 else
1717 Symbols.insert(llvm::lower_bound(Symbols, Sym), Sym);
1720 SmallString<40> Comments;
1721 raw_svector_ostream CommentStream(Comments);
1723 uint64_t VMAAdjustment = 0;
1724 if (shouldAdjustVA(Section))
1725 VMAAdjustment = AdjustVMA;
1727 // In executable and shared objects, r_offset holds a virtual address.
1728 // Subtract SectionAddr from the r_offset field of a relocation to get
1729 // the section offset.
1730 uint64_t RelAdjustment = Obj.isRelocatableObject() ? 0 : SectionAddr;
1731 uint64_t Size;
1732 uint64_t Index;
1733 bool PrintedSection = false;
1734 std::vector<RelocationRef> Rels = RelocMap[Section];
1735 std::vector<RelocationRef>::const_iterator RelCur = Rels.begin();
1736 std::vector<RelocationRef>::const_iterator RelEnd = Rels.end();
1738 // Loop over each chunk of code between two points where at least
1739 // one symbol is defined.
1740 for (size_t SI = 0, SE = Symbols.size(); SI != SE;) {
1741 // Advance SI past all the symbols starting at the same address,
1742 // and make an ArrayRef of them.
1743 unsigned FirstSI = SI;
1744 uint64_t Start = Symbols[SI].Addr;
1745 ArrayRef<SymbolInfoTy> SymbolsHere;
1746 while (SI != SE && Symbols[SI].Addr == Start)
1747 ++SI;
1748 SymbolsHere = ArrayRef<SymbolInfoTy>(&Symbols[FirstSI], SI - FirstSI);
1750 // Get the demangled names of all those symbols. We end up with a vector
1751 // of StringRef that holds the names we're going to use, and a vector of
1752 // std::string that stores the new strings returned by demangle(), if
1753 // any. If we don't call demangle() then that vector can stay empty.
1754 std::vector<StringRef> SymNamesHere;
1755 std::vector<std::string> DemangledSymNamesHere;
1756 if (Demangle) {
1757 // Fetch the demangled names and store them locally.
1758 for (const SymbolInfoTy &Symbol : SymbolsHere)
1759 DemangledSymNamesHere.push_back(demangle(Symbol.Name));
1760 // Now we've finished modifying that vector, it's safe to make
1761 // a vector of StringRefs pointing into it.
1762 SymNamesHere.insert(SymNamesHere.begin(), DemangledSymNamesHere.begin(),
1763 DemangledSymNamesHere.end());
1764 } else {
1765 for (const SymbolInfoTy &Symbol : SymbolsHere)
1766 SymNamesHere.push_back(Symbol.Name);
1769 // Distinguish ELF data from code symbols, which will be used later on to
1770 // decide whether to 'disassemble' this chunk as a data declaration via
1771 // dumpELFData(), or whether to treat it as code.
1773 // If data _and_ code symbols are defined at the same address, the code
1774 // takes priority, on the grounds that disassembling code is our main
1775 // purpose here, and it would be a worse failure to _not_ interpret
1776 // something that _was_ meaningful as code than vice versa.
1778 // Any ELF symbol type that is not clearly data will be regarded as code.
1779 // In particular, one of the uses of STT_NOTYPE is for branch targets
1780 // inside functions, for which STT_FUNC would be inaccurate.
1782 // So here, we spot whether there's any non-data symbol present at all,
1783 // and only set the DisassembleAsData flag if there isn't. Also, we use
1784 // this distinction to inform the decision of which symbol to print at
1785 // the head of the section, so that if we're printing code, we print a
1786 // code-related symbol name to go with it.
1787 bool DisassembleAsData = false;
1788 size_t DisplaySymIndex = SymbolsHere.size() - 1;
1789 if (Obj.isELF() && !DisassembleAll && Section.isText()) {
1790 DisassembleAsData = true; // unless we find a code symbol below
1792 for (size_t i = 0; i < SymbolsHere.size(); ++i) {
1793 uint8_t SymTy = SymbolsHere[i].Type;
1794 if (SymTy != ELF::STT_OBJECT && SymTy != ELF::STT_COMMON) {
1795 DisassembleAsData = false;
1796 DisplaySymIndex = i;
1801 // Decide which symbol(s) from this collection we're going to print.
1802 std::vector<bool> SymsToPrint(SymbolsHere.size(), false);
1803 // If the user has given the --disassemble-symbols option, then we must
1804 // display every symbol in that set, and no others.
1805 if (!DisasmSymbolSet.empty()) {
1806 bool FoundAny = false;
1807 for (size_t i = 0; i < SymbolsHere.size(); ++i) {
1808 if (DisasmSymbolSet.count(SymNamesHere[i])) {
1809 SymsToPrint[i] = true;
1810 FoundAny = true;
1814 // And if none of the symbols here is one that the user asked for, skip
1815 // disassembling this entire chunk of code.
1816 if (!FoundAny)
1817 continue;
1818 } else if (!SymbolsHere[DisplaySymIndex].IsMappingSymbol) {
1819 // Otherwise, print whichever symbol at this location is last in the
1820 // Symbols array, because that array is pre-sorted in a way intended to
1821 // correlate with priority of which symbol to display.
1822 SymsToPrint[DisplaySymIndex] = true;
1825 // Now that we know we're disassembling this section, override the choice
1826 // of which symbols to display by printing _all_ of them at this address
1827 // if the user asked for all symbols.
1829 // That way, '--show-all-symbols --disassemble-symbol=foo' will print
1830 // only the chunk of code headed by 'foo', but also show any other
1831 // symbols defined at that address, such as aliases for 'foo', or the ARM
1832 // mapping symbol preceding its code.
1833 if (ShowAllSymbols) {
1834 for (size_t i = 0; i < SymbolsHere.size(); ++i)
1835 SymsToPrint[i] = true;
1838 if (Start < SectionAddr || StopAddress <= Start)
1839 continue;
1841 for (size_t i = 0; i < SymbolsHere.size(); ++i)
1842 FoundDisasmSymbolSet.insert(SymNamesHere[i]);
1844 // The end is the section end, the beginning of the next symbol, or
1845 // --stop-address.
1846 uint64_t End = std::min<uint64_t>(SectionAddr + SectSize, StopAddress);
1847 if (SI < SE)
1848 End = std::min(End, Symbols[SI].Addr);
1849 if (Start >= End || End <= StartAddress)
1850 continue;
1851 Start -= SectionAddr;
1852 End -= SectionAddr;
1854 if (!PrintedSection) {
1855 PrintedSection = true;
1856 outs() << "\nDisassembly of section ";
1857 if (!SegmentName.empty())
1858 outs() << SegmentName << ",";
1859 outs() << SectionName << ":\n";
1862 bool PrintedLabel = false;
1863 for (size_t i = 0; i < SymbolsHere.size(); ++i) {
1864 if (!SymsToPrint[i])
1865 continue;
1867 const SymbolInfoTy &Symbol = SymbolsHere[i];
1868 const StringRef SymbolName = SymNamesHere[i];
1870 if (!PrintedLabel) {
1871 outs() << '\n';
1872 PrintedLabel = true;
1874 if (LeadingAddr)
1875 outs() << format(Is64Bits ? "%016" PRIx64 " " : "%08" PRIx64 " ",
1876 SectionAddr + Start + VMAAdjustment);
1877 if (Obj.isXCOFF() && SymbolDescription) {
1878 outs() << getXCOFFSymbolDescription(Symbol, SymbolName) << ":\n";
1879 } else
1880 outs() << '<' << SymbolName << ">:\n";
1883 // Don't print raw contents of a virtual section. A virtual section
1884 // doesn't have any contents in the file.
1885 if (Section.isVirtual()) {
1886 outs() << "...\n";
1887 continue;
1890 // See if any of the symbols defined at this location triggers target-
1891 // specific disassembly behavior, e.g. of special descriptors or function
1892 // prelude information.
1894 // We stop this loop at the first symbol that triggers some kind of
1895 // interesting behavior (if any), on the assumption that if two symbols
1896 // defined at the same address trigger two conflicting symbol handlers,
1897 // the object file is probably confused anyway, and it would make even
1898 // less sense to present the output of _both_ handlers, because that
1899 // would describe the same data twice.
1900 for (size_t SHI = 0; SHI < SymbolsHere.size(); ++SHI) {
1901 SymbolInfoTy Symbol = SymbolsHere[SHI];
1903 auto Status = DT->DisAsm->onSymbolStart(
1904 Symbol, Size, Bytes.slice(Start, End - Start), SectionAddr + Start,
1905 CommentStream);
1907 if (!Status) {
1908 // If onSymbolStart returns std::nullopt, that means it didn't trigger
1909 // any interesting handling for this symbol. Try the other symbols
1910 // defined at this address.
1911 continue;
1914 if (*Status == MCDisassembler::Fail) {
1915 // If onSymbolStart returns Fail, that means it identified some kind
1916 // of special data at this address, but wasn't able to disassemble it
1917 // meaningfully. So we fall back to disassembling the failed region
1918 // as bytes, assuming that the target detected the failure before
1919 // printing anything.
1921 // Return values Success or SoftFail (i.e no 'real' failure) are
1922 // expected to mean that the target has emitted its own output.
1924 // Either way, 'Size' will have been set to the amount of data
1925 // covered by whatever prologue the target identified. So we advance
1926 // our own position to beyond that. Sometimes that will be the entire
1927 // distance to the next symbol, and sometimes it will be just a
1928 // prologue and we should start disassembling instructions from where
1929 // it left off.
1930 outs() << DT->Context->getAsmInfo()->getCommentString()
1931 << " error in decoding " << SymNamesHere[SHI]
1932 << " : decoding failed region as bytes.\n";
1933 for (uint64_t I = 0; I < Size; ++I) {
1934 outs() << "\t.byte\t " << format_hex(Bytes[I], 1, /*Upper=*/true)
1935 << "\n";
1938 Start += Size;
1939 break;
1942 Index = Start;
1943 if (SectionAddr < StartAddress)
1944 Index = std::max<uint64_t>(Index, StartAddress - SectionAddr);
1946 if (DisassembleAsData) {
1947 dumpELFData(SectionAddr, Index, End, Bytes);
1948 Index = End;
1949 continue;
1952 bool DumpARMELFData = false;
1953 bool DumpTracebackTableForXCOFFFunction =
1954 Obj.isXCOFF() && Section.isText() && TracebackTable &&
1955 Symbols[SI - 1].XCOFFSymInfo.StorageMappingClass &&
1956 (*Symbols[SI - 1].XCOFFSymInfo.StorageMappingClass == XCOFF::XMC_PR);
1958 formatted_raw_ostream FOS(outs());
1960 // FIXME: Workaround for bug in formatted_raw_ostream. Color escape codes
1961 // are (incorrectly) written directly to the unbuffered raw_ostream
1962 // wrapped by the formatted_raw_ostream.
1963 if (DisassemblyColor == ColorOutput::Enable ||
1964 DisassemblyColor == ColorOutput::Auto)
1965 FOS.SetUnbuffered();
1967 std::unordered_map<uint64_t, std::string> AllLabels;
1968 std::unordered_map<uint64_t, std::vector<std::string>> BBAddrMapLabels;
1969 if (SymbolizeOperands) {
1970 collectLocalBranchTargets(Bytes, DT->InstrAnalysis.get(),
1971 DT->DisAsm.get(), DT->InstPrinter.get(),
1972 PrimaryTarget.SubtargetInfo.get(),
1973 SectionAddr, Index, End, AllLabels);
1974 collectBBAddrMapLabels(AddrToBBAddrMap, SectionAddr, Index, End,
1975 BBAddrMapLabels);
1978 if (DT->InstrAnalysis)
1979 DT->InstrAnalysis->resetState();
1981 while (Index < End) {
1982 // ARM and AArch64 ELF binaries can interleave data and text in the
1983 // same section. We rely on the markers introduced to understand what
1984 // we need to dump. If the data marker is within a function, it is
1985 // denoted as a word/short etc.
1986 if (!MappingSymbols.empty()) {
1987 char Kind = getMappingSymbolKind(MappingSymbols, Index);
1988 DumpARMELFData = Kind == 'd';
1989 if (SecondaryTarget) {
1990 if (Kind == 'a') {
1991 DT = PrimaryIsThumb ? &*SecondaryTarget : &PrimaryTarget;
1992 } else if (Kind == 't') {
1993 DT = PrimaryIsThumb ? &PrimaryTarget : &*SecondaryTarget;
1996 } else if (!CHPECodeMap.empty()) {
1997 uint64_t Address = SectionAddr + Index;
1998 auto It = partition_point(
1999 CHPECodeMap,
2000 [Address](const std::pair<uint64_t, uint64_t> &Entry) {
2001 return Entry.first <= Address;
2003 if (It != CHPECodeMap.begin() && Address < (It - 1)->second) {
2004 DT = &*SecondaryTarget;
2005 } else {
2006 DT = &PrimaryTarget;
2007 // X64 disassembler range may have left Index unaligned, so
2008 // make sure that it's aligned when we switch back to ARM64
2009 // code.
2010 Index = llvm::alignTo(Index, 4);
2011 if (Index >= End)
2012 break;
2016 if (DumpARMELFData) {
2017 Size = dumpARMELFData(SectionAddr, Index, End, Obj, Bytes,
2018 MappingSymbols, *DT->SubtargetInfo, FOS);
2019 } else {
2020 // When -z or --disassemble-zeroes are given we always dissasemble
2021 // them. Otherwise we might want to skip zero bytes we see.
2022 if (!DisassembleZeroes) {
2023 uint64_t MaxOffset = End - Index;
2024 // For --reloc: print zero blocks patched by relocations, so that
2025 // relocations can be shown in the dump.
2026 if (RelCur != RelEnd)
2027 MaxOffset = std::min(RelCur->getOffset() - RelAdjustment - Index,
2028 MaxOffset);
2030 if (size_t N =
2031 countSkippableZeroBytes(Bytes.slice(Index, MaxOffset))) {
2032 FOS << "\t\t..." << '\n';
2033 Index += N;
2034 continue;
2038 if (DumpTracebackTableForXCOFFFunction &&
2039 doesXCOFFTracebackTableBegin(Bytes.slice(Index, 4))) {
2040 dumpTracebackTable(Bytes.slice(Index),
2041 SectionAddr + Index + VMAAdjustment, FOS,
2042 SectionAddr + End + VMAAdjustment,
2043 *DT->SubtargetInfo, cast<XCOFFObjectFile>(&Obj));
2044 Index = End;
2045 continue;
2048 // Print local label if there's any.
2049 auto Iter1 = BBAddrMapLabels.find(SectionAddr + Index);
2050 if (Iter1 != BBAddrMapLabels.end()) {
2051 for (StringRef Label : Iter1->second)
2052 FOS << "<" << Label << ">:\n";
2053 } else {
2054 auto Iter2 = AllLabels.find(SectionAddr + Index);
2055 if (Iter2 != AllLabels.end())
2056 FOS << "<" << Iter2->second << ">:\n";
2059 // Disassemble a real instruction or a data when disassemble all is
2060 // provided
2061 MCInst Inst;
2062 ArrayRef<uint8_t> ThisBytes = Bytes.slice(Index);
2063 uint64_t ThisAddr = SectionAddr + Index;
2064 bool Disassembled = DT->DisAsm->getInstruction(
2065 Inst, Size, ThisBytes, ThisAddr, CommentStream);
2066 if (Size == 0)
2067 Size = std::min<uint64_t>(
2068 ThisBytes.size(),
2069 DT->DisAsm->suggestBytesToSkip(ThisBytes, ThisAddr));
2071 LVP.update({Index, Section.getIndex()},
2072 {Index + Size, Section.getIndex()}, Index + Size != End);
2074 DT->InstPrinter->setCommentStream(CommentStream);
2076 DT->Printer->printInst(
2077 *DT->InstPrinter, Disassembled ? &Inst : nullptr,
2078 Bytes.slice(Index, Size),
2079 {SectionAddr + Index + VMAAdjustment, Section.getIndex()}, FOS,
2080 "", *DT->SubtargetInfo, &SP, Obj.getFileName(), &Rels, LVP);
2082 DT->InstPrinter->setCommentStream(llvm::nulls());
2084 // If disassembly has failed, avoid analysing invalid/incomplete
2085 // instruction information. Otherwise, try to resolve the target
2086 // address (jump target or memory operand address) and print it on the
2087 // right of the instruction.
2088 if (Disassembled && DT->InstrAnalysis) {
2089 // Branch targets are printed just after the instructions.
2090 llvm::raw_ostream *TargetOS = &FOS;
2091 uint64_t Target;
2092 bool PrintTarget = DT->InstrAnalysis->evaluateBranch(
2093 Inst, SectionAddr + Index, Size, Target);
2094 if (!PrintTarget)
2095 if (std::optional<uint64_t> MaybeTarget =
2096 DT->InstrAnalysis->evaluateMemoryOperandAddress(
2097 Inst, DT->SubtargetInfo.get(), SectionAddr + Index,
2098 Size)) {
2099 Target = *MaybeTarget;
2100 PrintTarget = true;
2101 // Do not print real address when symbolizing.
2102 if (!SymbolizeOperands) {
2103 // Memory operand addresses are printed as comments.
2104 TargetOS = &CommentStream;
2105 *TargetOS << "0x" << Twine::utohexstr(Target);
2108 if (PrintTarget) {
2109 // In a relocatable object, the target's section must reside in
2110 // the same section as the call instruction or it is accessed
2111 // through a relocation.
2113 // In a non-relocatable object, the target may be in any section.
2114 // In that case, locate the section(s) containing the target
2115 // address and find the symbol in one of those, if possible.
2117 // N.B. We don't walk the relocations in the relocatable case yet.
2118 std::vector<const SectionSymbolsTy *> TargetSectionSymbols;
2119 if (!Obj.isRelocatableObject()) {
2120 auto It = llvm::partition_point(
2121 SectionAddresses,
2122 [=](const std::pair<uint64_t, SectionRef> &O) {
2123 return O.first <= Target;
2125 uint64_t TargetSecAddr = 0;
2126 while (It != SectionAddresses.begin()) {
2127 --It;
2128 if (TargetSecAddr == 0)
2129 TargetSecAddr = It->first;
2130 if (It->first != TargetSecAddr)
2131 break;
2132 TargetSectionSymbols.push_back(&AllSymbols[It->second]);
2134 } else {
2135 TargetSectionSymbols.push_back(&Symbols);
2137 TargetSectionSymbols.push_back(&AbsoluteSymbols);
2139 // Find the last symbol in the first candidate section whose
2140 // offset is less than or equal to the target. If there are no
2141 // such symbols, try in the next section and so on, before finally
2142 // using the nearest preceding absolute symbol (if any), if there
2143 // are no other valid symbols.
2144 const SymbolInfoTy *TargetSym = nullptr;
2145 for (const SectionSymbolsTy *TargetSymbols :
2146 TargetSectionSymbols) {
2147 auto It = llvm::partition_point(
2148 *TargetSymbols,
2149 [=](const SymbolInfoTy &O) { return O.Addr <= Target; });
2150 while (It != TargetSymbols->begin()) {
2151 --It;
2152 // Skip mapping symbols to avoid possible ambiguity as they
2153 // do not allow uniquely identifying the target address.
2154 if (!It->IsMappingSymbol) {
2155 TargetSym = &*It;
2156 break;
2159 if (TargetSym)
2160 break;
2163 // Print the labels corresponding to the target if there's any.
2164 bool BBAddrMapLabelAvailable = BBAddrMapLabels.count(Target);
2165 bool LabelAvailable = AllLabels.count(Target);
2166 if (TargetSym != nullptr) {
2167 uint64_t TargetAddress = TargetSym->Addr;
2168 uint64_t Disp = Target - TargetAddress;
2169 std::string TargetName = Demangle ? demangle(TargetSym->Name)
2170 : TargetSym->Name.str();
2172 *TargetOS << " <";
2173 if (!Disp) {
2174 // Always Print the binary symbol precisely corresponding to
2175 // the target address.
2176 *TargetOS << TargetName;
2177 } else if (BBAddrMapLabelAvailable) {
2178 *TargetOS << BBAddrMapLabels[Target].front();
2179 } else if (LabelAvailable) {
2180 *TargetOS << AllLabels[Target];
2181 } else {
2182 // Always Print the binary symbol plus an offset if there's no
2183 // local label corresponding to the target address.
2184 *TargetOS << TargetName << "+0x" << Twine::utohexstr(Disp);
2186 *TargetOS << ">";
2187 } else if (BBAddrMapLabelAvailable) {
2188 *TargetOS << " <" << BBAddrMapLabels[Target].front() << ">";
2189 } else if (LabelAvailable) {
2190 *TargetOS << " <" << AllLabels[Target] << ">";
2192 // By convention, each record in the comment stream should be
2193 // terminated.
2194 if (TargetOS == &CommentStream)
2195 *TargetOS << "\n";
2198 DT->InstrAnalysis->updateState(Inst, SectionAddr + Index);
2199 } else if (!Disassembled && DT->InstrAnalysis) {
2200 DT->InstrAnalysis->resetState();
2204 assert(DT->Context->getAsmInfo());
2205 emitPostInstructionInfo(FOS, *DT->Context->getAsmInfo(),
2206 *DT->SubtargetInfo, CommentStream.str(), LVP);
2207 Comments.clear();
2209 if (BTF)
2210 printBTFRelocation(FOS, *BTF, {Index, Section.getIndex()}, LVP);
2212 // Hexagon does this in pretty printer
2213 if (Obj.getArch() != Triple::hexagon) {
2214 // Print relocation for instruction and data.
2215 while (RelCur != RelEnd) {
2216 uint64_t Offset = RelCur->getOffset() - RelAdjustment;
2217 // If this relocation is hidden, skip it.
2218 if (getHidden(*RelCur) || SectionAddr + Offset < StartAddress) {
2219 ++RelCur;
2220 continue;
2223 // Stop when RelCur's offset is past the disassembled
2224 // instruction/data. Note that it's possible the disassembled data
2225 // is not the complete data: we might see the relocation printed in
2226 // the middle of the data, but this matches the binutils objdump
2227 // output.
2228 if (Offset >= Index + Size)
2229 break;
2231 // When --adjust-vma is used, update the address printed.
2232 if (RelCur->getSymbol() != Obj.symbol_end()) {
2233 Expected<section_iterator> SymSI =
2234 RelCur->getSymbol()->getSection();
2235 if (SymSI && *SymSI != Obj.section_end() &&
2236 shouldAdjustVA(**SymSI))
2237 Offset += AdjustVMA;
2240 printRelocation(FOS, Obj.getFileName(), *RelCur,
2241 SectionAddr + Offset, Is64Bits);
2242 LVP.printAfterOtherLine(FOS, true);
2243 ++RelCur;
2247 Index += Size;
2251 StringSet<> MissingDisasmSymbolSet =
2252 set_difference(DisasmSymbolSet, FoundDisasmSymbolSet);
2253 for (StringRef Sym : MissingDisasmSymbolSet.keys())
2254 reportWarning("failed to disassemble missing symbol " + Sym, FileName);
2257 static void disassembleObject(ObjectFile *Obj, bool InlineRelocs) {
2258 // If information useful for showing the disassembly is missing, try to find a
2259 // more complete binary and disassemble that instead.
2260 OwningBinary<Binary> FetchedBinary;
2261 if (Obj->symbols().empty()) {
2262 if (std::optional<OwningBinary<Binary>> FetchedBinaryOpt =
2263 fetchBinaryByBuildID(*Obj)) {
2264 if (auto *O = dyn_cast<ObjectFile>(FetchedBinaryOpt->getBinary())) {
2265 if (!O->symbols().empty() ||
2266 (!O->sections().empty() && Obj->sections().empty())) {
2267 FetchedBinary = std::move(*FetchedBinaryOpt);
2268 Obj = O;
2274 const Target *TheTarget = getTarget(Obj);
2276 // Package up features to be passed to target/subtarget
2277 Expected<SubtargetFeatures> FeaturesValue = Obj->getFeatures();
2278 if (!FeaturesValue)
2279 reportError(FeaturesValue.takeError(), Obj->getFileName());
2280 SubtargetFeatures Features = *FeaturesValue;
2281 if (!MAttrs.empty()) {
2282 for (unsigned I = 0; I != MAttrs.size(); ++I)
2283 Features.AddFeature(MAttrs[I]);
2284 } else if (MCPU.empty() && Obj->getArch() == llvm::Triple::aarch64) {
2285 Features.AddFeature("+all");
2288 if (MCPU.empty())
2289 MCPU = Obj->tryGetCPUName().value_or("").str();
2291 if (isArmElf(*Obj)) {
2292 // When disassembling big-endian Arm ELF, the instruction endianness is
2293 // determined in a complex way. In relocatable objects, AAELF32 mandates
2294 // that instruction endianness matches the ELF file endianness; in
2295 // executable images, that's true unless the file header has the EF_ARM_BE8
2296 // flag, in which case instructions are little-endian regardless of data
2297 // endianness.
2299 // We must set the big-endian-instructions SubtargetFeature to make the
2300 // disassembler read the instructions the right way round, and also tell
2301 // our own prettyprinter to retrieve the encodings the same way to print in
2302 // hex.
2303 const auto *Elf32BE = dyn_cast<ELF32BEObjectFile>(Obj);
2305 if (Elf32BE && (Elf32BE->isRelocatableObject() ||
2306 !(Elf32BE->getPlatformFlags() & ELF::EF_ARM_BE8))) {
2307 Features.AddFeature("+big-endian-instructions");
2308 ARMPrettyPrinterInst.setInstructionEndianness(llvm::endianness::big);
2309 } else {
2310 ARMPrettyPrinterInst.setInstructionEndianness(llvm::endianness::little);
2314 DisassemblerTarget PrimaryTarget(TheTarget, *Obj, TripleName, MCPU, Features);
2316 // If we have an ARM object file, we need a second disassembler, because
2317 // ARM CPUs have two different instruction sets: ARM mode, and Thumb mode.
2318 // We use mapping symbols to switch between the two assemblers, where
2319 // appropriate.
2320 std::optional<DisassemblerTarget> SecondaryTarget;
2322 if (isArmElf(*Obj)) {
2323 if (!PrimaryTarget.SubtargetInfo->checkFeatures("+mclass")) {
2324 if (PrimaryTarget.SubtargetInfo->checkFeatures("+thumb-mode"))
2325 Features.AddFeature("-thumb-mode");
2326 else
2327 Features.AddFeature("+thumb-mode");
2328 SecondaryTarget.emplace(PrimaryTarget, Features);
2330 } else if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
2331 const chpe_metadata *CHPEMetadata = COFFObj->getCHPEMetadata();
2332 if (CHPEMetadata && CHPEMetadata->CodeMapCount) {
2333 // Set up x86_64 disassembler for ARM64EC binaries.
2334 Triple X64Triple(TripleName);
2335 X64Triple.setArch(Triple::ArchType::x86_64);
2337 std::string Error;
2338 const Target *X64Target =
2339 TargetRegistry::lookupTarget("", X64Triple, Error);
2340 if (X64Target) {
2341 SubtargetFeatures X64Features;
2342 SecondaryTarget.emplace(X64Target, *Obj, X64Triple.getTriple(), "",
2343 X64Features);
2344 } else {
2345 reportWarning(Error, Obj->getFileName());
2350 const ObjectFile *DbgObj = Obj;
2351 if (!FetchedBinary.getBinary() && !Obj->hasDebugInfo()) {
2352 if (std::optional<OwningBinary<Binary>> DebugBinaryOpt =
2353 fetchBinaryByBuildID(*Obj)) {
2354 if (auto *FetchedObj =
2355 dyn_cast<const ObjectFile>(DebugBinaryOpt->getBinary())) {
2356 if (FetchedObj->hasDebugInfo()) {
2357 FetchedBinary = std::move(*DebugBinaryOpt);
2358 DbgObj = FetchedObj;
2364 std::unique_ptr<object::Binary> DSYMBinary;
2365 std::unique_ptr<MemoryBuffer> DSYMBuf;
2366 if (!DbgObj->hasDebugInfo()) {
2367 if (const MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*Obj)) {
2368 DbgObj = objdump::getMachODSymObject(MachOOF, Obj->getFileName(),
2369 DSYMBinary, DSYMBuf);
2370 if (!DbgObj)
2371 return;
2375 SourcePrinter SP(DbgObj, TheTarget->getName());
2377 for (StringRef Opt : DisassemblerOptions)
2378 if (!PrimaryTarget.InstPrinter->applyTargetSpecificCLOption(Opt))
2379 reportError(Obj->getFileName(),
2380 "Unrecognized disassembler option: " + Opt);
2382 disassembleObject(*Obj, *DbgObj, PrimaryTarget, SecondaryTarget, SP,
2383 InlineRelocs);
2386 void Dumper::printRelocations() {
2387 StringRef Fmt = O.getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
2389 // Build a mapping from relocation target to a vector of relocation
2390 // sections. Usually, there is an only one relocation section for
2391 // each relocated section.
2392 MapVector<SectionRef, std::vector<SectionRef>> SecToRelSec;
2393 uint64_t Ndx;
2394 for (const SectionRef &Section : ToolSectionFilter(O, &Ndx)) {
2395 if (O.isELF() && (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC))
2396 continue;
2397 if (Section.relocation_begin() == Section.relocation_end())
2398 continue;
2399 Expected<section_iterator> SecOrErr = Section.getRelocatedSection();
2400 if (!SecOrErr)
2401 reportError(O.getFileName(),
2402 "section (" + Twine(Ndx) +
2403 "): unable to get a relocation target: " +
2404 toString(SecOrErr.takeError()));
2405 SecToRelSec[**SecOrErr].push_back(Section);
2408 for (std::pair<SectionRef, std::vector<SectionRef>> &P : SecToRelSec) {
2409 StringRef SecName = unwrapOrError(P.first.getName(), O.getFileName());
2410 outs() << "\nRELOCATION RECORDS FOR [" << SecName << "]:\n";
2411 uint32_t OffsetPadding = (O.getBytesInAddress() > 4 ? 16 : 8);
2412 uint32_t TypePadding = 24;
2413 outs() << left_justify("OFFSET", OffsetPadding) << " "
2414 << left_justify("TYPE", TypePadding) << " "
2415 << "VALUE\n";
2417 for (SectionRef Section : P.second) {
2418 for (const RelocationRef &Reloc : Section.relocations()) {
2419 uint64_t Address = Reloc.getOffset();
2420 SmallString<32> RelocName;
2421 SmallString<32> ValueStr;
2422 if (Address < StartAddress || Address > StopAddress || getHidden(Reloc))
2423 continue;
2424 Reloc.getTypeName(RelocName);
2425 if (Error E = getRelocationValueString(Reloc, ValueStr))
2426 reportUniqueWarning(std::move(E));
2428 outs() << format(Fmt.data(), Address) << " "
2429 << left_justify(RelocName, TypePadding) << " " << ValueStr
2430 << "\n";
2436 // Returns true if we need to show LMA column when dumping section headers. We
2437 // show it only when the platform is ELF and either we have at least one section
2438 // whose VMA and LMA are different and/or when --show-lma flag is used.
2439 static bool shouldDisplayLMA(const ObjectFile &Obj) {
2440 if (!Obj.isELF())
2441 return false;
2442 for (const SectionRef &S : ToolSectionFilter(Obj))
2443 if (S.getAddress() != getELFSectionLMA(S))
2444 return true;
2445 return ShowLMA;
2448 static size_t getMaxSectionNameWidth(const ObjectFile &Obj) {
2449 // Default column width for names is 13 even if no names are that long.
2450 size_t MaxWidth = 13;
2451 for (const SectionRef &Section : ToolSectionFilter(Obj)) {
2452 StringRef Name = unwrapOrError(Section.getName(), Obj.getFileName());
2453 MaxWidth = std::max(MaxWidth, Name.size());
2455 return MaxWidth;
2458 void objdump::printSectionHeaders(ObjectFile &Obj) {
2459 if (Obj.isELF() && Obj.sections().empty())
2460 createFakeELFSections(Obj);
2462 size_t NameWidth = getMaxSectionNameWidth(Obj);
2463 size_t AddressWidth = 2 * Obj.getBytesInAddress();
2464 bool HasLMAColumn = shouldDisplayLMA(Obj);
2465 outs() << "\nSections:\n";
2466 if (HasLMAColumn)
2467 outs() << "Idx " << left_justify("Name", NameWidth) << " Size "
2468 << left_justify("VMA", AddressWidth) << " "
2469 << left_justify("LMA", AddressWidth) << " Type\n";
2470 else
2471 outs() << "Idx " << left_justify("Name", NameWidth) << " Size "
2472 << left_justify("VMA", AddressWidth) << " Type\n";
2474 uint64_t Idx;
2475 for (const SectionRef &Section : ToolSectionFilter(Obj, &Idx)) {
2476 StringRef Name = unwrapOrError(Section.getName(), Obj.getFileName());
2477 uint64_t VMA = Section.getAddress();
2478 if (shouldAdjustVA(Section))
2479 VMA += AdjustVMA;
2481 uint64_t Size = Section.getSize();
2483 std::string Type = Section.isText() ? "TEXT" : "";
2484 if (Section.isData())
2485 Type += Type.empty() ? "DATA" : ", DATA";
2486 if (Section.isBSS())
2487 Type += Type.empty() ? "BSS" : ", BSS";
2488 if (Section.isDebugSection())
2489 Type += Type.empty() ? "DEBUG" : ", DEBUG";
2491 if (HasLMAColumn)
2492 outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth,
2493 Name.str().c_str(), Size)
2494 << format_hex_no_prefix(VMA, AddressWidth) << " "
2495 << format_hex_no_prefix(getELFSectionLMA(Section), AddressWidth)
2496 << " " << Type << "\n";
2497 else
2498 outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth,
2499 Name.str().c_str(), Size)
2500 << format_hex_no_prefix(VMA, AddressWidth) << " " << Type << "\n";
2504 void objdump::printSectionContents(const ObjectFile *Obj) {
2505 const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj);
2507 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
2508 StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName());
2509 uint64_t BaseAddr = Section.getAddress();
2510 uint64_t Size = Section.getSize();
2511 if (!Size)
2512 continue;
2514 outs() << "Contents of section ";
2515 StringRef SegmentName = getSegmentName(MachO, Section);
2516 if (!SegmentName.empty())
2517 outs() << SegmentName << ",";
2518 outs() << Name << ":\n";
2519 if (Section.isBSS()) {
2520 outs() << format("<skipping contents of bss section at [%04" PRIx64
2521 ", %04" PRIx64 ")>\n",
2522 BaseAddr, BaseAddr + Size);
2523 continue;
2526 StringRef Contents = unwrapOrError(Section.getContents(), Obj->getFileName());
2528 // Dump out the content as hex and printable ascii characters.
2529 for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) {
2530 outs() << format(" %04" PRIx64 " ", BaseAddr + Addr);
2531 // Dump line of hex.
2532 for (std::size_t I = 0; I < 16; ++I) {
2533 if (I != 0 && I % 4 == 0)
2534 outs() << ' ';
2535 if (Addr + I < End)
2536 outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true)
2537 << hexdigit(Contents[Addr + I] & 0xF, true);
2538 else
2539 outs() << " ";
2541 // Print ascii.
2542 outs() << " ";
2543 for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) {
2544 if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF))
2545 outs() << Contents[Addr + I];
2546 else
2547 outs() << ".";
2549 outs() << "\n";
2554 void Dumper::printSymbolTable(StringRef ArchiveName, StringRef ArchitectureName,
2555 bool DumpDynamic) {
2556 if (O.isCOFF() && !DumpDynamic) {
2557 outs() << "\nSYMBOL TABLE:\n";
2558 printCOFFSymbolTable(cast<const COFFObjectFile>(O));
2559 return;
2562 const StringRef FileName = O.getFileName();
2564 if (!DumpDynamic) {
2565 outs() << "\nSYMBOL TABLE:\n";
2566 for (auto I = O.symbol_begin(); I != O.symbol_end(); ++I)
2567 printSymbol(*I, {}, FileName, ArchiveName, ArchitectureName, DumpDynamic);
2568 return;
2571 outs() << "\nDYNAMIC SYMBOL TABLE:\n";
2572 if (!O.isELF()) {
2573 reportWarning(
2574 "this operation is not currently supported for this file format",
2575 FileName);
2576 return;
2579 const ELFObjectFileBase *ELF = cast<const ELFObjectFileBase>(&O);
2580 auto Symbols = ELF->getDynamicSymbolIterators();
2581 Expected<std::vector<VersionEntry>> SymbolVersionsOrErr =
2582 ELF->readDynsymVersions();
2583 if (!SymbolVersionsOrErr) {
2584 reportWarning(toString(SymbolVersionsOrErr.takeError()), FileName);
2585 SymbolVersionsOrErr = std::vector<VersionEntry>();
2586 (void)!SymbolVersionsOrErr;
2588 for (auto &Sym : Symbols)
2589 printSymbol(Sym, *SymbolVersionsOrErr, FileName, ArchiveName,
2590 ArchitectureName, DumpDynamic);
2593 void Dumper::printSymbol(const SymbolRef &Symbol,
2594 ArrayRef<VersionEntry> SymbolVersions,
2595 StringRef FileName, StringRef ArchiveName,
2596 StringRef ArchitectureName, bool DumpDynamic) {
2597 const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(&O);
2598 Expected<uint64_t> AddrOrErr = Symbol.getAddress();
2599 if (!AddrOrErr) {
2600 reportUniqueWarning(AddrOrErr.takeError());
2601 return;
2603 uint64_t Address = *AddrOrErr;
2604 section_iterator SecI = unwrapOrError(Symbol.getSection(), FileName);
2605 if (SecI != O.section_end() && shouldAdjustVA(*SecI))
2606 Address += AdjustVMA;
2607 if ((Address < StartAddress) || (Address > StopAddress))
2608 return;
2609 SymbolRef::Type Type =
2610 unwrapOrError(Symbol.getType(), FileName, ArchiveName, ArchitectureName);
2611 uint32_t Flags =
2612 unwrapOrError(Symbol.getFlags(), FileName, ArchiveName, ArchitectureName);
2614 // Don't ask a Mach-O STAB symbol for its section unless you know that
2615 // STAB symbol's section field refers to a valid section index. Otherwise
2616 // the symbol may error trying to load a section that does not exist.
2617 bool IsSTAB = false;
2618 if (MachO) {
2619 DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
2620 uint8_t NType =
2621 (MachO->is64Bit() ? MachO->getSymbol64TableEntry(SymDRI).n_type
2622 : MachO->getSymbolTableEntry(SymDRI).n_type);
2623 if (NType & MachO::N_STAB)
2624 IsSTAB = true;
2626 section_iterator Section = IsSTAB
2627 ? O.section_end()
2628 : unwrapOrError(Symbol.getSection(), FileName,
2629 ArchiveName, ArchitectureName);
2631 StringRef Name;
2632 if (Type == SymbolRef::ST_Debug && Section != O.section_end()) {
2633 if (Expected<StringRef> NameOrErr = Section->getName())
2634 Name = *NameOrErr;
2635 else
2636 consumeError(NameOrErr.takeError());
2638 } else {
2639 Name = unwrapOrError(Symbol.getName(), FileName, ArchiveName,
2640 ArchitectureName);
2643 bool Global = Flags & SymbolRef::SF_Global;
2644 bool Weak = Flags & SymbolRef::SF_Weak;
2645 bool Absolute = Flags & SymbolRef::SF_Absolute;
2646 bool Common = Flags & SymbolRef::SF_Common;
2647 bool Hidden = Flags & SymbolRef::SF_Hidden;
2649 char GlobLoc = ' ';
2650 if ((Section != O.section_end() || Absolute) && !Weak)
2651 GlobLoc = Global ? 'g' : 'l';
2652 char IFunc = ' ';
2653 if (O.isELF()) {
2654 if (ELFSymbolRef(Symbol).getELFType() == ELF::STT_GNU_IFUNC)
2655 IFunc = 'i';
2656 if (ELFSymbolRef(Symbol).getBinding() == ELF::STB_GNU_UNIQUE)
2657 GlobLoc = 'u';
2660 char Debug = ' ';
2661 if (DumpDynamic)
2662 Debug = 'D';
2663 else if (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
2664 Debug = 'd';
2666 char FileFunc = ' ';
2667 if (Type == SymbolRef::ST_File)
2668 FileFunc = 'f';
2669 else if (Type == SymbolRef::ST_Function)
2670 FileFunc = 'F';
2671 else if (Type == SymbolRef::ST_Data)
2672 FileFunc = 'O';
2674 const char *Fmt = O.getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
2676 outs() << format(Fmt, Address) << " "
2677 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
2678 << (Weak ? 'w' : ' ') // Weak?
2679 << ' ' // Constructor. Not supported yet.
2680 << ' ' // Warning. Not supported yet.
2681 << IFunc // Indirect reference to another symbol.
2682 << Debug // Debugging (d) or dynamic (D) symbol.
2683 << FileFunc // Name of function (F), file (f) or object (O).
2684 << ' ';
2685 if (Absolute) {
2686 outs() << "*ABS*";
2687 } else if (Common) {
2688 outs() << "*COM*";
2689 } else if (Section == O.section_end()) {
2690 if (O.isXCOFF()) {
2691 XCOFFSymbolRef XCOFFSym = cast<const XCOFFObjectFile>(O).toSymbolRef(
2692 Symbol.getRawDataRefImpl());
2693 if (XCOFF::N_DEBUG == XCOFFSym.getSectionNumber())
2694 outs() << "*DEBUG*";
2695 else
2696 outs() << "*UND*";
2697 } else
2698 outs() << "*UND*";
2699 } else {
2700 StringRef SegmentName = getSegmentName(MachO, *Section);
2701 if (!SegmentName.empty())
2702 outs() << SegmentName << ",";
2703 StringRef SectionName = unwrapOrError(Section->getName(), FileName);
2704 outs() << SectionName;
2705 if (O.isXCOFF()) {
2706 std::optional<SymbolRef> SymRef =
2707 getXCOFFSymbolContainingSymbolRef(cast<XCOFFObjectFile>(O), Symbol);
2708 if (SymRef) {
2710 Expected<StringRef> NameOrErr = SymRef->getName();
2712 if (NameOrErr) {
2713 outs() << " (csect:";
2714 std::string SymName =
2715 Demangle ? demangle(*NameOrErr) : NameOrErr->str();
2717 if (SymbolDescription)
2718 SymName = getXCOFFSymbolDescription(createSymbolInfo(O, *SymRef),
2719 SymName);
2721 outs() << ' ' << SymName;
2722 outs() << ") ";
2723 } else
2724 reportWarning(toString(NameOrErr.takeError()), FileName);
2729 if (Common)
2730 outs() << '\t' << format(Fmt, static_cast<uint64_t>(Symbol.getAlignment()));
2731 else if (O.isXCOFF())
2732 outs() << '\t'
2733 << format(Fmt, cast<XCOFFObjectFile>(O).getSymbolSize(
2734 Symbol.getRawDataRefImpl()));
2735 else if (O.isELF())
2736 outs() << '\t' << format(Fmt, ELFSymbolRef(Symbol).getSize());
2738 if (O.isELF()) {
2739 if (!SymbolVersions.empty()) {
2740 const VersionEntry &Ver =
2741 SymbolVersions[Symbol.getRawDataRefImpl().d.b - 1];
2742 std::string Str;
2743 if (!Ver.Name.empty())
2744 Str = Ver.IsVerDef ? ' ' + Ver.Name : '(' + Ver.Name + ')';
2745 outs() << ' ' << left_justify(Str, 12);
2748 uint8_t Other = ELFSymbolRef(Symbol).getOther();
2749 switch (Other) {
2750 case ELF::STV_DEFAULT:
2751 break;
2752 case ELF::STV_INTERNAL:
2753 outs() << " .internal";
2754 break;
2755 case ELF::STV_HIDDEN:
2756 outs() << " .hidden";
2757 break;
2758 case ELF::STV_PROTECTED:
2759 outs() << " .protected";
2760 break;
2761 default:
2762 outs() << format(" 0x%02x", Other);
2763 break;
2765 } else if (Hidden) {
2766 outs() << " .hidden";
2769 std::string SymName = Demangle ? demangle(Name) : Name.str();
2770 if (O.isXCOFF() && SymbolDescription)
2771 SymName = getXCOFFSymbolDescription(createSymbolInfo(O, Symbol), SymName);
2773 outs() << ' ' << SymName << '\n';
2776 static void printUnwindInfo(const ObjectFile *O) {
2777 outs() << "Unwind info:\n\n";
2779 if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O))
2780 printCOFFUnwindInfo(Coff);
2781 else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O))
2782 printMachOUnwindInfo(MachO);
2783 else
2784 // TODO: Extract DWARF dump tool to objdump.
2785 WithColor::error(errs(), ToolName)
2786 << "This operation is only currently supported "
2787 "for COFF and MachO object files.\n";
2790 /// Dump the raw contents of the __clangast section so the output can be piped
2791 /// into llvm-bcanalyzer.
2792 static void printRawClangAST(const ObjectFile *Obj) {
2793 if (outs().is_displayed()) {
2794 WithColor::error(errs(), ToolName)
2795 << "The -raw-clang-ast option will dump the raw binary contents of "
2796 "the clang ast section.\n"
2797 "Please redirect the output to a file or another program such as "
2798 "llvm-bcanalyzer.\n";
2799 return;
2802 StringRef ClangASTSectionName("__clangast");
2803 if (Obj->isCOFF()) {
2804 ClangASTSectionName = "clangast";
2807 std::optional<object::SectionRef> ClangASTSection;
2808 for (auto Sec : ToolSectionFilter(*Obj)) {
2809 StringRef Name;
2810 if (Expected<StringRef> NameOrErr = Sec.getName())
2811 Name = *NameOrErr;
2812 else
2813 consumeError(NameOrErr.takeError());
2815 if (Name == ClangASTSectionName) {
2816 ClangASTSection = Sec;
2817 break;
2820 if (!ClangASTSection)
2821 return;
2823 StringRef ClangASTContents =
2824 unwrapOrError(ClangASTSection->getContents(), Obj->getFileName());
2825 outs().write(ClangASTContents.data(), ClangASTContents.size());
2828 static void printFaultMaps(const ObjectFile *Obj) {
2829 StringRef FaultMapSectionName;
2831 if (Obj->isELF()) {
2832 FaultMapSectionName = ".llvm_faultmaps";
2833 } else if (Obj->isMachO()) {
2834 FaultMapSectionName = "__llvm_faultmaps";
2835 } else {
2836 WithColor::error(errs(), ToolName)
2837 << "This operation is only currently supported "
2838 "for ELF and Mach-O executable files.\n";
2839 return;
2842 std::optional<object::SectionRef> FaultMapSection;
2844 for (auto Sec : ToolSectionFilter(*Obj)) {
2845 StringRef Name;
2846 if (Expected<StringRef> NameOrErr = Sec.getName())
2847 Name = *NameOrErr;
2848 else
2849 consumeError(NameOrErr.takeError());
2851 if (Name == FaultMapSectionName) {
2852 FaultMapSection = Sec;
2853 break;
2857 outs() << "FaultMap table:\n";
2859 if (!FaultMapSection) {
2860 outs() << "<not found>\n";
2861 return;
2864 StringRef FaultMapContents =
2865 unwrapOrError(FaultMapSection->getContents(), Obj->getFileName());
2866 FaultMapParser FMP(FaultMapContents.bytes_begin(),
2867 FaultMapContents.bytes_end());
2869 outs() << FMP;
2872 void Dumper::printPrivateHeaders() {
2873 reportError(O.getFileName(), "Invalid/Unsupported object file format");
2876 static void printFileHeaders(const ObjectFile *O) {
2877 if (!O->isELF() && !O->isCOFF())
2878 reportError(O->getFileName(), "Invalid/Unsupported object file format");
2880 Triple::ArchType AT = O->getArch();
2881 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
2882 uint64_t Address = unwrapOrError(O->getStartAddress(), O->getFileName());
2884 StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
2885 outs() << "start address: "
2886 << "0x" << format(Fmt.data(), Address) << "\n";
2889 static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
2890 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
2891 if (!ModeOrErr) {
2892 WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n";
2893 consumeError(ModeOrErr.takeError());
2894 return;
2896 sys::fs::perms Mode = ModeOrErr.get();
2897 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2898 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2899 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2900 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2901 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2902 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2903 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2904 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2905 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2907 outs() << " ";
2909 outs() << format("%d/%d %6" PRId64 " ", unwrapOrError(C.getUID(), Filename),
2910 unwrapOrError(C.getGID(), Filename),
2911 unwrapOrError(C.getRawSize(), Filename));
2913 StringRef RawLastModified = C.getRawLastModified();
2914 unsigned Seconds;
2915 if (RawLastModified.getAsInteger(10, Seconds))
2916 outs() << "(date: \"" << RawLastModified
2917 << "\" contains non-decimal chars) ";
2918 else {
2919 // Since ctime(3) returns a 26 character string of the form:
2920 // "Sun Sep 16 01:03:52 1973\n\0"
2921 // just print 24 characters.
2922 time_t t = Seconds;
2923 outs() << format("%.24s ", ctime(&t));
2926 StringRef Name = "";
2927 Expected<StringRef> NameOrErr = C.getName();
2928 if (!NameOrErr) {
2929 consumeError(NameOrErr.takeError());
2930 Name = unwrapOrError(C.getRawName(), Filename);
2931 } else {
2932 Name = NameOrErr.get();
2934 outs() << Name << "\n";
2937 // For ELF only now.
2938 static bool shouldWarnForInvalidStartStopAddress(ObjectFile *Obj) {
2939 if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj)) {
2940 if (Elf->getEType() != ELF::ET_REL)
2941 return true;
2943 return false;
2946 static void checkForInvalidStartStopAddress(ObjectFile *Obj,
2947 uint64_t Start, uint64_t Stop) {
2948 if (!shouldWarnForInvalidStartStopAddress(Obj))
2949 return;
2951 for (const SectionRef &Section : Obj->sections())
2952 if (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC) {
2953 uint64_t BaseAddr = Section.getAddress();
2954 uint64_t Size = Section.getSize();
2955 if ((Start < BaseAddr + Size) && Stop > BaseAddr)
2956 return;
2959 if (!HasStartAddressFlag)
2960 reportWarning("no section has address less than 0x" +
2961 Twine::utohexstr(Stop) + " specified by --stop-address",
2962 Obj->getFileName());
2963 else if (!HasStopAddressFlag)
2964 reportWarning("no section has address greater than or equal to 0x" +
2965 Twine::utohexstr(Start) + " specified by --start-address",
2966 Obj->getFileName());
2967 else
2968 reportWarning("no section overlaps the range [0x" +
2969 Twine::utohexstr(Start) + ",0x" + Twine::utohexstr(Stop) +
2970 ") specified by --start-address/--stop-address",
2971 Obj->getFileName());
2974 static void dumpObject(ObjectFile *O, const Archive *A = nullptr,
2975 const Archive::Child *C = nullptr) {
2976 Expected<std::unique_ptr<Dumper>> DumperOrErr = createDumper(*O);
2977 if (!DumperOrErr) {
2978 reportError(DumperOrErr.takeError(), O->getFileName(),
2979 A ? A->getFileName() : "");
2980 return;
2982 Dumper &D = **DumperOrErr;
2984 // Avoid other output when using a raw option.
2985 if (!RawClangAST) {
2986 outs() << '\n';
2987 if (A)
2988 outs() << A->getFileName() << "(" << O->getFileName() << ")";
2989 else
2990 outs() << O->getFileName();
2991 outs() << ":\tfile format " << O->getFileFormatName().lower() << "\n";
2994 if (HasStartAddressFlag || HasStopAddressFlag)
2995 checkForInvalidStartStopAddress(O, StartAddress, StopAddress);
2997 // TODO: Change print* free functions to Dumper member functions to utilitize
2998 // stateful functions like reportUniqueWarning.
3000 // Note: the order here matches GNU objdump for compatability.
3001 StringRef ArchiveName = A ? A->getFileName() : "";
3002 if (ArchiveHeaders && !MachOOpt && C)
3003 printArchiveChild(ArchiveName, *C);
3004 if (FileHeaders)
3005 printFileHeaders(O);
3006 if (PrivateHeaders || FirstPrivateHeader)
3007 D.printPrivateHeaders();
3008 if (SectionHeaders)
3009 printSectionHeaders(*O);
3010 if (SymbolTable)
3011 D.printSymbolTable(ArchiveName);
3012 if (DynamicSymbolTable)
3013 D.printSymbolTable(ArchiveName, /*ArchitectureName=*/"",
3014 /*DumpDynamic=*/true);
3015 if (DwarfDumpType != DIDT_Null) {
3016 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O);
3017 // Dump the complete DWARF structure.
3018 DIDumpOptions DumpOpts;
3019 DumpOpts.DumpType = DwarfDumpType;
3020 DICtx->dump(outs(), DumpOpts);
3022 if (Relocations && !Disassemble)
3023 D.printRelocations();
3024 if (DynamicRelocations)
3025 D.printDynamicRelocations();
3026 if (SectionContents)
3027 printSectionContents(O);
3028 if (Disassemble)
3029 disassembleObject(O, Relocations);
3030 if (UnwindInfo)
3031 printUnwindInfo(O);
3033 // Mach-O specific options:
3034 if (ExportsTrie)
3035 printExportsTrie(O);
3036 if (Rebase)
3037 printRebaseTable(O);
3038 if (Bind)
3039 printBindTable(O);
3040 if (LazyBind)
3041 printLazyBindTable(O);
3042 if (WeakBind)
3043 printWeakBindTable(O);
3045 // Other special sections:
3046 if (RawClangAST)
3047 printRawClangAST(O);
3048 if (FaultMapSection)
3049 printFaultMaps(O);
3050 if (Offloading)
3051 dumpOffloadBinary(*O);
3054 static void dumpObject(const COFFImportFile *I, const Archive *A,
3055 const Archive::Child *C = nullptr) {
3056 StringRef ArchiveName = A ? A->getFileName() : "";
3058 // Avoid other output when using a raw option.
3059 if (!RawClangAST)
3060 outs() << '\n'
3061 << ArchiveName << "(" << I->getFileName() << ")"
3062 << ":\tfile format COFF-import-file"
3063 << "\n\n";
3065 if (ArchiveHeaders && !MachOOpt && C)
3066 printArchiveChild(ArchiveName, *C);
3067 if (SymbolTable)
3068 printCOFFSymbolTable(*I);
3071 /// Dump each object file in \a a;
3072 static void dumpArchive(const Archive *A) {
3073 Error Err = Error::success();
3074 unsigned I = -1;
3075 for (auto &C : A->children(Err)) {
3076 ++I;
3077 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
3078 if (!ChildOrErr) {
3079 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
3080 reportError(std::move(E), getFileNameForError(C, I), A->getFileName());
3081 continue;
3083 if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
3084 dumpObject(O, A, &C);
3085 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
3086 dumpObject(I, A, &C);
3087 else
3088 reportError(errorCodeToError(object_error::invalid_file_type),
3089 A->getFileName());
3091 if (Err)
3092 reportError(std::move(Err), A->getFileName());
3095 /// Open file and figure out how to dump it.
3096 static void dumpInput(StringRef file) {
3097 // If we are using the Mach-O specific object file parser, then let it parse
3098 // the file and process the command line options. So the -arch flags can
3099 // be used to select specific slices, etc.
3100 if (MachOOpt) {
3101 parseInputMachO(file);
3102 return;
3105 // Attempt to open the binary.
3106 OwningBinary<Binary> OBinary = unwrapOrError(createBinary(file), file);
3107 Binary &Binary = *OBinary.getBinary();
3109 if (Archive *A = dyn_cast<Archive>(&Binary))
3110 dumpArchive(A);
3111 else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary))
3112 dumpObject(O);
3113 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
3114 parseInputMachO(UB);
3115 else if (OffloadBinary *OB = dyn_cast<OffloadBinary>(&Binary))
3116 dumpOffloadSections(*OB);
3117 else
3118 reportError(errorCodeToError(object_error::invalid_file_type), file);
3121 template <typename T>
3122 static void parseIntArg(const llvm::opt::InputArgList &InputArgs, int ID,
3123 T &Value) {
3124 if (const opt::Arg *A = InputArgs.getLastArg(ID)) {
3125 StringRef V(A->getValue());
3126 if (!llvm::to_integer(V, Value, 0)) {
3127 reportCmdLineError(A->getSpelling() +
3128 ": expected a non-negative integer, but got '" + V +
3129 "'");
3134 static object::BuildID parseBuildIDArg(const opt::Arg *A) {
3135 StringRef V(A->getValue());
3136 object::BuildID BID = parseBuildID(V);
3137 if (BID.empty())
3138 reportCmdLineError(A->getSpelling() + ": expected a build ID, but got '" +
3139 V + "'");
3140 return BID;
3143 void objdump::invalidArgValue(const opt::Arg *A) {
3144 reportCmdLineError("'" + StringRef(A->getValue()) +
3145 "' is not a valid value for '" + A->getSpelling() + "'");
3148 static std::vector<std::string>
3149 commaSeparatedValues(const llvm::opt::InputArgList &InputArgs, int ID) {
3150 std::vector<std::string> Values;
3151 for (StringRef Value : InputArgs.getAllArgValues(ID)) {
3152 llvm::SmallVector<StringRef, 2> SplitValues;
3153 llvm::SplitString(Value, SplitValues, ",");
3154 for (StringRef SplitValue : SplitValues)
3155 Values.push_back(SplitValue.str());
3157 return Values;
3160 static void parseOtoolOptions(const llvm::opt::InputArgList &InputArgs) {
3161 MachOOpt = true;
3162 FullLeadingAddr = true;
3163 PrintImmHex = true;
3165 ArchName = InputArgs.getLastArgValue(OTOOL_arch).str();
3166 LinkOptHints = InputArgs.hasArg(OTOOL_C);
3167 if (InputArgs.hasArg(OTOOL_d))
3168 FilterSections.push_back("__DATA,__data");
3169 DylibId = InputArgs.hasArg(OTOOL_D);
3170 UniversalHeaders = InputArgs.hasArg(OTOOL_f);
3171 DataInCode = InputArgs.hasArg(OTOOL_G);
3172 FirstPrivateHeader = InputArgs.hasArg(OTOOL_h);
3173 IndirectSymbols = InputArgs.hasArg(OTOOL_I);
3174 ShowRawInsn = InputArgs.hasArg(OTOOL_j);
3175 PrivateHeaders = InputArgs.hasArg(OTOOL_l);
3176 DylibsUsed = InputArgs.hasArg(OTOOL_L);
3177 MCPU = InputArgs.getLastArgValue(OTOOL_mcpu_EQ).str();
3178 ObjcMetaData = InputArgs.hasArg(OTOOL_o);
3179 DisSymName = InputArgs.getLastArgValue(OTOOL_p).str();
3180 InfoPlist = InputArgs.hasArg(OTOOL_P);
3181 Relocations = InputArgs.hasArg(OTOOL_r);
3182 if (const Arg *A = InputArgs.getLastArg(OTOOL_s)) {
3183 auto Filter = (A->getValue(0) + StringRef(",") + A->getValue(1)).str();
3184 FilterSections.push_back(Filter);
3186 if (InputArgs.hasArg(OTOOL_t))
3187 FilterSections.push_back("__TEXT,__text");
3188 Verbose = InputArgs.hasArg(OTOOL_v) || InputArgs.hasArg(OTOOL_V) ||
3189 InputArgs.hasArg(OTOOL_o);
3190 SymbolicOperands = InputArgs.hasArg(OTOOL_V);
3191 if (InputArgs.hasArg(OTOOL_x))
3192 FilterSections.push_back(",__text");
3193 LeadingAddr = LeadingHeaders = !InputArgs.hasArg(OTOOL_X);
3195 ChainedFixups = InputArgs.hasArg(OTOOL_chained_fixups);
3196 DyldInfo = InputArgs.hasArg(OTOOL_dyld_info);
3198 InputFilenames = InputArgs.getAllArgValues(OTOOL_INPUT);
3199 if (InputFilenames.empty())
3200 reportCmdLineError("no input file");
3202 for (const Arg *A : InputArgs) {
3203 const Option &O = A->getOption();
3204 if (O.getGroup().isValid() && O.getGroup().getID() == OTOOL_grp_obsolete) {
3205 reportCmdLineWarning(O.getPrefixedName() +
3206 " is obsolete and not implemented");
3211 static void parseObjdumpOptions(const llvm::opt::InputArgList &InputArgs) {
3212 parseIntArg(InputArgs, OBJDUMP_adjust_vma_EQ, AdjustVMA);
3213 AllHeaders = InputArgs.hasArg(OBJDUMP_all_headers);
3214 ArchName = InputArgs.getLastArgValue(OBJDUMP_arch_name_EQ).str();
3215 ArchiveHeaders = InputArgs.hasArg(OBJDUMP_archive_headers);
3216 Demangle = InputArgs.hasArg(OBJDUMP_demangle);
3217 Disassemble = InputArgs.hasArg(OBJDUMP_disassemble);
3218 DisassembleAll = InputArgs.hasArg(OBJDUMP_disassemble_all);
3219 SymbolDescription = InputArgs.hasArg(OBJDUMP_symbol_description);
3220 TracebackTable = InputArgs.hasArg(OBJDUMP_traceback_table);
3221 DisassembleSymbols =
3222 commaSeparatedValues(InputArgs, OBJDUMP_disassemble_symbols_EQ);
3223 DisassembleZeroes = InputArgs.hasArg(OBJDUMP_disassemble_zeroes);
3224 if (const opt::Arg *A = InputArgs.getLastArg(OBJDUMP_dwarf_EQ)) {
3225 DwarfDumpType = StringSwitch<DIDumpType>(A->getValue())
3226 .Case("frames", DIDT_DebugFrame)
3227 .Default(DIDT_Null);
3228 if (DwarfDumpType == DIDT_Null)
3229 invalidArgValue(A);
3231 DynamicRelocations = InputArgs.hasArg(OBJDUMP_dynamic_reloc);
3232 FaultMapSection = InputArgs.hasArg(OBJDUMP_fault_map_section);
3233 Offloading = InputArgs.hasArg(OBJDUMP_offloading);
3234 FileHeaders = InputArgs.hasArg(OBJDUMP_file_headers);
3235 SectionContents = InputArgs.hasArg(OBJDUMP_full_contents);
3236 PrintLines = InputArgs.hasArg(OBJDUMP_line_numbers);
3237 InputFilenames = InputArgs.getAllArgValues(OBJDUMP_INPUT);
3238 MachOOpt = InputArgs.hasArg(OBJDUMP_macho);
3239 MCPU = InputArgs.getLastArgValue(OBJDUMP_mcpu_EQ).str();
3240 MAttrs = commaSeparatedValues(InputArgs, OBJDUMP_mattr_EQ);
3241 ShowRawInsn = !InputArgs.hasArg(OBJDUMP_no_show_raw_insn);
3242 LeadingAddr = !InputArgs.hasArg(OBJDUMP_no_leading_addr);
3243 RawClangAST = InputArgs.hasArg(OBJDUMP_raw_clang_ast);
3244 Relocations = InputArgs.hasArg(OBJDUMP_reloc);
3245 PrintImmHex =
3246 InputArgs.hasFlag(OBJDUMP_print_imm_hex, OBJDUMP_no_print_imm_hex, true);
3247 PrivateHeaders = InputArgs.hasArg(OBJDUMP_private_headers);
3248 FilterSections = InputArgs.getAllArgValues(OBJDUMP_section_EQ);
3249 SectionHeaders = InputArgs.hasArg(OBJDUMP_section_headers);
3250 ShowAllSymbols = InputArgs.hasArg(OBJDUMP_show_all_symbols);
3251 ShowLMA = InputArgs.hasArg(OBJDUMP_show_lma);
3252 PrintSource = InputArgs.hasArg(OBJDUMP_source);
3253 parseIntArg(InputArgs, OBJDUMP_start_address_EQ, StartAddress);
3254 HasStartAddressFlag = InputArgs.hasArg(OBJDUMP_start_address_EQ);
3255 parseIntArg(InputArgs, OBJDUMP_stop_address_EQ, StopAddress);
3256 HasStopAddressFlag = InputArgs.hasArg(OBJDUMP_stop_address_EQ);
3257 SymbolTable = InputArgs.hasArg(OBJDUMP_syms);
3258 SymbolizeOperands = InputArgs.hasArg(OBJDUMP_symbolize_operands);
3259 DynamicSymbolTable = InputArgs.hasArg(OBJDUMP_dynamic_syms);
3260 TripleName = InputArgs.getLastArgValue(OBJDUMP_triple_EQ).str();
3261 UnwindInfo = InputArgs.hasArg(OBJDUMP_unwind_info);
3262 Wide = InputArgs.hasArg(OBJDUMP_wide);
3263 Prefix = InputArgs.getLastArgValue(OBJDUMP_prefix).str();
3264 parseIntArg(InputArgs, OBJDUMP_prefix_strip, PrefixStrip);
3265 if (const opt::Arg *A = InputArgs.getLastArg(OBJDUMP_debug_vars_EQ)) {
3266 DbgVariables = StringSwitch<DebugVarsFormat>(A->getValue())
3267 .Case("ascii", DVASCII)
3268 .Case("unicode", DVUnicode)
3269 .Default(DVInvalid);
3270 if (DbgVariables == DVInvalid)
3271 invalidArgValue(A);
3273 if (const opt::Arg *A = InputArgs.getLastArg(OBJDUMP_disassembler_color_EQ)) {
3274 DisassemblyColor = StringSwitch<ColorOutput>(A->getValue())
3275 .Case("on", ColorOutput::Enable)
3276 .Case("off", ColorOutput::Disable)
3277 .Case("terminal", ColorOutput::Auto)
3278 .Default(ColorOutput::Invalid);
3279 if (DisassemblyColor == ColorOutput::Invalid)
3280 invalidArgValue(A);
3283 parseIntArg(InputArgs, OBJDUMP_debug_vars_indent_EQ, DbgIndent);
3285 parseMachOOptions(InputArgs);
3287 // Parse -M (--disassembler-options) and deprecated
3288 // --x86-asm-syntax={att,intel}.
3290 // Note, for x86, the asm dialect (AssemblerDialect) is initialized when the
3291 // MCAsmInfo is constructed. MCInstPrinter::applyTargetSpecificCLOption is
3292 // called too late. For now we have to use the internal cl::opt option.
3293 const char *AsmSyntax = nullptr;
3294 for (const auto *A : InputArgs.filtered(OBJDUMP_disassembler_options_EQ,
3295 OBJDUMP_x86_asm_syntax_att,
3296 OBJDUMP_x86_asm_syntax_intel)) {
3297 switch (A->getOption().getID()) {
3298 case OBJDUMP_x86_asm_syntax_att:
3299 AsmSyntax = "--x86-asm-syntax=att";
3300 continue;
3301 case OBJDUMP_x86_asm_syntax_intel:
3302 AsmSyntax = "--x86-asm-syntax=intel";
3303 continue;
3306 SmallVector<StringRef, 2> Values;
3307 llvm::SplitString(A->getValue(), Values, ",");
3308 for (StringRef V : Values) {
3309 if (V == "att")
3310 AsmSyntax = "--x86-asm-syntax=att";
3311 else if (V == "intel")
3312 AsmSyntax = "--x86-asm-syntax=intel";
3313 else
3314 DisassemblerOptions.push_back(V.str());
3317 if (AsmSyntax) {
3318 const char *Argv[] = {"llvm-objdump", AsmSyntax};
3319 llvm::cl::ParseCommandLineOptions(2, Argv);
3322 // Look up any provided build IDs, then append them to the input filenames.
3323 for (const opt::Arg *A : InputArgs.filtered(OBJDUMP_build_id)) {
3324 object::BuildID BuildID = parseBuildIDArg(A);
3325 std::optional<std::string> Path = BIDFetcher->fetch(BuildID);
3326 if (!Path) {
3327 reportCmdLineError(A->getSpelling() + ": could not find build ID '" +
3328 A->getValue() + "'");
3330 InputFilenames.push_back(std::move(*Path));
3333 // objdump defaults to a.out if no filenames specified.
3334 if (InputFilenames.empty())
3335 InputFilenames.push_back("a.out");
3338 int llvm_objdump_main(int argc, char **argv, const llvm::ToolContext &) {
3339 using namespace llvm;
3340 InitLLVM X(argc, argv);
3342 ToolName = argv[0];
3343 std::unique_ptr<CommonOptTable> T;
3344 OptSpecifier Unknown, HelpFlag, HelpHiddenFlag, VersionFlag;
3346 StringRef Stem = sys::path::stem(ToolName);
3347 auto Is = [=](StringRef Tool) {
3348 // We need to recognize the following filenames:
3350 // llvm-objdump -> objdump
3351 // llvm-otool-10.exe -> otool
3352 // powerpc64-unknown-freebsd13-objdump -> objdump
3353 auto I = Stem.rfind_insensitive(Tool);
3354 return I != StringRef::npos &&
3355 (I + Tool.size() == Stem.size() || !isAlnum(Stem[I + Tool.size()]));
3357 if (Is("otool")) {
3358 T = std::make_unique<OtoolOptTable>();
3359 Unknown = OTOOL_UNKNOWN;
3360 HelpFlag = OTOOL_help;
3361 HelpHiddenFlag = OTOOL_help_hidden;
3362 VersionFlag = OTOOL_version;
3363 } else {
3364 T = std::make_unique<ObjdumpOptTable>();
3365 Unknown = OBJDUMP_UNKNOWN;
3366 HelpFlag = OBJDUMP_help;
3367 HelpHiddenFlag = OBJDUMP_help_hidden;
3368 VersionFlag = OBJDUMP_version;
3371 BumpPtrAllocator A;
3372 StringSaver Saver(A);
3373 opt::InputArgList InputArgs =
3374 T->parseArgs(argc, argv, Unknown, Saver,
3375 [&](StringRef Msg) { reportCmdLineError(Msg); });
3377 if (InputArgs.size() == 0 || InputArgs.hasArg(HelpFlag)) {
3378 T->printHelp(ToolName);
3379 return 0;
3381 if (InputArgs.hasArg(HelpHiddenFlag)) {
3382 T->printHelp(ToolName, /*ShowHidden=*/true);
3383 return 0;
3386 // Initialize targets and assembly printers/parsers.
3387 InitializeAllTargetInfos();
3388 InitializeAllTargetMCs();
3389 InitializeAllDisassemblers();
3391 if (InputArgs.hasArg(VersionFlag)) {
3392 cl::PrintVersionMessage();
3393 if (!Is("otool")) {
3394 outs() << '\n';
3395 TargetRegistry::printRegisteredTargetsForVersion(outs());
3397 return 0;
3400 // Initialize debuginfod.
3401 const bool ShouldUseDebuginfodByDefault =
3402 InputArgs.hasArg(OBJDUMP_build_id) || canUseDebuginfod();
3403 std::vector<std::string> DebugFileDirectories =
3404 InputArgs.getAllArgValues(OBJDUMP_debug_file_directory);
3405 if (InputArgs.hasFlag(OBJDUMP_debuginfod, OBJDUMP_no_debuginfod,
3406 ShouldUseDebuginfodByDefault)) {
3407 HTTPClient::initialize();
3408 BIDFetcher =
3409 std::make_unique<DebuginfodFetcher>(std::move(DebugFileDirectories));
3410 } else {
3411 BIDFetcher =
3412 std::make_unique<BuildIDFetcher>(std::move(DebugFileDirectories));
3415 if (Is("otool"))
3416 parseOtoolOptions(InputArgs);
3417 else
3418 parseObjdumpOptions(InputArgs);
3420 if (StartAddress >= StopAddress)
3421 reportCmdLineError("start address should be less than stop address");
3423 // Removes trailing separators from prefix.
3424 while (!Prefix.empty() && sys::path::is_separator(Prefix.back()))
3425 Prefix.pop_back();
3427 if (AllHeaders)
3428 ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations =
3429 SectionHeaders = SymbolTable = true;
3431 if (DisassembleAll || PrintSource || PrintLines || TracebackTable ||
3432 !DisassembleSymbols.empty())
3433 Disassemble = true;
3435 if (!ArchiveHeaders && !Disassemble && DwarfDumpType == DIDT_Null &&
3436 !DynamicRelocations && !FileHeaders && !PrivateHeaders && !RawClangAST &&
3437 !Relocations && !SectionHeaders && !SectionContents && !SymbolTable &&
3438 !DynamicSymbolTable && !UnwindInfo && !FaultMapSection && !Offloading &&
3439 !(MachOOpt &&
3440 (Bind || DataInCode || ChainedFixups || DyldInfo || DylibId ||
3441 DylibsUsed || ExportsTrie || FirstPrivateHeader ||
3442 FunctionStartsType != FunctionStartsMode::None || IndirectSymbols ||
3443 InfoPlist || LazyBind || LinkOptHints || ObjcMetaData || Rebase ||
3444 Rpaths || UniversalHeaders || WeakBind || !FilterSections.empty()))) {
3445 T->printHelp(ToolName);
3446 return 2;
3449 DisasmSymbolSet.insert(DisassembleSymbols.begin(), DisassembleSymbols.end());
3451 llvm::for_each(InputFilenames, dumpInput);
3453 warnOnNoMatchForSections();
3455 return EXIT_SUCCESS;