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.
12//
13// The flags and output of this program should be near identical to those of
14// binutils objdump.
15//
16//===----------------------------------------------------------------------===//
17
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/DenseMap.h"
28#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/SetOperations.h"
30#include "llvm/ADT/StringExtras.h"
31#include "llvm/ADT/Twine.h"
32#include "llvm/BinaryFormat/Wasm.h"
33#include "llvm/DebugInfo/BTF/BTFParser.h"
34#include "llvm/DebugInfo/DWARF/DWARFContext.h"
35#include "llvm/DebugInfo/Symbolize/Symbolize.h"
36#include "llvm/Debuginfod/BuildIDFetcher.h"
37#include "llvm/Debuginfod/Debuginfod.h"
38#include "llvm/Demangle/Demangle.h"
39#include "llvm/HTTP/HTTPClient.h"
40#include "llvm/MC/MCAsmInfo.h"
41#include "llvm/MC/MCContext.h"
42#include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
43#include "llvm/MC/MCInst.h"
44#include "llvm/MC/MCInstPrinter.h"
45#include "llvm/MC/MCInstrAnalysis.h"
46#include "llvm/MC/MCInstrInfo.h"
47#include "llvm/MC/MCObjectFileInfo.h"
48#include "llvm/MC/MCRegisterInfo.h"
49#include "llvm/MC/MCTargetOptions.h"
50#include "llvm/MC/TargetRegistry.h"
51#include "llvm/Object/BuildID.h"
52#include "llvm/Object/COFF.h"
53#include "llvm/Object/COFFImportFile.h"
54#include "llvm/Object/DXContainer.h"
55#include "llvm/Object/ELFObjectFile.h"
56#include "llvm/Object/ELFTypes.h"
57#include "llvm/Object/FaultMapParser.h"
58#include "llvm/Object/MachO.h"
59#include "llvm/Object/MachOUniversal.h"
60#include "llvm/Object/OffloadBinary.h"
61#include "llvm/Object/Wasm.h"
62#include "llvm/Option/Arg.h"
63#include "llvm/Option/ArgList.h"
64#include "llvm/Option/Option.h"
65#include "llvm/Support/Casting.h"
66#include "llvm/Support/Debug.h"
67#include "llvm/Support/Driver.h"
68#include "llvm/Support/Errc.h"
69#include "llvm/Support/FileSystem.h"
70#include "llvm/Support/Format.h"
71#include "llvm/Support/MemoryBuffer.h"
72#include "llvm/Support/SourceMgr.h"
73#include "llvm/Support/StringSaver.h"
74#include "llvm/Support/TargetSelect.h"
75#include "llvm/Support/WithColor.h"
76#include "llvm/Support/raw_ostream.h"
77#include "llvm/TargetParser/AVRTargetParser.h"
78#include "llvm/TargetParser/Host.h"
79#include "llvm/TargetParser/RISCVISAInfo.h"
80#include "llvm/TargetParser/Triple.h"
81#include <algorithm>
82#include <cctype>
83#include <cstring>
84#include <optional>
85#include <set>
86#include <system_error>
87
88using namespace llvm;
89using namespace llvm::object;
90using namespace llvm::objdump;
91using namespace llvm::opt;
92
93namespace {
94
95class CommonOptTable : public opt::OptTable {
96public:
97 CommonOptTable(const Tables &T, const char *Usage, const char *Description)
98 : opt::OptTable(T), Usage(Usage), Description(Description) {
99 setGroupedShortOptions(true);
100 }
101
102 void printHelp(StringRef Argv0, bool ShowHidden = false) const {
103 Argv0 = sys::path::filename(path: Argv0);
104 opt::OptTable::printHelp(OS&: outs(), Usage: (Argv0 + Usage).str().c_str(), Title: Description,
105 ShowHidden, ShowAllAliases: ShowHidden);
106 // TODO Replace this with OptTable API once it adds extrahelp support.
107 outs() << "\nPass @FILE as argument to read options from FILE.\n";
108 }
109
110private:
111 const char *Usage;
112 const char *Description;
113};
114
115// ObjdumpOptID is in ObjdumpOptID.h
116namespace objdump_opt {
117#define OPTTABLE_CODE
118#include "ObjdumpOpts.inc"
119} // namespace objdump_opt
120
121class ObjdumpOptTable : public CommonOptTable {
122public:
123 ObjdumpOptTable()
124 : CommonOptTable(objdump_opt::optionTables(),
125 " [options] <input object files>",
126 "llvm object file dumper") {}
127};
128
129enum OtoolOptID {
130 OTOOL_INVALID = 0, // This is not an option ID.
131#define OPTION(...) LLVM_MAKE_OPT_ID_WITH_ID_PREFIX(OTOOL_, __VA_ARGS__),
132#include "OtoolOpts.inc"
133#undef OPTION
134};
135
136namespace otool {
137#define OPTTABLE_CODE
138#include "OtoolOpts.inc"
139} // namespace otool
140
141class OtoolOptTable : public CommonOptTable {
142public:
143 OtoolOptTable()
144 : CommonOptTable(otool::optionTables(), " [option...] [file...]",
145 "Mach-O object file displaying tool") {}
146};
147
148struct BBAddrMapLabel {
149 std::string BlockLabel;
150 std::string PGOAnalysis;
151};
152
153// This class represents the BBAddrMap and PGOMap associated with a single
154// function.
155class BBAddrMapFunctionEntry {
156public:
157 BBAddrMapFunctionEntry(BBAddrMap AddrMap, PGOAnalysisMap PGOMap)
158 : AddrMap(std::move(AddrMap)), PGOMap(std::move(PGOMap)) {}
159
160 const BBAddrMap &getAddrMap() const { return AddrMap; }
161
162 // Returns the PGO string associated with the entry of index `PGOBBEntryIndex`
163 // in `PGOMap`. If PrettyPGOAnalysis is true, prints BFI as relative frequency
164 // and BPI as percentage. Otherwise raw values are displayed.
165 std::string constructPGOLabelString(size_t PGOBBEntryIndex,
166 bool PrettyPGOAnalysis) const {
167 if (!PGOMap.FeatEnable.hasPGOAnalysis())
168 return "";
169 std::string PGOString;
170 raw_string_ostream PGOSS(PGOString);
171
172 PGOSS << " (";
173 if (PGOMap.FeatEnable.FuncEntryCount && PGOBBEntryIndex == 0) {
174 PGOSS << "Entry count: " << Twine(PGOMap.FuncEntryCount);
175 if (PGOMap.FeatEnable.hasPGOAnalysisBBData()) {
176 PGOSS << ", ";
177 }
178 }
179
180 if (PGOMap.FeatEnable.hasPGOAnalysisBBData()) {
181
182 assert(PGOBBEntryIndex < PGOMap.BBEntries.size() &&
183 "Expected PGOAnalysisMap and BBAddrMap to have the same entries");
184 const PGOAnalysisMap::PGOBBEntry &PGOBBEntry =
185 PGOMap.BBEntries[PGOBBEntryIndex];
186
187 if (PGOMap.FeatEnable.BBFreq) {
188 PGOSS << "Frequency: ";
189 if (PrettyPGOAnalysis)
190 printRelativeBlockFreq(OS&: PGOSS, EntryFreq: PGOMap.BBEntries.front().BlockFreq,
191 Freq: PGOBBEntry.BlockFreq);
192 else
193 PGOSS << Twine(PGOBBEntry.BlockFreq.getFrequency());
194 if (PGOMap.FeatEnable.BrProb && PGOBBEntry.Successors.size() > 0) {
195 PGOSS << ", ";
196 }
197 }
198 if (PGOMap.FeatEnable.BrProb && PGOBBEntry.Successors.size() > 0) {
199 PGOSS << "Successors: ";
200 interleaveComma(
201 c: PGOBBEntry.Successors, os&: PGOSS,
202 each_fn: [&](const PGOAnalysisMap::PGOBBEntry::SuccessorEntry &SE) {
203 PGOSS << "BB" << SE.ID << ":";
204 if (PrettyPGOAnalysis)
205 PGOSS << "[" << SE.Prob << "]";
206 else
207 PGOSS.write_hex(N: SE.Prob.getNumerator());
208 });
209 }
210 }
211 PGOSS << ")";
212
213 return PGOString;
214 }
215
216private:
217 const BBAddrMap AddrMap;
218 const PGOAnalysisMap PGOMap;
219};
220
221// This class represents the BBAddrMap and PGOMap of potentially multiple
222// functions in a section.
223class BBAddrMapInfo {
224public:
225 void clear() {
226 FunctionAddrToMap.clear();
227 RangeBaseAddrToFunctionAddr.clear();
228 }
229
230 bool empty() const { return FunctionAddrToMap.empty(); }
231
232 void AddFunctionEntry(BBAddrMap AddrMap, PGOAnalysisMap PGOMap) {
233 uint64_t FunctionAddr = AddrMap.getFunctionAddress();
234 for (size_t I = 1; I < AddrMap.BBRanges.size(); ++I)
235 RangeBaseAddrToFunctionAddr.try_emplace(Key: AddrMap.BBRanges[I].BaseAddress,
236 Args&: FunctionAddr);
237 [[maybe_unused]] auto R = FunctionAddrToMap.try_emplace(
238 Key: FunctionAddr, Args: std::move(AddrMap), Args: std::move(PGOMap));
239 assert(R.second && "duplicate function address");
240 }
241
242 // Returns the BBAddrMap entry for the function associated with `BaseAddress`.
243 // `BaseAddress` could be the function address or the address of a range
244 // associated with that function. Returns `nullptr` if `BaseAddress` is not
245 // mapped to any entry.
246 const BBAddrMapFunctionEntry *getEntryForAddress(uint64_t BaseAddress) const {
247 uint64_t FunctionAddr = BaseAddress;
248 auto S = RangeBaseAddrToFunctionAddr.find(Val: BaseAddress);
249 if (S != RangeBaseAddrToFunctionAddr.end())
250 FunctionAddr = S->second;
251 auto R = FunctionAddrToMap.find(Val: FunctionAddr);
252 if (R == FunctionAddrToMap.end())
253 return nullptr;
254 return &R->second;
255 }
256
257private:
258 DenseMap<uint64_t, BBAddrMapFunctionEntry> FunctionAddrToMap;
259 DenseMap<uint64_t, uint64_t> RangeBaseAddrToFunctionAddr;
260};
261
262} // namespace
263
264#define DEBUG_TYPE "objdump"
265
266static uint64_t AdjustVMA;
267static bool AllHeaders;
268static std::string ArchName;
269bool objdump::ArchiveHeaders;
270bool objdump::Demangle;
271bool objdump::Disassemble;
272bool objdump::DisassembleAll;
273std::vector<std::string> objdump::DisassemblerOptions;
274bool objdump::SymbolDescription;
275bool objdump::TracebackTable;
276static std::vector<std::string> DisassembleSymbols;
277static bool DisassembleZeroes;
278ColorOutput objdump::DisassemblyColor;
279DIDumpType objdump::DwarfDumpType;
280static bool DynamicRelocations;
281static bool FaultMapSection;
282static bool FileHeaders;
283bool objdump::SectionContents;
284static std::vector<std::string> InputFilenames;
285bool objdump::PrintLines;
286static bool MachOOpt;
287std::string objdump::MCPU;
288std::vector<std::string> objdump::MAttrs;
289bool objdump::ShowRawInsn;
290bool objdump::LeadingAddr;
291static bool Offloading;
292static bool RawClangAST;
293bool objdump::Relocations;
294bool objdump::PrintImmHex;
295bool objdump::PrivateHeaders;
296std::vector<std::string> objdump::FilterSections;
297bool objdump::SectionHeaders;
298static bool ShowAllSymbols;
299static bool ShowLMA;
300bool objdump::PrintSource;
301
302static uint64_t StartAddress;
303static bool HasStartAddressFlag;
304static uint64_t StopAddress = UINT64_MAX;
305static bool HasStopAddressFlag;
306
307bool objdump::SymbolTable;
308static std::optional<bool> SymbolizeOperandsOption;
309static bool SymbolizeOperands;
310static bool PrettyPGOAnalysisMap;
311static bool DynamicSymbolTable;
312std::string objdump::TripleName;
313bool objdump::UnwindInfo;
314bool objdump::UnwindShowWODPool;
315std::string objdump::Prefix;
316uint32_t objdump::PrefixStrip;
317std::vector<std::pair<std::string, std::string>> objdump::SubstitutePaths;
318std::vector<std::string> objdump::SourceDirs;
319
320DebugFormat objdump::DbgVariables = DFDisabled;
321DebugFormat objdump::DbgInlinedFunctions = DFDisabled;
322
323int objdump::DbgIndent = 52;
324
325static StringSet<> DisasmSymbolSet;
326StringSet<> objdump::FoundSectionSet;
327static StringRef ToolName;
328
329std::unique_ptr<BuildIDFetcher> BIDFetcher;
330
331Dumper::Dumper(const object::ObjectFile &O) : O(O), OS(outs()) {
332 WarningHandler = [this](const Twine &Msg) {
333 if (Warnings.insert(key: Msg.str()).second)
334 reportWarning(Message: Msg, File: this->O.getFileName());
335 return Error::success();
336 };
337}
338
339void Dumper::reportUniqueWarning(Error Err) {
340 reportUniqueWarning(Msg: toString(E: std::move(Err)));
341}
342
343void Dumper::reportUniqueWarning(const Twine &Msg) {
344 cantFail(Err: WarningHandler(Msg));
345}
346
347static Expected<std::unique_ptr<Dumper>> createDumper(const ObjectFile &Obj) {
348 if (const auto *O = dyn_cast<COFFObjectFile>(Val: &Obj))
349 return createCOFFDumper(Obj: *O);
350 if (const auto *O = dyn_cast<ELFObjectFileBase>(Val: &Obj))
351 return createELFDumper(Obj: *O);
352 if (const auto *O = dyn_cast<MachOObjectFile>(Val: &Obj))
353 return createMachODumper(Obj: *O);
354 if (const auto *O = dyn_cast<WasmObjectFile>(Val: &Obj))
355 return createWasmDumper(Obj: *O);
356 if (const auto *O = dyn_cast<XCOFFObjectFile>(Val: &Obj))
357 return createXCOFFDumper(Obj: *O);
358 if (const auto *O = dyn_cast<DXContainerObjectFile>(Val: &Obj))
359 return createDXContainerDumper(Obj: *O);
360
361 return createStringError(EC: errc::invalid_argument,
362 S: "unsupported object file format");
363}
364
365namespace {
366struct FilterResult {
367 // True if the section should not be skipped.
368 bool Keep;
369
370 // True if the index counter should be incremented, even if the section should
371 // be skipped. For example, sections may be skipped if they are not included
372 // in the --section flag, but we still want those to count toward the section
373 // count.
374 bool IncrementIndex;
375};
376} // namespace
377
378static FilterResult checkSectionFilter(object::SectionRef S) {
379 if (FilterSections.empty())
380 return {/*Keep=*/true, /*IncrementIndex=*/true};
381
382 Expected<StringRef> SecNameOrErr = S.getName();
383 if (!SecNameOrErr) {
384 consumeError(Err: SecNameOrErr.takeError());
385 return {/*Keep=*/false, /*IncrementIndex=*/false};
386 }
387 StringRef SecName = *SecNameOrErr;
388
389 // StringSet does not allow empty key so avoid adding sections with
390 // no name (such as the section with index 0) here.
391 if (!SecName.empty())
392 FoundSectionSet.insert(key: SecName);
393
394 // Only show the section if it's in the FilterSections list, but always
395 // increment so the indexing is stable.
396 return {/*Keep=*/is_contained(Range&: FilterSections, Element: SecName),
397 /*IncrementIndex=*/true};
398}
399
400SectionFilter objdump::ToolSectionFilter(object::ObjectFile const &O,
401 uint64_t *Idx) {
402 // Start at UINT64_MAX so that the first index returned after an increment is
403 // zero (after the unsigned wrap).
404 if (Idx)
405 *Idx = UINT64_MAX;
406 return SectionFilter(
407 [Idx](object::SectionRef S) {
408 FilterResult Result = checkSectionFilter(S);
409 if (Idx != nullptr && Result.IncrementIndex)
410 *Idx += 1;
411 return Result.Keep;
412 },
413 O);
414}
415
416std::string objdump::getFileNameForError(const object::Archive::Child &C,
417 unsigned Index) {
418 Expected<StringRef> NameOrErr = C.getName();
419 if (NameOrErr)
420 return std::string(NameOrErr.get());
421 // If we have an error getting the name then we print the index of the archive
422 // member. Since we are already in an error state, we just ignore this error.
423 consumeError(Err: NameOrErr.takeError());
424 return "<file index: " + std::to_string(val: Index) + ">";
425}
426
427void objdump::reportWarning(const Twine &Message, StringRef File) {
428 // Output order between errs() and outs() matters especially for archive
429 // files where the output is per member object.
430 outs().flush();
431 WithColor::warning(OS&: errs(), Prefix: ToolName)
432 << "'" << File << "': " << Message << "\n";
433}
434
435[[noreturn]] void objdump::reportError(StringRef File, const Twine &Message) {
436 outs().flush();
437 WithColor::error(OS&: errs(), Prefix: ToolName) << "'" << File << "': " << Message << "\n";
438 exit(status: 1);
439}
440
441[[noreturn]] void objdump::reportError(Error E, StringRef FileName,
442 StringRef ArchiveName,
443 StringRef ArchitectureName) {
444 assert(E);
445 outs().flush();
446 WithColor::error(OS&: errs(), Prefix: ToolName);
447 if (ArchiveName != "")
448 errs() << ArchiveName << "(" << FileName << ")";
449 else
450 errs() << "'" << FileName << "'";
451 if (!ArchitectureName.empty())
452 errs() << " (for architecture " << ArchitectureName << ")";
453 errs() << ": ";
454 logAllUnhandledErrors(E: std::move(E), OS&: errs());
455 exit(status: 1);
456}
457
458static void reportCmdLineWarning(const Twine &Message) {
459 WithColor::warning(OS&: errs(), Prefix: ToolName) << Message << "\n";
460}
461
462[[noreturn]] static void reportCmdLineError(const Twine &Message) {
463 WithColor::error(OS&: errs(), Prefix: ToolName) << Message << "\n";
464 exit(status: 1);
465}
466
467static void warnOnNoMatchForSections() {
468 SetVector<StringRef> MissingSections;
469 for (StringRef S : FilterSections) {
470 if (FoundSectionSet.count(Key: S))
471 return;
472 // User may specify a unnamed section. Don't warn for it.
473 if (!S.empty())
474 MissingSections.insert(X: S);
475 }
476
477 // Warn only if no section in FilterSections is matched.
478 for (StringRef S : MissingSections)
479 reportCmdLineWarning(Message: "section '" + S +
480 "' mentioned in a -j/--section option, but not "
481 "found in any input file");
482}
483
484static const Target *getTarget(const ObjectFile *Obj) {
485 // Figure out the target triple.
486 Triple TheTriple("unknown-unknown-unknown");
487 if (TripleName.empty()) {
488 TheTriple = Obj->makeTriple();
489 } else {
490 TheTriple.setTriple(Triple::normalize(Str: TripleName));
491 auto Arch = Obj->getArch();
492 if (Arch == Triple::arm || Arch == Triple::armeb)
493 Obj->setARMSubArch(TheTriple);
494 }
495
496 // Get the target specific parser.
497 std::string Error;
498 const Target *TheTarget =
499 TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
500 if (!TheTarget)
501 reportError(File: Obj->getFileName(), Message: "cannot find target: " + Error);
502
503 // Update the triple name and return the found target.
504 TripleName = TheTriple.getTriple();
505 return TheTarget;
506}
507
508bool objdump::isRelocAddressLess(RelocationRef A, RelocationRef B) {
509 return A.getOffset() < B.getOffset();
510}
511
512static Error getRelocationValueString(const RelocationRef &Rel,
513 bool SymbolDescription,
514 SmallVectorImpl<char> &Result) {
515 const ObjectFile *Obj = Rel.getObject();
516 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Val: Obj))
517 return getELFRelocationValueString(Obj: ELF, Rel, Result);
518 if (auto *COFF = dyn_cast<COFFObjectFile>(Val: Obj))
519 return getCOFFRelocationValueString(Obj: COFF, Rel, Result);
520 if (auto *Wasm = dyn_cast<WasmObjectFile>(Val: Obj))
521 return getWasmRelocationValueString(Obj: Wasm, RelRef: Rel, Result);
522 if (auto *MachO = dyn_cast<MachOObjectFile>(Val: Obj))
523 return getMachORelocationValueString(Obj: MachO, RelRef: Rel, Result);
524 if (auto *XCOFF = dyn_cast<XCOFFObjectFile>(Val: Obj))
525 return getXCOFFRelocationValueString(Obj: *XCOFF, RelRef: Rel, SymbolDescription,
526 Result);
527 llvm_unreachable("unknown object file format");
528}
529
530/// Indicates whether this relocation should hidden when listing
531/// relocations, usually because it is the trailing part of a multipart
532/// relocation that will be printed as part of the leading relocation.
533static bool getHidden(RelocationRef RelRef) {
534 auto *MachO = dyn_cast<MachOObjectFile>(Val: RelRef.getObject());
535 if (!MachO)
536 return false;
537
538 unsigned Arch = MachO->getArch();
539 DataRefImpl Rel = RelRef.getRawDataRefImpl();
540 uint64_t Type = MachO->getRelocationType(Rel);
541
542 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
543 // is always hidden.
544 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc)
545 return Type == MachO::GENERIC_RELOC_PAIR;
546
547 if (Arch == Triple::x86_64) {
548 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
549 // an X86_64_RELOC_SUBTRACTOR.
550 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
551 DataRefImpl RelPrev = Rel;
552 RelPrev.d.a--;
553 uint64_t PrevType = MachO->getRelocationType(Rel: RelPrev);
554 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
555 return true;
556 }
557 }
558
559 return false;
560}
561
562/// Get the column at which we want to start printing the instruction
563/// disassembly, taking into account anything which appears to the left of it.
564unsigned objdump::getInstStartColumn(const MCSubtargetInfo &STI) {
565 return !ShowRawInsn ? 16 : STI.getTargetTriple().isX86() ? 40 : 24;
566}
567
568static void AlignToInstStartColumn(size_t Start, const MCSubtargetInfo &STI,
569 raw_ostream &OS) {
570 // The output of printInst starts with a tab. Print some spaces so that
571 // the tab has 1 column and advances to the target tab stop.
572 unsigned TabStop = getInstStartColumn(STI);
573 unsigned Column = OS.tell() - Start;
574 OS.indent(NumSpaces: Column < TabStop - 1 ? TabStop - 1 - Column : 7 - Column % 8);
575}
576
577void objdump::printRawData(ArrayRef<uint8_t> Bytes, uint64_t Address,
578 formatted_raw_ostream &OS,
579 MCSubtargetInfo const &STI) {
580 size_t Start = OS.tell();
581 if (LeadingAddr)
582 OS << format(Fmt: "%8" PRIx64 ":", Vals: Address);
583 if (ShowRawInsn) {
584 OS << ' ';
585 dumpBytes(Bytes, OS);
586 }
587 AlignToInstStartColumn(Start, STI, OS);
588}
589
590namespace {
591
592static bool isAArch64Elf(const ObjectFile &Obj) {
593 const auto *Elf = dyn_cast<ELFObjectFileBase>(Val: &Obj);
594 return Elf && Elf->getEMachine() == ELF::EM_AARCH64;
595}
596
597static bool isArmElf(const ObjectFile &Obj) {
598 const auto *Elf = dyn_cast<ELFObjectFileBase>(Val: &Obj);
599 return Elf && Elf->getEMachine() == ELF::EM_ARM;
600}
601
602static bool isCSKYElf(const ObjectFile &Obj) {
603 const auto *Elf = dyn_cast<ELFObjectFileBase>(Val: &Obj);
604 return Elf && Elf->getEMachine() == ELF::EM_CSKY;
605}
606
607static bool isRISCVElf(const ObjectFile &Obj) {
608 const auto *Elf = dyn_cast<ELFObjectFileBase>(Val: &Obj);
609 return Elf && Elf->getEMachine() == ELF::EM_RISCV;
610}
611
612static bool hasMappingSymbols(const ObjectFile &Obj) {
613 return isArmElf(Obj) || isAArch64Elf(Obj) || isCSKYElf(Obj) ||
614 isRISCVElf(Obj);
615}
616
617/// Get relocation type name, resolving RISCV vendor-specific relocations
618/// when preceded by R_RISCV_VENDOR at the same offset.
619static StringRef getRelocTypeName(const RelocationRef &Rel,
620 SmallVectorImpl<char> &RelocName,
621 std::string &CurrentRISCVVendorSymbol,
622 uint64_t &CurrentRISCVVendorOffset) {
623 Rel.getTypeName(Result&: RelocName);
624 const ObjectFile *Obj = Rel.getObject();
625 if (!isRISCVElf(Obj: *Obj))
626 return StringRef(RelocName.data(), RelocName.size());
627
628 uint64_t Type = Rel.getType();
629 uint64_t Offset = Rel.getOffset();
630 if (Type == ELF::R_RISCV_VENDOR) {
631 // Store vendor symbol name and offset for the next relocation.
632 symbol_iterator SI = Rel.getSymbol();
633 if (SI != Obj->symbol_end()) {
634 if (Expected<StringRef> SymName = SI->getName())
635 CurrentRISCVVendorSymbol = SymName->str();
636 }
637 CurrentRISCVVendorOffset = Offset;
638 } else if (!CurrentRISCVVendorSymbol.empty()) {
639 // Per RISC-V psABI, R_RISCV_VENDOR must be placed immediately before the
640 // vendor-specific relocation at the same offset. Clear the vendor symbol
641 // if this relocation doesn't form a valid pair.
642 if (Offset != CurrentRISCVVendorOffset ||
643 Type < ELF::R_RISCV_CUSTOM192 || Type > ELF::R_RISCV_CUSTOM255) {
644 CurrentRISCVVendorSymbol.clear();
645 } else {
646 // Valid vendor relocation pair - use vendor-specific name.
647 StringRef VendorRelocName = object::getRISCVVendorRelocationTypeName(
648 Type, Vendor: CurrentRISCVVendorSymbol);
649 CurrentRISCVVendorSymbol.clear();
650 if (VendorRelocName != "Unknown")
651 return VendorRelocName;
652 }
653 }
654 return StringRef(RelocName.data(), RelocName.size());
655}
656
657static void printRelocation(formatted_raw_ostream &OS, StringRef FileName,
658 const RelocationRef &Rel, uint64_t Address,
659 bool Is64Bits,
660 std::string &CurrentRISCVVendorSymbol,
661 uint64_t &CurrentRISCVVendorOffset) {
662 StringRef Fmt = Is64Bits ? "%016" PRIx64 ": " : "%08" PRIx64 ": ";
663 SmallString<16> RelocName;
664 SmallString<32> Val;
665 StringRef Name = getRelocTypeName(Rel, RelocName, CurrentRISCVVendorSymbol,
666 CurrentRISCVVendorOffset);
667 if (Error E = getRelocationValueString(Rel, SymbolDescription, Result&: Val))
668 reportError(E: std::move(E), FileName);
669 OS << (Is64Bits || !LeadingAddr ? "\t\t" : "\t\t\t");
670 if (LeadingAddr)
671 OS << format(Fmt: Fmt.data(), Vals: Address);
672 OS << Name << "\t" << Val;
673}
674
675static void printBTFRelocation(formatted_raw_ostream &FOS, llvm::BTFParser &BTF,
676 object::SectionedAddress Address,
677 LiveElementPrinter &LEP) {
678 const llvm::BTF::BPFFieldReloc *Reloc = BTF.findFieldReloc(Address);
679 if (!Reloc)
680 return;
681
682 SmallString<64> Val;
683 BTF.symbolize(Reloc, Result&: Val);
684 FOS << "\t\t";
685 if (LeadingAddr)
686 FOS << format(Fmt: "%016" PRIx64 ": ", Vals: Address.Address + AdjustVMA);
687 FOS << "CO-RE " << Val;
688 LEP.printAfterOtherLine(OS&: FOS, AfterInst: true);
689}
690
691class PrettyPrinter {
692public:
693 virtual ~PrettyPrinter() = default;
694 virtual void
695 printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
696 object::SectionedAddress Address, formatted_raw_ostream &OS,
697 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
698 StringRef ObjectFilename, std::vector<RelocationRef> *Rels,
699 LiveElementPrinter &LEP) {
700 if (SP && (PrintSource || PrintLines))
701 SP->printSourceLine(OS, Address, ObjectFilename, LEP);
702 LEP.printBoundaryLine(OS, Addr: Address, IsEnd: false);
703 LEP.printBetweenInsts(OS, MustPrint: false);
704
705 printRawData(Bytes, Address: Address.Address, OS, STI);
706
707 if (MI) {
708 // See MCInstPrinter::printInst. On targets where a PC relative immediate
709 // is relative to the next instruction and the length of a MCInst is
710 // difficult to measure (x86), this is the address of the next
711 // instruction.
712 uint64_t Addr =
713 Address.Address + (STI.getTargetTriple().isX86() ? Bytes.size() : 0);
714 IP.printInst(MI, Address: Addr, Annot: "", STI, OS);
715 } else
716 OS << "\t<unknown>";
717 }
718
719 virtual void emitPostInstructionInfo(formatted_raw_ostream &FOS,
720 const MCAsmInfo &MAI,
721 const MCSubtargetInfo &STI,
722 StringRef Comments,
723 LiveElementPrinter &LEP) {
724 do {
725 if (!Comments.empty()) {
726 // Emit a line of comments.
727 StringRef Comment;
728 std::tie(args&: Comment, args&: Comments) = Comments.split(Separator: '\n');
729 // MAI.getCommentColumn() assumes that instructions are printed at the
730 // position of 8, while getInstStartColumn() returns the actual
731 // position.
732 unsigned CommentColumn =
733 MAI.getCommentColumn() - 8 + getInstStartColumn(STI);
734 FOS.PadToColumn(NewCol: CommentColumn);
735 FOS << MAI.getCommentString() << ' ' << Comment;
736 }
737 LEP.printAfterInst(OS&: FOS);
738 FOS << "\n";
739 } while (!Comments.empty());
740 FOS.flush();
741 }
742
743 // Hook invoked when starting to disassemble a symbol at the current position.
744 // Default is no-op.
745 virtual void onSymbolStart() {}
746};
747PrettyPrinter PrettyPrinterInst;
748
749class HexagonPrettyPrinter : public PrettyPrinter {
750public:
751 void onSymbolStart() override { reset(); }
752
753 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
754 formatted_raw_ostream &OS) {
755 if (LeadingAddr)
756 OS << format(Fmt: "%8" PRIx64 ":", Vals: Address);
757 if (ShowRawInsn) {
758 OS << "\t";
759 if (Bytes.size() >= 4) {
760 dumpBytes(Bytes: Bytes.slice(N: 0, M: 4), OS);
761 uint32_t opcode =
762 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
763 OS << format(Fmt: "\t%08" PRIx32, Vals: opcode);
764 } else {
765 dumpBytes(Bytes, OS);
766 }
767 }
768 }
769
770 std::string getInstructionSeparator() const {
771 SmallString<40> Separator;
772 raw_svector_ostream OS(Separator);
773 if (ShouldClosePacket) {
774 OS << " }";
775 if (IsLoop0 || IsLoop1)
776 OS << " ";
777 if (IsLoop0)
778 OS << (IsLoop1 ? ":endloop01" : ":endloop0");
779 else if (IsLoop1)
780 OS << ":endloop1";
781 }
782 OS << '\n';
783 return OS.str().str();
784 }
785
786 void emitPostInstructionInfo(formatted_raw_ostream &FOS, const MCAsmInfo &MAI,
787 const MCSubtargetInfo &STI, StringRef Comments,
788 LiveElementPrinter &LEP) override {
789 // Hexagon does not write anything to the comment stream, so we can just
790 // print the separator.
791 LEP.printAfterInst(OS&: FOS);
792 FOS << getInstructionSeparator();
793 FOS.flush();
794 if (ShouldClosePacket)
795 reset();
796 }
797
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 LiveElementPrinter &LEP) override {
803 if (SP && (PrintSource || PrintLines))
804 SP->printSourceLine(OS, Address, ObjectFilename, LEP, Delimiter: "");
805 if (!MI) {
806 printLead(Bytes, Address: Address.Address, OS);
807 OS << " <unknown>";
808 reset();
809 return;
810 }
811
812 StringRef Preamble = IsStartOfBundle ? " { " : " ";
813
814 if (SP && (PrintSource || PrintLines))
815 SP->printSourceLine(OS, Address, ObjectFilename, LEP, Delimiter: "");
816 printLead(Bytes, Address: Address.Address, OS);
817 OS << Preamble;
818 std::string Buf;
819 {
820 raw_string_ostream TempStream(Buf);
821 IP.printInst(MI, Address: Address.Address, Annot: "", STI, OS&: TempStream);
822 }
823 StringRef Contents(Buf);
824
825 auto Duplex = Contents.split(Separator: '\v');
826 bool HasDuplex = !Duplex.second.empty();
827 if (HasDuplex) {
828 OS << Duplex.first;
829 OS << "; ";
830 OS << Duplex.second;
831 } else {
832 OS << Duplex.first;
833 }
834
835 uint32_t Instruction = support::endian::read32le(P: Bytes.data());
836
837 uint32_t ParseMask = 0x0000c000;
838 uint32_t PacketEndMask = 0x0000c000;
839 uint32_t LoopEndMask = 0x00008000;
840 uint32_t ParseBits = Instruction & ParseMask;
841
842 if (ParseBits == LoopEndMask) {
843 if (IsStartOfBundle)
844 IsLoop0 = true;
845 else
846 IsLoop1 = true;
847 }
848
849 IsStartOfBundle = false;
850
851 if (ParseBits == PacketEndMask || HasDuplex)
852 ShouldClosePacket = true;
853 }
854
855private:
856 bool IsStartOfBundle = true;
857 bool IsLoop0 = false;
858 bool IsLoop1 = false;
859 bool ShouldClosePacket = false;
860
861 void reset() {
862 IsStartOfBundle = true;
863 IsLoop0 = false;
864 IsLoop1 = false;
865 ShouldClosePacket = false;
866 }
867};
868HexagonPrettyPrinter HexagonPrettyPrinterInst;
869
870class AMDGCNPrettyPrinter : public PrettyPrinter {
871public:
872 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
873 object::SectionedAddress Address, formatted_raw_ostream &OS,
874 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
875 StringRef ObjectFilename, std::vector<RelocationRef> *Rels,
876 LiveElementPrinter &LEP) override {
877 if (SP && (PrintSource || PrintLines))
878 SP->printSourceLine(OS, Address, ObjectFilename, LEP);
879
880 if (MI) {
881 SmallString<40> InstStr;
882 raw_svector_ostream IS(InstStr);
883
884 IP.printInst(MI, Address: Address.Address, Annot: "", STI, OS&: IS);
885
886 OS << left_justify(Str: IS.str(), Width: 60);
887 } else {
888 // an unrecognized encoding - this is probably data so represent it
889 // using the .long directive, or .byte directive if fewer than 4 bytes
890 // remaining
891 if (Bytes.size() >= 4) {
892 OS << format(
893 Fmt: "\t.long 0x%08" PRIx32 " ",
894 Vals: support::endian::read32<llvm::endianness::little>(P: Bytes.data()));
895 OS.indent(NumSpaces: 42);
896 } else {
897 OS << format(Fmt: "\t.byte 0x%02" PRIx8, Vals: Bytes[0]);
898 for (unsigned int i = 1; i < Bytes.size(); i++)
899 OS << format(Fmt: ", 0x%02" PRIx8, Vals: Bytes[i]);
900 OS.indent(NumSpaces: 55 - (6 * Bytes.size()));
901 }
902 }
903
904 OS << format(Fmt: "// %012" PRIX64 ":", Vals: Address.Address);
905 if (Bytes.size() >= 4) {
906 // D should be casted to uint32_t here as it is passed by format to
907 // snprintf as vararg.
908 for (uint32_t D :
909 ArrayRef(reinterpret_cast<const support::little32_t *>(Bytes.data()),
910 Bytes.size() / 4))
911 OS << format(Fmt: " %08" PRIX32, Vals: D);
912 } else {
913 for (unsigned char B : Bytes)
914 OS << format(Fmt: " %02" PRIX8, Vals: B);
915 }
916
917 if (!Annot.empty())
918 OS << " // " << Annot;
919 }
920};
921AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
922
923class BPFPrettyPrinter : public PrettyPrinter {
924public:
925 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
926 object::SectionedAddress Address, formatted_raw_ostream &OS,
927 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
928 StringRef ObjectFilename, std::vector<RelocationRef> *Rels,
929 LiveElementPrinter &LEP) override {
930 if (SP && (PrintSource || PrintLines))
931 SP->printSourceLine(OS, Address, ObjectFilename, LEP);
932 if (LeadingAddr)
933 OS << format(Fmt: "%8" PRId64 ":", Vals: Address.Address / 8);
934 if (ShowRawInsn) {
935 OS << "\t";
936 dumpBytes(Bytes, OS);
937 }
938 if (MI)
939 IP.printInst(MI, Address: Address.Address, Annot: "", STI, OS);
940 else
941 OS << "\t<unknown>";
942 }
943};
944BPFPrettyPrinter BPFPrettyPrinterInst;
945
946class ARMPrettyPrinter : public PrettyPrinter {
947public:
948 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
949 object::SectionedAddress Address, formatted_raw_ostream &OS,
950 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
951 StringRef ObjectFilename, std::vector<RelocationRef> *Rels,
952 LiveElementPrinter &LEP) override {
953 if (SP && (PrintSource || PrintLines))
954 SP->printSourceLine(OS, Address, ObjectFilename, LEP);
955 LEP.printBoundaryLine(OS, Addr: Address, IsEnd: false);
956 LEP.printBetweenInsts(OS, MustPrint: false);
957
958 size_t Start = OS.tell();
959 if (LeadingAddr)
960 OS << format(Fmt: "%8" PRIx64 ":", Vals: Address.Address);
961 if (ShowRawInsn) {
962 size_t Pos = 0, End = Bytes.size();
963 if (STI.checkFeatures(FS: "+thumb-mode")) {
964 for (; Pos + 2 <= End; Pos += 2)
965 OS << ' '
966 << format_hex_no_prefix(
967 N: llvm::support::endian::read<uint16_t>(
968 memory: Bytes.data() + Pos, endian: InstructionEndianness),
969 Width: 4);
970 } else {
971 for (; Pos + 4 <= End; Pos += 4)
972 OS << ' '
973 << format_hex_no_prefix(
974 N: llvm::support::endian::read<uint32_t>(
975 memory: Bytes.data() + Pos, endian: InstructionEndianness),
976 Width: 8);
977 }
978 if (Pos < End) {
979 OS << ' ';
980 dumpBytes(Bytes: Bytes.slice(N: Pos), OS);
981 }
982 }
983
984 AlignToInstStartColumn(Start, STI, OS);
985
986 if (MI) {
987 IP.printInst(MI, Address: Address.Address, Annot: "", STI, OS);
988 } else
989 OS << "\t<unknown>";
990 }
991
992 void setInstructionEndianness(llvm::endianness Endianness) {
993 InstructionEndianness = Endianness;
994 }
995
996private:
997 llvm::endianness InstructionEndianness = llvm::endianness::little;
998};
999ARMPrettyPrinter ARMPrettyPrinterInst;
1000
1001class AArch64PrettyPrinter : public PrettyPrinter {
1002public:
1003 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1004 object::SectionedAddress Address, formatted_raw_ostream &OS,
1005 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
1006 StringRef ObjectFilename, std::vector<RelocationRef> *Rels,
1007 LiveElementPrinter &LEP) override {
1008 if (SP && (PrintSource || PrintLines))
1009 SP->printSourceLine(OS, Address, ObjectFilename, LEP);
1010 LEP.printBoundaryLine(OS, Addr: Address, IsEnd: false);
1011 LEP.printBetweenInsts(OS, MustPrint: false);
1012
1013 size_t Start = OS.tell();
1014 if (LeadingAddr)
1015 OS << format(Fmt: "%8" PRIx64 ":", Vals: Address.Address);
1016 if (ShowRawInsn) {
1017 size_t Pos = 0, End = Bytes.size();
1018 for (; Pos + 4 <= End; Pos += 4)
1019 OS << ' '
1020 << format_hex_no_prefix(
1021 N: llvm::support::endian::read<uint32_t>(
1022 memory: Bytes.data() + Pos, endian: llvm::endianness::little),
1023 Width: 8);
1024 if (Pos < End) {
1025 OS << ' ';
1026 dumpBytes(Bytes: Bytes.slice(N: Pos), OS);
1027 }
1028 }
1029
1030 AlignToInstStartColumn(Start, STI, OS);
1031
1032 if (MI) {
1033 IP.printInst(MI, Address: Address.Address, Annot: "", STI, OS);
1034 } else
1035 OS << "\t<unknown>";
1036 }
1037};
1038AArch64PrettyPrinter AArch64PrettyPrinterInst;
1039
1040class RISCVPrettyPrinter : public PrettyPrinter {
1041public:
1042 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1043 object::SectionedAddress Address, formatted_raw_ostream &OS,
1044 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
1045 StringRef ObjectFilename, std::vector<RelocationRef> *Rels,
1046 LiveElementPrinter &LEP) override {
1047 if (SP && (PrintSource || PrintLines))
1048 SP->printSourceLine(OS, Address, ObjectFilename, LEP);
1049 LEP.printBoundaryLine(OS, Addr: Address, IsEnd: false);
1050 LEP.printBetweenInsts(OS, MustPrint: false);
1051
1052 size_t Start = OS.tell();
1053 if (LeadingAddr)
1054 OS << format(Fmt: "%8" PRIx64 ":", Vals: Address.Address);
1055 if (ShowRawInsn) {
1056 size_t Pos = 0, End = Bytes.size();
1057 if (End % 4 == 0) {
1058 // 32-bit and 64-bit instructions.
1059 for (; Pos + 4 <= End; Pos += 4)
1060 OS << ' '
1061 << format_hex_no_prefix(
1062 N: llvm::support::endian::read<uint32_t>(
1063 memory: Bytes.data() + Pos, endian: llvm::endianness::little),
1064 Width: 8);
1065 } else if (End % 2 == 0) {
1066 // 16-bit and 48-bits instructions.
1067 for (; Pos + 2 <= End; Pos += 2)
1068 OS << ' '
1069 << format_hex_no_prefix(
1070 N: llvm::support::endian::read<uint16_t>(
1071 memory: Bytes.data() + Pos, endian: llvm::endianness::little),
1072 Width: 4);
1073 }
1074 if (Pos < End) {
1075 OS << ' ';
1076 dumpBytes(Bytes: Bytes.slice(N: Pos), OS);
1077 }
1078 }
1079
1080 AlignToInstStartColumn(Start, STI, OS);
1081
1082 if (MI) {
1083 IP.printInst(MI, Address: Address.Address, Annot: "", STI, OS);
1084 } else
1085 OS << "\t<unknown>";
1086 }
1087};
1088RISCVPrettyPrinter RISCVPrettyPrinterInst;
1089
1090PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
1091 switch (Triple.getArch()) {
1092 default:
1093 return PrettyPrinterInst;
1094 case Triple::hexagon:
1095 return HexagonPrettyPrinterInst;
1096 case Triple::amdgpu:
1097 return AMDGCNPrettyPrinterInst;
1098 case Triple::bpfel:
1099 case Triple::bpfeb:
1100 return BPFPrettyPrinterInst;
1101 case Triple::arm:
1102 case Triple::armeb:
1103 case Triple::thumb:
1104 case Triple::thumbeb:
1105 return ARMPrettyPrinterInst;
1106 case Triple::aarch64:
1107 case Triple::aarch64_be:
1108 case Triple::aarch64_32:
1109 return AArch64PrettyPrinterInst;
1110 case Triple::riscv32:
1111 case Triple::riscv64:
1112 return RISCVPrettyPrinterInst;
1113 }
1114}
1115
1116class DisassemblerTarget {
1117public:
1118 const Target *TheTarget;
1119 const Triple TheTriple;
1120 std::unique_ptr<const MCSubtargetInfo> SubtargetInfo;
1121 std::shared_ptr<MCContext> Context;
1122 std::unique_ptr<MCDisassembler> DisAsm;
1123 std::shared_ptr<MCInstrAnalysis> InstrAnalysis;
1124 std::shared_ptr<MCInstPrinter> InstPrinter;
1125 PrettyPrinter *Printer;
1126
1127 DisassemblerTarget(const Target *TheTarget, ObjectFile &Obj,
1128 StringRef TripleName, StringRef MCPU,
1129 SubtargetFeatures &Features);
1130 DisassemblerTarget(DisassemblerTarget &Other, SubtargetFeatures &Features);
1131
1132private:
1133 MCTargetOptions Options;
1134 std::shared_ptr<const MCRegisterInfo> RegisterInfo;
1135 std::shared_ptr<const MCAsmInfo> AsmInfo;
1136 std::shared_ptr<const MCInstrInfo> InstrInfo;
1137 std::shared_ptr<MCObjectFileInfo> ObjectFileInfo;
1138};
1139
1140DisassemblerTarget::DisassemblerTarget(const Target *TheTarget, ObjectFile &Obj,
1141 StringRef TripleName, StringRef MCPU,
1142 SubtargetFeatures &Features)
1143 : TheTarget(TheTarget), TheTriple(TripleName),
1144 Printer(&selectPrettyPrinter(Triple: TheTriple)),
1145 RegisterInfo(TheTarget->createMCRegInfo(TT: TheTriple)) {
1146 if (!RegisterInfo)
1147 reportError(File: Obj.getFileName(), Message: "no register info for target " + TripleName);
1148
1149 // Set up disassembler.
1150 AsmInfo.reset(p: TheTarget->createMCAsmInfo(MRI: *RegisterInfo, TheTriple, Options));
1151 if (!AsmInfo)
1152 reportError(File: Obj.getFileName(), Message: "no assembly info for target " + TripleName);
1153
1154 SubtargetInfo.reset(
1155 p: TheTarget->createMCSubtargetInfo(TheTriple, CPU: MCPU, Features: Features.getString()));
1156 if (!SubtargetInfo)
1157 reportError(File: Obj.getFileName(),
1158 Message: "no subtarget info for target " + TripleName);
1159 InstrInfo.reset(p: TheTarget->createMCInstrInfo());
1160 if (!InstrInfo)
1161 reportError(File: Obj.getFileName(),
1162 Message: "no instruction info for target " + TripleName);
1163 Context = std::make_shared<MCContext>(args: TheTriple, args: *AsmInfo, args: *RegisterInfo,
1164 args: *SubtargetInfo);
1165
1166 // FIXME: for now initialize MCObjectFileInfo with default values
1167 ObjectFileInfo.reset(
1168 p: TheTarget->createMCObjectFileInfo(Ctx&: *Context, /*PIC=*/false));
1169 Context->setObjectFileInfo(ObjectFileInfo.get());
1170
1171 DisAsm.reset(p: TheTarget->createMCDisassembler(STI: *SubtargetInfo, Ctx&: *Context));
1172 if (!DisAsm)
1173 reportError(File: Obj.getFileName(), Message: "no disassembler for target " + TripleName);
1174
1175 if (auto *ELFObj = dyn_cast<ELFObjectFileBase>(Val: &Obj)) {
1176 DisAsm->setABIVersion(ELFObj->getEIdentABIVersion());
1177 DisAsm->emitTargetIDIfSupported(OS&: outs(), EFlags: ELFObj->getPlatformFlags());
1178 }
1179
1180 InstrAnalysis.reset(p: TheTarget->createMCInstrAnalysis(Info: InstrInfo.get()));
1181
1182 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1183 InstPrinter.reset(p: TheTarget->createMCInstPrinter(
1184 T: TheTriple, SyntaxVariant: AsmPrinterVariant, MAI: *AsmInfo, MII: *InstrInfo, MRI: *RegisterInfo));
1185 if (!InstPrinter)
1186 reportError(File: Obj.getFileName(),
1187 Message: "no instruction printer for target " + TripleName);
1188 InstPrinter->setPrintImmHex(PrintImmHex);
1189 InstPrinter->setPrintBranchImmAsAddress(true);
1190 InstPrinter->setSymbolizeOperands(SymbolizeOperands);
1191 InstPrinter->setMCInstrAnalysis(InstrAnalysis.get());
1192
1193 switch (DisassemblyColor) {
1194 case ColorOutput::Enable:
1195 InstPrinter->setUseColor(true);
1196 break;
1197 case ColorOutput::Auto:
1198 InstPrinter->setUseColor(outs().has_colors());
1199 break;
1200 case ColorOutput::Disable:
1201 case ColorOutput::Invalid:
1202 InstPrinter->setUseColor(false);
1203 break;
1204 };
1205}
1206
1207DisassemblerTarget::DisassemblerTarget(DisassemblerTarget &Other,
1208 SubtargetFeatures &Features)
1209 : TheTarget(Other.TheTarget), TheTriple(Other.TheTriple),
1210 SubtargetInfo(TheTarget->createMCSubtargetInfo(TheTriple, CPU: MCPU,
1211 Features: Features.getString())),
1212 Context(Other.Context),
1213 DisAsm(TheTarget->createMCDisassembler(STI: *SubtargetInfo, Ctx&: *Context)),
1214 InstrAnalysis(Other.InstrAnalysis), InstPrinter(Other.InstPrinter),
1215 Printer(Other.Printer), RegisterInfo(Other.RegisterInfo),
1216 AsmInfo(Other.AsmInfo), InstrInfo(Other.InstrInfo),
1217 ObjectFileInfo(Other.ObjectFileInfo) {}
1218} // namespace
1219
1220static uint8_t getElfSymbolType(const ObjectFile &Obj, const SymbolRef &Sym) {
1221 assert(Obj.isELF());
1222 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Val: &Obj))
1223 return unwrapOrError(EO: Elf32LEObj->getSymbol(Sym: Sym.getRawDataRefImpl()),
1224 Args: Obj.getFileName())
1225 ->getType();
1226 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Val: &Obj))
1227 return unwrapOrError(EO: Elf64LEObj->getSymbol(Sym: Sym.getRawDataRefImpl()),
1228 Args: Obj.getFileName())
1229 ->getType();
1230 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Val: &Obj))
1231 return unwrapOrError(EO: Elf32BEObj->getSymbol(Sym: Sym.getRawDataRefImpl()),
1232 Args: Obj.getFileName())
1233 ->getType();
1234 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Val: &Obj))
1235 return unwrapOrError(EO: Elf64BEObj->getSymbol(Sym: Sym.getRawDataRefImpl()),
1236 Args: Obj.getFileName())
1237 ->getType();
1238 llvm_unreachable("Unsupported binary format");
1239}
1240
1241template <class ELFT>
1242static void
1243addDynamicElfSymbols(const ELFObjectFile<ELFT> &Obj,
1244 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1245 for (auto Symbol : Obj.getDynamicSymbolIterators()) {
1246 uint8_t SymbolType = Symbol.getELFType();
1247 if (SymbolType == ELF::STT_SECTION)
1248 continue;
1249
1250 uint64_t Address = unwrapOrError(Symbol.getAddress(), Obj.getFileName());
1251 // ELFSymbolRef::getAddress() returns size instead of value for common
1252 // symbols which is not desirable for disassembly output. Overriding.
1253 if (SymbolType == ELF::STT_COMMON)
1254 Address = unwrapOrError(Obj.getSymbol(Symbol.getRawDataRefImpl()),
1255 Obj.getFileName())
1256 ->st_value;
1257
1258 StringRef Name = unwrapOrError(Symbol.getName(), Obj.getFileName());
1259 if (Name.empty())
1260 continue;
1261
1262 section_iterator SecI =
1263 unwrapOrError(Symbol.getSection(), Obj.getFileName());
1264 if (SecI == Obj.section_end())
1265 continue;
1266
1267 AllSymbols[*SecI].emplace_back(args&: Address, args&: Name, args&: SymbolType);
1268 }
1269}
1270
1271static void
1272addDynamicElfSymbols(const ELFObjectFileBase &Obj,
1273 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1274 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Val: &Obj))
1275 addDynamicElfSymbols(Obj: *Elf32LEObj, AllSymbols);
1276 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Val: &Obj))
1277 addDynamicElfSymbols(Obj: *Elf64LEObj, AllSymbols);
1278 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Val: &Obj))
1279 addDynamicElfSymbols(Obj: *Elf32BEObj, AllSymbols);
1280 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Val: &Obj))
1281 addDynamicElfSymbols(Obj: *Elf64BEObj, AllSymbols);
1282 else
1283 llvm_unreachable("Unsupported binary format");
1284}
1285
1286static std::optional<SectionRef> getWasmCodeSection(const WasmObjectFile &Obj) {
1287 for (auto SecI : Obj.sections()) {
1288 const WasmSection &Section = Obj.getWasmSection(Section: SecI);
1289 if (Section.Type == wasm::WASM_SEC_CODE)
1290 return SecI;
1291 }
1292 return std::nullopt;
1293}
1294
1295static void
1296addMissingWasmCodeSymbols(const WasmObjectFile &Obj,
1297 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1298 std::optional<SectionRef> Section = getWasmCodeSection(Obj);
1299 if (!Section)
1300 return;
1301 SectionSymbolsTy &Symbols = AllSymbols[*Section];
1302
1303 std::set<uint64_t> SymbolAddresses;
1304 for (const auto &Sym : Symbols)
1305 SymbolAddresses.insert(x: Sym.Addr);
1306
1307 for (const wasm::WasmFunction &Function : Obj.functions()) {
1308 // This adjustment mirrors the one in WasmObjectFile::getSymbolAddress.
1309 uint32_t Adjustment = Obj.isRelocatableObject() || Obj.isSharedObject()
1310 ? 0
1311 : Section->getAddress();
1312 uint64_t Address = Function.CodeSectionOffset + Adjustment;
1313 // Only add fallback symbols for functions not already present in the symbol
1314 // table.
1315 if (SymbolAddresses.count(x: Address))
1316 continue;
1317 // This function has no symbol, so it should have no SymbolName.
1318 assert(Function.SymbolName.empty());
1319 // We use DebugName for the name, though it may be empty if there is no
1320 // "name" custom section, or that section is missing a name for this
1321 // function.
1322 StringRef Name = Function.DebugName;
1323 Symbols.emplace_back(args&: Address, args&: Name, args: ELF::STT_NOTYPE);
1324 }
1325}
1326
1327static DenseMap<StringRef, SectionRef> getSectionNames(const ObjectFile &Obj) {
1328 DenseMap<StringRef, SectionRef> Sections;
1329 for (SectionRef Section : Obj.sections()) {
1330 Expected<StringRef> SecNameOrErr = Section.getName();
1331 if (!SecNameOrErr) {
1332 consumeError(Err: SecNameOrErr.takeError());
1333 continue;
1334 }
1335 Sections[*SecNameOrErr] = Section;
1336 }
1337 return Sections;
1338}
1339
1340static void addPltEntries(const MCSubtargetInfo &STI, const ObjectFile &Obj,
1341 DenseMap<StringRef, SectionRef> &SectionNames,
1342 std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
1343 StringSaver &Saver) {
1344 auto *ElfObj = dyn_cast<ELFObjectFileBase>(Val: &Obj);
1345 if (!ElfObj)
1346 return;
1347 for (auto Plt : ElfObj->getPltEntries(STI)) {
1348 if (Plt.Symbol) {
1349 SymbolRef Symbol(*Plt.Symbol, ElfObj);
1350 uint8_t SymbolType = getElfSymbolType(Obj, Sym: Symbol);
1351 if (Expected<StringRef> NameOrErr = Symbol.getName()) {
1352 if (!NameOrErr->empty())
1353 AllSymbols[SectionNames[Plt.Section]].emplace_back(
1354 args&: Plt.Address, args: Saver.save(S: *NameOrErr + "@plt"), args&: SymbolType);
1355 continue;
1356 } else {
1357 // The warning has been reported in disassembleObject().
1358 consumeError(Err: NameOrErr.takeError());
1359 }
1360 }
1361 reportWarning(Message: "PLT entry at 0x" + Twine::utohexstr(Val: Plt.Address) +
1362 " references an invalid symbol",
1363 File: Obj.getFileName());
1364 }
1365}
1366
1367// Normally the disassembly output will skip blocks of zeroes. This function
1368// returns the number of zero bytes that can be skipped when dumping the
1369// disassembly of the instructions in Buf.
1370static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) {
1371 // Find the number of leading zeroes.
1372 size_t N = 0;
1373 while (N < Buf.size() && !Buf[N])
1374 ++N;
1375
1376 // We may want to skip blocks of zero bytes, but unless we see
1377 // at least 8 of them in a row.
1378 if (N < 8)
1379 return 0;
1380
1381 // We skip zeroes in multiples of 4 because do not want to truncate an
1382 // instruction if it starts with a zero byte.
1383 return N & ~0x3;
1384}
1385
1386// Returns a map from sections to their relocations.
1387static std::map<SectionRef, std::vector<RelocationRef>>
1388getRelocsMap(object::ObjectFile const &Obj) {
1389 std::map<SectionRef, std::vector<RelocationRef>> Ret;
1390 uint64_t I = (uint64_t)-1;
1391 for (SectionRef Sec : Obj.sections()) {
1392 ++I;
1393 Expected<section_iterator> RelocatedOrErr = Sec.getRelocatedSection();
1394 if (!RelocatedOrErr)
1395 reportError(File: Obj.getFileName(),
1396 Message: "section (" + Twine(I) +
1397 "): failed to get a relocated section: " +
1398 toString(E: RelocatedOrErr.takeError()));
1399
1400 section_iterator Relocated = *RelocatedOrErr;
1401 if (Relocated == Obj.section_end() || !checkSectionFilter(S: *Relocated).Keep)
1402 continue;
1403 std::vector<RelocationRef> &V = Ret[*Relocated];
1404 append_range(C&: V, R: Sec.relocations());
1405 // Sort relocations by address.
1406 llvm::stable_sort(Range&: V, C: isRelocAddressLess);
1407 }
1408 return Ret;
1409}
1410
1411// Used for --adjust-vma to check if address should be adjusted by the
1412// specified value for a given section.
1413// For ELF we do not adjust non-allocatable sections like debug ones,
1414// because they are not loadable.
1415// TODO: implement for other file formats.
1416static bool shouldAdjustVA(const SectionRef &Section) {
1417 const ObjectFile *Obj = Section.getObject();
1418 if (Obj->isELF())
1419 return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
1420 return false;
1421}
1422
1423typedef std::pair<uint64_t, char> MappingSymbolPair;
1424static char getMappingSymbolKind(ArrayRef<MappingSymbolPair> MappingSymbols,
1425 uint64_t Address) {
1426 auto It =
1427 partition_point(Range&: MappingSymbols, P: [Address](const MappingSymbolPair &Val) {
1428 return Val.first <= Address;
1429 });
1430 // Return zero for any address before the first mapping symbol; this means
1431 // we should use the default disassembly mode, depending on the target.
1432 if (It == MappingSymbols.begin())
1433 return '\x00';
1434 return (It - 1)->second;
1435}
1436
1437// Owns a cache of ISA string -> DisassemblerTarget for RISC-V per-region
1438// disassembly. A single instance spans the whole disassembly pass so each
1439// unique ISA string is parsed at most once regardless of how many sections
1440// or regions reference it.
1441class RISCVISATargetCache {
1442 // Maps the "<ISAString>" part after "$x" to a disassembler target
1443 // configured for that ISA. A null unique_ptr caches a parse failure so
1444 // we do not re-parse the same invalid string.
1445 StringMap<std::unique_ptr<DisassemblerTarget>> Cache;
1446 StringRef FileName;
1447
1448public:
1449 explicit RISCVISATargetCache(StringRef FileName) : FileName(FileName) {}
1450
1451 // Returns a DisassemblerTarget configured for ISAStr. Feature priority in
1452 // the returned target is (low -> high): Tag_RISCV_arch, the mapping-symbol
1453 // ISA, then --mattr, so an explicit --mattr on the command line overrides
1454 // both the attribute-recorded arch and the mapping symbol. If appending
1455 // --mattr on top of the mapping symbol would create a conflicting feature
1456 // set (e.g. mapping symbol rv64if combined with --mattr=+zfinx), the
1457 // --mattr layer is dropped for this region and only the mapping symbol
1458 // (layered on Tag_RISCV_arch) is used. Falls back to &Base when ISAStr is
1459 // empty or cannot be parsed; a parse failure is cached so the same bad
1460 // string is consumed only once.
1461 DisassemblerTarget *get(DisassemblerTarget &Base, StringRef ISAStr) {
1462 if (ISAStr.empty())
1463 return &Base;
1464 auto [It, Inserted] = Cache.try_emplace(Key: ISAStr);
1465 if (Inserted) {
1466 // The mapping symbol name (without the leading "$x") is a normalized
1467 // RISC-V arch string like "rv64i2p1_m2p0_a2p1_c2p0_v1p0_...".
1468 auto ParseResult = RISCVISAInfo::parseNormalizedArchString(Arch: ISAStr);
1469 if (ParseResult) {
1470 std::vector<std::string> ISAFeatures = (*ParseResult)->toFeatures();
1471 // Base's feature string already contains Tag_RISCV_arch followed by
1472 // --mattr. Appending the mapping-symbol features here puts the
1473 // mapping symbol above both; the --mattr re-layering below then puts
1474 // --mattr back on top as the highest-priority source.
1475 SubtargetFeatures Features(Base.SubtargetInfo->getFeatureString());
1476 // toFeatures() only emits the extensions from Exts (i, m, f, ...),
1477 // not the base-ISA XLEN. Derive 64bit from getXLen() so mapping
1478 // symbols that switch XLEN (e.g. rv64 inside an rv32 triple) reach
1479 // the decoder correctly.
1480 Features.AddFeature(String: "64bit", Enable: (*ParseResult)->getXLen() == 64);
1481 Features.addFeaturesVector(OtherFeatures: ISAFeatures);
1482 // Try to re-apply --mattr on top of the mapping symbol. Validate by
1483 // running the combined feature set through parseFeatures, which runs
1484 // postProcessAndChecking and catches mutually-exclusive pairs such
1485 // as f/zfinx. On conflict, silently drop --mattr for this region
1486 // rather than producing an inconsistent decoder.
1487 if (!MAttrs.empty()) {
1488 SubtargetFeatures Combined;
1489 Combined.addFeaturesVector(OtherFeatures: ISAFeatures);
1490 for (auto &F : MAttrs)
1491 Combined.AddFeature(String: F);
1492 if (auto Check = RISCVISAInfo::parseFeatures(
1493 XLen: (*ParseResult)->getXLen(), Features: Combined.getFeatures())) {
1494 for (auto &F : MAttrs)
1495 Features.AddFeature(String: F);
1496 } else {
1497 consumeError(Err: Check.takeError());
1498 }
1499 }
1500 It->second = std::make_unique<DisassemblerTarget>(args&: Base, args&: Features);
1501 } else {
1502 // Parse failed: warn so the user understands why the region falls
1503 // back to the default decoder, then leave the slot null so every
1504 // future query for this same string falls back to Base
1505 // (Tag_RISCV_arch / --mattr) without re-parsing or re-warning.
1506 reportWarning(Message: "could not parse ISA mapping symbol '$x" + ISAStr +
1507 "': " + toString(E: ParseResult.takeError()) +
1508 "; falling back to default disassembler",
1509 File: FileName);
1510 }
1511 }
1512 return It->second ? It->second.get() : &Base;
1513 }
1514};
1515
1516// Returns the DisassemblerTarget associated with the most recent RISC-V ISA
1517// mapping symbol at or before Address, or nullptr if none exists.
1518static DisassemblerTarget *getRISCVISAMappingTarget(
1519 ArrayRef<std::pair<uint64_t, DisassemblerTarget *>> Syms,
1520 uint64_t Address) {
1521 auto It = partition_point(
1522 Range&: Syms, P: [Address](const std::pair<uint64_t, DisassemblerTarget *> &Val) {
1523 return Val.first <= Address;
1524 });
1525 if (It == Syms.begin())
1526 return nullptr;
1527 return (It - 1)->second;
1528}
1529
1530static uint64_t dumpARMELFData(uint64_t SectionAddr, uint64_t Index,
1531 uint64_t End, const ObjectFile &Obj,
1532 ArrayRef<uint8_t> Bytes,
1533 ArrayRef<MappingSymbolPair> MappingSymbols,
1534 const MCSubtargetInfo &STI, raw_ostream &OS) {
1535 llvm::endianness Endian =
1536 Obj.isLittleEndian() ? llvm::endianness::little : llvm::endianness::big;
1537 size_t Start = OS.tell();
1538 OS << format(Fmt: "%8" PRIx64 ": ", Vals: SectionAddr + Index);
1539 if (Index + 4 <= End) {
1540 dumpBytes(Bytes: Bytes.slice(N: Index, M: 4), OS);
1541 AlignToInstStartColumn(Start, STI, OS);
1542 OS << "\t.word\t"
1543 << format_hex(N: support::endian::read32(P: Bytes.data() + Index, E: Endian), Width: 10);
1544 return 4;
1545 }
1546 if (Index + 2 <= End) {
1547 dumpBytes(Bytes: Bytes.slice(N: Index, M: 2), OS);
1548 AlignToInstStartColumn(Start, STI, OS);
1549 OS << "\t.short\t"
1550 << format_hex(N: support::endian::read16(P: Bytes.data() + Index, E: Endian), Width: 6);
1551 return 2;
1552 }
1553 dumpBytes(Bytes: Bytes.slice(N: Index, M: 1), OS);
1554 AlignToInstStartColumn(Start, STI, OS);
1555 OS << "\t.byte\t" << format_hex(N: Bytes[Index], Width: 4);
1556 return 1;
1557}
1558
1559static void dumpELFData(uint64_t SectionAddr, uint64_t Index, uint64_t End,
1560 ArrayRef<uint8_t> Bytes, raw_ostream &OS) {
1561 // print out data up to 8 bytes at a time in hex and ascii
1562 uint8_t AsciiData[9] = {'\0'};
1563 uint8_t Byte;
1564 int NumBytes = 0;
1565
1566 for (; Index < End; ++Index) {
1567 if (NumBytes == 0)
1568 OS << format(Fmt: "%8" PRIx64 ":", Vals: SectionAddr + Index);
1569 Byte = Bytes.slice(N: Index)[0];
1570 OS << format(Fmt: " %02x", Vals: Byte);
1571 AsciiData[NumBytes] = isPrint(C: Byte) ? Byte : '.';
1572
1573 uint8_t IndentOffset = 0;
1574 NumBytes++;
1575 if (Index == End - 1 || NumBytes > 8) {
1576 // Indent the space for less than 8 bytes data.
1577 // 2 spaces for byte and one for space between bytes
1578 IndentOffset = 3 * (8 - NumBytes);
1579 for (int Excess = NumBytes; Excess < 8; Excess++)
1580 AsciiData[Excess] = '\0';
1581 NumBytes = 8;
1582 }
1583 if (NumBytes == 8) {
1584 AsciiData[8] = '\0';
1585 OS << std::string(IndentOffset, ' ') << " ";
1586 OS << reinterpret_cast<char *>(AsciiData);
1587 OS << '\n';
1588 NumBytes = 0;
1589 }
1590 }
1591}
1592
1593SymbolInfoTy objdump::createSymbolInfo(const ObjectFile &Obj,
1594 const SymbolRef &Symbol,
1595 bool IsMappingSymbol) {
1596 const StringRef FileName = Obj.getFileName();
1597 const uint64_t Addr = unwrapOrError(EO: Symbol.getAddress(), Args: FileName);
1598 const StringRef Name = unwrapOrError(EO: Symbol.getName(), Args: FileName);
1599
1600 if (Obj.isXCOFF() && (SymbolDescription || TracebackTable)) {
1601 const auto &XCOFFObj = cast<XCOFFObjectFile>(Val: Obj);
1602 DataRefImpl SymbolDRI = Symbol.getRawDataRefImpl();
1603
1604 const uint32_t SymbolIndex = XCOFFObj.getSymbolIndex(SymEntPtr: SymbolDRI.p);
1605 std::optional<XCOFF::StorageMappingClass> Smc =
1606 getXCOFFSymbolCsectSMC(Obj: XCOFFObj, Sym: Symbol);
1607 return SymbolInfoTy(Smc, Addr, Name, SymbolIndex,
1608 isLabel(Obj: XCOFFObj, Sym: Symbol));
1609 } else if (Obj.isXCOFF()) {
1610 const SymbolRef::Type SymType = unwrapOrError(EO: Symbol.getType(), Args: FileName);
1611 return SymbolInfoTy(Addr, Name, SymType, /*IsMappingSymbol=*/false,
1612 /*IsXCOFF=*/true);
1613 } else if (Obj.isWasm()) {
1614 uint8_t SymType =
1615 cast<WasmObjectFile>(Val: &Obj)->getWasmSymbol(Symbol).Info.Kind;
1616 return SymbolInfoTy(Addr, Name, SymType, false);
1617 } else {
1618 uint8_t Type =
1619 Obj.isELF() ? getElfSymbolType(Obj, Sym: Symbol) : (uint8_t)ELF::STT_NOTYPE;
1620 return SymbolInfoTy(Addr, Name, Type, IsMappingSymbol);
1621 }
1622}
1623
1624static SymbolInfoTy createDummySymbolInfo(const ObjectFile &Obj,
1625 const uint64_t Addr, StringRef &Name,
1626 uint8_t Type) {
1627 if (Obj.isXCOFF() && (SymbolDescription || TracebackTable))
1628 return SymbolInfoTy(std::nullopt, Addr, Name, std::nullopt, false);
1629 if (Obj.isWasm())
1630 return SymbolInfoTy(Addr, Name, wasm::WASM_SYMBOL_TYPE_SECTION);
1631 return SymbolInfoTy(Addr, Name, Type);
1632}
1633
1634static void collectBBAddrMapLabels(
1635 const BBAddrMapInfo &FullAddrMap, uint64_t SectionAddr, uint64_t Start,
1636 uint64_t End, DenseMap<uint64_t, std::vector<BBAddrMapLabel>> &Labels) {
1637 if (FullAddrMap.empty())
1638 return;
1639 Labels.clear();
1640 uint64_t StartAddress = SectionAddr + Start;
1641 uint64_t EndAddress = SectionAddr + End;
1642 const BBAddrMapFunctionEntry *FunctionMap =
1643 FullAddrMap.getEntryForAddress(BaseAddress: StartAddress);
1644 if (!FunctionMap)
1645 return;
1646 std::optional<size_t> BBRangeIndex =
1647 FunctionMap->getAddrMap().getBBRangeIndexForBaseAddress(BaseAddress: StartAddress);
1648 if (!BBRangeIndex)
1649 return;
1650 size_t NumBBEntriesBeforeRange = 0;
1651 for (size_t I = 0; I < *BBRangeIndex; ++I)
1652 NumBBEntriesBeforeRange +=
1653 FunctionMap->getAddrMap().BBRanges[I].BBEntries.size();
1654 const auto &BBRange = FunctionMap->getAddrMap().BBRanges[*BBRangeIndex];
1655 for (size_t I = 0; I < BBRange.BBEntries.size(); ++I) {
1656 const BBAddrMap::BBEntry &BBEntry = BBRange.BBEntries[I];
1657 uint64_t BBAddress = BBEntry.Offset + BBRange.BaseAddress;
1658 if (BBAddress >= EndAddress)
1659 continue;
1660
1661 std::string LabelString = ("BB" + Twine(BBEntry.ID)).str();
1662 Labels[BBAddress].push_back(
1663 x: {.BlockLabel: LabelString, .PGOAnalysis: FunctionMap->constructPGOLabelString(
1664 PGOBBEntryIndex: NumBBEntriesBeforeRange + I, PrettyPGOAnalysis: PrettyPGOAnalysisMap)});
1665 }
1666}
1667
1668static void collectLocalBranchTargets(
1669 ArrayRef<uint8_t> Bytes, MCInstrAnalysis *MIA, MCDisassembler *DisAsm,
1670 MCInstPrinter *IP, const MCSubtargetInfo *STI, uint64_t SectionAddr,
1671 uint64_t Start, uint64_t End, DenseMap<uint64_t, std::string> &Labels) {
1672 // Supported by certain targets.
1673 const bool isPPC = STI->getTargetTriple().isPPC();
1674 const bool isX86 = STI->getTargetTriple().isX86();
1675 const bool isAArch64 = STI->getTargetTriple().isAArch64();
1676 const bool isBPF = STI->getTargetTriple().isBPF();
1677 const bool isRISCV = STI->getTargetTriple().isRISCV();
1678 if (!isPPC && !isX86 && !isAArch64 && !isBPF && !isRISCV)
1679 return;
1680
1681 if (MIA)
1682 MIA->resetState();
1683
1684 std::set<uint64_t> Targets;
1685 Start += SectionAddr;
1686 End += SectionAddr;
1687 const bool isXCOFF = STI->getTargetTriple().isOSBinFormatXCOFF();
1688 for (uint64_t Index = Start; Index < End;) {
1689 // Disassemble a real instruction and record function-local branch labels.
1690 MCInst Inst;
1691 uint64_t Size;
1692 ArrayRef<uint8_t> ThisBytes = Bytes.slice(N: Index - SectionAddr);
1693 bool Disassembled =
1694 DisAsm->getInstruction(Instr&: Inst, Size, Bytes: ThisBytes, Address: Index, CStream&: nulls());
1695 if (Size == 0)
1696 Size = std::min<uint64_t>(a: ThisBytes.size(),
1697 b: DisAsm->suggestBytesToSkip(Bytes: ThisBytes, Address: Index));
1698
1699 if (MIA) {
1700 if (Disassembled) {
1701 uint64_t Target;
1702 bool TargetKnown = MIA->evaluateBranch(Inst, Addr: Index, Size, Target);
1703 if (TargetKnown && (Target >= Start && Target < End) &&
1704 !Targets.count(x: Target)) {
1705 // On PowerPC and AIX, a function call is encoded as a branch to 0.
1706 // On other PowerPC platforms (ELF), a function call is encoded as
1707 // a branch to self. Do not add a label for these cases.
1708 if (!(isPPC &&
1709 ((Target == 0 && isXCOFF) || (Target == Index && !isXCOFF))))
1710 Targets.insert(x: Target);
1711 }
1712 MIA->updateState(Inst, STI, Addr: Index);
1713 } else
1714 MIA->resetState();
1715 }
1716 Index += Size;
1717 }
1718
1719 Labels.clear();
1720 for (auto [Idx, Target] : enumerate(First&: Targets))
1721 Labels[Target] = ("L" + Twine(Idx)).str();
1722}
1723
1724// Create an MCSymbolizer for the target and add it to the MCDisassembler.
1725// This is currently only used on AMDGPU, and assumes the format of the
1726// void * argument passed to AMDGPU's createMCSymbolizer.
1727static void addSymbolizer(
1728 MCContext &Ctx, const Target *Target, const Triple &TheTriple,
1729 MCDisassembler *DisAsm, uint64_t SectionAddr, ArrayRef<uint8_t> Bytes,
1730 SectionSymbolsTy &Symbols,
1731 std::vector<std::unique_ptr<std::string>> &SynthesizedLabelNames) {
1732
1733 std::unique_ptr<MCRelocationInfo> RelInfo(
1734 Target->createMCRelocationInfo(TT: TheTriple, Ctx));
1735 if (!RelInfo)
1736 return;
1737 std::unique_ptr<MCSymbolizer> Symbolizer(Target->createMCSymbolizer(
1738 TT: TheTriple, GetOpInfo: nullptr, SymbolLookUp: nullptr, DisInfo: &Symbols, Ctx: &Ctx, RelInfo: std::move(RelInfo)));
1739 MCSymbolizer *SymbolizerPtr = &*Symbolizer;
1740 DisAsm->setSymbolizer(std::move(Symbolizer));
1741
1742 if (!SymbolizeOperands)
1743 return;
1744
1745 // Synthesize labels referenced by branch instructions by
1746 // disassembling, discarding the output, and collecting the referenced
1747 // addresses from the symbolizer.
1748 for (size_t Index = 0; Index != Bytes.size();) {
1749 MCInst Inst;
1750 uint64_t Size;
1751 ArrayRef<uint8_t> ThisBytes = Bytes.slice(N: Index);
1752 const uint64_t ThisAddr = SectionAddr + Index;
1753 DisAsm->getInstruction(Instr&: Inst, Size, Bytes: ThisBytes, Address: ThisAddr, CStream&: nulls());
1754 if (Size == 0)
1755 Size = std::min<uint64_t>(a: ThisBytes.size(),
1756 b: DisAsm->suggestBytesToSkip(Bytes: ThisBytes, Address: Index));
1757 Index += Size;
1758 }
1759 ArrayRef<uint64_t> LabelAddrsRef = SymbolizerPtr->getReferencedAddresses();
1760 // Copy and sort to remove duplicates.
1761 std::vector<uint64_t> LabelAddrs;
1762 llvm::append_range(C&: LabelAddrs, R&: LabelAddrsRef);
1763 llvm::sort(C&: LabelAddrs);
1764 LabelAddrs.resize(new_size: llvm::unique(R&: LabelAddrs) - LabelAddrs.begin());
1765 // Add the labels.
1766 for (unsigned LabelNum = 0; LabelNum != LabelAddrs.size(); ++LabelNum) {
1767 auto Name = std::make_unique<std::string>();
1768 *Name = (Twine("L") + Twine(LabelNum)).str();
1769 SynthesizedLabelNames.push_back(x: std::move(Name));
1770 Symbols.push_back(x: SymbolInfoTy(
1771 LabelAddrs[LabelNum], *SynthesizedLabelNames.back(), ELF::STT_NOTYPE));
1772 }
1773 llvm::stable_sort(Range&: Symbols);
1774 // Recreate the symbolizer with the new symbols list.
1775 RelInfo.reset(p: Target->createMCRelocationInfo(TT: TheTriple, Ctx));
1776 Symbolizer.reset(p: Target->createMCSymbolizer(
1777 TT: TheTriple, GetOpInfo: nullptr, SymbolLookUp: nullptr, DisInfo: &Symbols, Ctx: &Ctx, RelInfo: std::move(RelInfo)));
1778 DisAsm->setSymbolizer(std::move(Symbolizer));
1779}
1780
1781static StringRef getSegmentName(const MachOObjectFile *MachO,
1782 const SectionRef &Section) {
1783 if (MachO) {
1784 DataRefImpl DR = Section.getRawDataRefImpl();
1785 StringRef SegmentName = MachO->getSectionFinalSegmentName(Sec: DR);
1786 return SegmentName;
1787 }
1788 return "";
1789}
1790
1791static void createFakeELFSections(ObjectFile &Obj) {
1792 assert(Obj.isELF());
1793 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Val: &Obj))
1794 Elf32LEObj->createFakeSections();
1795 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Val: &Obj))
1796 Elf64LEObj->createFakeSections();
1797 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Val: &Obj))
1798 Elf32BEObj->createFakeSections();
1799 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Val: &Obj))
1800 Elf64BEObj->createFakeSections();
1801 else
1802 llvm_unreachable("Unsupported binary format");
1803}
1804
1805// Tries to fetch a more complete version of the given object file using its
1806// Build ID. Returns std::nullopt if nothing was found.
1807static std::optional<OwningBinary<Binary>>
1808fetchBinaryByBuildID(const ObjectFile &Obj) {
1809 object::BuildIDRef BuildID = getBuildID(Obj: &Obj);
1810 if (BuildID.empty())
1811 return std::nullopt;
1812 Expected<std::string> Path = BIDFetcher->fetch(BuildID);
1813 if (!Path) {
1814 // Failure to fetch debuginfod is rarely an error and most users will not
1815 // care why this failed.
1816 consumeError(Err: Path.takeError());
1817 return std::nullopt;
1818 }
1819 Expected<OwningBinary<Binary>> DebugBinary = createBinary(Path: *Path);
1820 if (!DebugBinary) {
1821 reportWarning(Message: toString(E: DebugBinary.takeError()), File: *Path);
1822 return std::nullopt;
1823 }
1824 return std::move(*DebugBinary);
1825}
1826
1827static void
1828disassembleObject(ObjectFile &Obj, const ObjectFile &DbgObj,
1829 DisassemblerTarget &PrimaryTarget,
1830 std::optional<DisassemblerTarget> &SecondaryTarget,
1831 SourcePrinter &SP, bool InlineRelocs, raw_ostream &OS) {
1832 DisassemblerTarget *DT = &PrimaryTarget;
1833 bool PrimaryIsThumb = false;
1834 SmallVector<std::pair<uint64_t, uint64_t>, 0> CHPECodeMap;
1835
1836 if (SecondaryTarget) {
1837 if (isArmElf(Obj)) {
1838 PrimaryIsThumb =
1839 PrimaryTarget.SubtargetInfo->checkFeatures(FS: "+thumb-mode");
1840 } else if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Val: &Obj)) {
1841 const chpe_metadata *CHPEMetadata = COFFObj->getCHPEMetadata();
1842 if (CHPEMetadata && CHPEMetadata->CodeMapCount) {
1843 uintptr_t CodeMapInt;
1844 cantFail(Err: COFFObj->getRvaPtr(Rva: CHPEMetadata->CodeMap, Res&: CodeMapInt));
1845 auto CodeMap = reinterpret_cast<const chpe_range_entry *>(CodeMapInt);
1846
1847 for (uint32_t i = 0; i < CHPEMetadata->CodeMapCount; ++i) {
1848 if (CodeMap[i].getType() == chpe_range_type::Amd64 &&
1849 CodeMap[i].Length) {
1850 // Store x86_64 CHPE code ranges.
1851 uint64_t Start = CodeMap[i].getStart() + COFFObj->getImageBase();
1852 CHPECodeMap.emplace_back(Args&: Start, Args: Start + CodeMap[i].Length);
1853 }
1854 }
1855 llvm::sort(C&: CHPECodeMap);
1856 }
1857 }
1858 }
1859
1860 std::map<SectionRef, std::vector<RelocationRef>> RelocMap;
1861 if (InlineRelocs || Obj.isXCOFF())
1862 RelocMap = getRelocsMap(Obj);
1863 bool Is64Bits = Obj.getBytesInAddress() > 4;
1864
1865 // Create a mapping from virtual address to symbol name. This is used to
1866 // pretty print the symbols while disassembling.
1867 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1868 std::map<SectionRef, SmallVector<MappingSymbolPair, 0>> AllMappingSymbols;
1869 // ISA-specific DisassemblerTargets and per-section "$x<ISA>" mapping-symbol
1870 // indexes. Only allocated for RISC-V ELF objects so non-RISC-V disassembly
1871 // does not carry the (otherwise unused) containers. ISATargets is declared
1872 // before AllRISCVISAMappingSymbols so the raw DisassemblerTarget * entries
1873 // in that map never outlive the objects they point at.
1874 using RISCVISASymSection =
1875 SmallVector<std::pair<uint64_t, DisassemblerTarget *>, 0>;
1876 std::unique_ptr<RISCVISATargetCache> ISATargets;
1877 std::unique_ptr<std::map<SectionRef, RISCVISASymSection>>
1878 AllRISCVISAMappingSymbols;
1879 SectionSymbolsTy AbsoluteSymbols;
1880 const StringRef FileName = Obj.getFileName();
1881 if (isRISCVElf(Obj)) {
1882 ISATargets = std::make_unique<RISCVISATargetCache>(args: FileName);
1883 AllRISCVISAMappingSymbols =
1884 std::make_unique<std::map<SectionRef, RISCVISASymSection>>();
1885 }
1886 const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Val: &Obj);
1887 for (const SymbolRef &Symbol : Obj.symbols()) {
1888 Expected<StringRef> NameOrErr = Symbol.getName();
1889 if (!NameOrErr) {
1890 reportWarning(Message: toString(E: NameOrErr.takeError()), File: FileName);
1891 continue;
1892 }
1893 if (NameOrErr->empty() && !(Obj.isXCOFF() && SymbolDescription))
1894 continue;
1895
1896 if (Obj.isELF() &&
1897 (cantFail(ValOrErr: Symbol.getFlags()) & SymbolRef::SF_FormatSpecific)) {
1898 // Symbol is intended not to be displayed by default (STT_FILE,
1899 // STT_SECTION, or a mapping symbol). Ignore STT_SECTION symbols. We will
1900 // synthesize a section symbol if no symbol is defined at offset 0.
1901 //
1902 // For a mapping symbol, store it within both AllSymbols and
1903 // AllMappingSymbols. If --show-all-symbols is unspecified, its label will
1904 // not be printed in disassembly listing.
1905 if (getElfSymbolType(Obj, Sym: Symbol) != ELF::STT_SECTION &&
1906 hasMappingSymbols(Obj)) {
1907 section_iterator SecI = unwrapOrError(EO: Symbol.getSection(), Args: FileName);
1908 if (SecI != Obj.section_end()) {
1909 uint64_t SectionAddr = SecI->getAddress();
1910 uint64_t Address = cantFail(ValOrErr: Symbol.getAddress());
1911 StringRef Name = *NameOrErr;
1912 if (Name.consume_front(Prefix: "$") && Name.size() &&
1913 strchr(s: "adtx", c: Name[0])) {
1914 AllMappingSymbols[*SecI].emplace_back(Args: Address - SectionAddr,
1915 Args: Name[0]);
1916 // For RISC-V "$x<ISAString>" symbols, resolve the ISA string to a
1917 // DisassemblerTarget once and record the pointer so per-instruction
1918 // lookups are a single binary search.
1919 if (isRISCVElf(Obj) && Name[0] == 'x' && Name.size() > 1)
1920 (*AllRISCVISAMappingSymbols)[*SecI].emplace_back(
1921 Args: Address - SectionAddr,
1922 Args: ISATargets->get(Base&: PrimaryTarget, ISAStr: Name.substr(Start: 1)));
1923 AllSymbols[*SecI].push_back(
1924 x: createSymbolInfo(Obj, Symbol, /*MappingSymbol=*/IsMappingSymbol: true));
1925 }
1926 }
1927 }
1928 continue;
1929 }
1930
1931 if (MachO) {
1932 // __mh_(execute|dylib|dylinker|bundle|preload|object)_header are special
1933 // symbols that support MachO header introspection. They do not bind to
1934 // code locations and are irrelevant for disassembly.
1935 if (NameOrErr->starts_with(Prefix: "__mh_") && NameOrErr->ends_with(Suffix: "_header"))
1936 continue;
1937 // Don't ask a Mach-O STAB symbol for its section unless you know that
1938 // STAB symbol's section field refers to a valid section index. Otherwise
1939 // the symbol may error trying to load a section that does not exist.
1940 DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
1941 uint8_t NType =
1942 (MachO->is64Bit() ? MachO->getSymbol64TableEntry(DRI: SymDRI).n_type
1943 : MachO->getSymbolTableEntry(DRI: SymDRI).n_type);
1944 if (NType & MachO::N_STAB)
1945 continue;
1946 }
1947
1948 section_iterator SecI = unwrapOrError(EO: Symbol.getSection(), Args: FileName);
1949 if (SecI != Obj.section_end())
1950 AllSymbols[*SecI].push_back(x: createSymbolInfo(Obj, Symbol));
1951 else
1952 AbsoluteSymbols.push_back(x: createSymbolInfo(Obj, Symbol));
1953 }
1954
1955 if (AllSymbols.empty() && Obj.isELF())
1956 addDynamicElfSymbols(Obj: cast<ELFObjectFileBase>(Val&: Obj), AllSymbols);
1957
1958 if (Obj.isWasm())
1959 addMissingWasmCodeSymbols(Obj: cast<WasmObjectFile>(Val&: Obj), AllSymbols);
1960
1961 if (Obj.isELF() && Obj.sections().empty())
1962 createFakeELFSections(Obj);
1963
1964 DisassemblerTarget *PltTarget = DT;
1965 auto SectionNames = getSectionNames(Obj);
1966 if (SecondaryTarget && isArmElf(Obj)) {
1967 auto PltSectionRef = SectionNames.find(Val: ".plt");
1968 if (PltSectionRef != SectionNames.end()) {
1969 bool PltIsThumb = false;
1970 for (auto [Addr, SymbolName] : AllMappingSymbols[PltSectionRef->second]) {
1971 if (Addr != 0)
1972 continue;
1973
1974 if (SymbolName == 't') {
1975 PltIsThumb = true;
1976 break;
1977 }
1978 if (SymbolName == 'a')
1979 break;
1980 }
1981
1982 if (PrimaryTarget.SubtargetInfo->checkFeatures(FS: "+thumb-mode"))
1983 PltTarget = PltIsThumb ? &PrimaryTarget : &*SecondaryTarget;
1984 else
1985 PltTarget = PltIsThumb ? &*SecondaryTarget : &PrimaryTarget;
1986 }
1987 }
1988 BumpPtrAllocator A;
1989 StringSaver Saver(A);
1990 addPltEntries(STI: *PltTarget->SubtargetInfo, Obj, SectionNames, AllSymbols,
1991 Saver);
1992
1993 // Create a mapping from virtual address to section. An empty section can
1994 // cause more than one section at the same address. Sort such sections to be
1995 // before same-addressed non-empty sections so that symbol lookups prefer the
1996 // non-empty section.
1997 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1998 for (SectionRef Sec : Obj.sections())
1999 SectionAddresses.emplace_back(args: Sec.getAddress(), args&: Sec);
2000 llvm::stable_sort(Range&: SectionAddresses, C: [](const auto &LHS, const auto &RHS) {
2001 if (LHS.first != RHS.first)
2002 return LHS.first < RHS.first;
2003 return LHS.second.getSize() < RHS.second.getSize();
2004 });
2005
2006 // Linked executables (.exe and .dll files) typically don't include a real
2007 // symbol table but they might contain an export table.
2008 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Val: &Obj)) {
2009 for (const auto &ExportEntry : COFFObj->export_directories()) {
2010 StringRef Name;
2011 if (Error E = ExportEntry.getSymbolName(Result&: Name))
2012 reportError(E: std::move(E), FileName: Obj.getFileName());
2013 if (Name.empty())
2014 continue;
2015
2016 uint32_t RVA;
2017 if (Error E = ExportEntry.getExportRVA(Result&: RVA))
2018 reportError(E: std::move(E), FileName: Obj.getFileName());
2019
2020 uint64_t VA = COFFObj->getImageBase() + RVA;
2021 auto Sec = partition_point(
2022 Range&: SectionAddresses, P: [VA](const std::pair<uint64_t, SectionRef> &O) {
2023 return O.first <= VA;
2024 });
2025 if (Sec != SectionAddresses.begin()) {
2026 --Sec;
2027 AllSymbols[Sec->second].emplace_back(args&: VA, args&: Name, args: ELF::STT_NOTYPE);
2028 } else
2029 AbsoluteSymbols.emplace_back(args&: VA, args&: Name, args: ELF::STT_NOTYPE);
2030 }
2031 }
2032
2033 // Sort all the symbols, this allows us to use a simple binary search to find
2034 // Multiple symbols can have the same address. Use a stable sort to stabilize
2035 // the output.
2036 StringSet<> FoundDisasmSymbolSet;
2037 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
2038 llvm::stable_sort(Range&: SecSyms.second);
2039 llvm::stable_sort(Range&: AbsoluteSymbols);
2040
2041 std::unique_ptr<DWARFContext> DICtx;
2042 LiveElementPrinter LEP(*DT->Context->getRegisterInfo(), *DT->SubtargetInfo);
2043
2044 if (DbgVariables != DFDisabled || DbgInlinedFunctions != DFDisabled) {
2045 DICtx = DWARFContext::create(Obj: DbgObj);
2046 for (const std::unique_ptr<DWARFUnit> &CU : DICtx->compile_units())
2047 LEP.addCompileUnit(D: CU->getUnitDIE(ExtractUnitDIEOnly: false));
2048 }
2049
2050 LLVM_DEBUG(LEP.dump());
2051
2052 BBAddrMapInfo FullAddrMap;
2053 auto ReadBBAddrMap = [&](std::optional<unsigned> SectionIndex =
2054 std::nullopt) {
2055 FullAddrMap.clear();
2056 if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Val: &Obj)) {
2057 std::vector<PGOAnalysisMap> PGOAnalyses;
2058 auto BBAddrMapsOrErr = Elf->readBBAddrMap(TextSectionIndex: SectionIndex, PGOAnalyses: &PGOAnalyses);
2059 if (!BBAddrMapsOrErr) {
2060 reportWarning(Message: toString(E: BBAddrMapsOrErr.takeError()), File: Obj.getFileName());
2061 return;
2062 }
2063 for (auto &&[FunctionBBAddrMap, FunctionPGOAnalysis] :
2064 zip_equal(t&: *std::move(BBAddrMapsOrErr), u: std::move(PGOAnalyses))) {
2065 FullAddrMap.AddFunctionEntry(AddrMap: std::move(FunctionBBAddrMap),
2066 PGOMap: std::move(FunctionPGOAnalysis));
2067 }
2068 }
2069 };
2070
2071 // For non-relocatable objects, Read all LLVM_BB_ADDR_MAP sections into a
2072 // single mapping, since they don't have any conflicts.
2073 if (SymbolizeOperands && !Obj.isRelocatableObject())
2074 ReadBBAddrMap();
2075
2076 std::optional<llvm::BTFParser> BTF;
2077 if (InlineRelocs && BTFParser::hasBTFSections(Obj)) {
2078 BTF.emplace();
2079 BTFParser::ParseOptions Opts = {};
2080 Opts.LoadTypes = true;
2081 Opts.LoadRelocs = true;
2082 if (Error E = BTF->parse(Obj, Opts))
2083 WithColor::defaultErrorHandler(Err: std::move(E));
2084 }
2085
2086 for (const SectionRef &Section : ToolSectionFilter(O: Obj)) {
2087 if (FilterSections.empty() && !DisassembleAll &&
2088 (!Section.isText() || Section.isVirtual()))
2089 continue;
2090
2091 uint64_t SectionAddr = Section.getAddress();
2092 uint64_t SectSize = Section.getSize();
2093 if (!SectSize)
2094 continue;
2095
2096 // For relocatable object files, read the LLVM_BB_ADDR_MAP section
2097 // corresponding to this section, if present.
2098 if (SymbolizeOperands && Obj.isRelocatableObject())
2099 ReadBBAddrMap(Section.getIndex());
2100
2101 // Get the list of all the symbols in this section.
2102 SectionSymbolsTy &Symbols = AllSymbols[Section];
2103 auto &MappingSymbols = AllMappingSymbols[Section];
2104 llvm::sort(C&: MappingSymbols);
2105 RISCVISASymSection EmptyRISCVISASyms;
2106 auto &RISCVISASyms = AllRISCVISAMappingSymbols
2107 ? (*AllRISCVISAMappingSymbols)[Section]
2108 : EmptyRISCVISASyms;
2109 llvm::sort(C&: RISCVISASyms);
2110
2111 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(
2112 Input: unwrapOrError(EO: Section.getContents(), Args: Obj.getFileName()));
2113
2114 std::vector<std::unique_ptr<std::string>> SynthesizedLabelNames;
2115 if (Obj.isELF() && Obj.getArch() == Triple::amdgpu) {
2116 // AMDGPU disassembler uses symbolizer for printing labels
2117 addSymbolizer(Ctx&: *DT->Context, Target: DT->TheTarget, TheTriple: DT->TheTriple,
2118 DisAsm: DT->DisAsm.get(), SectionAddr, Bytes, Symbols,
2119 SynthesizedLabelNames);
2120 }
2121
2122 StringRef SegmentName = getSegmentName(MachO, Section);
2123 StringRef SectionName = unwrapOrError(EO: Section.getName(), Args: Obj.getFileName());
2124 // If the section has no symbol at the start, just insert a dummy one.
2125 // Without --show-all-symbols, also insert one if all symbols at the start
2126 // are mapping symbols.
2127 bool CreateDummy = Symbols.empty();
2128 if (!CreateDummy) {
2129 CreateDummy = true;
2130 for (auto &Sym : Symbols) {
2131 if (Sym.Addr != SectionAddr)
2132 break;
2133 if (!Sym.IsMappingSymbol || ShowAllSymbols)
2134 CreateDummy = false;
2135 }
2136 }
2137 if (CreateDummy) {
2138 SymbolInfoTy Sym = createDummySymbolInfo(
2139 Obj, Addr: SectionAddr, Name&: SectionName,
2140 Type: Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT);
2141 if (Obj.isXCOFF())
2142 Symbols.insert(position: Symbols.begin(), x: Sym);
2143 else
2144 Symbols.insert(position: llvm::lower_bound(Range&: Symbols, Value&: Sym), x: Sym);
2145 }
2146
2147 SmallString<40> Comments;
2148 raw_svector_ostream CommentStream(Comments);
2149
2150 uint64_t VMAAdjustment = 0;
2151 if (shouldAdjustVA(Section))
2152 VMAAdjustment = AdjustVMA;
2153
2154 // In executable and shared objects, r_offset holds a virtual address.
2155 // Subtract SectionAddr from the r_offset field of a relocation to get
2156 // the section offset.
2157 uint64_t RelAdjustment = Obj.isRelocatableObject() ? 0 : SectionAddr;
2158 uint64_t Size;
2159 uint64_t Index;
2160 bool PrintedSection = false;
2161 std::vector<RelocationRef> Rels = RelocMap[Section];
2162 std::vector<RelocationRef>::const_iterator RelCur = Rels.begin();
2163 std::vector<RelocationRef>::const_iterator RelEnd = Rels.end();
2164 std::string CurrentRISCVVendorSymbol;
2165 uint64_t CurrentRISCVVendorOffset = 0;
2166
2167 // Loop over each chunk of code between two points where at least
2168 // one symbol is defined.
2169 for (size_t SI = 0, SE = Symbols.size(); SI != SE;) {
2170 // Advance SI past all the symbols starting at the same address,
2171 // and make an ArrayRef of them.
2172 unsigned FirstSI = SI;
2173 uint64_t Start = Symbols[SI].Addr;
2174 ArrayRef<SymbolInfoTy> SymbolsHere;
2175 while (SI != SE && Symbols[SI].Addr == Start)
2176 ++SI;
2177 SymbolsHere = ArrayRef<SymbolInfoTy>(&Symbols[FirstSI], SI - FirstSI);
2178
2179 // Get the demangled names of all those symbols. We end up with a vector
2180 // of StringRef that holds the names we're going to use, and a vector of
2181 // std::string that stores the new strings returned by demangle(), if
2182 // any. If we don't call demangle() then that vector can stay empty.
2183 std::vector<StringRef> SymNamesHere;
2184 std::vector<std::string> DemangledSymNamesHere;
2185 if (Demangle) {
2186 // Fetch the demangled names and store them locally.
2187 for (const SymbolInfoTy &Symbol : SymbolsHere)
2188 DemangledSymNamesHere.push_back(x: demangle(MangledName: Symbol.Name));
2189 // Now we've finished modifying that vector, it's safe to make
2190 // a vector of StringRefs pointing into it.
2191 SymNamesHere.insert(position: SymNamesHere.begin(), first: DemangledSymNamesHere.begin(),
2192 last: DemangledSymNamesHere.end());
2193 } else {
2194 for (const SymbolInfoTy &Symbol : SymbolsHere)
2195 SymNamesHere.push_back(x: Symbol.Name);
2196 }
2197
2198 // Distinguish ELF data from code symbols, which will be used later on to
2199 // decide whether to 'disassemble' this chunk as a data declaration via
2200 // dumpELFData(), or whether to treat it as code.
2201 //
2202 // If data _and_ code symbols are defined at the same address, the code
2203 // takes priority, on the grounds that disassembling code is our main
2204 // purpose here, and it would be a worse failure to _not_ interpret
2205 // something that _was_ meaningful as code than vice versa.
2206 //
2207 // Any ELF symbol type that is not clearly data will be regarded as code.
2208 // In particular, one of the uses of STT_NOTYPE is for branch targets
2209 // inside functions, for which STT_FUNC would be inaccurate.
2210 //
2211 // So here, we spot whether there's any non-data symbol present at all,
2212 // and only set the DisassembleAsELFData flag if there isn't. Also, we use
2213 // this distinction to inform the decision of which symbol to print at
2214 // the head of the section, so that if we're printing code, we print a
2215 // code-related symbol name to go with it.
2216 bool DisassembleAsELFData = false;
2217 size_t DisplaySymIndex = SymbolsHere.size() - 1;
2218 if (Obj.isELF() && !DisassembleAll && Section.isText()) {
2219 DisassembleAsELFData = true; // unless we find a code symbol below
2220
2221 for (size_t i = 0; i < SymbolsHere.size(); ++i) {
2222 uint8_t SymTy = SymbolsHere[i].Type;
2223 if (SymTy != ELF::STT_OBJECT && SymTy != ELF::STT_COMMON) {
2224 DisassembleAsELFData = false;
2225 DisplaySymIndex = i;
2226 }
2227 }
2228 }
2229
2230 // Decide which symbol(s) from this collection we're going to print.
2231 std::vector<bool> SymsToPrint(SymbolsHere.size(), false);
2232 // If the user has given the --disassemble-symbols option, then we must
2233 // display every symbol in that set, and no others.
2234 if (!DisasmSymbolSet.empty()) {
2235 bool FoundAny = false;
2236 for (size_t i = 0; i < SymbolsHere.size(); ++i) {
2237 if (DisasmSymbolSet.count(Key: SymNamesHere[i])) {
2238 SymsToPrint[i] = true;
2239 FoundAny = true;
2240 }
2241 }
2242
2243 // And if none of the symbols here is one that the user asked for, skip
2244 // disassembling this entire chunk of code.
2245 if (!FoundAny)
2246 continue;
2247 } else if (!SymbolsHere[DisplaySymIndex].IsMappingSymbol) {
2248 // Otherwise, print whichever symbol at this location is last in the
2249 // Symbols array, because that array is pre-sorted in a way intended to
2250 // correlate with priority of which symbol to display.
2251 SymsToPrint[DisplaySymIndex] = true;
2252 }
2253
2254 // Now that we know we're disassembling this section, override the choice
2255 // of which symbols to display by printing _all_ of them at this address
2256 // if the user asked for all symbols.
2257 //
2258 // That way, '--show-all-symbols --disassemble-symbol=foo' will print
2259 // only the chunk of code headed by 'foo', but also show any other
2260 // symbols defined at that address, such as aliases for 'foo', or the ARM
2261 // mapping symbol preceding its code.
2262 if (ShowAllSymbols) {
2263 for (size_t i = 0; i < SymbolsHere.size(); ++i)
2264 SymsToPrint[i] = true;
2265 }
2266
2267 if (Start < SectionAddr || StopAddress <= Start)
2268 continue;
2269
2270 FoundDisasmSymbolSet.insert_range(R&: SymNamesHere);
2271
2272 // The end is the section end, the beginning of the next symbol, or
2273 // --stop-address.
2274 uint64_t End = std::min<uint64_t>(a: SectionAddr + SectSize, b: StopAddress);
2275 if (SI < SE)
2276 End = std::min(a: End, b: Symbols[SI].Addr);
2277 if (Start >= End || End <= StartAddress)
2278 continue;
2279 Start -= SectionAddr;
2280 End -= SectionAddr;
2281
2282 if (!PrintedSection) {
2283 PrintedSection = true;
2284 OS << "\nDisassembly of section ";
2285 if (!SegmentName.empty())
2286 OS << SegmentName << ",";
2287 OS << SectionName << ":\n";
2288 }
2289
2290 bool PrintedLabel = false;
2291 for (size_t i = 0; i < SymbolsHere.size(); ++i) {
2292 if (!SymsToPrint[i])
2293 continue;
2294
2295 const SymbolInfoTy &Symbol = SymbolsHere[i];
2296 const StringRef SymbolName = SymNamesHere[i];
2297
2298 if (!PrintedLabel) {
2299 OS << '\n';
2300 PrintedLabel = true;
2301 }
2302 if (LeadingAddr)
2303 OS << format(Fmt: Is64Bits ? "%016" PRIx64 " " : "%08" PRIx64 " ",
2304 Vals: SectionAddr + Start + VMAAdjustment);
2305 if (Obj.isXCOFF() && SymbolDescription) {
2306 OS << getXCOFFSymbolDescription(SymbolInfo: Symbol, SymbolName) << ":\n";
2307 } else
2308 OS << '<' << SymbolName << ">:\n";
2309 }
2310
2311 // Don't print raw contents of a virtual section. A virtual section
2312 // doesn't have any contents in the file.
2313 if (Section.isVirtual()) {
2314 OS << "...\n";
2315 continue;
2316 }
2317
2318 // See if any of the symbols defined at this location triggers target-
2319 // specific disassembly behavior, e.g. of special descriptors or function
2320 // prelude information.
2321 //
2322 // We stop this loop at the first symbol that triggers some kind of
2323 // interesting behavior (if any), on the assumption that if two symbols
2324 // defined at the same address trigger two conflicting symbol handlers,
2325 // the object file is probably confused anyway, and it would make even
2326 // less sense to present the output of _both_ handlers, because that
2327 // would describe the same data twice.
2328 for (size_t SHI = 0; SHI < SymbolsHere.size(); ++SHI) {
2329 SymbolInfoTy Symbol = SymbolsHere[SHI];
2330
2331 Expected<bool> RespondedOrErr = DT->DisAsm->onSymbolStart(
2332 Symbol, Size, Bytes: Bytes.slice(N: Start, M: End - Start), Address: SectionAddr + Start);
2333
2334 if (RespondedOrErr && !*RespondedOrErr) {
2335 // This symbol didn't trigger any interesting handling. Try the other
2336 // symbols defined at this address.
2337 continue;
2338 }
2339
2340 // If onSymbolStart returned an Error, that means it identified some
2341 // kind of special data at this address, but wasn't able to disassemble
2342 // it meaningfully. So we fall back to printing the error out and
2343 // disassembling the failed region as bytes, assuming that the target
2344 // detected the failure before printing anything.
2345 if (!RespondedOrErr) {
2346 std::string ErrMsgStr = toString(E: RespondedOrErr.takeError());
2347 StringRef ErrMsg = ErrMsgStr;
2348 do {
2349 StringRef Line;
2350 std::tie(args&: Line, args&: ErrMsg) = ErrMsg.split(Separator: '\n');
2351 OS << DT->Context->getAsmInfo().getCommentString()
2352 << " error decoding " << SymNamesHere[SHI] << ": " << Line
2353 << '\n';
2354 } while (!ErrMsg.empty());
2355
2356 if (Size) {
2357 OS << DT->Context->getAsmInfo().getCommentString()
2358 << " decoding failed region as bytes\n";
2359 for (uint64_t I = 0; I < Size; ++I)
2360 OS << "\t.byte\t " << format_hex(N: Bytes[I], Width: 1, /*Upper=*/true)
2361 << '\n';
2362 }
2363 }
2364
2365 // Regardless of whether onSymbolStart returned an Error or true, 'Size'
2366 // will have been set to the amount of data covered by whatever prologue
2367 // the target identified. So we advance our own position to beyond that.
2368 // Sometimes that will be the entire distance to the next symbol, and
2369 // sometimes it will be just a prologue and we should start
2370 // disassembling instructions from where it left off.
2371 Start += Size;
2372 break;
2373 }
2374 // Allow targets to reset any per-symbol state.
2375 DT->Printer->onSymbolStart();
2376 formatted_raw_ostream FOS(OS);
2377 Index = Start;
2378 if (SectionAddr < StartAddress)
2379 Index = std::max<uint64_t>(a: Index, b: StartAddress - SectionAddr);
2380
2381 if (DisassembleAsELFData) {
2382 dumpELFData(SectionAddr, Index, End, Bytes, OS&: FOS);
2383 Index = End;
2384 continue;
2385 }
2386
2387 // Skip relocations from symbols that are not dumped.
2388 for (; RelCur != RelEnd; ++RelCur) {
2389 uint64_t Offset = RelCur->getOffset() - RelAdjustment;
2390 if (Index <= Offset)
2391 break;
2392 }
2393
2394 bool DumpARMELFData = false;
2395 bool DumpTracebackTableForXCOFFFunction =
2396 Obj.isXCOFF() && Section.isText() && TracebackTable &&
2397 Symbols[SI - 1].XCOFFSymInfo.StorageMappingClass &&
2398 (*Symbols[SI - 1].XCOFFSymInfo.StorageMappingClass == XCOFF::XMC_PR);
2399
2400 DenseMap<uint64_t, std::string> AllLabels;
2401 DenseMap<uint64_t, std::vector<BBAddrMapLabel>> BBAddrMapLabels;
2402 if (SymbolizeOperands) {
2403 collectLocalBranchTargets(Bytes, MIA: DT->InstrAnalysis.get(),
2404 DisAsm: DT->DisAsm.get(), IP: DT->InstPrinter.get(),
2405 STI: PrimaryTarget.SubtargetInfo.get(),
2406 SectionAddr, Start: Index, End, Labels&: AllLabels);
2407 collectBBAddrMapLabels(FullAddrMap, SectionAddr, Start: Index, End,
2408 Labels&: BBAddrMapLabels);
2409 }
2410
2411 if (DT->InstrAnalysis)
2412 DT->InstrAnalysis->resetState();
2413
2414 while (Index < End) {
2415 uint64_t RelOffset;
2416
2417 // ARM and AArch64 ELF binaries can interleave data and text in the
2418 // same section. We rely on the markers introduced to understand what
2419 // we need to dump. If the data marker is within a function, it is
2420 // denoted as a word/short etc.
2421 if (!MappingSymbols.empty()) {
2422 char Kind = getMappingSymbolKind(MappingSymbols, Address: Index);
2423 DumpARMELFData = Kind == 'd';
2424 if (SecondaryTarget) {
2425 if (Kind == 'a') {
2426 DT = PrimaryIsThumb ? &*SecondaryTarget : &PrimaryTarget;
2427 } else if (Kind == 't') {
2428 DT = PrimaryIsThumb ? &PrimaryTarget : &*SecondaryTarget;
2429 }
2430 }
2431 // RISC-V ISA-aware disassembly: when a "$x<ISAString>" mapping
2432 // symbol is active, use the pre-resolved DisassemblerTarget whose
2433 // STI reflects the indicated ISA so that ISA-specific instructions
2434 // (e.g., vector instructions inside .option arch, +v) are decoded
2435 // correctly.
2436 if (!RISCVISASyms.empty()) {
2437 if (DisassemblerTarget *T =
2438 getRISCVISAMappingTarget(Syms: RISCVISASyms, Address: Index))
2439 DT = T;
2440 else
2441 DT = &PrimaryTarget;
2442 }
2443 } else if (!CHPECodeMap.empty()) {
2444 uint64_t Address = SectionAddr + Index;
2445 auto It = partition_point(
2446 Range&: CHPECodeMap,
2447 P: [Address](const std::pair<uint64_t, uint64_t> &Entry) {
2448 return Entry.first <= Address;
2449 });
2450 if (It != CHPECodeMap.begin() && Address < (It - 1)->second) {
2451 DT = &*SecondaryTarget;
2452 } else {
2453 DT = &PrimaryTarget;
2454 // X64 disassembler range may have left Index unaligned, so
2455 // make sure that it's aligned when we switch back to ARM64
2456 // code.
2457 Index = llvm::alignTo(Value: Index, Align: 4);
2458 if (Index >= End)
2459 break;
2460 }
2461 }
2462
2463 auto findRel = [&]() {
2464 while (RelCur != RelEnd) {
2465 RelOffset = RelCur->getOffset() - RelAdjustment;
2466 // If this relocation is hidden, skip it.
2467 if (getHidden(RelRef: *RelCur) || SectionAddr + RelOffset < StartAddress) {
2468 ++RelCur;
2469 continue;
2470 }
2471
2472 // Stop when RelCur's offset is past the disassembled
2473 // instruction/data.
2474 if (RelOffset >= Index + Size)
2475 return false;
2476 if (RelOffset >= Index)
2477 return true;
2478 ++RelCur;
2479 }
2480 return false;
2481 };
2482
2483 // When -z or --disassemble-zeroes are given we always dissasemble
2484 // them. Otherwise we might want to skip zero bytes we see.
2485 if (!DisassembleZeroes) {
2486 uint64_t MaxOffset = End - Index;
2487 // For --reloc: print zero blocks patched by relocations, so that
2488 // relocations can be shown in the dump.
2489 if (InlineRelocs && RelCur != RelEnd)
2490 MaxOffset = std::min(a: RelCur->getOffset() - RelAdjustment - Index,
2491 b: MaxOffset);
2492
2493 if (size_t N =
2494 countSkippableZeroBytes(Buf: Bytes.slice(N: Index, M: MaxOffset))) {
2495 FOS << "\t\t..." << '\n';
2496 Index += N;
2497 continue;
2498 }
2499 }
2500
2501 if (DumpARMELFData) {
2502 Size = dumpARMELFData(SectionAddr, Index, End, Obj, Bytes,
2503 MappingSymbols, STI: *DT->SubtargetInfo, OS&: FOS);
2504 } else {
2505
2506 if (DumpTracebackTableForXCOFFFunction &&
2507 doesXCOFFTracebackTableBegin(Bytes: Bytes.slice(N: Index, M: 4))) {
2508 dumpTracebackTable(Bytes: Bytes.slice(N: Index),
2509 Address: SectionAddr + Index + VMAAdjustment, OS&: FOS,
2510 End: SectionAddr + End + VMAAdjustment,
2511 STI: *DT->SubtargetInfo, Obj: cast<XCOFFObjectFile>(Val: &Obj));
2512 Index = End;
2513 continue;
2514 }
2515
2516 // Print local label if there's any.
2517 auto Iter1 = BBAddrMapLabels.find(Val: SectionAddr + Index);
2518 if (Iter1 != BBAddrMapLabels.end()) {
2519 for (const auto &BBLabel : Iter1->second)
2520 FOS << "<" << BBLabel.BlockLabel << ">" << BBLabel.PGOAnalysis
2521 << ":\n";
2522 } else {
2523 auto Iter2 = AllLabels.find(Val: SectionAddr + Index);
2524 if (Iter2 != AllLabels.end())
2525 FOS << "<" << Iter2->second << ">:\n";
2526 }
2527
2528 // Disassemble a real instruction or a data when disassemble all is
2529 // provided
2530 MCInst Inst;
2531 ArrayRef<uint8_t> ThisBytes = Bytes.slice(N: Index);
2532 uint64_t ThisAddr = SectionAddr + Index + VMAAdjustment;
2533 bool Disassembled = DT->DisAsm->getInstruction(
2534 Instr&: Inst, Size, Bytes: ThisBytes, Address: ThisAddr, CStream&: CommentStream);
2535 if (Size == 0)
2536 Size = std::min<uint64_t>(
2537 a: ThisBytes.size(),
2538 b: DT->DisAsm->suggestBytesToSkip(Bytes: ThisBytes, Address: ThisAddr));
2539
2540 LEP.update(ThisAddr: {.Address: ThisAddr, .SectionIndex: Section.getIndex()},
2541 NextAddr: {.Address: ThisAddr + Size, .SectionIndex: Section.getIndex()},
2542 IncludeDefinedVars: Index + Size != End);
2543
2544 DT->InstPrinter->setCommentStream(CommentStream);
2545
2546 DT->Printer->printInst(
2547 IP&: *DT->InstPrinter, MI: Disassembled ? &Inst : nullptr,
2548 Bytes: Bytes.slice(N: Index, M: Size),
2549 Address: {.Address: SectionAddr + Index + VMAAdjustment, .SectionIndex: Section.getIndex()}, OS&: FOS,
2550 Annot: "", STI: *DT->SubtargetInfo, SP: &SP, ObjectFilename: Obj.getFileName(), Rels: &Rels, LEP);
2551
2552 DT->InstPrinter->setCommentStream(llvm::nulls());
2553
2554 // If disassembly succeeds, we try to resolve the target address
2555 // (jump target or memory operand address) and print it to the
2556 // right of the instruction.
2557 //
2558 // Otherwise, we don't print anything else so that we avoid
2559 // analyzing invalid or incomplete instruction information.
2560 if (Disassembled && DT->InstrAnalysis) {
2561 llvm::raw_ostream *TargetOS = &FOS;
2562 uint64_t Target;
2563 bool PrintTarget = DT->InstrAnalysis->evaluateBranch(
2564 Inst, Addr: SectionAddr + Index, Size, Target);
2565
2566 if (!PrintTarget) {
2567 if (std::optional<uint64_t> MaybeTarget =
2568 DT->InstrAnalysis->evaluateMemoryOperandAddress(
2569 Inst, STI: DT->SubtargetInfo.get(), Addr: SectionAddr + Index,
2570 Size)) {
2571 Target = *MaybeTarget;
2572 PrintTarget = true;
2573 // Do not print real address when symbolizing.
2574 if (!SymbolizeOperands) {
2575 // Memory operand addresses are printed as comments.
2576 TargetOS = &CommentStream;
2577 *TargetOS << "0x" << Twine::utohexstr(Val: Target);
2578 }
2579 }
2580 }
2581
2582 if (PrintTarget) {
2583 // In a relocatable object, the target's section must reside in
2584 // the same section as the call instruction or it is accessed
2585 // through a relocation.
2586 //
2587 // In a non-relocatable object, the target may be in any section.
2588 // In that case, locate the section(s) containing the target
2589 // address and find the symbol in one of those, if possible.
2590 //
2591 // N.B. Except for XCOFF, we don't walk the relocations in the
2592 // relocatable case yet.
2593 std::vector<const SectionSymbolsTy *> TargetSectionSymbols;
2594 if (!Obj.isRelocatableObject()) {
2595 auto It = llvm::partition_point(
2596 Range&: SectionAddresses,
2597 P: [=](const std::pair<uint64_t, SectionRef> &O) {
2598 return O.first <= Target;
2599 });
2600 uint64_t TargetSecAddr = 0;
2601 while (It != SectionAddresses.begin()) {
2602 --It;
2603 if (TargetSecAddr == 0)
2604 TargetSecAddr = It->first;
2605 if (It->first != TargetSecAddr)
2606 break;
2607 TargetSectionSymbols.push_back(x: &AllSymbols[It->second]);
2608 }
2609 } else {
2610 TargetSectionSymbols.push_back(x: &Symbols);
2611 }
2612 TargetSectionSymbols.push_back(x: &AbsoluteSymbols);
2613
2614 // Find the last symbol in the first candidate section whose
2615 // offset is less than or equal to the target. If there are no
2616 // such symbols, try in the next section and so on, before finally
2617 // using the nearest preceding absolute symbol (if any), if there
2618 // are no other valid symbols.
2619 const SymbolInfoTy *TargetSym = nullptr;
2620 for (const SectionSymbolsTy *TargetSymbols :
2621 TargetSectionSymbols) {
2622 auto It = llvm::partition_point(
2623 Range: *TargetSymbols,
2624 P: [=](const SymbolInfoTy &O) { return O.Addr <= Target; });
2625 while (It != TargetSymbols->begin()) {
2626 --It;
2627 // Skip mapping symbols to avoid possible ambiguity as they
2628 // do not allow uniquely identifying the target address.
2629 if (!It->IsMappingSymbol) {
2630 TargetSym = &*It;
2631 break;
2632 }
2633 }
2634 if (TargetSym)
2635 break;
2636 }
2637
2638 // Branch targets are printed just after the instructions.
2639 // Print the labels corresponding to the target if there's any.
2640 bool BBAddrMapLabelAvailable = BBAddrMapLabels.count(Val: Target);
2641 bool LabelAvailable = AllLabels.count(Val: Target);
2642
2643 if (TargetSym != nullptr) {
2644 uint64_t TargetAddress = TargetSym->Addr;
2645 uint64_t Disp = Target - TargetAddress;
2646 std::string TargetName = Demangle ? demangle(MangledName: TargetSym->Name)
2647 : TargetSym->Name.str();
2648 bool RelFixedUp = false;
2649 SmallString<32> Val;
2650
2651 *TargetOS << " <";
2652 // On XCOFF, we use relocations, even without -r, so we
2653 // can print the correct name for an extern function call.
2654 if (Obj.isXCOFF() && findRel()) {
2655 // Check for possible branch relocations and
2656 // branches to fixup code.
2657 bool BranchRelocationType = true;
2658 XCOFF::RelocationType RelocType;
2659 if (Obj.is64Bit()) {
2660 const XCOFFRelocation64 *Reloc =
2661 reinterpret_cast<XCOFFRelocation64 *>(
2662 RelCur->getRawDataRefImpl().p);
2663 RelFixedUp = Reloc->isFixupIndicated();
2664 RelocType = Reloc->Type;
2665 } else {
2666 const XCOFFRelocation32 *Reloc =
2667 reinterpret_cast<XCOFFRelocation32 *>(
2668 RelCur->getRawDataRefImpl().p);
2669 RelFixedUp = Reloc->isFixupIndicated();
2670 RelocType = Reloc->Type;
2671 }
2672 BranchRelocationType =
2673 RelocType == XCOFF::R_BA || RelocType == XCOFF::R_BR ||
2674 RelocType == XCOFF::R_RBA || RelocType == XCOFF::R_RBR;
2675
2676 // If we have a valid relocation, try to print its
2677 // corresponding symbol name. Multiple relocations on the
2678 // same instruction are not handled.
2679 // Branches to fixup code will have the RelFixedUp flag set in
2680 // the RLD. For these instructions, we print the correct
2681 // branch target, but print the referenced symbol as a
2682 // comment.
2683 if (Error E = getRelocationValueString(Rel: *RelCur, SymbolDescription: false, Result&: Val)) {
2684 // If -r was used, this error will be printed later.
2685 // Otherwise, we ignore the error and print what
2686 // would have been printed without using relocations.
2687 consumeError(Err: std::move(E));
2688 *TargetOS << TargetName;
2689 RelFixedUp = false; // Suppress comment for RLD sym name
2690 } else if (BranchRelocationType && !RelFixedUp)
2691 *TargetOS << Val;
2692 else
2693 *TargetOS << TargetName;
2694 if (Disp)
2695 *TargetOS << "+0x" << Twine::utohexstr(Val: Disp);
2696 } else if (!Disp) {
2697 *TargetOS << TargetName;
2698 } else if (BBAddrMapLabelAvailable) {
2699 *TargetOS << BBAddrMapLabels[Target].front().BlockLabel;
2700 } else if (LabelAvailable) {
2701 *TargetOS << AllLabels[Target];
2702 } else {
2703 // Always Print the binary symbol plus an offset if there's no
2704 // local label corresponding to the target address.
2705 *TargetOS << TargetName << "+0x" << Twine::utohexstr(Val: Disp);
2706 }
2707 *TargetOS << ">";
2708 if (RelFixedUp && !InlineRelocs) {
2709 // We have fixup code for a relocation. We print the
2710 // referenced symbol as a comment.
2711 *TargetOS << "\t# " << Val;
2712 }
2713
2714 } else if (BBAddrMapLabelAvailable) {
2715 *TargetOS << " <" << BBAddrMapLabels[Target].front().BlockLabel
2716 << ">";
2717 } else if (LabelAvailable) {
2718 *TargetOS << " <" << AllLabels[Target] << ">";
2719 }
2720 // By convention, each record in the comment stream should be
2721 // terminated.
2722 if (TargetOS == &CommentStream)
2723 *TargetOS << "\n";
2724 }
2725
2726 DT->InstrAnalysis->updateState(Inst, STI: DT->SubtargetInfo.get(),
2727 Addr: SectionAddr + Index);
2728 } else if (!Disassembled && DT->InstrAnalysis) {
2729 DT->InstrAnalysis->resetState();
2730 }
2731 }
2732
2733 DT->Printer->emitPostInstructionInfo(FOS, MAI: DT->Context->getAsmInfo(),
2734 STI: *DT->SubtargetInfo,
2735 Comments: CommentStream.str(), LEP);
2736 Comments.clear();
2737
2738 if (BTF)
2739 printBTFRelocation(FOS, BTF&: *BTF, Address: {.Address: Index, .SectionIndex: Section.getIndex()}, LEP);
2740
2741 if (InlineRelocs) {
2742 while (findRel()) {
2743 // When --adjust-vma is used, update the address printed.
2744 printRelocation(OS&: FOS, FileName: Obj.getFileName(), Rel: *RelCur,
2745 Address: SectionAddr + RelOffset + VMAAdjustment, Is64Bits,
2746 CurrentRISCVVendorSymbol, CurrentRISCVVendorOffset);
2747 LEP.printAfterOtherLine(OS&: FOS, AfterInst: true);
2748 ++RelCur;
2749 }
2750 }
2751
2752 object::SectionedAddress NextAddr = {
2753 .Address: SectionAddr + Index + VMAAdjustment + Size, .SectionIndex: Section.getIndex()};
2754 LEP.printBoundaryLine(OS&: FOS, Addr: NextAddr, IsEnd: true);
2755
2756 Index += Size;
2757 }
2758 }
2759 }
2760 StringSet<> MissingDisasmSymbolSet =
2761 set_difference(S1: DisasmSymbolSet, S2: FoundDisasmSymbolSet);
2762 for (StringRef Sym : MissingDisasmSymbolSet.keys())
2763 reportWarning(Message: "failed to disassemble missing symbol " + Sym, File: FileName);
2764}
2765
2766static void disassembleObject(ObjectFile *Obj, bool InlineRelocs,
2767 raw_ostream &OS) {
2768 // If information useful for showing the disassembly is missing, try to find a
2769 // more complete binary and disassemble that instead.
2770 OwningBinary<Binary> FetchedBinary;
2771 if (Obj->symbols().empty()) {
2772 if (std::optional<OwningBinary<Binary>> FetchedBinaryOpt =
2773 fetchBinaryByBuildID(Obj: *Obj)) {
2774 if (auto *O = dyn_cast<ObjectFile>(Val: FetchedBinaryOpt->getBinary())) {
2775 if (!O->symbols().empty() ||
2776 (!O->sections().empty() && Obj->sections().empty())) {
2777 FetchedBinary = std::move(*FetchedBinaryOpt);
2778 Obj = O;
2779 }
2780 }
2781 }
2782 }
2783
2784 const Target *TheTarget = getTarget(Obj);
2785
2786 // Default --symbolize-operands to on for BPF, since BPF users expect to see
2787 // basic block labels in disassembly.
2788 SymbolizeOperands =
2789 SymbolizeOperandsOption.value_or(u: Obj->makeTriple().isBPF());
2790
2791 // Package up features to be passed to target/subtarget
2792 Expected<SubtargetFeatures> FeaturesValue = Obj->getFeatures();
2793 if (!FeaturesValue)
2794 reportError(E: FeaturesValue.takeError(), FileName: Obj->getFileName());
2795 SubtargetFeatures Features = *FeaturesValue;
2796 if (!MAttrs.empty()) {
2797 for (unsigned I = 0; I != MAttrs.size(); ++I)
2798 Features.AddFeature(String: MAttrs[I]);
2799 } else if (MCPU.empty() && Obj->makeTriple().isAArch64()) {
2800 Features.AddFeature(String: "+all");
2801 } else if (MCPU.empty() && Obj->makeTriple().isAVR()) {
2802 if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Val: Obj)) {
2803 if (Expected<std::string> VersionOrErr = AVR::getFeatureSetFromEFlag(
2804 EFlag: Elf->getPlatformFlags() & ELF::EF_AVR_ARCH_MASK)) {
2805 Features.AddFeature(String: '+' + *VersionOrErr);
2806 } else {
2807 // If the architecture version cannot be determined from ELF flags,
2808 // fall back to the baseline "avr0" ISA. The AVR disassembler
2809 // requires a valid feature specification to function correctly.
2810 reportWarning(Message: toString(E: VersionOrErr.takeError()) +
2811 ": defaulting to avr0",
2812 File: Obj->getFileName());
2813 Features.AddFeature(String: "+avr0");
2814 }
2815 }
2816 }
2817
2818 if (MCPU.empty())
2819 MCPU = Obj->tryGetCPUName().value_or(u: "").str();
2820
2821 if (isArmElf(Obj: *Obj)) {
2822 // When disassembling big-endian Arm ELF, the instruction endianness is
2823 // determined in a complex way. In relocatable objects, AAELF32 mandates
2824 // that instruction endianness matches the ELF file endianness; in
2825 // executable images, that's true unless the file header has the EF_ARM_BE8
2826 // flag, in which case instructions are little-endian regardless of data
2827 // endianness.
2828 //
2829 // We must set the big-endian-instructions SubtargetFeature to make the
2830 // disassembler read the instructions the right way round, and also tell
2831 // our own prettyprinter to retrieve the encodings the same way to print in
2832 // hex.
2833 const auto *Elf32BE = dyn_cast<ELF32BEObjectFile>(Val: Obj);
2834
2835 if (Elf32BE && (Elf32BE->isRelocatableObject() ||
2836 !(Elf32BE->getPlatformFlags() & ELF::EF_ARM_BE8))) {
2837 Features.AddFeature(String: "+big-endian-instructions");
2838 ARMPrettyPrinterInst.setInstructionEndianness(llvm::endianness::big);
2839 } else {
2840 ARMPrettyPrinterInst.setInstructionEndianness(llvm::endianness::little);
2841 }
2842 }
2843
2844 DisassemblerTarget PrimaryTarget(TheTarget, *Obj, TripleName, MCPU, Features);
2845
2846 // If we have an ARM object file, we need a second disassembler, because
2847 // ARM CPUs have two different instruction sets: ARM mode, and Thumb mode.
2848 // We use mapping symbols to switch between the two assemblers, where
2849 // appropriate.
2850 std::optional<DisassemblerTarget> SecondaryTarget;
2851
2852 if (isArmElf(Obj: *Obj)) {
2853 if (!PrimaryTarget.SubtargetInfo->checkFeatures(FS: "+mclass")) {
2854 if (PrimaryTarget.SubtargetInfo->checkFeatures(FS: "+thumb-mode"))
2855 Features.AddFeature(String: "-thumb-mode");
2856 else
2857 Features.AddFeature(String: "+thumb-mode");
2858 SecondaryTarget.emplace(args&: PrimaryTarget, args&: Features);
2859 }
2860 } else if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Val: Obj)) {
2861 const chpe_metadata *CHPEMetadata = COFFObj->getCHPEMetadata();
2862 if (CHPEMetadata && CHPEMetadata->CodeMapCount) {
2863 // Set up x86_64 disassembler for ARM64EC binaries.
2864 Triple X64Triple(TripleName);
2865 X64Triple.setArch(Kind: Triple::ArchType::x86_64);
2866
2867 std::string Error;
2868 const Target *X64Target =
2869 TargetRegistry::lookupTarget(ArchName: "", TheTriple&: X64Triple, Error);
2870 if (X64Target) {
2871 SubtargetFeatures X64Features;
2872 SecondaryTarget.emplace(args&: X64Target, args&: *Obj, args: X64Triple.getTriple(), args: "",
2873 args&: X64Features);
2874 } else {
2875 reportWarning(Message: Error, File: Obj->getFileName());
2876 }
2877 }
2878 }
2879
2880 const ObjectFile *DbgObj = Obj;
2881 if (!FetchedBinary.getBinary() && !Obj->hasDebugInfo()) {
2882 if (std::optional<OwningBinary<Binary>> DebugBinaryOpt =
2883 fetchBinaryByBuildID(Obj: *Obj)) {
2884 if (auto *FetchedObj =
2885 dyn_cast<const ObjectFile>(Val: DebugBinaryOpt->getBinary())) {
2886 if (FetchedObj->hasDebugInfo()) {
2887 FetchedBinary = std::move(*DebugBinaryOpt);
2888 DbgObj = FetchedObj;
2889 }
2890 }
2891 }
2892 }
2893
2894 std::unique_ptr<object::Binary> DSYMBinary;
2895 std::unique_ptr<MemoryBuffer> DSYMBuf;
2896 if (!DbgObj->hasDebugInfo()) {
2897 if (const MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(Val: &*Obj)) {
2898 DbgObj = objdump::getMachODSymObject(O: MachOOF, Filename: Obj->getFileName(),
2899 DSYMBinary, DSYMBuf);
2900 if (!DbgObj)
2901 return;
2902 }
2903 }
2904
2905 SourcePrinter SP(DbgObj, TheTarget->getName());
2906
2907 for (StringRef Opt : DisassemblerOptions)
2908 if (!PrimaryTarget.InstPrinter->applyTargetSpecificCLOption(Opt))
2909 reportError(File: Obj->getFileName(),
2910 Message: "Unrecognized disassembler option: " + Opt);
2911
2912 disassembleObject(Obj&: *Obj, DbgObj: *DbgObj, PrimaryTarget, SecondaryTarget, SP,
2913 InlineRelocs, OS);
2914}
2915
2916void Dumper::printRelocations() {
2917 StringRef Fmt = O.getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
2918
2919 // Build a mapping from relocation target to a vector of relocation
2920 // sections. Usually, there is an only one relocation section for
2921 // each relocated section.
2922 MapVector<SectionRef, std::vector<SectionRef>> SecToRelSec;
2923 uint64_t Ndx;
2924 for (const SectionRef &Section : ToolSectionFilter(O, Idx: &Ndx)) {
2925 if (O.isELF() && (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC))
2926 continue;
2927 if (Section.relocations().empty())
2928 continue;
2929 Expected<section_iterator> SecOrErr = Section.getRelocatedSection();
2930 if (!SecOrErr)
2931 reportError(File: O.getFileName(),
2932 Message: "section (" + Twine(Ndx) +
2933 "): unable to get a relocation target: " +
2934 toString(E: SecOrErr.takeError()));
2935 SecToRelSec[**SecOrErr].push_back(x: Section);
2936 }
2937
2938 for (std::pair<SectionRef, std::vector<SectionRef>> &P : SecToRelSec) {
2939 StringRef SecName = unwrapOrError(EO: P.first.getName(), Args: O.getFileName());
2940 outs() << "\nRELOCATION RECORDS FOR [" << SecName << "]:\n";
2941 uint32_t OffsetPadding = (O.getBytesInAddress() > 4 ? 16 : 8);
2942 uint32_t TypePadding = 24;
2943 outs() << left_justify(Str: "OFFSET", Width: OffsetPadding) << " "
2944 << left_justify(Str: "TYPE", Width: TypePadding) << " "
2945 << "VALUE\n";
2946
2947 for (SectionRef Section : P.second) {
2948 // CREL sections require decoding, each section may have its own specific
2949 // decode problems.
2950 if (O.isELF() && ELFSectionRef(Section).getType() == ELF::SHT_CREL) {
2951 StringRef Err =
2952 cast<const ELFObjectFileBase>(Val: O).getCrelDecodeProblem(Sec: Section);
2953 if (!Err.empty()) {
2954 reportUniqueWarning(Msg: Err);
2955 continue;
2956 }
2957 }
2958 std::string CurrentRISCVVendorSymbol;
2959 uint64_t CurrentRISCVVendorOffset = 0;
2960 for (const RelocationRef &Reloc : Section.relocations()) {
2961 uint64_t Address = Reloc.getOffset();
2962 SmallString<32> RelocName;
2963 SmallString<32> ValueStr;
2964 if (Address < StartAddress || Address > StopAddress || getHidden(RelRef: Reloc))
2965 continue;
2966 StringRef Name = getRelocTypeName(Rel: Reloc, RelocName,
2967 CurrentRISCVVendorSymbol,
2968 CurrentRISCVVendorOffset);
2969 if (Error E =
2970 getRelocationValueString(Rel: Reloc, SymbolDescription, Result&: ValueStr))
2971 reportUniqueWarning(Err: std::move(E));
2972
2973 outs() << format(Fmt: Fmt.data(), Vals: Address) << " "
2974 << left_justify(Str: Name, Width: TypePadding) << " " << ValueStr << "\n";
2975 }
2976 }
2977 }
2978}
2979
2980// Returns true if we need to show LMA column when dumping section headers. We
2981// show it only when the platform is ELF and either we have at least one section
2982// whose VMA and LMA are different and/or when --show-lma flag is used.
2983static bool shouldDisplayLMA(const ObjectFile &Obj) {
2984 if (!Obj.isELF())
2985 return false;
2986 for (const SectionRef &S : ToolSectionFilter(O: Obj))
2987 if (S.getAddress() != getELFSectionLMA(Sec: S))
2988 return true;
2989 return ShowLMA;
2990}
2991
2992static size_t getMaxSectionNameWidth(const ObjectFile &Obj) {
2993 // Default column width for names is 13 even if no names are that long.
2994 size_t MaxWidth = 13;
2995 for (const SectionRef &Section : ToolSectionFilter(O: Obj)) {
2996 StringRef Name = unwrapOrError(EO: Section.getName(), Args: Obj.getFileName());
2997 MaxWidth = std::max(a: MaxWidth, b: Name.size());
2998 }
2999 return MaxWidth;
3000}
3001
3002void objdump::printSectionHeaders(ObjectFile &Obj) {
3003 if (Obj.isELF() && Obj.sections().empty())
3004 createFakeELFSections(Obj);
3005
3006 size_t NameWidth = getMaxSectionNameWidth(Obj);
3007 size_t AddressWidth = 2 * Obj.getBytesInAddress();
3008 bool HasLMAColumn = shouldDisplayLMA(Obj);
3009 outs() << "\nSections:\n";
3010 if (HasLMAColumn)
3011 outs() << "Idx " << left_justify(Str: "Name", Width: NameWidth) << " Size "
3012 << left_justify(Str: "VMA", Width: AddressWidth) << " "
3013 << left_justify(Str: "LMA", Width: AddressWidth) << " Type\n";
3014 else
3015 outs() << "Idx " << left_justify(Str: "Name", Width: NameWidth) << " Size "
3016 << left_justify(Str: "VMA", Width: AddressWidth) << " Type\n";
3017
3018 uint64_t Idx;
3019 for (const SectionRef &Section : ToolSectionFilter(O: Obj, Idx: &Idx)) {
3020 StringRef Name = unwrapOrError(EO: Section.getName(), Args: Obj.getFileName());
3021 uint64_t VMA = Section.getAddress();
3022 if (shouldAdjustVA(Section))
3023 VMA += AdjustVMA;
3024
3025 uint64_t Size = Section.getSize();
3026
3027 std::string Type = Section.isText() ? "TEXT" : "";
3028 if (Section.isData())
3029 Type += Type.empty() ? "DATA" : ", DATA";
3030 if (Section.isBSS())
3031 Type += Type.empty() ? "BSS" : ", BSS";
3032 if (Section.isDebugSection())
3033 Type += Type.empty() ? "DEBUG" : ", DEBUG";
3034
3035 if (HasLMAColumn)
3036 outs() << format(Fmt: "%3" PRIu64 " %-*s %08" PRIx64 " ", Vals: Idx, Vals: NameWidth,
3037 Vals: Name.str().c_str(), Vals: Size)
3038 << format_hex_no_prefix(N: VMA, Width: AddressWidth) << " "
3039 << format_hex_no_prefix(N: getELFSectionLMA(Sec: Section), Width: AddressWidth)
3040 << " " << Type << "\n";
3041 else
3042 outs() << format(Fmt: "%3" PRIu64 " %-*s %08" PRIx64 " ", Vals: Idx, Vals: NameWidth,
3043 Vals: Name.str().c_str(), Vals: Size)
3044 << format_hex_no_prefix(N: VMA, Width: AddressWidth) << " " << Type << "\n";
3045 }
3046}
3047
3048void objdump::printSectionContents(const ObjectFile *Obj) {
3049 const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Val: Obj);
3050
3051 for (const SectionRef &Section : ToolSectionFilter(O: *Obj)) {
3052 StringRef Name = unwrapOrError(EO: Section.getName(), Args: Obj->getFileName());
3053 uint64_t BaseAddr = Section.getAddress();
3054 uint64_t Size = Section.getSize();
3055 if (!Size)
3056 continue;
3057
3058 outs() << "Contents of section ";
3059 StringRef SegmentName = getSegmentName(MachO, Section);
3060 if (!SegmentName.empty())
3061 outs() << SegmentName << ",";
3062 outs() << Name << ":\n";
3063 if (Section.isBSS()) {
3064 outs() << format(Fmt: "<skipping contents of bss section at [%04" PRIx64
3065 ", %04" PRIx64 ")>\n",
3066 Vals: BaseAddr, Vals: BaseAddr + Size);
3067 continue;
3068 }
3069
3070 StringRef Contents =
3071 unwrapOrError(EO: Section.getContents(), Args: Obj->getFileName());
3072
3073 // Dump out the content as hex and printable ascii characters.
3074 for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) {
3075 outs() << format(Fmt: " %04" PRIx64 " ", Vals: BaseAddr + Addr);
3076 // Dump line of hex.
3077 for (std::size_t I = 0; I < 16; ++I) {
3078 if (I != 0 && I % 4 == 0)
3079 outs() << ' ';
3080 if (Addr + I < End)
3081 outs() << hexdigit(X: (Contents[Addr + I] >> 4) & 0xF, LowerCase: true)
3082 << hexdigit(X: Contents[Addr + I] & 0xF, LowerCase: true);
3083 else
3084 outs() << " ";
3085 }
3086 // Print ascii.
3087 outs() << " ";
3088 for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) {
3089 if (isPrint(C: static_cast<unsigned char>(Contents[Addr + I]) & 0xFF))
3090 outs() << Contents[Addr + I];
3091 else
3092 outs() << ".";
3093 }
3094 outs() << "\n";
3095 }
3096 }
3097}
3098
3099void Dumper::printSymbolTable(StringRef ArchiveName, StringRef ArchitectureName,
3100 bool DumpDynamic) {
3101 if (O.isCOFF() && !DumpDynamic) {
3102 outs() << "\nSYMBOL TABLE:\n";
3103 printCOFFSymbolTable(O: cast<const COFFObjectFile>(Val: O));
3104 return;
3105 }
3106
3107 const StringRef FileName = O.getFileName();
3108
3109 if (!DumpDynamic) {
3110 outs() << "\nSYMBOL TABLE:\n";
3111 for (auto I = O.symbol_begin(); I != O.symbol_end(); ++I)
3112 printSymbol(Symbol: *I, SymbolVersions: {}, FileName, ArchiveName, ArchitectureName, DumpDynamic);
3113 return;
3114 }
3115
3116 outs() << "\nDYNAMIC SYMBOL TABLE:\n";
3117 if (!O.isELF()) {
3118 reportWarning(
3119 Message: "this operation is not currently supported for this file format",
3120 File: FileName);
3121 return;
3122 }
3123
3124 const ELFObjectFileBase *ELF = cast<const ELFObjectFileBase>(Val: &O);
3125 auto Symbols = ELF->getDynamicSymbolIterators();
3126 Expected<std::vector<VersionEntry>> SymbolVersionsOrErr =
3127 ELF->readDynsymVersions();
3128 if (!SymbolVersionsOrErr) {
3129 reportWarning(Message: toString(E: SymbolVersionsOrErr.takeError()), File: FileName);
3130 SymbolVersionsOrErr = std::vector<VersionEntry>();
3131 (void)!SymbolVersionsOrErr;
3132 }
3133 for (auto &Sym : Symbols)
3134 printSymbol(Symbol: Sym, SymbolVersions: *SymbolVersionsOrErr, FileName, ArchiveName,
3135 ArchitectureName, DumpDynamic);
3136}
3137
3138void Dumper::printSymbol(const SymbolRef &Symbol,
3139 ArrayRef<VersionEntry> SymbolVersions,
3140 StringRef FileName, StringRef ArchiveName,
3141 StringRef ArchitectureName, bool DumpDynamic) {
3142 const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Val: &O);
3143 Expected<uint64_t> AddrOrErr = Symbol.getAddress();
3144 if (!AddrOrErr) {
3145 reportUniqueWarning(Err: AddrOrErr.takeError());
3146 return;
3147 }
3148
3149 // Don't ask a Mach-O STAB symbol for its section unless you know that
3150 // STAB symbol's section field refers to a valid section index. Otherwise
3151 // the symbol may error trying to load a section that does not exist.
3152 bool IsSTAB = false;
3153 if (MachO) {
3154 DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
3155 uint8_t NType =
3156 (MachO->is64Bit() ? MachO->getSymbol64TableEntry(DRI: SymDRI).n_type
3157 : MachO->getSymbolTableEntry(DRI: SymDRI).n_type);
3158 if (NType & MachO::N_STAB)
3159 IsSTAB = true;
3160 }
3161 section_iterator Section = IsSTAB
3162 ? O.section_end()
3163 : unwrapOrError(EO: Symbol.getSection(), Args&: FileName,
3164 Args&: ArchiveName, Args&: ArchitectureName);
3165
3166 uint64_t Address = *AddrOrErr;
3167 if (Section != O.section_end() && shouldAdjustVA(Section: *Section))
3168 Address += AdjustVMA;
3169 if ((Address < StartAddress) || (Address > StopAddress))
3170 return;
3171 SymbolRef::Type Type =
3172 unwrapOrError(EO: Symbol.getType(), Args&: FileName, Args&: ArchiveName, Args&: ArchitectureName);
3173 uint32_t Flags =
3174 unwrapOrError(EO: Symbol.getFlags(), Args&: FileName, Args&: ArchiveName, Args&: ArchitectureName);
3175
3176 StringRef Name;
3177 if (Type == SymbolRef::ST_Debug && Section != O.section_end()) {
3178 if (Expected<StringRef> NameOrErr = Section->getName())
3179 Name = *NameOrErr;
3180 else
3181 consumeError(Err: NameOrErr.takeError());
3182
3183 } else {
3184 Name = unwrapOrError(EO: Symbol.getName(), Args&: FileName, Args&: ArchiveName,
3185 Args&: ArchitectureName);
3186 }
3187
3188 bool Global = Flags & SymbolRef::SF_Global;
3189 bool Weak = Flags & SymbolRef::SF_Weak;
3190 bool Absolute = Flags & SymbolRef::SF_Absolute;
3191 bool Common = Flags & SymbolRef::SF_Common;
3192 bool Hidden = Flags & SymbolRef::SF_Hidden;
3193
3194 char GlobLoc = ' ';
3195 if ((Section != O.section_end() || Absolute) && !Weak)
3196 GlobLoc = Global ? 'g' : 'l';
3197 char IFunc = ' ';
3198 if (O.isELF()) {
3199 if (ELFSymbolRef(Symbol).getELFType() == ELF::STT_GNU_IFUNC)
3200 IFunc = 'i';
3201 if (ELFSymbolRef(Symbol).getBinding() == ELF::STB_GNU_UNIQUE)
3202 GlobLoc = 'u';
3203 }
3204
3205 char Debug = ' ';
3206 if (DumpDynamic)
3207 Debug = 'D';
3208 else if (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
3209 Debug = 'd';
3210
3211 char FileFunc = ' ';
3212 if (Type == SymbolRef::ST_File)
3213 FileFunc = 'f';
3214 else if (Type == SymbolRef::ST_Function)
3215 FileFunc = 'F';
3216 else if (Type == SymbolRef::ST_Data)
3217 FileFunc = 'O';
3218
3219 const char *Fmt = O.getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
3220
3221 outs() << format(Fmt, Vals: Address) << " "
3222 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
3223 << (Weak ? 'w' : ' ') // Weak?
3224 << ' ' // Constructor. Not supported yet.
3225 << ' ' // Warning. Not supported yet.
3226 << IFunc // Indirect reference to another symbol.
3227 << Debug // Debugging (d) or dynamic (D) symbol.
3228 << FileFunc // Name of function (F), file (f) or object (O).
3229 << ' ';
3230 if (Absolute) {
3231 outs() << "*ABS*";
3232 } else if (Common) {
3233 outs() << "*COM*";
3234 } else if (Section == O.section_end()) {
3235 if (O.isXCOFF()) {
3236 XCOFFSymbolRef XCOFFSym = cast<const XCOFFObjectFile>(Val: O).toSymbolRef(
3237 Ref: Symbol.getRawDataRefImpl());
3238 if (XCOFF::N_DEBUG == XCOFFSym.getSectionNumber())
3239 outs() << "*DEBUG*";
3240 else
3241 outs() << "*UND*";
3242 } else
3243 outs() << "*UND*";
3244 } else {
3245 StringRef SegmentName = getSegmentName(MachO, Section: *Section);
3246 if (!SegmentName.empty())
3247 outs() << SegmentName << ",";
3248 StringRef SectionName = unwrapOrError(EO: Section->getName(), Args&: FileName);
3249 outs() << SectionName;
3250 if (O.isXCOFF()) {
3251 std::optional<SymbolRef> SymRef =
3252 getXCOFFSymbolContainingSymbolRef(Obj: cast<XCOFFObjectFile>(Val: O), Sym: Symbol);
3253 if (SymRef) {
3254
3255 Expected<StringRef> NameOrErr = SymRef->getName();
3256
3257 if (NameOrErr) {
3258 outs() << " (csect:";
3259 std::string SymName =
3260 Demangle ? demangle(MangledName: *NameOrErr) : NameOrErr->str();
3261
3262 if (SymbolDescription)
3263 SymName = getXCOFFSymbolDescription(SymbolInfo: createSymbolInfo(Obj: O, Symbol: *SymRef),
3264 SymbolName: SymName);
3265
3266 outs() << ' ' << SymName;
3267 outs() << ") ";
3268 } else
3269 reportWarning(Message: toString(E: NameOrErr.takeError()), File: FileName);
3270 }
3271 }
3272 }
3273
3274 if (Common)
3275 outs() << '\t' << format(Fmt, Vals: static_cast<uint64_t>(Symbol.getAlignment()));
3276 else if (O.isXCOFF())
3277 outs() << '\t'
3278 << format(Fmt, Vals: cast<XCOFFObjectFile>(Val: O).getSymbolSize(
3279 Symb: Symbol.getRawDataRefImpl()));
3280 else if (O.isELF())
3281 outs() << '\t' << format(Fmt, Vals: ELFSymbolRef(Symbol).getSize());
3282 else if (O.isWasm())
3283 outs() << '\t'
3284 << format(Fmt, Vals: static_cast<uint64_t>(
3285 cast<WasmObjectFile>(Val: O).getSymbolSize(Sym: Symbol)));
3286
3287 if (O.isELF()) {
3288 if (!SymbolVersions.empty()) {
3289 const VersionEntry &Ver =
3290 SymbolVersions[Symbol.getRawDataRefImpl().d.b - 1];
3291 std::string Str;
3292 if (!Ver.Name.empty())
3293 Str = Ver.IsVerDef ? ' ' + Ver.Name : '(' + Ver.Name + ')';
3294 outs() << ' ' << left_justify(Str, Width: 12);
3295 }
3296
3297 uint8_t Other = ELFSymbolRef(Symbol).getOther();
3298 switch (Other) {
3299 case ELF::STV_DEFAULT:
3300 break;
3301 case ELF::STV_INTERNAL:
3302 outs() << " .internal";
3303 break;
3304 case ELF::STV_HIDDEN:
3305 outs() << " .hidden";
3306 break;
3307 case ELF::STV_PROTECTED:
3308 outs() << " .protected";
3309 break;
3310 default:
3311 outs() << format(Fmt: " 0x%02x", Vals: Other);
3312 break;
3313 }
3314 } else if (Hidden) {
3315 outs() << " .hidden";
3316 }
3317
3318 std::string SymName = Demangle ? demangle(MangledName: Name) : Name.str();
3319 if (O.isXCOFF() && SymbolDescription)
3320 SymName = getXCOFFSymbolDescription(SymbolInfo: createSymbolInfo(Obj: O, Symbol), SymbolName: SymName);
3321
3322 outs() << ' ' << SymName << '\n';
3323}
3324
3325static void printUnwindInfo(const ObjectFile *O) {
3326 outs() << "Unwind info:\n\n";
3327
3328 if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(Val: O))
3329 printCOFFUnwindInfo(O: Coff);
3330 else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: O))
3331 printMachOUnwindInfo(O: MachO);
3332 else
3333 // TODO: Extract DWARF dump tool to objdump.
3334 WithColor::error(OS&: errs(), Prefix: ToolName)
3335 << "This operation is only currently supported "
3336 "for COFF and MachO object files.\n";
3337}
3338
3339/// Dump the raw contents of the __clangast section so the output can be piped
3340/// into llvm-bcanalyzer.
3341static void printRawClangAST(const ObjectFile *Obj) {
3342 if (outs().is_displayed()) {
3343 WithColor::error(OS&: errs(), Prefix: ToolName)
3344 << "The -raw-clang-ast option will dump the raw binary contents of "
3345 "the clang ast section.\n"
3346 "Please redirect the output to a file or another program such as "
3347 "llvm-bcanalyzer.\n";
3348 return;
3349 }
3350
3351 StringRef ClangASTSectionName("__clangast");
3352 if (Obj->isCOFF()) {
3353 ClangASTSectionName = "clangast";
3354 }
3355
3356 std::optional<object::SectionRef> ClangASTSection;
3357 for (auto Sec : ToolSectionFilter(O: *Obj)) {
3358 StringRef Name;
3359 if (Expected<StringRef> NameOrErr = Sec.getName())
3360 Name = *NameOrErr;
3361 else
3362 consumeError(Err: NameOrErr.takeError());
3363
3364 if (Name == ClangASTSectionName) {
3365 ClangASTSection = Sec;
3366 break;
3367 }
3368 }
3369 if (!ClangASTSection)
3370 return;
3371
3372 StringRef ClangASTContents =
3373 unwrapOrError(EO: ClangASTSection->getContents(), Args: Obj->getFileName());
3374 outs().write(Ptr: ClangASTContents.data(), Size: ClangASTContents.size());
3375}
3376
3377static void printFaultMaps(const ObjectFile *Obj) {
3378 StringRef FaultMapSectionName;
3379
3380 if (Obj->isELF()) {
3381 FaultMapSectionName = ".llvm_faultmaps";
3382 } else if (Obj->isMachO()) {
3383 FaultMapSectionName = "__llvm_faultmaps";
3384 } else {
3385 WithColor::error(OS&: errs(), Prefix: ToolName)
3386 << "This operation is only currently supported "
3387 "for ELF and Mach-O executable files.\n";
3388 return;
3389 }
3390
3391 std::optional<object::SectionRef> FaultMapSection;
3392
3393 for (auto Sec : ToolSectionFilter(O: *Obj)) {
3394 StringRef Name;
3395 if (Expected<StringRef> NameOrErr = Sec.getName())
3396 Name = *NameOrErr;
3397 else
3398 consumeError(Err: NameOrErr.takeError());
3399
3400 if (Name == FaultMapSectionName) {
3401 FaultMapSection = Sec;
3402 break;
3403 }
3404 }
3405
3406 outs() << "FaultMap table:\n";
3407
3408 if (!FaultMapSection) {
3409 outs() << "<not found>\n";
3410 return;
3411 }
3412
3413 StringRef FaultMapContents =
3414 unwrapOrError(EO: FaultMapSection->getContents(), Args: Obj->getFileName());
3415 FaultMapParser FMP(FaultMapContents.bytes_begin(),
3416 FaultMapContents.bytes_end());
3417
3418 outs() << FMP;
3419}
3420
3421void Dumper::printPrivateHeaders() {
3422 reportError(File: O.getFileName(), Message: "Invalid/Unsupported object file format");
3423}
3424
3425static void printFileHeaders(const ObjectFile *O) {
3426 if (!O->isELF() && !O->isCOFF() && !O->isXCOFF())
3427 reportError(File: O->getFileName(), Message: "Invalid/Unsupported object file format");
3428
3429 Triple::ArchType AT = O->getArch();
3430 outs() << "architecture: " << Triple::getArchTypeName(Kind: AT) << "\n";
3431 uint64_t Address = unwrapOrError(EO: O->getStartAddress(), Args: O->getFileName());
3432
3433 StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
3434 outs() << "start address: "
3435 << "0x" << format(Fmt: Fmt.data(), Vals: Address) << "\n";
3436}
3437
3438static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
3439 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
3440 if (!ModeOrErr) {
3441 WithColor::error(OS&: errs(), Prefix: ToolName) << "ill-formed archive entry.\n";
3442 consumeError(Err: ModeOrErr.takeError());
3443 return;
3444 }
3445 sys::fs::perms Mode = ModeOrErr.get();
3446 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
3447 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
3448 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
3449 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
3450 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
3451 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
3452 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
3453 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
3454 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
3455
3456 outs() << " ";
3457
3458 outs() << format(Fmt: "%d/%d %6" PRId64 " ", Vals: unwrapOrError(EO: C.getUID(), Args&: Filename),
3459 Vals: unwrapOrError(EO: C.getGID(), Args&: Filename),
3460 Vals: unwrapOrError(EO: C.getRawSize(), Args&: Filename));
3461
3462 StringRef RawLastModified = C.getRawLastModified();
3463 unsigned Seconds;
3464 if (RawLastModified.getAsInteger(Radix: 10, Result&: Seconds))
3465 outs() << "(date: \"" << RawLastModified
3466 << "\" contains non-decimal chars) ";
3467 else {
3468 // Since ctime(3) returns a 26 character string of the form:
3469 // "Sun Sep 16 01:03:52 1973\n\0"
3470 // just print 24 characters.
3471 time_t t = Seconds;
3472 outs() << format(Fmt: "%.24s ", Vals: ctime(timer: &t));
3473 }
3474
3475 StringRef Name = "";
3476 Expected<StringRef> NameOrErr = C.getName();
3477 if (!NameOrErr) {
3478 consumeError(Err: NameOrErr.takeError());
3479 Name = unwrapOrError(EO: C.getRawName(), Args&: Filename);
3480 } else {
3481 Name = NameOrErr.get();
3482 }
3483 outs() << Name << "\n";
3484}
3485
3486// For ELF only now.
3487static bool shouldWarnForInvalidStartStopAddress(ObjectFile *Obj) {
3488 if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Val: Obj)) {
3489 if (Elf->getEType() != ELF::ET_REL)
3490 return true;
3491 }
3492 return false;
3493}
3494
3495static void checkForInvalidStartStopAddress(ObjectFile *Obj, uint64_t Start,
3496 uint64_t Stop) {
3497 if (!shouldWarnForInvalidStartStopAddress(Obj))
3498 return;
3499
3500 for (const SectionRef &Section : Obj->sections())
3501 if (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC) {
3502 uint64_t BaseAddr = Section.getAddress();
3503 uint64_t Size = Section.getSize();
3504 if ((Start < BaseAddr + Size) && Stop > BaseAddr)
3505 return;
3506 }
3507
3508 if (!HasStartAddressFlag)
3509 reportWarning(Message: "no section has address less than 0x" +
3510 Twine::utohexstr(Val: Stop) + " specified by --stop-address",
3511 File: Obj->getFileName());
3512 else if (!HasStopAddressFlag)
3513 reportWarning(Message: "no section has address greater than or equal to 0x" +
3514 Twine::utohexstr(Val: Start) + " specified by --start-address",
3515 File: Obj->getFileName());
3516 else
3517 reportWarning(Message: "no section overlaps the range [0x" +
3518 Twine::utohexstr(Val: Start) + ",0x" + Twine::utohexstr(Val: Stop) +
3519 ") specified by --start-address/--stop-address",
3520 File: Obj->getFileName());
3521}
3522
3523static void dumpObject(ObjectFile *O, const Archive *A = nullptr,
3524 const Archive::Child *C = nullptr) {
3525 Expected<std::unique_ptr<Dumper>> DumperOrErr = createDumper(Obj: *O);
3526 if (!DumperOrErr) {
3527 reportError(E: DumperOrErr.takeError(), FileName: O->getFileName(),
3528 ArchiveName: A ? A->getFileName() : "");
3529 return;
3530 }
3531 Dumper &D = **DumperOrErr;
3532
3533 // Avoid other output when using a raw option.
3534 if (!RawClangAST) {
3535 outs() << '\n';
3536 if (A)
3537 outs() << A->getFileName() << "(" << O->getFileName() << ")";
3538 else
3539 outs() << O->getFileName();
3540 outs() << ":\tfile format " << O->getFileFormatName().lower() << "\n";
3541 }
3542
3543 if (HasStartAddressFlag || HasStopAddressFlag)
3544 checkForInvalidStartStopAddress(Obj: O, Start: StartAddress, Stop: StopAddress);
3545
3546 // TODO: Change print* free functions to Dumper member functions to utilitize
3547 // stateful functions like reportUniqueWarning.
3548
3549 // Note: the order here matches GNU objdump for compatability.
3550 StringRef ArchiveName = A ? A->getFileName() : "";
3551 if (ArchiveHeaders && !MachOOpt && C)
3552 printArchiveChild(Filename: ArchiveName, C: *C);
3553 if (FileHeaders)
3554 printFileHeaders(O);
3555 if (PrivateHeaders || FirstPrivateHeader)
3556 D.printPrivateHeaders();
3557 if (SectionHeaders)
3558 printSectionHeaders(Obj&: *O);
3559 if (SymbolTable)
3560 D.printSymbolTable(ArchiveName);
3561 if (DynamicSymbolTable)
3562 D.printSymbolTable(ArchiveName, /*ArchitectureName=*/"",
3563 /*DumpDynamic=*/true);
3564 if (DwarfDumpType != DIDT_Null) {
3565 std::unique_ptr<DIContext> DICtx = DWARFContext::create(Obj: *O);
3566 // Dump the complete DWARF structure.
3567 DIDumpOptions DumpOpts;
3568 DumpOpts.DumpType = DwarfDumpType;
3569 DICtx->dump(OS&: outs(), DumpOpts);
3570 }
3571 if (Relocations && !Disassemble)
3572 D.printRelocations();
3573 if (DynamicRelocations)
3574 D.printDynamicRelocations();
3575 if (SectionContents)
3576 printSectionContents(Obj: O);
3577 if (Disassemble)
3578 disassembleObject(Obj: O, InlineRelocs: Relocations, OS&: outs());
3579 if (UnwindInfo)
3580 printUnwindInfo(O);
3581
3582 // Mach-O specific options:
3583 if (ExportsTrie)
3584 printExportsTrie(O);
3585 if (Rebase)
3586 printRebaseTable(O);
3587 if (Bind)
3588 printBindTable(O);
3589 if (LazyBind)
3590 printLazyBindTable(O);
3591 if (WeakBind)
3592 printWeakBindTable(O);
3593
3594 // Other special sections:
3595 if (RawClangAST)
3596 printRawClangAST(Obj: O);
3597 if (FaultMapSection)
3598 printFaultMaps(Obj: O);
3599 if (Offloading)
3600 dumpOffloadBinary(O: *O, ArchName: StringRef(ArchName));
3601}
3602
3603static void dumpObject(const COFFImportFile *I, const Archive *A,
3604 const Archive::Child *C = nullptr) {
3605 StringRef ArchiveName = A ? A->getFileName() : "";
3606
3607 // Avoid other output when using a raw option.
3608 if (!RawClangAST)
3609 outs() << '\n'
3610 << ArchiveName << "(" << I->getFileName() << ")"
3611 << ":\tfile format COFF-import-file"
3612 << "\n\n";
3613
3614 if (ArchiveHeaders && !MachOOpt && C)
3615 printArchiveChild(Filename: ArchiveName, C: *C);
3616 if (SymbolTable)
3617 printCOFFSymbolTable(I: *I);
3618}
3619
3620/// Dump each object file in \a a;
3621static void dumpArchive(const Archive *A) {
3622 Error Err = Error::success();
3623 unsigned I = -1;
3624 for (auto &C : A->children(Err)) {
3625 ++I;
3626 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
3627 if (!ChildOrErr) {
3628 if (auto E = isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
3629 reportError(E: std::move(E), FileName: getFileNameForError(C, Index: I), ArchiveName: A->getFileName());
3630 continue;
3631 }
3632 if (ObjectFile *O = dyn_cast<ObjectFile>(Val: &*ChildOrErr.get()))
3633 dumpObject(O, A, C: &C);
3634 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(Val: &*ChildOrErr.get()))
3635 dumpObject(I, A, C: &C);
3636 else
3637 reportError(E: errorCodeToError(EC: object_error::invalid_file_type),
3638 FileName: A->getFileName());
3639 }
3640 if (Err)
3641 reportError(E: std::move(Err), FileName: A->getFileName());
3642}
3643
3644/// Open file and figure out how to dump it.
3645static void dumpInput(StringRef file) {
3646 // If we are using the Mach-O specific object file parser, then let it parse
3647 // the file and process the command line options. So the -arch flags can
3648 // be used to select specific slices, etc.
3649 if (MachOOpt) {
3650 parseInputMachO(Filename: file);
3651 return;
3652 }
3653
3654 // Attempt to open the binary.
3655 OwningBinary<Binary> OBinary = unwrapOrError(EO: createBinary(Path: file), Args&: file);
3656 Binary &Binary = *OBinary.getBinary();
3657
3658 if (Archive *A = dyn_cast<Archive>(Val: &Binary))
3659 dumpArchive(A);
3660 else if (ObjectFile *O = dyn_cast<ObjectFile>(Val: &Binary))
3661 dumpObject(O);
3662 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Val: &Binary))
3663 parseInputMachO(UB);
3664 else if (OffloadBinary *OB = dyn_cast<OffloadBinary>(Val: &Binary))
3665 dumpOffloadSections(OB: *OB);
3666 else
3667 reportError(E: errorCodeToError(EC: object_error::invalid_file_type), FileName: file);
3668}
3669
3670template <typename T>
3671static void parseIntArg(const llvm::opt::InputArgList &InputArgs, int ID,
3672 T &Value) {
3673 if (const opt::Arg *A = InputArgs.getLastArg(Ids: ID)) {
3674 StringRef V(A->getValue());
3675 if (!llvm::to_integer(V, Value, 0)) {
3676 reportCmdLineError(Message: A->getSpelling() +
3677 ": expected a non-negative integer, but got '" + V +
3678 "'");
3679 }
3680 }
3681}
3682
3683static object::BuildID parseBuildIDArg(const opt::Arg *A) {
3684 StringRef V(A->getValue());
3685 object::BuildID BID = parseBuildID(Str: V);
3686 if (BID.empty())
3687 reportCmdLineError(Message: A->getSpelling() + ": expected a build ID, but got '" +
3688 V + "'");
3689 return BID;
3690}
3691
3692void objdump::invalidArgValue(const opt::Arg *A) {
3693 reportCmdLineError(Message: "'" + StringRef(A->getValue()) +
3694 "' is not a valid value for '" + A->getSpelling() + "'");
3695}
3696
3697static std::vector<std::string>
3698commaSeparatedValues(const llvm::opt::InputArgList &InputArgs, int ID) {
3699 std::vector<std::string> Values;
3700 for (StringRef Value : InputArgs.getAllArgValues(Id: ID)) {
3701 llvm::SmallVector<StringRef, 2> SplitValues;
3702 llvm::SplitString(Source: Value, OutFragments&: SplitValues, Delimiters: ",");
3703 for (StringRef SplitValue : SplitValues)
3704 Values.push_back(x: SplitValue.str());
3705 }
3706 return Values;
3707}
3708
3709static void mcpuHelp() {
3710 Triple TheTriple;
3711
3712 if (!TripleName.empty()) {
3713 TheTriple.setTriple(TripleName);
3714 } else {
3715 assert(!InputFilenames.empty());
3716 Expected<OwningBinary<Binary>> OBinary = createBinary(Path: InputFilenames[0]);
3717 if (Error E = OBinary.takeError()) {
3718 reportError(File: InputFilenames[0], Message: "triple was not specified and could not "
3719 "be inferred from the input file: " +
3720 toString(E: std::move(E)));
3721 }
3722
3723 Binary *Bin = OBinary->getBinary();
3724 if (ObjectFile *Obj = dyn_cast<ObjectFile>(Val: Bin)) {
3725 TheTriple = Obj->makeTriple();
3726 } else if (Archive *A = dyn_cast<Archive>(Val: Bin)) {
3727 Error Err = Error::success();
3728 unsigned I = -1;
3729 for (auto &C : A->children(Err)) {
3730 ++I;
3731 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
3732 if (!ChildOrErr) {
3733 if (auto E = isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
3734 reportError(E: std::move(E), FileName: getFileNameForError(C, Index: I),
3735 ArchiveName: A->getFileName());
3736 continue;
3737 }
3738 if (ObjectFile *Obj = dyn_cast<ObjectFile>(Val: &*ChildOrErr.get())) {
3739 TheTriple = Obj->makeTriple();
3740 break;
3741 }
3742 }
3743 if (Err)
3744 reportError(E: std::move(Err), FileName: A->getFileName());
3745 }
3746 if (TheTriple.empty())
3747 reportError(File: InputFilenames[0],
3748 Message: "target triple could not be derived from input file");
3749 }
3750
3751 std::string ErrMessage;
3752 const Target *DummyTarget =
3753 TargetRegistry::lookupTarget(TheTriple, Error&: ErrMessage);
3754 if (!DummyTarget)
3755 reportCmdLineError(Message: ErrMessage);
3756 // We need to access the Help() through the corresponding MCSubtargetInfo.
3757 // To avoid a memory leak, we wrap the createMcSubtargetInfo result in a
3758 // unique_ptr.
3759 std::unique_ptr<MCSubtargetInfo> MSI(
3760 DummyTarget->createMCSubtargetInfo(TheTriple, CPU: "help", Features: ""));
3761}
3762
3763static void parseOtoolOptions(const llvm::opt::InputArgList &InputArgs) {
3764 MachOOpt = true;
3765 FullLeadingAddr = true;
3766 PrintImmHex = true;
3767
3768 ArchName = InputArgs.getLastArgValue(Id: OTOOL_arch).str();
3769 if (!ArchName.empty())
3770 ArchFlags.push_back(x: ArchName);
3771 ArchiveHeaders = InputArgs.hasArg(Ids: OTOOL_a);
3772 LinkOptHints = InputArgs.hasArg(Ids: OTOOL_C);
3773 if (InputArgs.hasArg(Ids: OTOOL_d))
3774 FilterSections.push_back(x: "__DATA,__data");
3775 DylibId = InputArgs.hasArg(Ids: OTOOL_D);
3776 UniversalHeaders = InputArgs.hasArg(Ids: OTOOL_f);
3777 DataInCode = InputArgs.hasArg(Ids: OTOOL_G);
3778 FirstPrivateHeader = InputArgs.hasArg(Ids: OTOOL_h);
3779 IndirectSymbols = InputArgs.hasArg(Ids: OTOOL_I);
3780 ShowRawInsn = InputArgs.hasArg(Ids: OTOOL_j);
3781 PrivateHeaders = InputArgs.hasArg(Ids: OTOOL_l);
3782 DylibsUsed = InputArgs.hasArg(Ids: OTOOL_L);
3783 MCPU = InputArgs.getLastArgValue(Id: OTOOL_mcpu_EQ).str();
3784 ObjcMetaData = InputArgs.hasArg(Ids: OTOOL_o);
3785 DisSymName = InputArgs.getLastArgValue(Id: OTOOL_p).str();
3786 InfoPlist = InputArgs.hasArg(Ids: OTOOL_P);
3787 Relocations = InputArgs.hasArg(Ids: OTOOL_r);
3788 if (const Arg *A = InputArgs.getLastArg(Ids: OTOOL_s)) {
3789 auto Filter = (A->getValue(N: 0) + StringRef(",") + A->getValue(N: 1)).str();
3790 FilterSections.push_back(x: Filter);
3791 }
3792 if (InputArgs.hasArg(Ids: OTOOL_t))
3793 FilterSections.push_back(x: "__TEXT,__text");
3794 Verbose = InputArgs.hasArg(Ids: OTOOL_v) || InputArgs.hasArg(Ids: OTOOL_V) ||
3795 InputArgs.hasArg(Ids: OTOOL_o);
3796 SymbolicOperands = InputArgs.hasArg(Ids: OTOOL_V);
3797 if (InputArgs.hasArg(Ids: OTOOL_x))
3798 FilterSections.push_back(x: ",__text");
3799 LeadingAddr = LeadingHeaders = !InputArgs.hasArg(Ids: OTOOL_X);
3800
3801 ChainedFixups = InputArgs.hasArg(Ids: OTOOL_chained_fixups);
3802 DyldInfo = InputArgs.hasArg(Ids: OTOOL_dyld_info);
3803
3804 UseMemberSyntax = !InputArgs.hasArg(Ids: OTOOL_m);
3805
3806 InputFilenames = InputArgs.getAllArgValues(Id: OTOOL_INPUT);
3807 if (InputFilenames.empty())
3808 reportCmdLineError(Message: "no input file");
3809
3810 for (const Arg *A : InputArgs) {
3811 const Option &O = A->getOption();
3812 if (O.getGroup().isValid() && O.getGroup().getID() == OTOOL_grp_obsolete) {
3813 reportCmdLineWarning(Message: O.getPrefixedName() +
3814 " is obsolete and not implemented");
3815 }
3816 }
3817}
3818
3819static void parseObjdumpOptions(const llvm::opt::InputArgList &InputArgs) {
3820 parseIntArg(InputArgs, ID: OBJDUMP_adjust_vma_EQ, Value&: AdjustVMA);
3821 AllHeaders = InputArgs.hasArg(Ids: OBJDUMP_all_headers);
3822 ArchName = InputArgs.getLastArgValue(Id: OBJDUMP_arch_name_EQ).str();
3823 ArchiveHeaders = InputArgs.hasArg(Ids: OBJDUMP_archive_headers);
3824 Demangle = InputArgs.hasArg(Ids: OBJDUMP_demangle);
3825 Disassemble = InputArgs.hasArg(Ids: OBJDUMP_disassemble);
3826 DisassembleAll = InputArgs.hasArg(Ids: OBJDUMP_disassemble_all);
3827 SymbolDescription = InputArgs.hasArg(Ids: OBJDUMP_symbol_description);
3828 TracebackTable = InputArgs.hasArg(Ids: OBJDUMP_traceback_table);
3829 DisassembleSymbols =
3830 commaSeparatedValues(InputArgs, ID: OBJDUMP_disassemble_symbols_EQ);
3831 for (auto Sym : InputArgs.getAllArgValues(Id: OBJDUMP_disassemble_EQ))
3832 DisassembleSymbols.push_back(x: Sym);
3833 DisassembleZeroes = InputArgs.hasArg(Ids: OBJDUMP_disassemble_zeroes);
3834 if (const opt::Arg *A = InputArgs.getLastArg(Ids: OBJDUMP_dwarf_EQ)) {
3835 DwarfDumpType = StringSwitch<DIDumpType>(A->getValue())
3836 .Case(S: "frames", Value: DIDT_DebugFrame)
3837 .Default(Value: DIDT_Null);
3838 if (DwarfDumpType == DIDT_Null)
3839 invalidArgValue(A);
3840 }
3841 DynamicRelocations = InputArgs.hasArg(Ids: OBJDUMP_dynamic_reloc);
3842 FaultMapSection = InputArgs.hasArg(Ids: OBJDUMP_fault_map_section);
3843 Offloading = InputArgs.hasArg(Ids: OBJDUMP_offloading);
3844 FileHeaders = InputArgs.hasArg(Ids: OBJDUMP_file_headers);
3845 SectionContents = InputArgs.hasArg(Ids: OBJDUMP_full_contents);
3846 PrintLines = InputArgs.hasArg(Ids: OBJDUMP_line_numbers);
3847 InputFilenames = InputArgs.getAllArgValues(Id: OBJDUMP_INPUT);
3848 MachOOpt = InputArgs.hasArg(Ids: OBJDUMP_macho);
3849 MCPU = InputArgs.getLastArgValue(Id: OBJDUMP_mcpu_EQ).str();
3850 MAttrs = commaSeparatedValues(InputArgs, ID: OBJDUMP_mattr_EQ);
3851 ShowRawInsn = !InputArgs.hasArg(Ids: OBJDUMP_no_show_raw_insn);
3852 LeadingAddr = !InputArgs.hasArg(Ids: OBJDUMP_no_leading_addr);
3853 RawClangAST = InputArgs.hasArg(Ids: OBJDUMP_raw_clang_ast);
3854 Relocations = InputArgs.hasArg(Ids: OBJDUMP_reloc);
3855 PrintImmHex =
3856 InputArgs.hasFlag(Pos: OBJDUMP_print_imm_hex, Neg: OBJDUMP_no_print_imm_hex, Default: true);
3857 PrivateHeaders = InputArgs.hasArg(Ids: OBJDUMP_private_headers);
3858 FilterSections = InputArgs.getAllArgValues(Id: OBJDUMP_section_EQ);
3859 SectionHeaders = InputArgs.hasArg(Ids: OBJDUMP_section_headers);
3860 ShowAllSymbols = InputArgs.hasArg(Ids: OBJDUMP_show_all_symbols);
3861 ShowLMA = InputArgs.hasArg(Ids: OBJDUMP_show_lma);
3862 PrintSource = InputArgs.hasArg(Ids: OBJDUMP_source);
3863 parseIntArg(InputArgs, ID: OBJDUMP_start_address_EQ, Value&: StartAddress);
3864 HasStartAddressFlag = InputArgs.hasArg(Ids: OBJDUMP_start_address_EQ);
3865 parseIntArg(InputArgs, ID: OBJDUMP_stop_address_EQ, Value&: StopAddress);
3866 HasStopAddressFlag = InputArgs.hasArg(Ids: OBJDUMP_stop_address_EQ);
3867 SymbolTable = InputArgs.hasArg(Ids: OBJDUMP_syms);
3868 if (const opt::Arg *A = InputArgs.getLastArg(Ids: OBJDUMP_symbolize_operands,
3869 Ids: OBJDUMP_no_symbolize_operands))
3870 SymbolizeOperandsOption =
3871 A->getOption().matches(ID: OBJDUMP_symbolize_operands);
3872 PrettyPGOAnalysisMap = InputArgs.hasArg(Ids: OBJDUMP_pretty_pgo_analysis_map);
3873 if (PrettyPGOAnalysisMap && !SymbolizeOperandsOption.value_or(u: false))
3874 reportCmdLineWarning(Message: "--symbolize-operands must be enabled for "
3875 "--pretty-pgo-analysis-map to have an effect");
3876 DynamicSymbolTable = InputArgs.hasArg(Ids: OBJDUMP_dynamic_syms);
3877 TripleName = InputArgs.getLastArgValue(Id: OBJDUMP_triple_EQ).str();
3878 UnwindInfo = InputArgs.hasArg(Ids: OBJDUMP_unwind_info);
3879 UnwindShowWODPool = InputArgs.hasArg(Ids: OBJDUMP_unwind_show_wod_pool);
3880 Prefix = InputArgs.getLastArgValue(Id: OBJDUMP_prefix).str();
3881 parseIntArg(InputArgs, ID: OBJDUMP_prefix_strip, Value&: PrefixStrip);
3882 for (const opt::Arg *A : InputArgs.filtered(Ids: OBJDUMP_substitute_path)) {
3883 StringRef From = A->getValue(N: 0);
3884 if (From.empty())
3885 reportCmdLineError(Message: A->getSpelling() + ": <from> must not be empty");
3886 SubstitutePaths.emplace_back(args: From.str(), args: A->getValue(N: 1));
3887 }
3888 for (StringRef Dir : InputArgs.getAllArgValues(Id: OBJDUMP_source_dir)) {
3889 if (Dir.empty())
3890 reportCmdLineError(Message: "--source-dir argument must not be empty");
3891 SourceDirs.insert(position: SourceDirs.end(), x: Dir.str());
3892 }
3893
3894 if (const opt::Arg *A = InputArgs.getLastArg(Ids: OBJDUMP_debug_vars_EQ)) {
3895 DbgVariables = StringSwitch<DebugFormat>(A->getValue())
3896 .Case(S: "ascii", Value: DFASCII)
3897 .Case(S: "unicode", Value: DFUnicode)
3898 .Default(Value: DFInvalid);
3899 if (DbgVariables == DFInvalid)
3900 invalidArgValue(A);
3901 }
3902
3903 if (const opt::Arg *A =
3904 InputArgs.getLastArg(Ids: OBJDUMP_debug_inlined_funcs_EQ)) {
3905 DbgInlinedFunctions = StringSwitch<DebugFormat>(A->getValue())
3906 .Case(S: "ascii", Value: DFASCII)
3907 .Case(S: "limits-only", Value: DFLimitsOnly)
3908 .Case(S: "unicode", Value: DFUnicode)
3909 .Default(Value: DFInvalid);
3910 if (DbgInlinedFunctions == DFInvalid)
3911 invalidArgValue(A);
3912 }
3913
3914 if (const opt::Arg *A = InputArgs.getLastArg(Ids: OBJDUMP_disassembler_color_EQ)) {
3915 DisassemblyColor = StringSwitch<ColorOutput>(A->getValue())
3916 .Case(S: "on", Value: ColorOutput::Enable)
3917 .Case(S: "off", Value: ColorOutput::Disable)
3918 .Case(S: "terminal", Value: ColorOutput::Auto)
3919 .Default(Value: ColorOutput::Invalid);
3920 if (DisassemblyColor == ColorOutput::Invalid)
3921 invalidArgValue(A);
3922 }
3923
3924 parseIntArg(InputArgs, ID: OBJDUMP_debug_indent_EQ, Value&: DbgIndent);
3925
3926 parseMachOOptions(InputArgs);
3927
3928 // Parse -M (--disassembler-options) and deprecated
3929 // --x86-asm-syntax={att,intel}.
3930 //
3931 // Note, for x86, the asm dialect (AssemblerDialect) is initialized when the
3932 // MCAsmInfo is constructed. MCInstPrinter::applyTargetSpecificCLOption is
3933 // called too late. For now we have to use the internal cl::opt option.
3934 const char *AsmSyntax = nullptr;
3935 for (const auto *A : InputArgs.filtered(Ids: OBJDUMP_disassembler_options_EQ,
3936 Ids: OBJDUMP_x86_asm_syntax_att,
3937 Ids: OBJDUMP_x86_asm_syntax_intel)) {
3938 switch (A->getOption().getID()) {
3939 case OBJDUMP_x86_asm_syntax_att:
3940 AsmSyntax = "--x86-asm-syntax=att";
3941 continue;
3942 case OBJDUMP_x86_asm_syntax_intel:
3943 AsmSyntax = "--x86-asm-syntax=intel";
3944 continue;
3945 }
3946
3947 SmallVector<StringRef, 2> Values;
3948 llvm::SplitString(Source: A->getValue(), OutFragments&: Values, Delimiters: ",");
3949 for (StringRef V : Values) {
3950 if (V == "att")
3951 AsmSyntax = "--x86-asm-syntax=att";
3952 else if (V == "intel")
3953 AsmSyntax = "--x86-asm-syntax=intel";
3954 else
3955 DisassemblerOptions.push_back(x: V.str());
3956 }
3957 }
3958 SmallVector<const char *> Args = {"llvm-objdump"};
3959 for (const opt::Arg *A : InputArgs.filtered(Ids: OBJDUMP_mllvm))
3960 Args.push_back(Elt: A->getValue());
3961 if (AsmSyntax)
3962 Args.push_back(Elt: AsmSyntax);
3963 if (Args.size() > 1)
3964 llvm::cl::ParseCommandLineOptions(argc: Args.size(), argv: Args.data());
3965
3966 // Look up any provided build IDs, then append them to the input filenames.
3967 for (const opt::Arg *A : InputArgs.filtered(Ids: OBJDUMP_build_id)) {
3968 object::BuildID BuildID = parseBuildIDArg(A);
3969 Expected<std::string> Path = BIDFetcher->fetch(BuildID);
3970 if (!Path) {
3971 // Most users will not care why this failed.
3972 consumeError(Err: Path.takeError());
3973 reportCmdLineError(Message: A->getSpelling() + ": could not find build ID '" +
3974 A->getValue() + "'");
3975 }
3976 InputFilenames.push_back(x: std::move(*Path));
3977 }
3978
3979 // objdump defaults to a.out if no filenames specified.
3980 if (InputFilenames.empty())
3981 InputFilenames.push_back(x: "a.out");
3982}
3983
3984int llvm_objdump_main(int argc, char **argv, const llvm::ToolContext &) {
3985 using namespace llvm;
3986
3987 ToolName = argv[0];
3988 std::unique_ptr<CommonOptTable> T;
3989 OptSpecifier Unknown, HelpFlag, HelpHiddenFlag, VersionFlag;
3990
3991 StringRef Stem = sys::path::stem(path: ToolName);
3992 auto Is = [=](StringRef Tool) {
3993 // We need to recognize the following filenames:
3994 //
3995 // llvm-objdump -> objdump
3996 // llvm-otool-10.exe -> otool
3997 // powerpc64-unknown-freebsd13-objdump -> objdump
3998 auto I = Stem.rfind_insensitive(Str: Tool);
3999 return I != StringRef::npos &&
4000 (I + Tool.size() == Stem.size() || !isAlnum(C: Stem[I + Tool.size()]));
4001 };
4002 if (Is("otool")) {
4003 IsOtool = true;
4004 T = std::make_unique<OtoolOptTable>();
4005 Unknown = OTOOL_UNKNOWN;
4006 HelpFlag = OTOOL_help;
4007 HelpHiddenFlag = OTOOL_help_hidden;
4008 VersionFlag = OTOOL_version;
4009 } else {
4010 T = std::make_unique<ObjdumpOptTable>();
4011 Unknown = OBJDUMP_UNKNOWN;
4012 HelpFlag = OBJDUMP_help;
4013 HelpHiddenFlag = OBJDUMP_help_hidden;
4014 VersionFlag = OBJDUMP_version;
4015 }
4016
4017 BumpPtrAllocator A;
4018 StringSaver Saver(A);
4019 opt::InputArgList InputArgs =
4020 T->parseArgs(Argc: argc, Argv: argv, Unknown, Saver,
4021 ErrorFn: [&](StringRef Msg) { reportCmdLineError(Message: Msg); });
4022
4023 if (InputArgs.size() == 0 || InputArgs.hasArg(Ids: HelpFlag)) {
4024 T->printHelp(Argv0: ToolName);
4025 return 0;
4026 }
4027 if (InputArgs.hasArg(Ids: HelpHiddenFlag)) {
4028 T->printHelp(Argv0: ToolName, /*ShowHidden=*/true);
4029 return 0;
4030 }
4031
4032 // Initialize targets and assembly printers/parsers.
4033 InitializeAllTargetInfos();
4034 InitializeAllTargetMCs();
4035 InitializeAllDisassemblers();
4036
4037 if (InputArgs.hasArg(Ids: VersionFlag)) {
4038 cl::PrintVersionMessage();
4039 if (!Is("otool")) {
4040 outs() << '\n';
4041 TargetRegistry::printRegisteredTargetsForVersion(OS&: outs());
4042 }
4043 return 0;
4044 }
4045
4046 // Initialize debuginfod.
4047 const bool ShouldUseDebuginfodByDefault =
4048 InputArgs.hasArg(Ids: OBJDUMP_build_id) || canUseDebuginfod();
4049 std::vector<std::string> DebugFileDirectories =
4050 InputArgs.getAllArgValues(Id: OBJDUMP_debug_file_directory);
4051 if (InputArgs.hasFlag(Pos: OBJDUMP_debuginfod, Neg: OBJDUMP_no_debuginfod,
4052 Default: ShouldUseDebuginfodByDefault)) {
4053 HTTPClient::initialize();
4054 BIDFetcher =
4055 std::make_unique<DebuginfodFetcher>(args: std::move(DebugFileDirectories));
4056 } else {
4057 BIDFetcher =
4058 std::make_unique<BuildIDFetcher>(args: std::move(DebugFileDirectories));
4059 }
4060
4061 if (Is("otool"))
4062 parseOtoolOptions(InputArgs);
4063 else
4064 parseObjdumpOptions(InputArgs);
4065
4066 if (StartAddress >= StopAddress)
4067 reportCmdLineError(Message: "start address should be less than stop address");
4068
4069 // Removes trailing separators from prefix.
4070 while (!Prefix.empty() && sys::path::is_separator(value: Prefix.back()))
4071 Prefix.pop_back();
4072
4073 if (AllHeaders)
4074 ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations =
4075 SectionHeaders = SymbolTable = true;
4076
4077 if (DisassembleAll || PrintSource || PrintLines || TracebackTable ||
4078 !DisassembleSymbols.empty())
4079 Disassemble = true;
4080
4081 const bool PrintCpuHelp = (MCPU == "help" || is_contained(Range&: MAttrs, Element: "help"));
4082
4083 const bool ShouldDump =
4084 ArchiveHeaders || Disassemble || DwarfDumpType != DIDT_Null ||
4085 DynamicRelocations || FileHeaders || PrivateHeaders || RawClangAST ||
4086 Relocations || SectionHeaders || SectionContents || SymbolTable ||
4087 DynamicSymbolTable || UnwindInfo || FaultMapSection || Offloading ||
4088 (MachOOpt &&
4089 (Bind || DataInCode || ChainedFixups || DyldInfo || DylibId ||
4090 DylibsUsed || ExportsTrie || FirstPrivateHeader ||
4091 FunctionStartsType != FunctionStartsMode::None || IndirectSymbols ||
4092 InfoPlist || LazyBind || LinkOptHints || ObjcMetaData || Rebase ||
4093 Rpaths || UniversalHeaders || WeakBind || !FilterSections.empty()));
4094
4095 if (!ShouldDump && !PrintCpuHelp) {
4096 T->printHelp(Argv0: ToolName);
4097 return 2;
4098 }
4099
4100 if (PrintCpuHelp) {
4101 mcpuHelp();
4102 if (!ShouldDump)
4103 return EXIT_SUCCESS;
4104 }
4105
4106 DisasmSymbolSet.insert_range(R&: DisassembleSymbols);
4107
4108 llvm::for_each(Range&: InputFilenames, F: dumpInput);
4109
4110 warnOnNoMatchForSections();
4111
4112 return EXIT_SUCCESS;
4113}
4114