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