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