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