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