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