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