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