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