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