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