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