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::amdgpu:
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 Expected<std::string> Path = BIDFetcher->fetch(BuildID);
1842 if (!Path) {
1843 // Failure to fetch debuginfod is rarely an error and most users will not
1844 // care why this failed.
1845 consumeError(Err: Path.takeError());
1846 return std::nullopt;
1847 }
1848 Expected<OwningBinary<Binary>> DebugBinary = createBinary(Path: *Path);
1849 if (!DebugBinary) {
1850 reportWarning(Message: toString(E: DebugBinary.takeError()), File: *Path);
1851 return std::nullopt;
1852 }
1853 return std::move(*DebugBinary);
1854}
1855
1856static void
1857disassembleObject(ObjectFile &Obj, const ObjectFile &DbgObj,
1858 DisassemblerTarget &PrimaryTarget,
1859 std::optional<DisassemblerTarget> &SecondaryTarget,
1860 SourcePrinter &SP, bool InlineRelocs, raw_ostream &OS) {
1861 DisassemblerTarget *DT = &PrimaryTarget;
1862 bool PrimaryIsThumb = false;
1863 SmallVector<std::pair<uint64_t, uint64_t>, 0> CHPECodeMap;
1864
1865 if (SecondaryTarget) {
1866 if (isArmElf(Obj)) {
1867 PrimaryIsThumb =
1868 PrimaryTarget.SubtargetInfo->checkFeatures(FS: "+thumb-mode");
1869 } else if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Val: &Obj)) {
1870 const chpe_metadata *CHPEMetadata = COFFObj->getCHPEMetadata();
1871 if (CHPEMetadata && CHPEMetadata->CodeMapCount) {
1872 uintptr_t CodeMapInt;
1873 cantFail(Err: COFFObj->getRvaPtr(Rva: CHPEMetadata->CodeMap, Res&: CodeMapInt));
1874 auto CodeMap = reinterpret_cast<const chpe_range_entry *>(CodeMapInt);
1875
1876 for (uint32_t i = 0; i < CHPEMetadata->CodeMapCount; ++i) {
1877 if (CodeMap[i].getType() == chpe_range_type::Amd64 &&
1878 CodeMap[i].Length) {
1879 // Store x86_64 CHPE code ranges.
1880 uint64_t Start = CodeMap[i].getStart() + COFFObj->getImageBase();
1881 CHPECodeMap.emplace_back(Args&: Start, Args: Start + CodeMap[i].Length);
1882 }
1883 }
1884 llvm::sort(C&: CHPECodeMap);
1885 }
1886 }
1887 }
1888
1889 std::map<SectionRef, std::vector<RelocationRef>> RelocMap;
1890 if (InlineRelocs || Obj.isXCOFF())
1891 RelocMap = getRelocsMap(Obj);
1892 bool Is64Bits = Obj.getBytesInAddress() > 4;
1893
1894 // Create a mapping from virtual address to symbol name. This is used to
1895 // pretty print the symbols while disassembling.
1896 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1897 std::map<SectionRef, SmallVector<MappingSymbolPair, 0>> AllMappingSymbols;
1898 // ISA-specific DisassemblerTargets and per-section "$x<ISA>" mapping-symbol
1899 // indexes. Only allocated for RISC-V ELF objects so non-RISC-V disassembly
1900 // does not carry the (otherwise unused) containers. ISATargets is declared
1901 // before AllRISCVISAMappingSymbols so the raw DisassemblerTarget * entries
1902 // in that map never outlive the objects they point at.
1903 using RISCVISASymSection =
1904 SmallVector<std::pair<uint64_t, DisassemblerTarget *>, 0>;
1905 std::unique_ptr<RISCVISATargetCache> ISATargets;
1906 std::unique_ptr<std::map<SectionRef, RISCVISASymSection>>
1907 AllRISCVISAMappingSymbols;
1908 SectionSymbolsTy AbsoluteSymbols;
1909 const StringRef FileName = Obj.getFileName();
1910 if (isRISCVElf(Obj)) {
1911 ISATargets = std::make_unique<RISCVISATargetCache>(args: FileName);
1912 AllRISCVISAMappingSymbols =
1913 std::make_unique<std::map<SectionRef, RISCVISASymSection>>();
1914 }
1915 const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Val: &Obj);
1916 for (const SymbolRef &Symbol : Obj.symbols()) {
1917 Expected<StringRef> NameOrErr = Symbol.getName();
1918 if (!NameOrErr) {
1919 reportWarning(Message: toString(E: NameOrErr.takeError()), File: FileName);
1920 continue;
1921 }
1922 if (NameOrErr->empty() && !(Obj.isXCOFF() && SymbolDescription))
1923 continue;
1924
1925 if (Obj.isELF() &&
1926 (cantFail(ValOrErr: Symbol.getFlags()) & SymbolRef::SF_FormatSpecific)) {
1927 // Symbol is intended not to be displayed by default (STT_FILE,
1928 // STT_SECTION, or a mapping symbol). Ignore STT_SECTION symbols. We will
1929 // synthesize a section symbol if no symbol is defined at offset 0.
1930 //
1931 // For a mapping symbol, store it within both AllSymbols and
1932 // AllMappingSymbols. If --show-all-symbols is unspecified, its label will
1933 // not be printed in disassembly listing.
1934 if (getElfSymbolType(Obj, Sym: Symbol) != ELF::STT_SECTION &&
1935 hasMappingSymbols(Obj)) {
1936 section_iterator SecI = unwrapOrError(EO: Symbol.getSection(), Args: FileName);
1937 if (SecI != Obj.section_end()) {
1938 uint64_t SectionAddr = SecI->getAddress();
1939 uint64_t Address = cantFail(ValOrErr: Symbol.getAddress());
1940 StringRef Name = *NameOrErr;
1941 if (Name.consume_front(Prefix: "$") && Name.size() &&
1942 strchr(s: "adtx", c: Name[0])) {
1943 AllMappingSymbols[*SecI].emplace_back(Args: Address - SectionAddr,
1944 Args: Name[0]);
1945 // For RISC-V "$x<ISAString>" symbols, resolve the ISA string to a
1946 // DisassemblerTarget once and record the pointer so per-instruction
1947 // lookups are a single binary search.
1948 if (isRISCVElf(Obj) && Name[0] == 'x' && Name.size() > 1)
1949 (*AllRISCVISAMappingSymbols)[*SecI].emplace_back(
1950 Args: Address - SectionAddr,
1951 Args: ISATargets->get(Base&: PrimaryTarget, ISAStr: Name.substr(Start: 1)));
1952 AllSymbols[*SecI].push_back(
1953 x: createSymbolInfo(Obj, Symbol, /*MappingSymbol=*/IsMappingSymbol: true));
1954 }
1955 }
1956 }
1957 continue;
1958 }
1959
1960 if (MachO) {
1961 // __mh_(execute|dylib|dylinker|bundle|preload|object)_header are special
1962 // symbols that support MachO header introspection. They do not bind to
1963 // code locations and are irrelevant for disassembly.
1964 if (NameOrErr->starts_with(Prefix: "__mh_") && NameOrErr->ends_with(Suffix: "_header"))
1965 continue;
1966 // Don't ask a Mach-O STAB symbol for its section unless you know that
1967 // STAB symbol's section field refers to a valid section index. Otherwise
1968 // the symbol may error trying to load a section that does not exist.
1969 DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
1970 uint8_t NType =
1971 (MachO->is64Bit() ? MachO->getSymbol64TableEntry(DRI: SymDRI).n_type
1972 : MachO->getSymbolTableEntry(DRI: SymDRI).n_type);
1973 if (NType & MachO::N_STAB)
1974 continue;
1975 }
1976
1977 section_iterator SecI = unwrapOrError(EO: Symbol.getSection(), Args: FileName);
1978 if (SecI != Obj.section_end())
1979 AllSymbols[*SecI].push_back(x: createSymbolInfo(Obj, Symbol));
1980 else
1981 AbsoluteSymbols.push_back(x: createSymbolInfo(Obj, Symbol));
1982 }
1983
1984 if (AllSymbols.empty() && Obj.isELF())
1985 addDynamicElfSymbols(Obj: cast<ELFObjectFileBase>(Val&: Obj), AllSymbols);
1986
1987 if (Obj.isWasm())
1988 addMissingWasmCodeSymbols(Obj: cast<WasmObjectFile>(Val&: Obj), AllSymbols);
1989
1990 if (Obj.isELF() && Obj.sections().empty())
1991 createFakeELFSections(Obj);
1992
1993 DisassemblerTarget *PltTarget = DT;
1994 auto SectionNames = getSectionNames(Obj);
1995 if (SecondaryTarget && isArmElf(Obj)) {
1996 auto PltSectionRef = SectionNames.find(Val: ".plt");
1997 if (PltSectionRef != SectionNames.end()) {
1998 bool PltIsThumb = false;
1999 for (auto [Addr, SymbolName] : AllMappingSymbols[PltSectionRef->second]) {
2000 if (Addr != 0)
2001 continue;
2002
2003 if (SymbolName == 't') {
2004 PltIsThumb = true;
2005 break;
2006 }
2007 if (SymbolName == 'a')
2008 break;
2009 }
2010
2011 if (PrimaryTarget.SubtargetInfo->checkFeatures(FS: "+thumb-mode"))
2012 PltTarget = PltIsThumb ? &PrimaryTarget : &*SecondaryTarget;
2013 else
2014 PltTarget = PltIsThumb ? &*SecondaryTarget : &PrimaryTarget;
2015 }
2016 }
2017 BumpPtrAllocator A;
2018 StringSaver Saver(A);
2019 addPltEntries(STI: *PltTarget->SubtargetInfo, Obj, SectionNames, AllSymbols,
2020 Saver);
2021
2022 // Create a mapping from virtual address to section. An empty section can
2023 // cause more than one section at the same address. Sort such sections to be
2024 // before same-addressed non-empty sections so that symbol lookups prefer the
2025 // non-empty section.
2026 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
2027 for (SectionRef Sec : Obj.sections())
2028 SectionAddresses.emplace_back(args: Sec.getAddress(), args&: Sec);
2029 llvm::stable_sort(Range&: SectionAddresses, C: [](const auto &LHS, const auto &RHS) {
2030 if (LHS.first != RHS.first)
2031 return LHS.first < RHS.first;
2032 return LHS.second.getSize() < RHS.second.getSize();
2033 });
2034
2035 // Linked executables (.exe and .dll files) typically don't include a real
2036 // symbol table but they might contain an export table.
2037 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Val: &Obj)) {
2038 for (const auto &ExportEntry : COFFObj->export_directories()) {
2039 StringRef Name;
2040 if (Error E = ExportEntry.getSymbolName(Result&: Name))
2041 reportError(E: std::move(E), FileName: Obj.getFileName());
2042 if (Name.empty())
2043 continue;
2044
2045 uint32_t RVA;
2046 if (Error E = ExportEntry.getExportRVA(Result&: RVA))
2047 reportError(E: std::move(E), FileName: Obj.getFileName());
2048
2049 uint64_t VA = COFFObj->getImageBase() + RVA;
2050 auto Sec = partition_point(
2051 Range&: SectionAddresses, P: [VA](const std::pair<uint64_t, SectionRef> &O) {
2052 return O.first <= VA;
2053 });
2054 if (Sec != SectionAddresses.begin()) {
2055 --Sec;
2056 AllSymbols[Sec->second].emplace_back(args&: VA, args&: Name, args: ELF::STT_NOTYPE);
2057 } else
2058 AbsoluteSymbols.emplace_back(args&: VA, args&: Name, args: ELF::STT_NOTYPE);
2059 }
2060 }
2061
2062 // Sort all the symbols, this allows us to use a simple binary search to find
2063 // Multiple symbols can have the same address. Use a stable sort to stabilize
2064 // the output.
2065 StringSet<> FoundDisasmSymbolSet;
2066 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
2067 llvm::stable_sort(Range&: SecSyms.second);
2068 llvm::stable_sort(Range&: AbsoluteSymbols);
2069
2070 std::unique_ptr<DWARFContext> DICtx;
2071 LiveElementPrinter LEP(*DT->Context->getRegisterInfo(), *DT->SubtargetInfo);
2072
2073 if (DbgVariables != DFDisabled || DbgInlinedFunctions != DFDisabled) {
2074 DICtx = DWARFContext::create(Obj: DbgObj);
2075 for (const std::unique_ptr<DWARFUnit> &CU : DICtx->compile_units())
2076 LEP.addCompileUnit(D: CU->getUnitDIE(ExtractUnitDIEOnly: false));
2077 }
2078
2079 LLVM_DEBUG(LEP.dump());
2080
2081 BBAddrMapInfo FullAddrMap;
2082 auto ReadBBAddrMap = [&](std::optional<unsigned> SectionIndex =
2083 std::nullopt) {
2084 FullAddrMap.clear();
2085 if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Val: &Obj)) {
2086 std::vector<PGOAnalysisMap> PGOAnalyses;
2087 auto BBAddrMapsOrErr = Elf->readBBAddrMap(TextSectionIndex: SectionIndex, PGOAnalyses: &PGOAnalyses);
2088 if (!BBAddrMapsOrErr) {
2089 reportWarning(Message: toString(E: BBAddrMapsOrErr.takeError()), File: Obj.getFileName());
2090 return;
2091 }
2092 for (auto &&[FunctionBBAddrMap, FunctionPGOAnalysis] :
2093 zip_equal(t&: *std::move(BBAddrMapsOrErr), u: std::move(PGOAnalyses))) {
2094 FullAddrMap.AddFunctionEntry(AddrMap: std::move(FunctionBBAddrMap),
2095 PGOMap: std::move(FunctionPGOAnalysis));
2096 }
2097 }
2098 };
2099
2100 // For non-relocatable objects, Read all LLVM_BB_ADDR_MAP sections into a
2101 // single mapping, since they don't have any conflicts.
2102 if (SymbolizeOperands && !Obj.isRelocatableObject())
2103 ReadBBAddrMap();
2104
2105 std::optional<llvm::BTFParser> BTF;
2106 if (InlineRelocs && BTFParser::hasBTFSections(Obj)) {
2107 BTF.emplace();
2108 BTFParser::ParseOptions Opts = {};
2109 Opts.LoadTypes = true;
2110 Opts.LoadRelocs = true;
2111 if (Error E = BTF->parse(Obj, Opts))
2112 WithColor::defaultErrorHandler(Err: std::move(E));
2113 }
2114
2115 for (const SectionRef &Section : ToolSectionFilter(O: Obj)) {
2116 if (FilterSections.empty() && !DisassembleAll &&
2117 (!Section.isText() || Section.isVirtual()))
2118 continue;
2119
2120 uint64_t SectionAddr = Section.getAddress();
2121 uint64_t SectSize = Section.getSize();
2122 if (!SectSize)
2123 continue;
2124
2125 // For relocatable object files, read the LLVM_BB_ADDR_MAP section
2126 // corresponding to this section, if present.
2127 if (SymbolizeOperands && Obj.isRelocatableObject())
2128 ReadBBAddrMap(Section.getIndex());
2129
2130 // Get the list of all the symbols in this section.
2131 SectionSymbolsTy &Symbols = AllSymbols[Section];
2132 auto &MappingSymbols = AllMappingSymbols[Section];
2133 llvm::sort(C&: MappingSymbols);
2134 RISCVISASymSection EmptyRISCVISASyms;
2135 auto &RISCVISASyms = AllRISCVISAMappingSymbols
2136 ? (*AllRISCVISAMappingSymbols)[Section]
2137 : EmptyRISCVISASyms;
2138 llvm::sort(C&: RISCVISASyms);
2139
2140 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(
2141 Input: unwrapOrError(EO: Section.getContents(), Args: Obj.getFileName()));
2142
2143 std::vector<std::unique_ptr<std::string>> SynthesizedLabelNames;
2144 if (Obj.isELF() && Obj.getArch() == Triple::amdgpu) {
2145 // AMDGPU disassembler uses symbolizer for printing labels
2146 addSymbolizer(Ctx&: *DT->Context, Target: DT->TheTarget, TheTriple: DT->TheTriple,
2147 DisAsm: DT->DisAsm.get(), SectionAddr, Bytes, Symbols,
2148 SynthesizedLabelNames);
2149 }
2150
2151 StringRef SegmentName = getSegmentName(MachO, Section);
2152 StringRef SectionName = unwrapOrError(EO: Section.getName(), Args: Obj.getFileName());
2153 // If the section has no symbol at the start, just insert a dummy one.
2154 // Without --show-all-symbols, also insert one if all symbols at the start
2155 // are mapping symbols.
2156 bool CreateDummy = Symbols.empty();
2157 if (!CreateDummy) {
2158 CreateDummy = true;
2159 for (auto &Sym : Symbols) {
2160 if (Sym.Addr != SectionAddr)
2161 break;
2162 if (!Sym.IsMappingSymbol || ShowAllSymbols)
2163 CreateDummy = false;
2164 }
2165 }
2166 if (CreateDummy) {
2167 SymbolInfoTy Sym = createDummySymbolInfo(
2168 Obj, Addr: SectionAddr, Name&: SectionName,
2169 Type: Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT);
2170 if (Obj.isXCOFF())
2171 Symbols.insert(position: Symbols.begin(), x: Sym);
2172 else
2173 Symbols.insert(position: llvm::lower_bound(Range&: Symbols, Value&: Sym), x: Sym);
2174 }
2175
2176 SmallString<40> Comments;
2177 raw_svector_ostream CommentStream(Comments);
2178
2179 uint64_t VMAAdjustment = 0;
2180 if (shouldAdjustVA(Section))
2181 VMAAdjustment = AdjustVMA;
2182
2183 // In executable and shared objects, r_offset holds a virtual address.
2184 // Subtract SectionAddr from the r_offset field of a relocation to get
2185 // the section offset.
2186 uint64_t RelAdjustment = Obj.isRelocatableObject() ? 0 : SectionAddr;
2187 uint64_t Size;
2188 uint64_t Index;
2189 bool PrintedSection = false;
2190 std::vector<RelocationRef> Rels = RelocMap[Section];
2191 std::vector<RelocationRef>::const_iterator RelCur = Rels.begin();
2192 std::vector<RelocationRef>::const_iterator RelEnd = Rels.end();
2193 std::string CurrentRISCVVendorSymbol;
2194 uint64_t CurrentRISCVVendorOffset = 0;
2195
2196 // Loop over each chunk of code between two points where at least
2197 // one symbol is defined.
2198 for (size_t SI = 0, SE = Symbols.size(); SI != SE;) {
2199 // Advance SI past all the symbols starting at the same address,
2200 // and make an ArrayRef of them.
2201 unsigned FirstSI = SI;
2202 uint64_t Start = Symbols[SI].Addr;
2203 ArrayRef<SymbolInfoTy> SymbolsHere;
2204 while (SI != SE && Symbols[SI].Addr == Start)
2205 ++SI;
2206 SymbolsHere = ArrayRef<SymbolInfoTy>(&Symbols[FirstSI], SI - FirstSI);
2207
2208 // Get the demangled names of all those symbols. We end up with a vector
2209 // of StringRef that holds the names we're going to use, and a vector of
2210 // std::string that stores the new strings returned by demangle(), if
2211 // any. If we don't call demangle() then that vector can stay empty.
2212 std::vector<StringRef> SymNamesHere;
2213 std::vector<std::string> DemangledSymNamesHere;
2214 if (Demangle) {
2215 // Fetch the demangled names and store them locally.
2216 for (const SymbolInfoTy &Symbol : SymbolsHere)
2217 DemangledSymNamesHere.push_back(x: demangle(MangledName: Symbol.Name));
2218 // Now we've finished modifying that vector, it's safe to make
2219 // a vector of StringRefs pointing into it.
2220 SymNamesHere.insert(position: SymNamesHere.begin(), first: DemangledSymNamesHere.begin(),
2221 last: DemangledSymNamesHere.end());
2222 } else {
2223 for (const SymbolInfoTy &Symbol : SymbolsHere)
2224 SymNamesHere.push_back(x: Symbol.Name);
2225 }
2226
2227 // Distinguish ELF data from code symbols, which will be used later on to
2228 // decide whether to 'disassemble' this chunk as a data declaration via
2229 // dumpELFData(), or whether to treat it as code.
2230 //
2231 // If data _and_ code symbols are defined at the same address, the code
2232 // takes priority, on the grounds that disassembling code is our main
2233 // purpose here, and it would be a worse failure to _not_ interpret
2234 // something that _was_ meaningful as code than vice versa.
2235 //
2236 // Any ELF symbol type that is not clearly data will be regarded as code.
2237 // In particular, one of the uses of STT_NOTYPE is for branch targets
2238 // inside functions, for which STT_FUNC would be inaccurate.
2239 //
2240 // So here, we spot whether there's any non-data symbol present at all,
2241 // and only set the DisassembleAsELFData flag if there isn't. Also, we use
2242 // this distinction to inform the decision of which symbol to print at
2243 // the head of the section, so that if we're printing code, we print a
2244 // code-related symbol name to go with it.
2245 bool DisassembleAsELFData = false;
2246 size_t DisplaySymIndex = SymbolsHere.size() - 1;
2247 if (Obj.isELF() && !DisassembleAll && Section.isText()) {
2248 DisassembleAsELFData = true; // unless we find a code symbol below
2249
2250 for (size_t i = 0; i < SymbolsHere.size(); ++i) {
2251 uint8_t SymTy = SymbolsHere[i].Type;
2252 if (SymTy != ELF::STT_OBJECT && SymTy != ELF::STT_COMMON) {
2253 DisassembleAsELFData = false;
2254 DisplaySymIndex = i;
2255 }
2256 }
2257 }
2258
2259 // Decide which symbol(s) from this collection we're going to print.
2260 std::vector<bool> SymsToPrint(SymbolsHere.size(), false);
2261 // If the user has given the --disassemble-symbols option, then we must
2262 // display every symbol in that set, and no others.
2263 if (!DisasmSymbolSet.empty()) {
2264 bool FoundAny = false;
2265 for (size_t i = 0; i < SymbolsHere.size(); ++i) {
2266 if (DisasmSymbolSet.count(Key: SymNamesHere[i])) {
2267 SymsToPrint[i] = true;
2268 FoundAny = true;
2269 }
2270 }
2271
2272 // And if none of the symbols here is one that the user asked for, skip
2273 // disassembling this entire chunk of code.
2274 if (!FoundAny)
2275 continue;
2276 } else if (!SymbolsHere[DisplaySymIndex].IsMappingSymbol) {
2277 // Otherwise, print whichever symbol at this location is last in the
2278 // Symbols array, because that array is pre-sorted in a way intended to
2279 // correlate with priority of which symbol to display.
2280 SymsToPrint[DisplaySymIndex] = true;
2281 }
2282
2283 // Now that we know we're disassembling this section, override the choice
2284 // of which symbols to display by printing _all_ of them at this address
2285 // if the user asked for all symbols.
2286 //
2287 // That way, '--show-all-symbols --disassemble-symbol=foo' will print
2288 // only the chunk of code headed by 'foo', but also show any other
2289 // symbols defined at that address, such as aliases for 'foo', or the ARM
2290 // mapping symbol preceding its code.
2291 if (ShowAllSymbols) {
2292 for (size_t i = 0; i < SymbolsHere.size(); ++i)
2293 SymsToPrint[i] = true;
2294 }
2295
2296 if (Start < SectionAddr || StopAddress <= Start)
2297 continue;
2298
2299 FoundDisasmSymbolSet.insert_range(R&: SymNamesHere);
2300
2301 // The end is the section end, the beginning of the next symbol, or
2302 // --stop-address.
2303 uint64_t End = std::min<uint64_t>(a: SectionAddr + SectSize, b: StopAddress);
2304 if (SI < SE)
2305 End = std::min(a: End, b: Symbols[SI].Addr);
2306 if (Start >= End || End <= StartAddress)
2307 continue;
2308 Start -= SectionAddr;
2309 End -= SectionAddr;
2310
2311 if (!PrintedSection) {
2312 PrintedSection = true;
2313 OS << "\nDisassembly of section ";
2314 if (!SegmentName.empty())
2315 OS << SegmentName << ",";
2316 OS << SectionName << ":\n";
2317 }
2318
2319 bool PrintedLabel = false;
2320 for (size_t i = 0; i < SymbolsHere.size(); ++i) {
2321 if (!SymsToPrint[i])
2322 continue;
2323
2324 const SymbolInfoTy &Symbol = SymbolsHere[i];
2325 const StringRef SymbolName = SymNamesHere[i];
2326
2327 if (!PrintedLabel) {
2328 OS << '\n';
2329 PrintedLabel = true;
2330 }
2331 if (LeadingAddr)
2332 OS << format(Fmt: Is64Bits ? "%016" PRIx64 " " : "%08" PRIx64 " ",
2333 Vals: SectionAddr + Start + VMAAdjustment);
2334 if (Obj.isXCOFF() && SymbolDescription) {
2335 OS << getXCOFFSymbolDescription(SymbolInfo: Symbol, SymbolName) << ":\n";
2336 } else
2337 OS << '<' << SymbolName << ">:\n";
2338 }
2339
2340 // Don't print raw contents of a virtual section. A virtual section
2341 // doesn't have any contents in the file.
2342 if (Section.isVirtual()) {
2343 OS << "...\n";
2344 continue;
2345 }
2346
2347 // See if any of the symbols defined at this location triggers target-
2348 // specific disassembly behavior, e.g. of special descriptors or function
2349 // prelude information.
2350 //
2351 // We stop this loop at the first symbol that triggers some kind of
2352 // interesting behavior (if any), on the assumption that if two symbols
2353 // defined at the same address trigger two conflicting symbol handlers,
2354 // the object file is probably confused anyway, and it would make even
2355 // less sense to present the output of _both_ handlers, because that
2356 // would describe the same data twice.
2357 for (size_t SHI = 0; SHI < SymbolsHere.size(); ++SHI) {
2358 SymbolInfoTy Symbol = SymbolsHere[SHI];
2359
2360 Expected<bool> RespondedOrErr = DT->DisAsm->onSymbolStart(
2361 Symbol, Size, Bytes: Bytes.slice(N: Start, M: End - Start), Address: SectionAddr + Start);
2362
2363 if (RespondedOrErr && !*RespondedOrErr) {
2364 // This symbol didn't trigger any interesting handling. Try the other
2365 // symbols defined at this address.
2366 continue;
2367 }
2368
2369 // If onSymbolStart returned an Error, that means it identified some
2370 // kind of special data at this address, but wasn't able to disassemble
2371 // it meaningfully. So we fall back to printing the error out and
2372 // disassembling the failed region as bytes, assuming that the target
2373 // detected the failure before printing anything.
2374 if (!RespondedOrErr) {
2375 std::string ErrMsgStr = toString(E: RespondedOrErr.takeError());
2376 StringRef ErrMsg = ErrMsgStr;
2377 do {
2378 StringRef Line;
2379 std::tie(args&: Line, args&: ErrMsg) = ErrMsg.split(Separator: '\n');
2380 OS << DT->Context->getAsmInfo().getCommentString()
2381 << " error decoding " << SymNamesHere[SHI] << ": " << Line
2382 << '\n';
2383 } while (!ErrMsg.empty());
2384
2385 if (Size) {
2386 OS << DT->Context->getAsmInfo().getCommentString()
2387 << " decoding failed region as bytes\n";
2388 for (uint64_t I = 0; I < Size; ++I)
2389 OS << "\t.byte\t " << format_hex(N: Bytes[I], Width: 1, /*Upper=*/true)
2390 << '\n';
2391 }
2392 }
2393
2394 // Regardless of whether onSymbolStart returned an Error or true, 'Size'
2395 // will have been set to the amount of data covered by whatever prologue
2396 // the target identified. So we advance our own position to beyond that.
2397 // Sometimes that will be the entire distance to the next symbol, and
2398 // sometimes it will be just a prologue and we should start
2399 // disassembling instructions from where it left off.
2400 Start += Size;
2401 break;
2402 }
2403 // Allow targets to reset any per-symbol state.
2404 DT->Printer->onSymbolStart();
2405 formatted_raw_ostream FOS(OS);
2406 Index = Start;
2407 if (SectionAddr < StartAddress)
2408 Index = std::max<uint64_t>(a: Index, b: StartAddress - SectionAddr);
2409
2410 if (DisassembleAsELFData) {
2411 dumpELFData(SectionAddr, Index, End, Bytes, OS&: FOS);
2412 Index = End;
2413 continue;
2414 }
2415
2416 // Skip relocations from symbols that are not dumped.
2417 for (; RelCur != RelEnd; ++RelCur) {
2418 uint64_t Offset = RelCur->getOffset() - RelAdjustment;
2419 if (Index <= Offset)
2420 break;
2421 }
2422
2423 bool DumpARMELFData = false;
2424 bool DumpTracebackTableForXCOFFFunction =
2425 Obj.isXCOFF() && Section.isText() && TracebackTable &&
2426 Symbols[SI - 1].XCOFFSymInfo.StorageMappingClass &&
2427 (*Symbols[SI - 1].XCOFFSymInfo.StorageMappingClass == XCOFF::XMC_PR);
2428
2429 DenseMap<uint64_t, std::string> AllLabels;
2430 DenseMap<uint64_t, std::vector<BBAddrMapLabel>> BBAddrMapLabels;
2431 if (SymbolizeOperands) {
2432 collectLocalBranchTargets(Bytes, MIA: DT->InstrAnalysis.get(),
2433 DisAsm: DT->DisAsm.get(), IP: DT->InstPrinter.get(),
2434 STI: PrimaryTarget.SubtargetInfo.get(),
2435 SectionAddr, Start: Index, End, Labels&: AllLabels);
2436 collectBBAddrMapLabels(FullAddrMap, SectionAddr, Start: Index, End,
2437 Labels&: BBAddrMapLabels);
2438 }
2439
2440 if (DT->InstrAnalysis)
2441 DT->InstrAnalysis->resetState();
2442
2443 while (Index < End) {
2444 uint64_t RelOffset;
2445
2446 // ARM and AArch64 ELF binaries can interleave data and text in the
2447 // same section. We rely on the markers introduced to understand what
2448 // we need to dump. If the data marker is within a function, it is
2449 // denoted as a word/short etc.
2450 if (!MappingSymbols.empty()) {
2451 char Kind = getMappingSymbolKind(MappingSymbols, Address: Index);
2452 DumpARMELFData = Kind == 'd';
2453 if (SecondaryTarget) {
2454 if (Kind == 'a') {
2455 DT = PrimaryIsThumb ? &*SecondaryTarget : &PrimaryTarget;
2456 } else if (Kind == 't') {
2457 DT = PrimaryIsThumb ? &PrimaryTarget : &*SecondaryTarget;
2458 }
2459 }
2460 // RISC-V ISA-aware disassembly: when a "$x<ISAString>" mapping
2461 // symbol is active, use the pre-resolved DisassemblerTarget whose
2462 // STI reflects the indicated ISA so that ISA-specific instructions
2463 // (e.g., vector instructions inside .option arch, +v) are decoded
2464 // correctly.
2465 if (!RISCVISASyms.empty()) {
2466 if (DisassemblerTarget *T =
2467 getRISCVISAMappingTarget(Syms: RISCVISASyms, Address: Index))
2468 DT = T;
2469 else
2470 DT = &PrimaryTarget;
2471 }
2472 } else if (!CHPECodeMap.empty()) {
2473 uint64_t Address = SectionAddr + Index;
2474 auto It = partition_point(
2475 Range&: CHPECodeMap,
2476 P: [Address](const std::pair<uint64_t, uint64_t> &Entry) {
2477 return Entry.first <= Address;
2478 });
2479 if (It != CHPECodeMap.begin() && Address < (It - 1)->second) {
2480 DT = &*SecondaryTarget;
2481 } else {
2482 DT = &PrimaryTarget;
2483 // X64 disassembler range may have left Index unaligned, so
2484 // make sure that it's aligned when we switch back to ARM64
2485 // code.
2486 Index = llvm::alignTo(Value: Index, Align: 4);
2487 if (Index >= End)
2488 break;
2489 }
2490 }
2491
2492 auto findRel = [&]() {
2493 while (RelCur != RelEnd) {
2494 RelOffset = RelCur->getOffset() - RelAdjustment;
2495 // If this relocation is hidden, skip it.
2496 if (getHidden(RelRef: *RelCur) || SectionAddr + RelOffset < StartAddress) {
2497 ++RelCur;
2498 continue;
2499 }
2500
2501 // Stop when RelCur's offset is past the disassembled
2502 // instruction/data.
2503 if (RelOffset >= Index + Size)
2504 return false;
2505 if (RelOffset >= Index)
2506 return true;
2507 ++RelCur;
2508 }
2509 return false;
2510 };
2511
2512 // When -z or --disassemble-zeroes are given we always dissasemble
2513 // them. Otherwise we might want to skip zero bytes we see.
2514 if (!DisassembleZeroes) {
2515 uint64_t MaxOffset = End - Index;
2516 // For --reloc: print zero blocks patched by relocations, so that
2517 // relocations can be shown in the dump.
2518 if (InlineRelocs && RelCur != RelEnd)
2519 MaxOffset = std::min(a: RelCur->getOffset() - RelAdjustment - Index,
2520 b: MaxOffset);
2521
2522 if (size_t N =
2523 countSkippableZeroBytes(Buf: Bytes.slice(N: Index, M: MaxOffset))) {
2524 FOS << "\t\t..." << '\n';
2525 Index += N;
2526 continue;
2527 }
2528 }
2529
2530 if (DumpARMELFData) {
2531 Size = dumpARMELFData(SectionAddr, Index, End, Obj, Bytes,
2532 MappingSymbols, STI: *DT->SubtargetInfo, OS&: FOS);
2533 } else {
2534
2535 if (DumpTracebackTableForXCOFFFunction &&
2536 doesXCOFFTracebackTableBegin(Bytes: Bytes.slice(N: Index, M: 4))) {
2537 dumpTracebackTable(Bytes: Bytes.slice(N: Index),
2538 Address: SectionAddr + Index + VMAAdjustment, OS&: FOS,
2539 End: SectionAddr + End + VMAAdjustment,
2540 STI: *DT->SubtargetInfo, Obj: cast<XCOFFObjectFile>(Val: &Obj));
2541 Index = End;
2542 continue;
2543 }
2544
2545 // Print local label if there's any.
2546 auto Iter1 = BBAddrMapLabels.find(Val: SectionAddr + Index);
2547 if (Iter1 != BBAddrMapLabels.end()) {
2548 for (const auto &BBLabel : Iter1->second)
2549 FOS << "<" << BBLabel.BlockLabel << ">" << BBLabel.PGOAnalysis
2550 << ":\n";
2551 } else {
2552 auto Iter2 = AllLabels.find(Val: SectionAddr + Index);
2553 if (Iter2 != AllLabels.end())
2554 FOS << "<" << Iter2->second << ">:\n";
2555 }
2556
2557 // Disassemble a real instruction or a data when disassemble all is
2558 // provided
2559 MCInst Inst;
2560 ArrayRef<uint8_t> ThisBytes = Bytes.slice(N: Index);
2561 uint64_t ThisAddr = SectionAddr + Index + VMAAdjustment;
2562 bool Disassembled = DT->DisAsm->getInstruction(
2563 Instr&: Inst, Size, Bytes: ThisBytes, Address: ThisAddr, CStream&: CommentStream);
2564 if (Size == 0)
2565 Size = std::min<uint64_t>(
2566 a: ThisBytes.size(),
2567 b: DT->DisAsm->suggestBytesToSkip(Bytes: ThisBytes, Address: ThisAddr));
2568
2569 LEP.update(ThisAddr: {.Address: ThisAddr, .SectionIndex: Section.getIndex()},
2570 NextAddr: {.Address: ThisAddr + Size, .SectionIndex: Section.getIndex()},
2571 IncludeDefinedVars: Index + Size != End);
2572
2573 DT->InstPrinter->setCommentStream(CommentStream);
2574
2575 DT->Printer->printInst(
2576 IP&: *DT->InstPrinter, MI: Disassembled ? &Inst : nullptr,
2577 Bytes: Bytes.slice(N: Index, M: Size),
2578 Address: {.Address: SectionAddr + Index + VMAAdjustment, .SectionIndex: Section.getIndex()}, OS&: FOS,
2579 Annot: "", STI: *DT->SubtargetInfo, SP: &SP, ObjectFilename: Obj.getFileName(), Rels: &Rels, LEP);
2580
2581 DT->InstPrinter->setCommentStream(llvm::nulls());
2582
2583 // If disassembly succeeds, we try to resolve the target address
2584 // (jump target or memory operand address) and print it to the
2585 // right of the instruction.
2586 //
2587 // Otherwise, we don't print anything else so that we avoid
2588 // analyzing invalid or incomplete instruction information.
2589 if (Disassembled && DT->InstrAnalysis) {
2590 llvm::raw_ostream *TargetOS = &FOS;
2591 uint64_t Target;
2592 bool PrintTarget = DT->InstrAnalysis->evaluateBranch(
2593 Inst, Addr: SectionAddr + Index, Size, Target);
2594
2595 if (!PrintTarget) {
2596 if (std::optional<uint64_t> MaybeTarget =
2597 DT->InstrAnalysis->evaluateMemoryOperandAddress(
2598 Inst, STI: DT->SubtargetInfo.get(), Addr: SectionAddr + Index,
2599 Size)) {
2600 Target = *MaybeTarget;
2601 PrintTarget = true;
2602 // Do not print real address when symbolizing.
2603 if (!SymbolizeOperands) {
2604 // Memory operand addresses are printed as comments.
2605 TargetOS = &CommentStream;
2606 *TargetOS << "0x" << Twine::utohexstr(Val: Target);
2607 }
2608 }
2609 }
2610
2611 if (PrintTarget) {
2612 // In a relocatable object, the target's section must reside in
2613 // the same section as the call instruction or it is accessed
2614 // through a relocation.
2615 //
2616 // In a non-relocatable object, the target may be in any section.
2617 // In that case, locate the section(s) containing the target
2618 // address and find the symbol in one of those, if possible.
2619 //
2620 // N.B. Except for XCOFF, we don't walk the relocations in the
2621 // relocatable case yet.
2622 std::vector<const SectionSymbolsTy *> TargetSectionSymbols;
2623 if (!Obj.isRelocatableObject()) {
2624 auto It = llvm::partition_point(
2625 Range&: SectionAddresses,
2626 P: [=](const std::pair<uint64_t, SectionRef> &O) {
2627 return O.first <= Target;
2628 });
2629 uint64_t TargetSecAddr = 0;
2630 while (It != SectionAddresses.begin()) {
2631 --It;
2632 if (TargetSecAddr == 0)
2633 TargetSecAddr = It->first;
2634 if (It->first != TargetSecAddr)
2635 break;
2636 TargetSectionSymbols.push_back(x: &AllSymbols[It->second]);
2637 }
2638 } else {
2639 TargetSectionSymbols.push_back(x: &Symbols);
2640 }
2641 TargetSectionSymbols.push_back(x: &AbsoluteSymbols);
2642
2643 // Find the last symbol in the first candidate section whose
2644 // offset is less than or equal to the target. If there are no
2645 // such symbols, try in the next section and so on, before finally
2646 // using the nearest preceding absolute symbol (if any), if there
2647 // are no other valid symbols.
2648 const SymbolInfoTy *TargetSym = nullptr;
2649 for (const SectionSymbolsTy *TargetSymbols :
2650 TargetSectionSymbols) {
2651 auto It = llvm::partition_point(
2652 Range: *TargetSymbols,
2653 P: [=](const SymbolInfoTy &O) { return O.Addr <= Target; });
2654 while (It != TargetSymbols->begin()) {
2655 --It;
2656 // Skip mapping symbols to avoid possible ambiguity as they
2657 // do not allow uniquely identifying the target address.
2658 if (!It->IsMappingSymbol) {
2659 TargetSym = &*It;
2660 break;
2661 }
2662 }
2663 if (TargetSym)
2664 break;
2665 }
2666
2667 // Branch targets are printed just after the instructions.
2668 // Print the labels corresponding to the target if there's any.
2669 bool BBAddrMapLabelAvailable = BBAddrMapLabels.count(Val: Target);
2670 bool LabelAvailable = AllLabels.count(Val: Target);
2671
2672 if (TargetSym != nullptr) {
2673 uint64_t TargetAddress = TargetSym->Addr;
2674 uint64_t Disp = Target - TargetAddress;
2675 std::string TargetName = Demangle ? demangle(MangledName: TargetSym->Name)
2676 : TargetSym->Name.str();
2677 bool RelFixedUp = false;
2678 SmallString<32> Val;
2679
2680 *TargetOS << " <";
2681 // On XCOFF, we use relocations, even without -r, so we
2682 // can print the correct name for an extern function call.
2683 if (Obj.isXCOFF() && findRel()) {
2684 // Check for possible branch relocations and
2685 // branches to fixup code.
2686 bool BranchRelocationType = true;
2687 XCOFF::RelocationType RelocType;
2688 if (Obj.is64Bit()) {
2689 const XCOFFRelocation64 *Reloc =
2690 reinterpret_cast<XCOFFRelocation64 *>(
2691 RelCur->getRawDataRefImpl().p);
2692 RelFixedUp = Reloc->isFixupIndicated();
2693 RelocType = Reloc->Type;
2694 } else {
2695 const XCOFFRelocation32 *Reloc =
2696 reinterpret_cast<XCOFFRelocation32 *>(
2697 RelCur->getRawDataRefImpl().p);
2698 RelFixedUp = Reloc->isFixupIndicated();
2699 RelocType = Reloc->Type;
2700 }
2701 BranchRelocationType =
2702 RelocType == XCOFF::R_BA || RelocType == XCOFF::R_BR ||
2703 RelocType == XCOFF::R_RBA || RelocType == XCOFF::R_RBR;
2704
2705 // If we have a valid relocation, try to print its
2706 // corresponding symbol name. Multiple relocations on the
2707 // same instruction are not handled.
2708 // Branches to fixup code will have the RelFixedUp flag set in
2709 // the RLD. For these instructions, we print the correct
2710 // branch target, but print the referenced symbol as a
2711 // comment.
2712 if (Error E = getRelocationValueString(Rel: *RelCur, SymbolDescription: false, Result&: Val)) {
2713 // If -r was used, this error will be printed later.
2714 // Otherwise, we ignore the error and print what
2715 // would have been printed without using relocations.
2716 consumeError(Err: std::move(E));
2717 *TargetOS << TargetName;
2718 RelFixedUp = false; // Suppress comment for RLD sym name
2719 } else if (BranchRelocationType && !RelFixedUp)
2720 *TargetOS << Val;
2721 else
2722 *TargetOS << TargetName;
2723 if (Disp)
2724 *TargetOS << "+0x" << Twine::utohexstr(Val: Disp);
2725 } else if (!Disp) {
2726 *TargetOS << TargetName;
2727 } else if (BBAddrMapLabelAvailable) {
2728 *TargetOS << BBAddrMapLabels[Target].front().BlockLabel;
2729 } else if (LabelAvailable) {
2730 *TargetOS << AllLabels[Target];
2731 } else {
2732 // Always Print the binary symbol plus an offset if there's no
2733 // local label corresponding to the target address.
2734 *TargetOS << TargetName << "+0x" << Twine::utohexstr(Val: Disp);
2735 }
2736 *TargetOS << ">";
2737 if (RelFixedUp && !InlineRelocs) {
2738 // We have fixup code for a relocation. We print the
2739 // referenced symbol as a comment.
2740 *TargetOS << "\t# " << Val;
2741 }
2742
2743 } else if (BBAddrMapLabelAvailable) {
2744 *TargetOS << " <" << BBAddrMapLabels[Target].front().BlockLabel
2745 << ">";
2746 } else if (LabelAvailable) {
2747 *TargetOS << " <" << AllLabels[Target] << ">";
2748 }
2749 // By convention, each record in the comment stream should be
2750 // terminated.
2751 if (TargetOS == &CommentStream)
2752 *TargetOS << "\n";
2753 }
2754
2755 DT->InstrAnalysis->updateState(Inst, STI: DT->SubtargetInfo.get(),
2756 Addr: SectionAddr + Index);
2757 } else if (!Disassembled && DT->InstrAnalysis) {
2758 DT->InstrAnalysis->resetState();
2759 }
2760 }
2761
2762 DT->Printer->emitPostInstructionInfo(FOS, MAI: DT->Context->getAsmInfo(),
2763 STI: *DT->SubtargetInfo,
2764 Comments: CommentStream.str(), LEP);
2765 Comments.clear();
2766
2767 if (BTF)
2768 printBTFRelocation(FOS, BTF&: *BTF, Address: {.Address: Index, .SectionIndex: Section.getIndex()}, LEP);
2769
2770 if (InlineRelocs) {
2771 while (findRel()) {
2772 // When --adjust-vma is used, update the address printed.
2773 printRelocation(OS&: FOS, FileName: Obj.getFileName(), Rel: *RelCur,
2774 Address: SectionAddr + RelOffset + VMAAdjustment, Is64Bits,
2775 CurrentRISCVVendorSymbol, CurrentRISCVVendorOffset);
2776 LEP.printAfterOtherLine(OS&: FOS, AfterInst: true);
2777 ++RelCur;
2778 }
2779 }
2780
2781 object::SectionedAddress NextAddr = {
2782 .Address: SectionAddr + Index + VMAAdjustment + Size, .SectionIndex: Section.getIndex()};
2783 LEP.printBoundaryLine(OS&: FOS, Addr: NextAddr, IsEnd: true);
2784
2785 Index += Size;
2786 }
2787 }
2788 }
2789 StringSet<> MissingDisasmSymbolSet =
2790 set_difference(S1: DisasmSymbolSet, S2: FoundDisasmSymbolSet);
2791 for (StringRef Sym : MissingDisasmSymbolSet.keys())
2792 reportWarning(Message: "failed to disassemble missing symbol " + Sym, File: FileName);
2793}
2794
2795static void disassembleObject(ObjectFile *Obj, bool InlineRelocs,
2796 raw_ostream &OS) {
2797 // If information useful for showing the disassembly is missing, try to find a
2798 // more complete binary and disassemble that instead.
2799 OwningBinary<Binary> FetchedBinary;
2800 if (Obj->symbols().empty()) {
2801 if (std::optional<OwningBinary<Binary>> FetchedBinaryOpt =
2802 fetchBinaryByBuildID(Obj: *Obj)) {
2803 if (auto *O = dyn_cast<ObjectFile>(Val: FetchedBinaryOpt->getBinary())) {
2804 if (!O->symbols().empty() ||
2805 (!O->sections().empty() && Obj->sections().empty())) {
2806 FetchedBinary = std::move(*FetchedBinaryOpt);
2807 Obj = O;
2808 }
2809 }
2810 }
2811 }
2812
2813 const Target *TheTarget = getTarget(Obj);
2814
2815 // Default --symbolize-operands to on for BPF, since BPF users expect to see
2816 // basic block labels in disassembly.
2817 SymbolizeOperands =
2818 SymbolizeOperandsOption.value_or(u: Obj->makeTriple().isBPF());
2819
2820 // Package up features to be passed to target/subtarget
2821 Expected<SubtargetFeatures> FeaturesValue = Obj->getFeatures();
2822 if (!FeaturesValue)
2823 reportError(E: FeaturesValue.takeError(), FileName: Obj->getFileName());
2824 SubtargetFeatures Features = *FeaturesValue;
2825 if (!MAttrs.empty()) {
2826 for (unsigned I = 0; I != MAttrs.size(); ++I)
2827 Features.AddFeature(String: MAttrs[I]);
2828 } else if (MCPU.empty() && Obj->makeTriple().isAArch64()) {
2829 Features.AddFeature(String: "+all");
2830 } else if (MCPU.empty() && Obj->makeTriple().isAVR()) {
2831 if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Val: Obj)) {
2832 if (Expected<std::string> VersionOrErr = AVR::getFeatureSetFromEFlag(
2833 EFlag: Elf->getPlatformFlags() & ELF::EF_AVR_ARCH_MASK)) {
2834 Features.AddFeature(String: '+' + *VersionOrErr);
2835 } else {
2836 // If the architecture version cannot be determined from ELF flags,
2837 // fall back to the baseline "avr0" ISA. The AVR disassembler
2838 // requires a valid feature specification to function correctly.
2839 reportWarning(Message: toString(E: VersionOrErr.takeError()) +
2840 ": defaulting to avr0",
2841 File: Obj->getFileName());
2842 Features.AddFeature(String: "+avr0");
2843 }
2844 }
2845 }
2846
2847 if (MCPU.empty())
2848 MCPU = Obj->tryGetCPUName().value_or(u: "").str();
2849
2850 if (isArmElf(Obj: *Obj)) {
2851 // When disassembling big-endian Arm ELF, the instruction endianness is
2852 // determined in a complex way. In relocatable objects, AAELF32 mandates
2853 // that instruction endianness matches the ELF file endianness; in
2854 // executable images, that's true unless the file header has the EF_ARM_BE8
2855 // flag, in which case instructions are little-endian regardless of data
2856 // endianness.
2857 //
2858 // We must set the big-endian-instructions SubtargetFeature to make the
2859 // disassembler read the instructions the right way round, and also tell
2860 // our own prettyprinter to retrieve the encodings the same way to print in
2861 // hex.
2862 const auto *Elf32BE = dyn_cast<ELF32BEObjectFile>(Val: Obj);
2863
2864 if (Elf32BE && (Elf32BE->isRelocatableObject() ||
2865 !(Elf32BE->getPlatformFlags() & ELF::EF_ARM_BE8))) {
2866 Features.AddFeature(String: "+big-endian-instructions");
2867 ARMPrettyPrinterInst.setInstructionEndianness(llvm::endianness::big);
2868 } else {
2869 ARMPrettyPrinterInst.setInstructionEndianness(llvm::endianness::little);
2870 }
2871 }
2872
2873 DisassemblerTarget PrimaryTarget(TheTarget, *Obj, TripleName, MCPU, Features);
2874
2875 // If we have an ARM object file, we need a second disassembler, because
2876 // ARM CPUs have two different instruction sets: ARM mode, and Thumb mode.
2877 // We use mapping symbols to switch between the two assemblers, where
2878 // appropriate.
2879 std::optional<DisassemblerTarget> SecondaryTarget;
2880
2881 if (isArmElf(Obj: *Obj)) {
2882 if (!PrimaryTarget.SubtargetInfo->checkFeatures(FS: "+mclass")) {
2883 if (PrimaryTarget.SubtargetInfo->checkFeatures(FS: "+thumb-mode"))
2884 Features.AddFeature(String: "-thumb-mode");
2885 else
2886 Features.AddFeature(String: "+thumb-mode");
2887 SecondaryTarget.emplace(args&: PrimaryTarget, args&: Features);
2888 }
2889 } else if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Val: Obj)) {
2890 const chpe_metadata *CHPEMetadata = COFFObj->getCHPEMetadata();
2891 if (CHPEMetadata && CHPEMetadata->CodeMapCount) {
2892 // Set up x86_64 disassembler for ARM64EC binaries.
2893 Triple X64Triple(TripleName);
2894 X64Triple.setArch(Kind: Triple::ArchType::x86_64);
2895
2896 std::string Error;
2897 const Target *X64Target =
2898 TargetRegistry::lookupTarget(ArchName: "", TheTriple&: X64Triple, Error);
2899 if (X64Target) {
2900 SubtargetFeatures X64Features;
2901 SecondaryTarget.emplace(args&: X64Target, args&: *Obj, args: X64Triple.getTriple(), args: "",
2902 args&: X64Features);
2903 } else {
2904 reportWarning(Message: Error, File: Obj->getFileName());
2905 }
2906 }
2907 }
2908
2909 const ObjectFile *DbgObj = Obj;
2910 if (!FetchedBinary.getBinary() && !Obj->hasDebugInfo()) {
2911 if (std::optional<OwningBinary<Binary>> DebugBinaryOpt =
2912 fetchBinaryByBuildID(Obj: *Obj)) {
2913 if (auto *FetchedObj =
2914 dyn_cast<const ObjectFile>(Val: DebugBinaryOpt->getBinary())) {
2915 if (FetchedObj->hasDebugInfo()) {
2916 FetchedBinary = std::move(*DebugBinaryOpt);
2917 DbgObj = FetchedObj;
2918 }
2919 }
2920 }
2921 }
2922
2923 std::unique_ptr<object::Binary> DSYMBinary;
2924 std::unique_ptr<MemoryBuffer> DSYMBuf;
2925 if (!DbgObj->hasDebugInfo()) {
2926 if (const MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(Val: &*Obj)) {
2927 DbgObj = objdump::getMachODSymObject(O: MachOOF, Filename: Obj->getFileName(),
2928 DSYMBinary, DSYMBuf);
2929 if (!DbgObj)
2930 return;
2931 }
2932 }
2933
2934 SourcePrinter SP(DbgObj, TheTarget->getName());
2935
2936 for (StringRef Opt : DisassemblerOptions)
2937 if (!PrimaryTarget.InstPrinter->applyTargetSpecificCLOption(Opt))
2938 reportError(File: Obj->getFileName(),
2939 Message: "Unrecognized disassembler option: " + Opt);
2940
2941 disassembleObject(Obj&: *Obj, DbgObj: *DbgObj, PrimaryTarget, SecondaryTarget, SP,
2942 InlineRelocs, OS);
2943}
2944
2945void Dumper::printRelocations() {
2946 StringRef Fmt = O.getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
2947
2948 // Build a mapping from relocation target to a vector of relocation
2949 // sections. Usually, there is an only one relocation section for
2950 // each relocated section.
2951 MapVector<SectionRef, std::vector<SectionRef>> SecToRelSec;
2952 uint64_t Ndx;
2953 for (const SectionRef &Section : ToolSectionFilter(O, Idx: &Ndx)) {
2954 if (O.isELF() && (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC))
2955 continue;
2956 if (Section.relocations().empty())
2957 continue;
2958 Expected<section_iterator> SecOrErr = Section.getRelocatedSection();
2959 if (!SecOrErr)
2960 reportError(File: O.getFileName(),
2961 Message: "section (" + Twine(Ndx) +
2962 "): unable to get a relocation target: " +
2963 toString(E: SecOrErr.takeError()));
2964 SecToRelSec[**SecOrErr].push_back(x: Section);
2965 }
2966
2967 for (std::pair<SectionRef, std::vector<SectionRef>> &P : SecToRelSec) {
2968 StringRef SecName = unwrapOrError(EO: P.first.getName(), Args: O.getFileName());
2969 outs() << "\nRELOCATION RECORDS FOR [" << SecName << "]:\n";
2970 uint32_t OffsetPadding = (O.getBytesInAddress() > 4 ? 16 : 8);
2971 uint32_t TypePadding = 24;
2972 outs() << left_justify(Str: "OFFSET", Width: OffsetPadding) << " "
2973 << left_justify(Str: "TYPE", Width: TypePadding) << " "
2974 << "VALUE\n";
2975
2976 for (SectionRef Section : P.second) {
2977 // CREL sections require decoding, each section may have its own specific
2978 // decode problems.
2979 if (O.isELF() && ELFSectionRef(Section).getType() == ELF::SHT_CREL) {
2980 StringRef Err =
2981 cast<const ELFObjectFileBase>(Val: O).getCrelDecodeProblem(Sec: Section);
2982 if (!Err.empty()) {
2983 reportUniqueWarning(Msg: Err);
2984 continue;
2985 }
2986 }
2987 std::string CurrentRISCVVendorSymbol;
2988 uint64_t CurrentRISCVVendorOffset = 0;
2989 for (const RelocationRef &Reloc : Section.relocations()) {
2990 uint64_t Address = Reloc.getOffset();
2991 SmallString<32> RelocName;
2992 SmallString<32> ValueStr;
2993 if (Address < StartAddress || Address > StopAddress || getHidden(RelRef: Reloc))
2994 continue;
2995 StringRef Name = getRelocTypeName(Rel: Reloc, RelocName,
2996 CurrentRISCVVendorSymbol,
2997 CurrentRISCVVendorOffset);
2998 if (Error E =
2999 getRelocationValueString(Rel: Reloc, SymbolDescription, Result&: ValueStr))
3000 reportUniqueWarning(Err: std::move(E));
3001
3002 outs() << format(Fmt: Fmt.data(), Vals: Address) << " "
3003 << left_justify(Str: Name, Width: TypePadding) << " " << ValueStr << "\n";
3004 }
3005 }
3006 }
3007}
3008
3009// Returns true if we need to show LMA column when dumping section headers. We
3010// show it only when the platform is ELF and either we have at least one section
3011// whose VMA and LMA are different and/or when --show-lma flag is used.
3012static bool shouldDisplayLMA(const ObjectFile &Obj) {
3013 if (!Obj.isELF())
3014 return false;
3015 for (const SectionRef &S : ToolSectionFilter(O: Obj))
3016 if (S.getAddress() != getELFSectionLMA(Sec: S))
3017 return true;
3018 return ShowLMA;
3019}
3020
3021static size_t getMaxSectionNameWidth(const ObjectFile &Obj) {
3022 // Default column width for names is 13 even if no names are that long.
3023 size_t MaxWidth = 13;
3024 for (const SectionRef &Section : ToolSectionFilter(O: Obj)) {
3025 StringRef Name = unwrapOrError(EO: Section.getName(), Args: Obj.getFileName());
3026 MaxWidth = std::max(a: MaxWidth, b: Name.size());
3027 }
3028 return MaxWidth;
3029}
3030
3031void objdump::printSectionHeaders(ObjectFile &Obj) {
3032 if (Obj.isELF() && Obj.sections().empty())
3033 createFakeELFSections(Obj);
3034
3035 size_t NameWidth = getMaxSectionNameWidth(Obj);
3036 size_t AddressWidth = 2 * Obj.getBytesInAddress();
3037 bool HasLMAColumn = shouldDisplayLMA(Obj);
3038 outs() << "\nSections:\n";
3039 if (HasLMAColumn)
3040 outs() << "Idx " << left_justify(Str: "Name", Width: NameWidth) << " Size "
3041 << left_justify(Str: "VMA", Width: AddressWidth) << " "
3042 << left_justify(Str: "LMA", Width: AddressWidth) << " Type\n";
3043 else
3044 outs() << "Idx " << left_justify(Str: "Name", Width: NameWidth) << " Size "
3045 << left_justify(Str: "VMA", Width: AddressWidth) << " Type\n";
3046
3047 uint64_t Idx;
3048 for (const SectionRef &Section : ToolSectionFilter(O: Obj, Idx: &Idx)) {
3049 StringRef Name = unwrapOrError(EO: Section.getName(), Args: Obj.getFileName());
3050 uint64_t VMA = Section.getAddress();
3051 if (shouldAdjustVA(Section))
3052 VMA += AdjustVMA;
3053
3054 uint64_t Size = Section.getSize();
3055
3056 std::string Type = Section.isText() ? "TEXT" : "";
3057 if (Section.isData())
3058 Type += Type.empty() ? "DATA" : ", DATA";
3059 if (Section.isBSS())
3060 Type += Type.empty() ? "BSS" : ", BSS";
3061 if (Section.isDebugSection())
3062 Type += Type.empty() ? "DEBUG" : ", DEBUG";
3063
3064 if (HasLMAColumn)
3065 outs() << format(Fmt: "%3" PRIu64 " %-*s %08" PRIx64 " ", Vals: Idx, Vals: NameWidth,
3066 Vals: Name.str().c_str(), Vals: Size)
3067 << format_hex_no_prefix(N: VMA, Width: AddressWidth) << " "
3068 << format_hex_no_prefix(N: getELFSectionLMA(Sec: Section), Width: AddressWidth)
3069 << " " << Type << "\n";
3070 else
3071 outs() << format(Fmt: "%3" PRIu64 " %-*s %08" PRIx64 " ", Vals: Idx, Vals: NameWidth,
3072 Vals: Name.str().c_str(), Vals: Size)
3073 << format_hex_no_prefix(N: VMA, Width: AddressWidth) << " " << Type << "\n";
3074 }
3075}
3076
3077void objdump::printSectionContents(const ObjectFile *Obj) {
3078 const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Val: Obj);
3079
3080 for (const SectionRef &Section : ToolSectionFilter(O: *Obj)) {
3081 StringRef Name = unwrapOrError(EO: Section.getName(), Args: Obj->getFileName());
3082 uint64_t BaseAddr = Section.getAddress();
3083 uint64_t Size = Section.getSize();
3084 if (!Size)
3085 continue;
3086
3087 outs() << "Contents of section ";
3088 StringRef SegmentName = getSegmentName(MachO, Section);
3089 if (!SegmentName.empty())
3090 outs() << SegmentName << ",";
3091 outs() << Name << ":\n";
3092 if (Section.isBSS()) {
3093 outs() << format(Fmt: "<skipping contents of bss section at [%04" PRIx64
3094 ", %04" PRIx64 ")>\n",
3095 Vals: BaseAddr, Vals: BaseAddr + Size);
3096 continue;
3097 }
3098
3099 StringRef Contents =
3100 unwrapOrError(EO: Section.getContents(), Args: Obj->getFileName());
3101
3102 // Dump out the content as hex and printable ascii characters.
3103 for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) {
3104 outs() << format(Fmt: " %04" PRIx64 " ", Vals: BaseAddr + Addr);
3105 // Dump line of hex.
3106 for (std::size_t I = 0; I < 16; ++I) {
3107 if (I != 0 && I % 4 == 0)
3108 outs() << ' ';
3109 if (Addr + I < End)
3110 outs() << hexdigit(X: (Contents[Addr + I] >> 4) & 0xF, LowerCase: true)
3111 << hexdigit(X: Contents[Addr + I] & 0xF, LowerCase: true);
3112 else
3113 outs() << " ";
3114 }
3115 // Print ascii.
3116 outs() << " ";
3117 for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) {
3118 if (isPrint(C: static_cast<unsigned char>(Contents[Addr + I]) & 0xFF))
3119 outs() << Contents[Addr + I];
3120 else
3121 outs() << ".";
3122 }
3123 outs() << "\n";
3124 }
3125 }
3126}
3127
3128void Dumper::printSymbolTable(StringRef ArchiveName, StringRef ArchitectureName,
3129 bool DumpDynamic) {
3130 if (O.isCOFF() && !DumpDynamic) {
3131 outs() << "\nSYMBOL TABLE:\n";
3132 printCOFFSymbolTable(O: cast<const COFFObjectFile>(Val: O));
3133 return;
3134 }
3135
3136 const StringRef FileName = O.getFileName();
3137
3138 if (!DumpDynamic) {
3139 outs() << "\nSYMBOL TABLE:\n";
3140 for (auto I = O.symbol_begin(); I != O.symbol_end(); ++I)
3141 printSymbol(Symbol: *I, SymbolVersions: {}, FileName, ArchiveName, ArchitectureName, DumpDynamic);
3142 return;
3143 }
3144
3145 outs() << "\nDYNAMIC SYMBOL TABLE:\n";
3146 if (!O.isELF()) {
3147 reportWarning(
3148 Message: "this operation is not currently supported for this file format",
3149 File: FileName);
3150 return;
3151 }
3152
3153 const ELFObjectFileBase *ELF = cast<const ELFObjectFileBase>(Val: &O);
3154 auto Symbols = ELF->getDynamicSymbolIterators();
3155 Expected<std::vector<VersionEntry>> SymbolVersionsOrErr =
3156 ELF->readDynsymVersions();
3157 if (!SymbolVersionsOrErr) {
3158 reportWarning(Message: toString(E: SymbolVersionsOrErr.takeError()), File: FileName);
3159 SymbolVersionsOrErr = std::vector<VersionEntry>();
3160 (void)!SymbolVersionsOrErr;
3161 }
3162 for (auto &Sym : Symbols)
3163 printSymbol(Symbol: Sym, SymbolVersions: *SymbolVersionsOrErr, FileName, ArchiveName,
3164 ArchitectureName, DumpDynamic);
3165}
3166
3167void Dumper::printSymbol(const SymbolRef &Symbol,
3168 ArrayRef<VersionEntry> SymbolVersions,
3169 StringRef FileName, StringRef ArchiveName,
3170 StringRef ArchitectureName, bool DumpDynamic) {
3171 const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Val: &O);
3172 Expected<uint64_t> AddrOrErr = Symbol.getAddress();
3173 if (!AddrOrErr) {
3174 reportUniqueWarning(Err: AddrOrErr.takeError());
3175 return;
3176 }
3177
3178 // Don't ask a Mach-O STAB symbol for its section unless you know that
3179 // STAB symbol's section field refers to a valid section index. Otherwise
3180 // the symbol may error trying to load a section that does not exist.
3181 bool IsSTAB = false;
3182 if (MachO) {
3183 DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
3184 uint8_t NType =
3185 (MachO->is64Bit() ? MachO->getSymbol64TableEntry(DRI: SymDRI).n_type
3186 : MachO->getSymbolTableEntry(DRI: SymDRI).n_type);
3187 if (NType & MachO::N_STAB)
3188 IsSTAB = true;
3189 }
3190 section_iterator Section = IsSTAB
3191 ? O.section_end()
3192 : unwrapOrError(EO: Symbol.getSection(), Args&: FileName,
3193 Args&: ArchiveName, Args&: ArchitectureName);
3194
3195 uint64_t Address = *AddrOrErr;
3196 if (Section != O.section_end() && shouldAdjustVA(Section: *Section))
3197 Address += AdjustVMA;
3198 if ((Address < StartAddress) || (Address > StopAddress))
3199 return;
3200 SymbolRef::Type Type =
3201 unwrapOrError(EO: Symbol.getType(), Args&: FileName, Args&: ArchiveName, Args&: ArchitectureName);
3202 uint32_t Flags =
3203 unwrapOrError(EO: Symbol.getFlags(), Args&: FileName, Args&: ArchiveName, Args&: ArchitectureName);
3204
3205 StringRef Name;
3206 if (Type == SymbolRef::ST_Debug && Section != O.section_end()) {
3207 if (Expected<StringRef> NameOrErr = Section->getName())
3208 Name = *NameOrErr;
3209 else
3210 consumeError(Err: NameOrErr.takeError());
3211
3212 } else {
3213 Name = unwrapOrError(EO: Symbol.getName(), Args&: FileName, Args&: ArchiveName,
3214 Args&: ArchitectureName);
3215 }
3216
3217 bool Global = Flags & SymbolRef::SF_Global;
3218 bool Weak = Flags & SymbolRef::SF_Weak;
3219 bool Absolute = Flags & SymbolRef::SF_Absolute;
3220 bool Common = Flags & SymbolRef::SF_Common;
3221 bool Hidden = Flags & SymbolRef::SF_Hidden;
3222
3223 char GlobLoc = ' ';
3224 if ((Section != O.section_end() || Absolute) && !Weak)
3225 GlobLoc = Global ? 'g' : 'l';
3226 char IFunc = ' ';
3227 if (O.isELF()) {
3228 if (ELFSymbolRef(Symbol).getELFType() == ELF::STT_GNU_IFUNC)
3229 IFunc = 'i';
3230 if (ELFSymbolRef(Symbol).getBinding() == ELF::STB_GNU_UNIQUE)
3231 GlobLoc = 'u';
3232 }
3233
3234 char Debug = ' ';
3235 if (DumpDynamic)
3236 Debug = 'D';
3237 else if (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
3238 Debug = 'd';
3239
3240 char FileFunc = ' ';
3241 if (Type == SymbolRef::ST_File)
3242 FileFunc = 'f';
3243 else if (Type == SymbolRef::ST_Function)
3244 FileFunc = 'F';
3245 else if (Type == SymbolRef::ST_Data)
3246 FileFunc = 'O';
3247
3248 const char *Fmt = O.getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
3249
3250 outs() << format(Fmt, Vals: Address) << " "
3251 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
3252 << (Weak ? 'w' : ' ') // Weak?
3253 << ' ' // Constructor. Not supported yet.
3254 << ' ' // Warning. Not supported yet.
3255 << IFunc // Indirect reference to another symbol.
3256 << Debug // Debugging (d) or dynamic (D) symbol.
3257 << FileFunc // Name of function (F), file (f) or object (O).
3258 << ' ';
3259 if (Absolute) {
3260 outs() << "*ABS*";
3261 } else if (Common) {
3262 outs() << "*COM*";
3263 } else if (Section == O.section_end()) {
3264 if (O.isXCOFF()) {
3265 XCOFFSymbolRef XCOFFSym = cast<const XCOFFObjectFile>(Val: O).toSymbolRef(
3266 Ref: Symbol.getRawDataRefImpl());
3267 if (XCOFF::N_DEBUG == XCOFFSym.getSectionNumber())
3268 outs() << "*DEBUG*";
3269 else
3270 outs() << "*UND*";
3271 } else
3272 outs() << "*UND*";
3273 } else {
3274 StringRef SegmentName = getSegmentName(MachO, Section: *Section);
3275 if (!SegmentName.empty())
3276 outs() << SegmentName << ",";
3277 StringRef SectionName = unwrapOrError(EO: Section->getName(), Args&: FileName);
3278 outs() << SectionName;
3279 if (O.isXCOFF()) {
3280 std::optional<SymbolRef> SymRef =
3281 getXCOFFSymbolContainingSymbolRef(Obj: cast<XCOFFObjectFile>(Val: O), Sym: Symbol);
3282 if (SymRef) {
3283
3284 Expected<StringRef> NameOrErr = SymRef->getName();
3285
3286 if (NameOrErr) {
3287 outs() << " (csect:";
3288 std::string SymName =
3289 Demangle ? demangle(MangledName: *NameOrErr) : NameOrErr->str();
3290
3291 if (SymbolDescription)
3292 SymName = getXCOFFSymbolDescription(SymbolInfo: createSymbolInfo(Obj: O, Symbol: *SymRef),
3293 SymbolName: SymName);
3294
3295 outs() << ' ' << SymName;
3296 outs() << ") ";
3297 } else
3298 reportWarning(Message: toString(E: NameOrErr.takeError()), File: FileName);
3299 }
3300 }
3301 }
3302
3303 if (Common)
3304 outs() << '\t' << format(Fmt, Vals: static_cast<uint64_t>(Symbol.getAlignment()));
3305 else if (O.isXCOFF())
3306 outs() << '\t'
3307 << format(Fmt, Vals: cast<XCOFFObjectFile>(Val: O).getSymbolSize(
3308 Symb: Symbol.getRawDataRefImpl()));
3309 else if (O.isELF())
3310 outs() << '\t' << format(Fmt, Vals: ELFSymbolRef(Symbol).getSize());
3311 else if (O.isWasm())
3312 outs() << '\t'
3313 << format(Fmt, Vals: static_cast<uint64_t>(
3314 cast<WasmObjectFile>(Val: O).getSymbolSize(Sym: Symbol)));
3315
3316 if (O.isELF()) {
3317 if (!SymbolVersions.empty()) {
3318 const VersionEntry &Ver =
3319 SymbolVersions[Symbol.getRawDataRefImpl().d.b - 1];
3320 std::string Str;
3321 if (!Ver.Name.empty())
3322 Str = Ver.IsVerDef ? ' ' + Ver.Name : '(' + Ver.Name + ')';
3323 outs() << ' ' << left_justify(Str, Width: 12);
3324 }
3325
3326 uint8_t Other = ELFSymbolRef(Symbol).getOther();
3327 switch (Other) {
3328 case ELF::STV_DEFAULT:
3329 break;
3330 case ELF::STV_INTERNAL:
3331 outs() << " .internal";
3332 break;
3333 case ELF::STV_HIDDEN:
3334 outs() << " .hidden";
3335 break;
3336 case ELF::STV_PROTECTED:
3337 outs() << " .protected";
3338 break;
3339 default:
3340 outs() << format(Fmt: " 0x%02x", Vals: Other);
3341 break;
3342 }
3343 } else if (Hidden) {
3344 outs() << " .hidden";
3345 }
3346
3347 std::string SymName = Demangle ? demangle(MangledName: Name) : Name.str();
3348 if (O.isXCOFF() && SymbolDescription)
3349 SymName = getXCOFFSymbolDescription(SymbolInfo: createSymbolInfo(Obj: O, Symbol), SymbolName: SymName);
3350
3351 outs() << ' ' << SymName << '\n';
3352}
3353
3354static void printUnwindInfo(const ObjectFile *O) {
3355 outs() << "Unwind info:\n\n";
3356
3357 if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(Val: O))
3358 printCOFFUnwindInfo(O: Coff);
3359 else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: O))
3360 printMachOUnwindInfo(O: MachO);
3361 else
3362 // TODO: Extract DWARF dump tool to objdump.
3363 WithColor::error(OS&: errs(), Prefix: ToolName)
3364 << "This operation is only currently supported "
3365 "for COFF and MachO object files.\n";
3366}
3367
3368/// Dump the raw contents of the __clangast section so the output can be piped
3369/// into llvm-bcanalyzer.
3370static void printRawClangAST(const ObjectFile *Obj) {
3371 if (outs().is_displayed()) {
3372 WithColor::error(OS&: errs(), Prefix: ToolName)
3373 << "The -raw-clang-ast option will dump the raw binary contents of "
3374 "the clang ast section.\n"
3375 "Please redirect the output to a file or another program such as "
3376 "llvm-bcanalyzer.\n";
3377 return;
3378 }
3379
3380 StringRef ClangASTSectionName("__clangast");
3381 if (Obj->isCOFF()) {
3382 ClangASTSectionName = "clangast";
3383 }
3384
3385 std::optional<object::SectionRef> ClangASTSection;
3386 for (auto Sec : ToolSectionFilter(O: *Obj)) {
3387 StringRef Name;
3388 if (Expected<StringRef> NameOrErr = Sec.getName())
3389 Name = *NameOrErr;
3390 else
3391 consumeError(Err: NameOrErr.takeError());
3392
3393 if (Name == ClangASTSectionName) {
3394 ClangASTSection = Sec;
3395 break;
3396 }
3397 }
3398 if (!ClangASTSection)
3399 return;
3400
3401 StringRef ClangASTContents =
3402 unwrapOrError(EO: ClangASTSection->getContents(), Args: Obj->getFileName());
3403 outs().write(Ptr: ClangASTContents.data(), Size: ClangASTContents.size());
3404}
3405
3406static void printFaultMaps(const ObjectFile *Obj) {
3407 StringRef FaultMapSectionName;
3408
3409 if (Obj->isELF()) {
3410 FaultMapSectionName = ".llvm_faultmaps";
3411 } else if (Obj->isMachO()) {
3412 FaultMapSectionName = "__llvm_faultmaps";
3413 } else {
3414 WithColor::error(OS&: errs(), Prefix: ToolName)
3415 << "This operation is only currently supported "
3416 "for ELF and Mach-O executable files.\n";
3417 return;
3418 }
3419
3420 std::optional<object::SectionRef> FaultMapSection;
3421
3422 for (auto Sec : ToolSectionFilter(O: *Obj)) {
3423 StringRef Name;
3424 if (Expected<StringRef> NameOrErr = Sec.getName())
3425 Name = *NameOrErr;
3426 else
3427 consumeError(Err: NameOrErr.takeError());
3428
3429 if (Name == FaultMapSectionName) {
3430 FaultMapSection = Sec;
3431 break;
3432 }
3433 }
3434
3435 outs() << "FaultMap table:\n";
3436
3437 if (!FaultMapSection) {
3438 outs() << "<not found>\n";
3439 return;
3440 }
3441
3442 StringRef FaultMapContents =
3443 unwrapOrError(EO: FaultMapSection->getContents(), Args: Obj->getFileName());
3444 FaultMapParser FMP(FaultMapContents.bytes_begin(),
3445 FaultMapContents.bytes_end());
3446
3447 outs() << FMP;
3448}
3449
3450void Dumper::printPrivateHeaders() {
3451 reportError(File: O.getFileName(), Message: "Invalid/Unsupported object file format");
3452}
3453
3454static void printFileHeaders(const ObjectFile *O) {
3455 if (!O->isELF() && !O->isCOFF() && !O->isXCOFF())
3456 reportError(File: O->getFileName(), Message: "Invalid/Unsupported object file format");
3457
3458 Triple::ArchType AT = O->getArch();
3459 outs() << "architecture: " << Triple::getArchTypeName(Kind: AT) << "\n";
3460 uint64_t Address = unwrapOrError(EO: O->getStartAddress(), Args: O->getFileName());
3461
3462 StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
3463 outs() << "start address: "
3464 << "0x" << format(Fmt: Fmt.data(), Vals: Address) << "\n";
3465}
3466
3467static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
3468 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
3469 if (!ModeOrErr) {
3470 WithColor::error(OS&: errs(), Prefix: ToolName) << "ill-formed archive entry.\n";
3471 consumeError(Err: ModeOrErr.takeError());
3472 return;
3473 }
3474 sys::fs::perms Mode = ModeOrErr.get();
3475 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
3476 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
3477 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
3478 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
3479 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
3480 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
3481 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
3482 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
3483 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
3484
3485 outs() << " ";
3486
3487 outs() << format(Fmt: "%d/%d %6" PRId64 " ", Vals: unwrapOrError(EO: C.getUID(), Args&: Filename),
3488 Vals: unwrapOrError(EO: C.getGID(), Args&: Filename),
3489 Vals: unwrapOrError(EO: C.getRawSize(), Args&: Filename));
3490
3491 StringRef RawLastModified = C.getRawLastModified();
3492 unsigned Seconds;
3493 if (RawLastModified.getAsInteger(Radix: 10, Result&: Seconds))
3494 outs() << "(date: \"" << RawLastModified
3495 << "\" contains non-decimal chars) ";
3496 else {
3497 // Since ctime(3) returns a 26 character string of the form:
3498 // "Sun Sep 16 01:03:52 1973\n\0"
3499 // just print 24 characters.
3500 time_t t = Seconds;
3501 outs() << format(Fmt: "%.24s ", Vals: ctime(timer: &t));
3502 }
3503
3504 StringRef Name = "";
3505 Expected<StringRef> NameOrErr = C.getName();
3506 if (!NameOrErr) {
3507 consumeError(Err: NameOrErr.takeError());
3508 Name = unwrapOrError(EO: C.getRawName(), Args&: Filename);
3509 } else {
3510 Name = NameOrErr.get();
3511 }
3512 outs() << Name << "\n";
3513}
3514
3515// For ELF only now.
3516static bool shouldWarnForInvalidStartStopAddress(ObjectFile *Obj) {
3517 if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Val: Obj)) {
3518 if (Elf->getEType() != ELF::ET_REL)
3519 return true;
3520 }
3521 return false;
3522}
3523
3524static void checkForInvalidStartStopAddress(ObjectFile *Obj, uint64_t Start,
3525 uint64_t Stop) {
3526 if (!shouldWarnForInvalidStartStopAddress(Obj))
3527 return;
3528
3529 for (const SectionRef &Section : Obj->sections())
3530 if (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC) {
3531 uint64_t BaseAddr = Section.getAddress();
3532 uint64_t Size = Section.getSize();
3533 if ((Start < BaseAddr + Size) && Stop > BaseAddr)
3534 return;
3535 }
3536
3537 if (!HasStartAddressFlag)
3538 reportWarning(Message: "no section has address less than 0x" +
3539 Twine::utohexstr(Val: Stop) + " specified by --stop-address",
3540 File: Obj->getFileName());
3541 else if (!HasStopAddressFlag)
3542 reportWarning(Message: "no section has address greater than or equal to 0x" +
3543 Twine::utohexstr(Val: Start) + " specified by --start-address",
3544 File: Obj->getFileName());
3545 else
3546 reportWarning(Message: "no section overlaps the range [0x" +
3547 Twine::utohexstr(Val: Start) + ",0x" + Twine::utohexstr(Val: Stop) +
3548 ") specified by --start-address/--stop-address",
3549 File: Obj->getFileName());
3550}
3551
3552static void dumpObject(ObjectFile *O, const Archive *A = nullptr,
3553 const Archive::Child *C = nullptr) {
3554 Expected<std::unique_ptr<Dumper>> DumperOrErr = createDumper(Obj: *O);
3555 if (!DumperOrErr) {
3556 reportError(E: DumperOrErr.takeError(), FileName: O->getFileName(),
3557 ArchiveName: A ? A->getFileName() : "");
3558 return;
3559 }
3560 Dumper &D = **DumperOrErr;
3561
3562 // Avoid other output when using a raw option.
3563 if (!RawClangAST) {
3564 outs() << '\n';
3565 if (A)
3566 outs() << A->getFileName() << "(" << O->getFileName() << ")";
3567 else
3568 outs() << O->getFileName();
3569 outs() << ":\tfile format " << O->getFileFormatName().lower() << "\n";
3570 }
3571
3572 if (HasStartAddressFlag || HasStopAddressFlag)
3573 checkForInvalidStartStopAddress(Obj: O, Start: StartAddress, Stop: StopAddress);
3574
3575 // TODO: Change print* free functions to Dumper member functions to utilitize
3576 // stateful functions like reportUniqueWarning.
3577
3578 // Note: the order here matches GNU objdump for compatability.
3579 StringRef ArchiveName = A ? A->getFileName() : "";
3580 if (ArchiveHeaders && !MachOOpt && C)
3581 printArchiveChild(Filename: ArchiveName, C: *C);
3582 if (FileHeaders)
3583 printFileHeaders(O);
3584 if (PrivateHeaders || FirstPrivateHeader)
3585 D.printPrivateHeaders();
3586 if (SectionHeaders)
3587 printSectionHeaders(Obj&: *O);
3588 if (SymbolTable)
3589 D.printSymbolTable(ArchiveName);
3590 if (DynamicSymbolTable)
3591 D.printSymbolTable(ArchiveName, /*ArchitectureName=*/"",
3592 /*DumpDynamic=*/true);
3593 if (DwarfDumpType != DIDT_Null) {
3594 std::unique_ptr<DIContext> DICtx = DWARFContext::create(Obj: *O);
3595 // Dump the complete DWARF structure.
3596 DIDumpOptions DumpOpts;
3597 DumpOpts.DumpType = DwarfDumpType;
3598 DICtx->dump(OS&: outs(), DumpOpts);
3599 }
3600 if (Relocations && !Disassemble)
3601 D.printRelocations();
3602 if (DynamicRelocations)
3603 D.printDynamicRelocations();
3604 if (SectionContents)
3605 printSectionContents(Obj: O);
3606 if (Disassemble)
3607 disassembleObject(Obj: O, InlineRelocs: Relocations, OS&: outs());
3608 if (UnwindInfo)
3609 printUnwindInfo(O);
3610
3611 // Mach-O specific options:
3612 if (ExportsTrie)
3613 printExportsTrie(O);
3614 if (Rebase)
3615 printRebaseTable(O);
3616 if (Bind)
3617 printBindTable(O);
3618 if (LazyBind)
3619 printLazyBindTable(O);
3620 if (WeakBind)
3621 printWeakBindTable(O);
3622
3623 // Other special sections:
3624 if (RawClangAST)
3625 printRawClangAST(Obj: O);
3626 if (FaultMapSection)
3627 printFaultMaps(Obj: O);
3628 if (Offloading)
3629 dumpOffloadBinary(O: *O, ArchName: StringRef(ArchName));
3630}
3631
3632static void dumpObject(const COFFImportFile *I, const Archive *A,
3633 const Archive::Child *C = nullptr) {
3634 StringRef ArchiveName = A ? A->getFileName() : "";
3635
3636 // Avoid other output when using a raw option.
3637 if (!RawClangAST)
3638 outs() << '\n'
3639 << ArchiveName << "(" << I->getFileName() << ")"
3640 << ":\tfile format COFF-import-file"
3641 << "\n\n";
3642
3643 if (ArchiveHeaders && !MachOOpt && C)
3644 printArchiveChild(Filename: ArchiveName, C: *C);
3645 if (SymbolTable)
3646 printCOFFSymbolTable(I: *I);
3647}
3648
3649/// Dump each object file in \a a;
3650static void dumpArchive(const Archive *A) {
3651 Error Err = Error::success();
3652 unsigned I = -1;
3653 for (auto &C : A->children(Err)) {
3654 ++I;
3655 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
3656 if (!ChildOrErr) {
3657 if (auto E = isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
3658 reportError(E: std::move(E), FileName: getFileNameForError(C, Index: I), ArchiveName: A->getFileName());
3659 continue;
3660 }
3661 if (ObjectFile *O = dyn_cast<ObjectFile>(Val: &*ChildOrErr.get()))
3662 dumpObject(O, A, C: &C);
3663 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(Val: &*ChildOrErr.get()))
3664 dumpObject(I, A, C: &C);
3665 else
3666 reportError(E: errorCodeToError(EC: object_error::invalid_file_type),
3667 FileName: A->getFileName());
3668 }
3669 if (Err)
3670 reportError(E: std::move(Err), FileName: A->getFileName());
3671}
3672
3673/// Open file and figure out how to dump it.
3674static void dumpInput(StringRef file) {
3675 // If we are using the Mach-O specific object file parser, then let it parse
3676 // the file and process the command line options. So the -arch flags can
3677 // be used to select specific slices, etc.
3678 if (MachOOpt) {
3679 parseInputMachO(Filename: file);
3680 return;
3681 }
3682
3683 // Attempt to open the binary.
3684 OwningBinary<Binary> OBinary = unwrapOrError(EO: createBinary(Path: file), Args&: file);
3685 Binary &Binary = *OBinary.getBinary();
3686
3687 if (Archive *A = dyn_cast<Archive>(Val: &Binary))
3688 dumpArchive(A);
3689 else if (ObjectFile *O = dyn_cast<ObjectFile>(Val: &Binary))
3690 dumpObject(O);
3691 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Val: &Binary))
3692 parseInputMachO(UB);
3693 else if (OffloadBinary *OB = dyn_cast<OffloadBinary>(Val: &Binary))
3694 dumpOffloadSections(OB: *OB);
3695 else
3696 reportError(E: errorCodeToError(EC: object_error::invalid_file_type), FileName: file);
3697}
3698
3699template <typename T>
3700static void parseIntArg(const llvm::opt::InputArgList &InputArgs, int ID,
3701 T &Value) {
3702 if (const opt::Arg *A = InputArgs.getLastArg(Ids: ID)) {
3703 StringRef V(A->getValue());
3704 if (!llvm::to_integer(V, Value, 0)) {
3705 reportCmdLineError(Message: A->getSpelling() +
3706 ": expected a non-negative integer, but got '" + V +
3707 "'");
3708 }
3709 }
3710}
3711
3712static object::BuildID parseBuildIDArg(const opt::Arg *A) {
3713 StringRef V(A->getValue());
3714 object::BuildID BID = parseBuildID(Str: V);
3715 if (BID.empty())
3716 reportCmdLineError(Message: A->getSpelling() + ": expected a build ID, but got '" +
3717 V + "'");
3718 return BID;
3719}
3720
3721void objdump::invalidArgValue(const opt::Arg *A) {
3722 reportCmdLineError(Message: "'" + StringRef(A->getValue()) +
3723 "' is not a valid value for '" + A->getSpelling() + "'");
3724}
3725
3726static std::vector<std::string>
3727commaSeparatedValues(const llvm::opt::InputArgList &InputArgs, int ID) {
3728 std::vector<std::string> Values;
3729 for (StringRef Value : InputArgs.getAllArgValues(Id: ID)) {
3730 llvm::SmallVector<StringRef, 2> SplitValues;
3731 llvm::SplitString(Source: Value, OutFragments&: SplitValues, Delimiters: ",");
3732 for (StringRef SplitValue : SplitValues)
3733 Values.push_back(x: SplitValue.str());
3734 }
3735 return Values;
3736}
3737
3738static void mcpuHelp() {
3739 Triple TheTriple;
3740
3741 if (!TripleName.empty()) {
3742 TheTriple.setTriple(TripleName);
3743 } else {
3744 assert(!InputFilenames.empty());
3745 Expected<OwningBinary<Binary>> OBinary = createBinary(Path: InputFilenames[0]);
3746 if (Error E = OBinary.takeError()) {
3747 reportError(File: InputFilenames[0], Message: "triple was not specified and could not "
3748 "be inferred from the input file: " +
3749 toString(E: std::move(E)));
3750 }
3751
3752 Binary *Bin = OBinary->getBinary();
3753 if (ObjectFile *Obj = dyn_cast<ObjectFile>(Val: Bin)) {
3754 TheTriple = Obj->makeTriple();
3755 } else if (Archive *A = dyn_cast<Archive>(Val: Bin)) {
3756 Error Err = Error::success();
3757 unsigned I = -1;
3758 for (auto &C : A->children(Err)) {
3759 ++I;
3760 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
3761 if (!ChildOrErr) {
3762 if (auto E = isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
3763 reportError(E: std::move(E), FileName: getFileNameForError(C, Index: I),
3764 ArchiveName: A->getFileName());
3765 continue;
3766 }
3767 if (ObjectFile *Obj = dyn_cast<ObjectFile>(Val: &*ChildOrErr.get())) {
3768 TheTriple = Obj->makeTriple();
3769 break;
3770 }
3771 }
3772 if (Err)
3773 reportError(E: std::move(Err), FileName: A->getFileName());
3774 }
3775 if (TheTriple.empty())
3776 reportError(File: InputFilenames[0],
3777 Message: "target triple could not be derived from input file");
3778 }
3779
3780 std::string ErrMessage;
3781 const Target *DummyTarget =
3782 TargetRegistry::lookupTarget(TheTriple, Error&: ErrMessage);
3783 if (!DummyTarget)
3784 reportCmdLineError(Message: ErrMessage);
3785 // We need to access the Help() through the corresponding MCSubtargetInfo.
3786 // To avoid a memory leak, we wrap the createMcSubtargetInfo result in a
3787 // unique_ptr.
3788 std::unique_ptr<MCSubtargetInfo> MSI(
3789 DummyTarget->createMCSubtargetInfo(TheTriple, CPU: "help", Features: ""));
3790}
3791
3792static void parseOtoolOptions(const llvm::opt::InputArgList &InputArgs) {
3793 MachOOpt = true;
3794 FullLeadingAddr = true;
3795 PrintImmHex = true;
3796
3797 ArchName = InputArgs.getLastArgValue(Id: OTOOL_arch).str();
3798 if (!ArchName.empty())
3799 ArchFlags.push_back(x: ArchName);
3800 ArchiveHeaders = InputArgs.hasArg(Ids: OTOOL_a);
3801 LinkOptHints = InputArgs.hasArg(Ids: OTOOL_C);
3802 if (InputArgs.hasArg(Ids: OTOOL_d))
3803 FilterSections.push_back(x: "__DATA,__data");
3804 DylibId = InputArgs.hasArg(Ids: OTOOL_D);
3805 UniversalHeaders = InputArgs.hasArg(Ids: OTOOL_f);
3806 DataInCode = InputArgs.hasArg(Ids: OTOOL_G);
3807 FirstPrivateHeader = InputArgs.hasArg(Ids: OTOOL_h);
3808 IndirectSymbols = InputArgs.hasArg(Ids: OTOOL_I);
3809 ShowRawInsn = InputArgs.hasArg(Ids: OTOOL_j);
3810 PrivateHeaders = InputArgs.hasArg(Ids: OTOOL_l);
3811 DylibsUsed = InputArgs.hasArg(Ids: OTOOL_L);
3812 MCPU = InputArgs.getLastArgValue(Id: OTOOL_mcpu_EQ).str();
3813 ObjcMetaData = InputArgs.hasArg(Ids: OTOOL_o);
3814 DisSymName = InputArgs.getLastArgValue(Id: OTOOL_p).str();
3815 InfoPlist = InputArgs.hasArg(Ids: OTOOL_P);
3816 Relocations = InputArgs.hasArg(Ids: OTOOL_r);
3817 if (const Arg *A = InputArgs.getLastArg(Ids: OTOOL_s)) {
3818 auto Filter = (A->getValue(N: 0) + StringRef(",") + A->getValue(N: 1)).str();
3819 FilterSections.push_back(x: Filter);
3820 }
3821 if (InputArgs.hasArg(Ids: OTOOL_t))
3822 FilterSections.push_back(x: "__TEXT,__text");
3823 Verbose = InputArgs.hasArg(Ids: OTOOL_v) || InputArgs.hasArg(Ids: OTOOL_V) ||
3824 InputArgs.hasArg(Ids: OTOOL_o);
3825 SymbolicOperands = InputArgs.hasArg(Ids: OTOOL_V);
3826 if (InputArgs.hasArg(Ids: OTOOL_x))
3827 FilterSections.push_back(x: ",__text");
3828 LeadingAddr = LeadingHeaders = !InputArgs.hasArg(Ids: OTOOL_X);
3829
3830 ChainedFixups = InputArgs.hasArg(Ids: OTOOL_chained_fixups);
3831 DyldInfo = InputArgs.hasArg(Ids: OTOOL_dyld_info);
3832
3833 UseMemberSyntax = !InputArgs.hasArg(Ids: OTOOL_m);
3834
3835 InputFilenames = InputArgs.getAllArgValues(Id: OTOOL_INPUT);
3836 if (InputFilenames.empty())
3837 reportCmdLineError(Message: "no input file");
3838
3839 for (const Arg *A : InputArgs) {
3840 const Option &O = A->getOption();
3841 if (O.getGroup().isValid() && O.getGroup().getID() == OTOOL_grp_obsolete) {
3842 reportCmdLineWarning(Message: O.getPrefixedName() +
3843 " is obsolete and not implemented");
3844 }
3845 }
3846}
3847
3848static void parseObjdumpOptions(const llvm::opt::InputArgList &InputArgs) {
3849 parseIntArg(InputArgs, ID: OBJDUMP_adjust_vma_EQ, Value&: AdjustVMA);
3850 AllHeaders = InputArgs.hasArg(Ids: OBJDUMP_all_headers);
3851 ArchName = InputArgs.getLastArgValue(Id: OBJDUMP_arch_name_EQ).str();
3852 ArchiveHeaders = InputArgs.hasArg(Ids: OBJDUMP_archive_headers);
3853 Demangle = InputArgs.hasArg(Ids: OBJDUMP_demangle);
3854 Disassemble = InputArgs.hasArg(Ids: OBJDUMP_disassemble);
3855 DisassembleAll = InputArgs.hasArg(Ids: OBJDUMP_disassemble_all);
3856 SymbolDescription = InputArgs.hasArg(Ids: OBJDUMP_symbol_description);
3857 TracebackTable = InputArgs.hasArg(Ids: OBJDUMP_traceback_table);
3858 DisassembleSymbols =
3859 commaSeparatedValues(InputArgs, ID: OBJDUMP_disassemble_symbols_EQ);
3860 for (auto Sym : InputArgs.getAllArgValues(Id: OBJDUMP_disassemble_EQ))
3861 DisassembleSymbols.push_back(x: Sym);
3862 DisassembleZeroes = InputArgs.hasArg(Ids: OBJDUMP_disassemble_zeroes);
3863 if (const opt::Arg *A = InputArgs.getLastArg(Ids: OBJDUMP_dwarf_EQ)) {
3864 DwarfDumpType = StringSwitch<DIDumpType>(A->getValue())
3865 .Case(S: "frames", Value: DIDT_DebugFrame)
3866 .Default(Value: DIDT_Null);
3867 if (DwarfDumpType == DIDT_Null)
3868 invalidArgValue(A);
3869 }
3870 DynamicRelocations = InputArgs.hasArg(Ids: OBJDUMP_dynamic_reloc);
3871 FaultMapSection = InputArgs.hasArg(Ids: OBJDUMP_fault_map_section);
3872 Offloading = InputArgs.hasArg(Ids: OBJDUMP_offloading);
3873 FileHeaders = InputArgs.hasArg(Ids: OBJDUMP_file_headers);
3874 SectionContents = InputArgs.hasArg(Ids: OBJDUMP_full_contents);
3875 PrintLines = InputArgs.hasArg(Ids: OBJDUMP_line_numbers);
3876 InputFilenames = InputArgs.getAllArgValues(Id: OBJDUMP_INPUT);
3877 MachOOpt = InputArgs.hasArg(Ids: OBJDUMP_macho);
3878 MCPU = InputArgs.getLastArgValue(Id: OBJDUMP_mcpu_EQ).str();
3879 MAttrs = commaSeparatedValues(InputArgs, ID: OBJDUMP_mattr_EQ);
3880 ShowRawInsn = !InputArgs.hasArg(Ids: OBJDUMP_no_show_raw_insn);
3881 LeadingAddr = !InputArgs.hasArg(Ids: OBJDUMP_no_leading_addr);
3882 RawClangAST = InputArgs.hasArg(Ids: OBJDUMP_raw_clang_ast);
3883 Relocations = InputArgs.hasArg(Ids: OBJDUMP_reloc);
3884 PrintImmHex =
3885 InputArgs.hasFlag(Pos: OBJDUMP_print_imm_hex, Neg: OBJDUMP_no_print_imm_hex, Default: true);
3886 PrivateHeaders = InputArgs.hasArg(Ids: OBJDUMP_private_headers);
3887 FilterSections = InputArgs.getAllArgValues(Id: OBJDUMP_section_EQ);
3888 SectionHeaders = InputArgs.hasArg(Ids: OBJDUMP_section_headers);
3889 ShowAllSymbols = InputArgs.hasArg(Ids: OBJDUMP_show_all_symbols);
3890 ShowLMA = InputArgs.hasArg(Ids: OBJDUMP_show_lma);
3891 PrintSource = InputArgs.hasArg(Ids: OBJDUMP_source);
3892 parseIntArg(InputArgs, ID: OBJDUMP_start_address_EQ, Value&: StartAddress);
3893 HasStartAddressFlag = InputArgs.hasArg(Ids: OBJDUMP_start_address_EQ);
3894 parseIntArg(InputArgs, ID: OBJDUMP_stop_address_EQ, Value&: StopAddress);
3895 HasStopAddressFlag = InputArgs.hasArg(Ids: OBJDUMP_stop_address_EQ);
3896 SymbolTable = InputArgs.hasArg(Ids: OBJDUMP_syms);
3897 if (const opt::Arg *A = InputArgs.getLastArg(Ids: OBJDUMP_symbolize_operands,
3898 Ids: OBJDUMP_no_symbolize_operands))
3899 SymbolizeOperandsOption =
3900 A->getOption().matches(ID: OBJDUMP_symbolize_operands);
3901 PrettyPGOAnalysisMap = InputArgs.hasArg(Ids: OBJDUMP_pretty_pgo_analysis_map);
3902 if (PrettyPGOAnalysisMap && !SymbolizeOperandsOption.value_or(u: false))
3903 reportCmdLineWarning(Message: "--symbolize-operands must be enabled for "
3904 "--pretty-pgo-analysis-map to have an effect");
3905 DynamicSymbolTable = InputArgs.hasArg(Ids: OBJDUMP_dynamic_syms);
3906 TripleName = InputArgs.getLastArgValue(Id: OBJDUMP_triple_EQ).str();
3907 UnwindInfo = InputArgs.hasArg(Ids: OBJDUMP_unwind_info);
3908 UnwindShowWODPool = InputArgs.hasArg(Ids: OBJDUMP_unwind_show_wod_pool);
3909 Prefix = InputArgs.getLastArgValue(Id: OBJDUMP_prefix).str();
3910 parseIntArg(InputArgs, ID: OBJDUMP_prefix_strip, Value&: PrefixStrip);
3911 for (const opt::Arg *A : InputArgs.filtered(Ids: OBJDUMP_substitute_path)) {
3912 StringRef From = A->getValue(N: 0);
3913 if (From.empty())
3914 reportCmdLineError(Message: A->getSpelling() + ": <from> must not be empty");
3915 SubstitutePaths.emplace_back(args: From.str(), args: A->getValue(N: 1));
3916 }
3917 for (StringRef Dir : InputArgs.getAllArgValues(Id: OBJDUMP_source_dir)) {
3918 if (Dir.empty())
3919 reportCmdLineError(Message: "--source-dir argument must not be empty");
3920 SourceDirs.insert(position: SourceDirs.end(), x: Dir.str());
3921 }
3922
3923 if (const opt::Arg *A = InputArgs.getLastArg(Ids: OBJDUMP_debug_vars_EQ)) {
3924 DbgVariables = StringSwitch<DebugFormat>(A->getValue())
3925 .Case(S: "ascii", Value: DFASCII)
3926 .Case(S: "unicode", Value: DFUnicode)
3927 .Default(Value: DFInvalid);
3928 if (DbgVariables == DFInvalid)
3929 invalidArgValue(A);
3930 }
3931
3932 if (const opt::Arg *A =
3933 InputArgs.getLastArg(Ids: OBJDUMP_debug_inlined_funcs_EQ)) {
3934 DbgInlinedFunctions = StringSwitch<DebugFormat>(A->getValue())
3935 .Case(S: "ascii", Value: DFASCII)
3936 .Case(S: "limits-only", Value: DFLimitsOnly)
3937 .Case(S: "unicode", Value: DFUnicode)
3938 .Default(Value: DFInvalid);
3939 if (DbgInlinedFunctions == DFInvalid)
3940 invalidArgValue(A);
3941 }
3942
3943 if (const opt::Arg *A = InputArgs.getLastArg(Ids: OBJDUMP_disassembler_color_EQ)) {
3944 DisassemblyColor = StringSwitch<ColorOutput>(A->getValue())
3945 .Case(S: "on", Value: ColorOutput::Enable)
3946 .Case(S: "off", Value: ColorOutput::Disable)
3947 .Case(S: "terminal", Value: ColorOutput::Auto)
3948 .Default(Value: ColorOutput::Invalid);
3949 if (DisassemblyColor == ColorOutput::Invalid)
3950 invalidArgValue(A);
3951 }
3952
3953 parseIntArg(InputArgs, ID: OBJDUMP_debug_indent_EQ, Value&: DbgIndent);
3954
3955 parseMachOOptions(InputArgs);
3956
3957 // Parse -M (--disassembler-options) and deprecated
3958 // --x86-asm-syntax={att,intel}.
3959 //
3960 // Note, for x86, the asm dialect (AssemblerDialect) is initialized when the
3961 // MCAsmInfo is constructed. MCInstPrinter::applyTargetSpecificCLOption is
3962 // called too late. For now we have to use the internal cl::opt option.
3963 const char *AsmSyntax = nullptr;
3964 for (const auto *A : InputArgs.filtered(Ids: OBJDUMP_disassembler_options_EQ,
3965 Ids: OBJDUMP_x86_asm_syntax_att,
3966 Ids: OBJDUMP_x86_asm_syntax_intel)) {
3967 switch (A->getOption().getID()) {
3968 case OBJDUMP_x86_asm_syntax_att:
3969 AsmSyntax = "--x86-asm-syntax=att";
3970 continue;
3971 case OBJDUMP_x86_asm_syntax_intel:
3972 AsmSyntax = "--x86-asm-syntax=intel";
3973 continue;
3974 }
3975
3976 SmallVector<StringRef, 2> Values;
3977 llvm::SplitString(Source: A->getValue(), OutFragments&: Values, Delimiters: ",");
3978 for (StringRef V : Values) {
3979 if (V == "att")
3980 AsmSyntax = "--x86-asm-syntax=att";
3981 else if (V == "intel")
3982 AsmSyntax = "--x86-asm-syntax=intel";
3983 else
3984 DisassemblerOptions.push_back(x: V.str());
3985 }
3986 }
3987 SmallVector<const char *> Args = {"llvm-objdump"};
3988 for (const opt::Arg *A : InputArgs.filtered(Ids: OBJDUMP_mllvm))
3989 Args.push_back(Elt: A->getValue());
3990 if (AsmSyntax)
3991 Args.push_back(Elt: AsmSyntax);
3992 if (Args.size() > 1)
3993 llvm::cl::ParseCommandLineOptions(argc: Args.size(), argv: Args.data());
3994
3995 // Look up any provided build IDs, then append them to the input filenames.
3996 for (const opt::Arg *A : InputArgs.filtered(Ids: OBJDUMP_build_id)) {
3997 object::BuildID BuildID = parseBuildIDArg(A);
3998 Expected<std::string> Path = BIDFetcher->fetch(BuildID);
3999 if (!Path) {
4000 // Most users will not care why this failed.
4001 consumeError(Err: Path.takeError());
4002 reportCmdLineError(Message: A->getSpelling() + ": could not find build ID '" +
4003 A->getValue() + "'");
4004 }
4005 InputFilenames.push_back(x: std::move(*Path));
4006 }
4007
4008 // objdump defaults to a.out if no filenames specified.
4009 if (InputFilenames.empty())
4010 InputFilenames.push_back(x: "a.out");
4011}
4012
4013int llvm_objdump_main(int argc, char **argv, const llvm::ToolContext &) {
4014 using namespace llvm;
4015
4016 ToolName = argv[0];
4017 std::unique_ptr<CommonOptTable> T;
4018 OptSpecifier Unknown, HelpFlag, HelpHiddenFlag, VersionFlag;
4019
4020 StringRef Stem = sys::path::stem(path: ToolName);
4021 auto Is = [=](StringRef Tool) {
4022 // We need to recognize the following filenames:
4023 //
4024 // llvm-objdump -> objdump
4025 // llvm-otool-10.exe -> otool
4026 // powerpc64-unknown-freebsd13-objdump -> objdump
4027 auto I = Stem.rfind_insensitive(Str: Tool);
4028 return I != StringRef::npos &&
4029 (I + Tool.size() == Stem.size() || !isAlnum(C: Stem[I + Tool.size()]));
4030 };
4031 if (Is("otool")) {
4032 IsOtool = true;
4033 T = std::make_unique<OtoolOptTable>();
4034 Unknown = OTOOL_UNKNOWN;
4035 HelpFlag = OTOOL_help;
4036 HelpHiddenFlag = OTOOL_help_hidden;
4037 VersionFlag = OTOOL_version;
4038 } else {
4039 T = std::make_unique<ObjdumpOptTable>();
4040 Unknown = OBJDUMP_UNKNOWN;
4041 HelpFlag = OBJDUMP_help;
4042 HelpHiddenFlag = OBJDUMP_help_hidden;
4043 VersionFlag = OBJDUMP_version;
4044 }
4045
4046 BumpPtrAllocator A;
4047 StringSaver Saver(A);
4048 opt::InputArgList InputArgs =
4049 T->parseArgs(Argc: argc, Argv: argv, Unknown, Saver,
4050 ErrorFn: [&](StringRef Msg) { reportCmdLineError(Message: Msg); });
4051
4052 if (InputArgs.size() == 0 || InputArgs.hasArg(Ids: HelpFlag)) {
4053 T->printHelp(Argv0: ToolName);
4054 return 0;
4055 }
4056 if (InputArgs.hasArg(Ids: HelpHiddenFlag)) {
4057 T->printHelp(Argv0: ToolName, /*ShowHidden=*/true);
4058 return 0;
4059 }
4060
4061 // Initialize targets and assembly printers/parsers.
4062 InitializeAllTargetInfos();
4063 InitializeAllTargetMCs();
4064 InitializeAllDisassemblers();
4065
4066 if (InputArgs.hasArg(Ids: VersionFlag)) {
4067 cl::PrintVersionMessage();
4068 if (!Is("otool")) {
4069 outs() << '\n';
4070 TargetRegistry::printRegisteredTargetsForVersion(OS&: outs());
4071 }
4072 return 0;
4073 }
4074
4075 // Initialize debuginfod.
4076 const bool ShouldUseDebuginfodByDefault =
4077 InputArgs.hasArg(Ids: OBJDUMP_build_id) || canUseDebuginfod();
4078 std::vector<std::string> DebugFileDirectories =
4079 InputArgs.getAllArgValues(Id: OBJDUMP_debug_file_directory);
4080 if (InputArgs.hasFlag(Pos: OBJDUMP_debuginfod, Neg: OBJDUMP_no_debuginfod,
4081 Default: ShouldUseDebuginfodByDefault)) {
4082 HTTPClient::initialize();
4083 BIDFetcher =
4084 std::make_unique<DebuginfodFetcher>(args: std::move(DebugFileDirectories));
4085 } else {
4086 BIDFetcher =
4087 std::make_unique<BuildIDFetcher>(args: std::move(DebugFileDirectories));
4088 }
4089
4090 if (Is("otool"))
4091 parseOtoolOptions(InputArgs);
4092 else
4093 parseObjdumpOptions(InputArgs);
4094
4095 if (StartAddress >= StopAddress)
4096 reportCmdLineError(Message: "start address should be less than stop address");
4097
4098 // Removes trailing separators from prefix.
4099 while (!Prefix.empty() && sys::path::is_separator(value: Prefix.back()))
4100 Prefix.pop_back();
4101
4102 if (AllHeaders)
4103 ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations =
4104 SectionHeaders = SymbolTable = true;
4105
4106 if (DisassembleAll || PrintSource || PrintLines || TracebackTable ||
4107 !DisassembleSymbols.empty())
4108 Disassemble = true;
4109
4110 const bool PrintCpuHelp = (MCPU == "help" || is_contained(Range&: MAttrs, Element: "help"));
4111
4112 const bool ShouldDump =
4113 ArchiveHeaders || Disassemble || DwarfDumpType != DIDT_Null ||
4114 DynamicRelocations || FileHeaders || PrivateHeaders || RawClangAST ||
4115 Relocations || SectionHeaders || SectionContents || SymbolTable ||
4116 DynamicSymbolTable || UnwindInfo || FaultMapSection || Offloading ||
4117 (MachOOpt &&
4118 (Bind || DataInCode || ChainedFixups || DyldInfo || DylibId ||
4119 DylibsUsed || ExportsTrie || FirstPrivateHeader ||
4120 FunctionStartsType != FunctionStartsMode::None || IndirectSymbols ||
4121 InfoPlist || LazyBind || LinkOptHints || ObjcMetaData || Rebase ||
4122 Rpaths || UniversalHeaders || WeakBind || !FilterSections.empty()));
4123
4124 if (!ShouldDump && !PrintCpuHelp) {
4125 T->printHelp(Argv0: ToolName);
4126 return 2;
4127 }
4128
4129 if (PrintCpuHelp) {
4130 mcpuHelp();
4131 if (!ShouldDump)
4132 return EXIT_SUCCESS;
4133 }
4134
4135 DisasmSymbolSet.insert_range(R&: DisassembleSymbols);
4136
4137 llvm::for_each(Range&: InputFilenames, F: dumpInput);
4138
4139 warnOnNoMatchForSections();
4140
4141 return EXIT_SUCCESS;
4142}
4143