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