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