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