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