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