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