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