xref: /llvm-project/llvm/tools/llvm-objdump/llvm-objdump.cpp (revision 68e814d9114b6c8910642298714dad6fa79ccad2)
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 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
951   switch(Triple.getArch()) {
952   default:
953     return PrettyPrinterInst;
954   case Triple::hexagon:
955     return HexagonPrettyPrinterInst;
956   case Triple::amdgcn:
957     return AMDGCNPrettyPrinterInst;
958   case Triple::bpfel:
959   case Triple::bpfeb:
960     return BPFPrettyPrinterInst;
961   case Triple::arm:
962   case Triple::armeb:
963   case Triple::thumb:
964   case Triple::thumbeb:
965     return ARMPrettyPrinterInst;
966   case Triple::aarch64:
967   case Triple::aarch64_be:
968   case Triple::aarch64_32:
969     return AArch64PrettyPrinterInst;
970   }
971 }
972 
973 class DisassemblerTarget {
974 public:
975   const Target *TheTarget;
976   std::unique_ptr<const MCSubtargetInfo> SubtargetInfo;
977   std::shared_ptr<MCContext> Context;
978   std::unique_ptr<MCDisassembler> DisAsm;
979   std::shared_ptr<MCInstrAnalysis> InstrAnalysis;
980   std::shared_ptr<MCInstPrinter> InstPrinter;
981   PrettyPrinter *Printer;
982 
983   DisassemblerTarget(const Target *TheTarget, ObjectFile &Obj,
984                      StringRef TripleName, StringRef MCPU,
985                      SubtargetFeatures &Features);
986   DisassemblerTarget(DisassemblerTarget &Other, SubtargetFeatures &Features);
987 
988 private:
989   MCTargetOptions Options;
990   std::shared_ptr<const MCRegisterInfo> RegisterInfo;
991   std::shared_ptr<const MCAsmInfo> AsmInfo;
992   std::shared_ptr<const MCInstrInfo> InstrInfo;
993   std::shared_ptr<MCObjectFileInfo> ObjectFileInfo;
994 };
995 
996 DisassemblerTarget::DisassemblerTarget(const Target *TheTarget, ObjectFile &Obj,
997                                        StringRef TripleName, StringRef MCPU,
998                                        SubtargetFeatures &Features)
999     : TheTarget(TheTarget),
1000       Printer(&selectPrettyPrinter(Triple(TripleName))),
1001       RegisterInfo(TheTarget->createMCRegInfo(TripleName)) {
1002   if (!RegisterInfo)
1003     reportError(Obj.getFileName(), "no register info for target " + TripleName);
1004 
1005   // Set up disassembler.
1006   AsmInfo.reset(TheTarget->createMCAsmInfo(*RegisterInfo, TripleName, Options));
1007   if (!AsmInfo)
1008     reportError(Obj.getFileName(), "no assembly info for target " + TripleName);
1009 
1010   SubtargetInfo.reset(
1011       TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1012   if (!SubtargetInfo)
1013     reportError(Obj.getFileName(),
1014                 "no subtarget info for target " + TripleName);
1015   InstrInfo.reset(TheTarget->createMCInstrInfo());
1016   if (!InstrInfo)
1017     reportError(Obj.getFileName(),
1018                 "no instruction info for target " + TripleName);
1019   Context =
1020       std::make_shared<MCContext>(Triple(TripleName), AsmInfo.get(),
1021                                   RegisterInfo.get(), SubtargetInfo.get());
1022 
1023   // FIXME: for now initialize MCObjectFileInfo with default values
1024   ObjectFileInfo.reset(
1025       TheTarget->createMCObjectFileInfo(*Context, /*PIC=*/false));
1026   Context->setObjectFileInfo(ObjectFileInfo.get());
1027 
1028   DisAsm.reset(TheTarget->createMCDisassembler(*SubtargetInfo, *Context));
1029   if (!DisAsm)
1030     reportError(Obj.getFileName(), "no disassembler for target " + TripleName);
1031 
1032   if (auto *ELFObj = dyn_cast<ELFObjectFileBase>(&Obj))
1033     DisAsm->setABIVersion(ELFObj->getEIdentABIVersion());
1034 
1035   InstrAnalysis.reset(TheTarget->createMCInstrAnalysis(InstrInfo.get()));
1036 
1037   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1038   InstPrinter.reset(TheTarget->createMCInstPrinter(Triple(TripleName),
1039                                                    AsmPrinterVariant, *AsmInfo,
1040                                                    *InstrInfo, *RegisterInfo));
1041   if (!InstPrinter)
1042     reportError(Obj.getFileName(),
1043                 "no instruction printer for target " + TripleName);
1044   InstPrinter->setPrintImmHex(PrintImmHex);
1045   InstPrinter->setPrintBranchImmAsAddress(true);
1046   InstPrinter->setSymbolizeOperands(SymbolizeOperands);
1047   InstPrinter->setMCInstrAnalysis(InstrAnalysis.get());
1048 
1049   switch (DisassemblyColor) {
1050   case ColorOutput::Enable:
1051     InstPrinter->setUseColor(true);
1052     break;
1053   case ColorOutput::Auto:
1054     InstPrinter->setUseColor(outs().has_colors());
1055     break;
1056   case ColorOutput::Disable:
1057   case ColorOutput::Invalid:
1058     InstPrinter->setUseColor(false);
1059     break;
1060   };
1061 }
1062 
1063 DisassemblerTarget::DisassemblerTarget(DisassemblerTarget &Other,
1064                                        SubtargetFeatures &Features)
1065     : TheTarget(Other.TheTarget),
1066       SubtargetInfo(TheTarget->createMCSubtargetInfo(TripleName, MCPU,
1067                                                      Features.getString())),
1068       Context(Other.Context),
1069       DisAsm(TheTarget->createMCDisassembler(*SubtargetInfo, *Context)),
1070       InstrAnalysis(Other.InstrAnalysis), InstPrinter(Other.InstPrinter),
1071       Printer(Other.Printer), RegisterInfo(Other.RegisterInfo),
1072       AsmInfo(Other.AsmInfo), InstrInfo(Other.InstrInfo),
1073       ObjectFileInfo(Other.ObjectFileInfo) {}
1074 } // namespace
1075 
1076 static uint8_t getElfSymbolType(const ObjectFile &Obj, const SymbolRef &Sym) {
1077   assert(Obj.isELF());
1078   if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(&Obj))
1079     return unwrapOrError(Elf32LEObj->getSymbol(Sym.getRawDataRefImpl()),
1080                          Obj.getFileName())
1081         ->getType();
1082   if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(&Obj))
1083     return unwrapOrError(Elf64LEObj->getSymbol(Sym.getRawDataRefImpl()),
1084                          Obj.getFileName())
1085         ->getType();
1086   if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(&Obj))
1087     return unwrapOrError(Elf32BEObj->getSymbol(Sym.getRawDataRefImpl()),
1088                          Obj.getFileName())
1089         ->getType();
1090   if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(&Obj))
1091     return unwrapOrError(Elf64BEObj->getSymbol(Sym.getRawDataRefImpl()),
1092                          Obj.getFileName())
1093         ->getType();
1094   llvm_unreachable("Unsupported binary format");
1095 }
1096 
1097 template <class ELFT>
1098 static void
1099 addDynamicElfSymbols(const ELFObjectFile<ELFT> &Obj,
1100                      std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1101   for (auto Symbol : Obj.getDynamicSymbolIterators()) {
1102     uint8_t SymbolType = Symbol.getELFType();
1103     if (SymbolType == ELF::STT_SECTION)
1104       continue;
1105 
1106     uint64_t Address = unwrapOrError(Symbol.getAddress(), Obj.getFileName());
1107     // ELFSymbolRef::getAddress() returns size instead of value for common
1108     // symbols which is not desirable for disassembly output. Overriding.
1109     if (SymbolType == ELF::STT_COMMON)
1110       Address = unwrapOrError(Obj.getSymbol(Symbol.getRawDataRefImpl()),
1111                               Obj.getFileName())
1112                     ->st_value;
1113 
1114     StringRef Name = unwrapOrError(Symbol.getName(), Obj.getFileName());
1115     if (Name.empty())
1116       continue;
1117 
1118     section_iterator SecI =
1119         unwrapOrError(Symbol.getSection(), Obj.getFileName());
1120     if (SecI == Obj.section_end())
1121       continue;
1122 
1123     AllSymbols[*SecI].emplace_back(Address, Name, SymbolType);
1124   }
1125 }
1126 
1127 static void
1128 addDynamicElfSymbols(const ELFObjectFileBase &Obj,
1129                      std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1130   if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(&Obj))
1131     addDynamicElfSymbols(*Elf32LEObj, AllSymbols);
1132   else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(&Obj))
1133     addDynamicElfSymbols(*Elf64LEObj, AllSymbols);
1134   else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(&Obj))
1135     addDynamicElfSymbols(*Elf32BEObj, AllSymbols);
1136   else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(&Obj))
1137     addDynamicElfSymbols(*Elf64BEObj, AllSymbols);
1138   else
1139     llvm_unreachable("Unsupported binary format");
1140 }
1141 
1142 static std::optional<SectionRef> getWasmCodeSection(const WasmObjectFile &Obj) {
1143   for (auto SecI : Obj.sections()) {
1144     const WasmSection &Section = Obj.getWasmSection(SecI);
1145     if (Section.Type == wasm::WASM_SEC_CODE)
1146       return SecI;
1147   }
1148   return std::nullopt;
1149 }
1150 
1151 static void
1152 addMissingWasmCodeSymbols(const WasmObjectFile &Obj,
1153                           std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1154   std::optional<SectionRef> Section = getWasmCodeSection(Obj);
1155   if (!Section)
1156     return;
1157   SectionSymbolsTy &Symbols = AllSymbols[*Section];
1158 
1159   std::set<uint64_t> SymbolAddresses;
1160   for (const auto &Sym : Symbols)
1161     SymbolAddresses.insert(Sym.Addr);
1162 
1163   for (const wasm::WasmFunction &Function : Obj.functions()) {
1164     // This adjustment mirrors the one in WasmObjectFile::getSymbolAddress.
1165     uint32_t Adjustment = Obj.isRelocatableObject() || Obj.isSharedObject()
1166                               ? 0
1167                               : Section->getAddress();
1168     uint64_t Address = Function.CodeSectionOffset + Adjustment;
1169     // Only add fallback symbols for functions not already present in the symbol
1170     // table.
1171     if (SymbolAddresses.count(Address))
1172       continue;
1173     // This function has no symbol, so it should have no SymbolName.
1174     assert(Function.SymbolName.empty());
1175     // We use DebugName for the name, though it may be empty if there is no
1176     // "name" custom section, or that section is missing a name for this
1177     // function.
1178     StringRef Name = Function.DebugName;
1179     Symbols.emplace_back(Address, Name, ELF::STT_NOTYPE);
1180   }
1181 }
1182 
1183 static void addPltEntries(const ObjectFile &Obj,
1184                           std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
1185                           StringSaver &Saver) {
1186   auto *ElfObj = dyn_cast<ELFObjectFileBase>(&Obj);
1187   if (!ElfObj)
1188     return;
1189   DenseMap<StringRef, SectionRef> Sections;
1190   for (SectionRef Section : Obj.sections()) {
1191     Expected<StringRef> SecNameOrErr = Section.getName();
1192     if (!SecNameOrErr) {
1193       consumeError(SecNameOrErr.takeError());
1194       continue;
1195     }
1196     Sections[*SecNameOrErr] = Section;
1197   }
1198   for (auto Plt : ElfObj->getPltEntries()) {
1199     if (Plt.Symbol) {
1200       SymbolRef Symbol(*Plt.Symbol, ElfObj);
1201       uint8_t SymbolType = getElfSymbolType(Obj, Symbol);
1202       if (Expected<StringRef> NameOrErr = Symbol.getName()) {
1203         if (!NameOrErr->empty())
1204           AllSymbols[Sections[Plt.Section]].emplace_back(
1205               Plt.Address, Saver.save((*NameOrErr + "@plt").str()), SymbolType);
1206         continue;
1207       } else {
1208         // The warning has been reported in disassembleObject().
1209         consumeError(NameOrErr.takeError());
1210       }
1211     }
1212     reportWarning("PLT entry at 0x" + Twine::utohexstr(Plt.Address) +
1213                       " references an invalid symbol",
1214                   Obj.getFileName());
1215   }
1216 }
1217 
1218 // Normally the disassembly output will skip blocks of zeroes. This function
1219 // returns the number of zero bytes that can be skipped when dumping the
1220 // disassembly of the instructions in Buf.
1221 static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) {
1222   // Find the number of leading zeroes.
1223   size_t N = 0;
1224   while (N < Buf.size() && !Buf[N])
1225     ++N;
1226 
1227   // We may want to skip blocks of zero bytes, but unless we see
1228   // at least 8 of them in a row.
1229   if (N < 8)
1230     return 0;
1231 
1232   // We skip zeroes in multiples of 4 because do not want to truncate an
1233   // instruction if it starts with a zero byte.
1234   return N & ~0x3;
1235 }
1236 
1237 // Returns a map from sections to their relocations.
1238 static std::map<SectionRef, std::vector<RelocationRef>>
1239 getRelocsMap(object::ObjectFile const &Obj) {
1240   std::map<SectionRef, std::vector<RelocationRef>> Ret;
1241   uint64_t I = (uint64_t)-1;
1242   for (SectionRef Sec : Obj.sections()) {
1243     ++I;
1244     Expected<section_iterator> RelocatedOrErr = Sec.getRelocatedSection();
1245     if (!RelocatedOrErr)
1246       reportError(Obj.getFileName(),
1247                   "section (" + Twine(I) +
1248                       "): failed to get a relocated section: " +
1249                       toString(RelocatedOrErr.takeError()));
1250 
1251     section_iterator Relocated = *RelocatedOrErr;
1252     if (Relocated == Obj.section_end() || !checkSectionFilter(*Relocated).Keep)
1253       continue;
1254     std::vector<RelocationRef> &V = Ret[*Relocated];
1255     append_range(V, Sec.relocations());
1256     // Sort relocations by address.
1257     llvm::stable_sort(V, isRelocAddressLess);
1258   }
1259   return Ret;
1260 }
1261 
1262 // Used for --adjust-vma to check if address should be adjusted by the
1263 // specified value for a given section.
1264 // For ELF we do not adjust non-allocatable sections like debug ones,
1265 // because they are not loadable.
1266 // TODO: implement for other file formats.
1267 static bool shouldAdjustVA(const SectionRef &Section) {
1268   const ObjectFile *Obj = Section.getObject();
1269   if (Obj->isELF())
1270     return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
1271   return false;
1272 }
1273 
1274 
1275 typedef std::pair<uint64_t, char> MappingSymbolPair;
1276 static char getMappingSymbolKind(ArrayRef<MappingSymbolPair> MappingSymbols,
1277                                  uint64_t Address) {
1278   auto It =
1279       partition_point(MappingSymbols, [Address](const MappingSymbolPair &Val) {
1280         return Val.first <= Address;
1281       });
1282   // Return zero for any address before the first mapping symbol; this means
1283   // we should use the default disassembly mode, depending on the target.
1284   if (It == MappingSymbols.begin())
1285     return '\x00';
1286   return (It - 1)->second;
1287 }
1288 
1289 static uint64_t dumpARMELFData(uint64_t SectionAddr, uint64_t Index,
1290                                uint64_t End, const ObjectFile &Obj,
1291                                ArrayRef<uint8_t> Bytes,
1292                                ArrayRef<MappingSymbolPair> MappingSymbols,
1293                                const MCSubtargetInfo &STI, raw_ostream &OS) {
1294   llvm::endianness Endian =
1295       Obj.isLittleEndian() ? llvm::endianness::little : llvm::endianness::big;
1296   size_t Start = OS.tell();
1297   OS << format("%8" PRIx64 ": ", SectionAddr + Index);
1298   if (Index + 4 <= End) {
1299     dumpBytes(Bytes.slice(Index, 4), OS);
1300     AlignToInstStartColumn(Start, STI, OS);
1301     OS << "\t.word\t"
1302            << format_hex(support::endian::read32(Bytes.data() + Index, Endian),
1303                          10);
1304     return 4;
1305   }
1306   if (Index + 2 <= End) {
1307     dumpBytes(Bytes.slice(Index, 2), OS);
1308     AlignToInstStartColumn(Start, STI, OS);
1309     OS << "\t.short\t"
1310        << format_hex(support::endian::read16(Bytes.data() + Index, Endian), 6);
1311     return 2;
1312   }
1313   dumpBytes(Bytes.slice(Index, 1), OS);
1314   AlignToInstStartColumn(Start, STI, OS);
1315   OS << "\t.byte\t" << format_hex(Bytes[Index], 4);
1316   return 1;
1317 }
1318 
1319 static void dumpELFData(uint64_t SectionAddr, uint64_t Index, uint64_t End,
1320                         ArrayRef<uint8_t> Bytes) {
1321   // print out data up to 8 bytes at a time in hex and ascii
1322   uint8_t AsciiData[9] = {'\0'};
1323   uint8_t Byte;
1324   int NumBytes = 0;
1325 
1326   for (; Index < End; ++Index) {
1327     if (NumBytes == 0)
1328       outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1329     Byte = Bytes.slice(Index)[0];
1330     outs() << format(" %02x", Byte);
1331     AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
1332 
1333     uint8_t IndentOffset = 0;
1334     NumBytes++;
1335     if (Index == End - 1 || NumBytes > 8) {
1336       // Indent the space for less than 8 bytes data.
1337       // 2 spaces for byte and one for space between bytes
1338       IndentOffset = 3 * (8 - NumBytes);
1339       for (int Excess = NumBytes; Excess < 8; Excess++)
1340         AsciiData[Excess] = '\0';
1341       NumBytes = 8;
1342     }
1343     if (NumBytes == 8) {
1344       AsciiData[8] = '\0';
1345       outs() << std::string(IndentOffset, ' ') << "         ";
1346       outs() << reinterpret_cast<char *>(AsciiData);
1347       outs() << '\n';
1348       NumBytes = 0;
1349     }
1350   }
1351 }
1352 
1353 SymbolInfoTy objdump::createSymbolInfo(const ObjectFile &Obj,
1354                                        const SymbolRef &Symbol,
1355                                        bool IsMappingSymbol) {
1356   const StringRef FileName = Obj.getFileName();
1357   const uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
1358   const StringRef Name = unwrapOrError(Symbol.getName(), FileName);
1359 
1360   if (Obj.isXCOFF() && (SymbolDescription || TracebackTable)) {
1361     const auto &XCOFFObj = cast<XCOFFObjectFile>(Obj);
1362     DataRefImpl SymbolDRI = Symbol.getRawDataRefImpl();
1363 
1364     const uint32_t SymbolIndex = XCOFFObj.getSymbolIndex(SymbolDRI.p);
1365     std::optional<XCOFF::StorageMappingClass> Smc =
1366         getXCOFFSymbolCsectSMC(XCOFFObj, Symbol);
1367     return SymbolInfoTy(Smc, Addr, Name, SymbolIndex,
1368                         isLabel(XCOFFObj, Symbol));
1369   } else if (Obj.isXCOFF()) {
1370     const SymbolRef::Type SymType = unwrapOrError(Symbol.getType(), FileName);
1371     return SymbolInfoTy(Addr, Name, SymType, /*IsMappingSymbol=*/false,
1372                         /*IsXCOFF=*/true);
1373   } else if (Obj.isWasm()) {
1374     uint8_t SymType =
1375         cast<WasmObjectFile>(&Obj)->getWasmSymbol(Symbol).Info.Kind;
1376     return SymbolInfoTy(Addr, Name, SymType, false);
1377   } else {
1378     uint8_t Type =
1379         Obj.isELF() ? getElfSymbolType(Obj, Symbol) : (uint8_t)ELF::STT_NOTYPE;
1380     return SymbolInfoTy(Addr, Name, Type, IsMappingSymbol);
1381   }
1382 }
1383 
1384 static SymbolInfoTy createDummySymbolInfo(const ObjectFile &Obj,
1385                                           const uint64_t Addr, StringRef &Name,
1386                                           uint8_t Type) {
1387   if (Obj.isXCOFF() && (SymbolDescription || TracebackTable))
1388     return SymbolInfoTy(std::nullopt, Addr, Name, std::nullopt, false);
1389   if (Obj.isWasm())
1390     return SymbolInfoTy(Addr, Name, wasm::WASM_SYMBOL_TYPE_SECTION);
1391   return SymbolInfoTy(Addr, Name, Type);
1392 }
1393 
1394 static void collectBBAddrMapLabels(
1395     const BBAddrMapInfo &FullAddrMap, uint64_t SectionAddr, uint64_t Start,
1396     uint64_t End,
1397     std::unordered_map<uint64_t, std::vector<BBAddrMapLabel>> &Labels) {
1398   if (FullAddrMap.empty())
1399     return;
1400   Labels.clear();
1401   uint64_t StartAddress = SectionAddr + Start;
1402   uint64_t EndAddress = SectionAddr + End;
1403   const BBAddrMapFunctionEntry *FunctionMap =
1404       FullAddrMap.getEntryForAddress(StartAddress);
1405   if (!FunctionMap)
1406     return;
1407   std::optional<size_t> BBRangeIndex =
1408       FunctionMap->getAddrMap().getBBRangeIndexForBaseAddress(StartAddress);
1409   if (!BBRangeIndex)
1410     return;
1411   size_t NumBBEntriesBeforeRange = 0;
1412   for (size_t I = 0; I < *BBRangeIndex; ++I)
1413     NumBBEntriesBeforeRange +=
1414         FunctionMap->getAddrMap().BBRanges[I].BBEntries.size();
1415   const auto &BBRange = FunctionMap->getAddrMap().BBRanges[*BBRangeIndex];
1416   for (size_t I = 0; I < BBRange.BBEntries.size(); ++I) {
1417     const BBAddrMap::BBEntry &BBEntry = BBRange.BBEntries[I];
1418     uint64_t BBAddress = BBEntry.Offset + BBRange.BaseAddress;
1419     if (BBAddress >= EndAddress)
1420       continue;
1421 
1422     std::string LabelString = ("BB" + Twine(BBEntry.ID)).str();
1423     Labels[BBAddress].push_back(
1424         {LabelString, FunctionMap->constructPGOLabelString(
1425                           NumBBEntriesBeforeRange + I, PrettyPGOAnalysisMap)});
1426   }
1427 }
1428 
1429 static void
1430 collectLocalBranchTargets(ArrayRef<uint8_t> Bytes, MCInstrAnalysis *MIA,
1431                           MCDisassembler *DisAsm, MCInstPrinter *IP,
1432                           const MCSubtargetInfo *STI, uint64_t SectionAddr,
1433                           uint64_t Start, uint64_t End,
1434                           std::unordered_map<uint64_t, std::string> &Labels) {
1435   // So far only supports PowerPC and X86.
1436   const bool isPPC = STI->getTargetTriple().isPPC();
1437   if (!isPPC && !STI->getTargetTriple().isX86())
1438     return;
1439 
1440   if (MIA)
1441     MIA->resetState();
1442 
1443   Labels.clear();
1444   unsigned LabelCount = 0;
1445   Start += SectionAddr;
1446   End += SectionAddr;
1447   const bool isXCOFF = STI->getTargetTriple().isOSBinFormatXCOFF();
1448   for (uint64_t Index = Start; Index < End;) {
1449     // Disassemble a real instruction and record function-local branch labels.
1450     MCInst Inst;
1451     uint64_t Size;
1452     ArrayRef<uint8_t> ThisBytes = Bytes.slice(Index - SectionAddr);
1453     bool Disassembled =
1454         DisAsm->getInstruction(Inst, Size, ThisBytes, Index, nulls());
1455     if (Size == 0)
1456       Size = std::min<uint64_t>(ThisBytes.size(),
1457                                 DisAsm->suggestBytesToSkip(ThisBytes, Index));
1458 
1459     if (MIA) {
1460       if (Disassembled) {
1461         uint64_t Target;
1462         bool TargetKnown = MIA->evaluateBranch(Inst, Index, Size, Target);
1463         if (TargetKnown && (Target >= Start && Target < End) &&
1464             !Labels.count(Target)) {
1465           // On PowerPC and AIX, a function call is encoded as a branch to 0.
1466           // On other PowerPC platforms (ELF), a function call is encoded as
1467           // a branch to self. Do not add a label for these cases.
1468           if (!(isPPC &&
1469                 ((Target == 0 && isXCOFF) || (Target == Index && !isXCOFF))))
1470             Labels[Target] = ("L" + Twine(LabelCount++)).str();
1471         }
1472         MIA->updateState(Inst, Index);
1473       } else
1474         MIA->resetState();
1475     }
1476     Index += Size;
1477   }
1478 }
1479 
1480 // Create an MCSymbolizer for the target and add it to the MCDisassembler.
1481 // This is currently only used on AMDGPU, and assumes the format of the
1482 // void * argument passed to AMDGPU's createMCSymbolizer.
1483 static void addSymbolizer(
1484     MCContext &Ctx, const Target *Target, StringRef TripleName,
1485     MCDisassembler *DisAsm, uint64_t SectionAddr, ArrayRef<uint8_t> Bytes,
1486     SectionSymbolsTy &Symbols,
1487     std::vector<std::unique_ptr<std::string>> &SynthesizedLabelNames) {
1488 
1489   std::unique_ptr<MCRelocationInfo> RelInfo(
1490       Target->createMCRelocationInfo(TripleName, Ctx));
1491   if (!RelInfo)
1492     return;
1493   std::unique_ptr<MCSymbolizer> Symbolizer(Target->createMCSymbolizer(
1494       TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1495   MCSymbolizer *SymbolizerPtr = &*Symbolizer;
1496   DisAsm->setSymbolizer(std::move(Symbolizer));
1497 
1498   if (!SymbolizeOperands)
1499     return;
1500 
1501   // Synthesize labels referenced by branch instructions by
1502   // disassembling, discarding the output, and collecting the referenced
1503   // addresses from the symbolizer.
1504   for (size_t Index = 0; Index != Bytes.size();) {
1505     MCInst Inst;
1506     uint64_t Size;
1507     ArrayRef<uint8_t> ThisBytes = Bytes.slice(Index);
1508     const uint64_t ThisAddr = SectionAddr + Index;
1509     DisAsm->getInstruction(Inst, Size, ThisBytes, ThisAddr, nulls());
1510     if (Size == 0)
1511       Size = std::min<uint64_t>(ThisBytes.size(),
1512                                 DisAsm->suggestBytesToSkip(ThisBytes, Index));
1513     Index += Size;
1514   }
1515   ArrayRef<uint64_t> LabelAddrsRef = SymbolizerPtr->getReferencedAddresses();
1516   // Copy and sort to remove duplicates.
1517   std::vector<uint64_t> LabelAddrs;
1518   LabelAddrs.insert(LabelAddrs.end(), LabelAddrsRef.begin(),
1519                     LabelAddrsRef.end());
1520   llvm::sort(LabelAddrs);
1521   LabelAddrs.resize(std::unique(LabelAddrs.begin(), LabelAddrs.end()) -
1522                     LabelAddrs.begin());
1523   // Add the labels.
1524   for (unsigned LabelNum = 0; LabelNum != LabelAddrs.size(); ++LabelNum) {
1525     auto Name = std::make_unique<std::string>();
1526     *Name = (Twine("L") + Twine(LabelNum)).str();
1527     SynthesizedLabelNames.push_back(std::move(Name));
1528     Symbols.push_back(SymbolInfoTy(
1529         LabelAddrs[LabelNum], *SynthesizedLabelNames.back(), ELF::STT_NOTYPE));
1530   }
1531   llvm::stable_sort(Symbols);
1532   // Recreate the symbolizer with the new symbols list.
1533   RelInfo.reset(Target->createMCRelocationInfo(TripleName, Ctx));
1534   Symbolizer.reset(Target->createMCSymbolizer(
1535       TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1536   DisAsm->setSymbolizer(std::move(Symbolizer));
1537 }
1538 
1539 static StringRef getSegmentName(const MachOObjectFile *MachO,
1540                                 const SectionRef &Section) {
1541   if (MachO) {
1542     DataRefImpl DR = Section.getRawDataRefImpl();
1543     StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1544     return SegmentName;
1545   }
1546   return "";
1547 }
1548 
1549 static void emitPostInstructionInfo(formatted_raw_ostream &FOS,
1550                                     const MCAsmInfo &MAI,
1551                                     const MCSubtargetInfo &STI,
1552                                     StringRef Comments,
1553                                     LiveVariablePrinter &LVP) {
1554   do {
1555     if (!Comments.empty()) {
1556       // Emit a line of comments.
1557       StringRef Comment;
1558       std::tie(Comment, Comments) = Comments.split('\n');
1559       // MAI.getCommentColumn() assumes that instructions are printed at the
1560       // position of 8, while getInstStartColumn() returns the actual position.
1561       unsigned CommentColumn =
1562           MAI.getCommentColumn() - 8 + getInstStartColumn(STI);
1563       FOS.PadToColumn(CommentColumn);
1564       FOS << MAI.getCommentString() << ' ' << Comment;
1565     }
1566     LVP.printAfterInst(FOS);
1567     FOS << '\n';
1568   } while (!Comments.empty());
1569   FOS.flush();
1570 }
1571 
1572 static void createFakeELFSections(ObjectFile &Obj) {
1573   assert(Obj.isELF());
1574   if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(&Obj))
1575     Elf32LEObj->createFakeSections();
1576   else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(&Obj))
1577     Elf64LEObj->createFakeSections();
1578   else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(&Obj))
1579     Elf32BEObj->createFakeSections();
1580   else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(&Obj))
1581     Elf64BEObj->createFakeSections();
1582   else
1583     llvm_unreachable("Unsupported binary format");
1584 }
1585 
1586 // Tries to fetch a more complete version of the given object file using its
1587 // Build ID. Returns std::nullopt if nothing was found.
1588 static std::optional<OwningBinary<Binary>>
1589 fetchBinaryByBuildID(const ObjectFile &Obj) {
1590   object::BuildIDRef BuildID = getBuildID(&Obj);
1591   if (BuildID.empty())
1592     return std::nullopt;
1593   std::optional<std::string> Path = BIDFetcher->fetch(BuildID);
1594   if (!Path)
1595     return std::nullopt;
1596   Expected<OwningBinary<Binary>> DebugBinary = createBinary(*Path);
1597   if (!DebugBinary) {
1598     reportWarning(toString(DebugBinary.takeError()), *Path);
1599     return std::nullopt;
1600   }
1601   return std::move(*DebugBinary);
1602 }
1603 
1604 static void
1605 disassembleObject(ObjectFile &Obj, const ObjectFile &DbgObj,
1606                   DisassemblerTarget &PrimaryTarget,
1607                   std::optional<DisassemblerTarget> &SecondaryTarget,
1608                   SourcePrinter &SP, bool InlineRelocs) {
1609   DisassemblerTarget *DT = &PrimaryTarget;
1610   bool PrimaryIsThumb = false;
1611   SmallVector<std::pair<uint64_t, uint64_t>, 0> CHPECodeMap;
1612 
1613   if (SecondaryTarget) {
1614     if (isArmElf(Obj)) {
1615       PrimaryIsThumb =
1616           PrimaryTarget.SubtargetInfo->checkFeatures("+thumb-mode");
1617     } else if (const auto *COFFObj = dyn_cast<COFFObjectFile>(&Obj)) {
1618       const chpe_metadata *CHPEMetadata = COFFObj->getCHPEMetadata();
1619       if (CHPEMetadata && CHPEMetadata->CodeMapCount) {
1620         uintptr_t CodeMapInt;
1621         cantFail(COFFObj->getRvaPtr(CHPEMetadata->CodeMap, CodeMapInt));
1622         auto CodeMap = reinterpret_cast<const chpe_range_entry *>(CodeMapInt);
1623 
1624         for (uint32_t i = 0; i < CHPEMetadata->CodeMapCount; ++i) {
1625           if (CodeMap[i].getType() == chpe_range_type::Amd64 &&
1626               CodeMap[i].Length) {
1627             // Store x86_64 CHPE code ranges.
1628             uint64_t Start = CodeMap[i].getStart() + COFFObj->getImageBase();
1629             CHPECodeMap.emplace_back(Start, Start + CodeMap[i].Length);
1630           }
1631         }
1632         llvm::sort(CHPECodeMap);
1633       }
1634     }
1635   }
1636 
1637   std::map<SectionRef, std::vector<RelocationRef>> RelocMap;
1638   if (InlineRelocs || Obj.isXCOFF())
1639     RelocMap = getRelocsMap(Obj);
1640   bool Is64Bits = Obj.getBytesInAddress() > 4;
1641 
1642   // Create a mapping from virtual address to symbol name.  This is used to
1643   // pretty print the symbols while disassembling.
1644   std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1645   std::map<SectionRef, SmallVector<MappingSymbolPair, 0>> AllMappingSymbols;
1646   SectionSymbolsTy AbsoluteSymbols;
1647   const StringRef FileName = Obj.getFileName();
1648   const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(&Obj);
1649   for (const SymbolRef &Symbol : Obj.symbols()) {
1650     Expected<StringRef> NameOrErr = Symbol.getName();
1651     if (!NameOrErr) {
1652       reportWarning(toString(NameOrErr.takeError()), FileName);
1653       continue;
1654     }
1655     if (NameOrErr->empty() && !(Obj.isXCOFF() && SymbolDescription))
1656       continue;
1657 
1658     if (Obj.isELF() &&
1659         (cantFail(Symbol.getFlags()) & SymbolRef::SF_FormatSpecific)) {
1660       // Symbol is intended not to be displayed by default (STT_FILE,
1661       // STT_SECTION, or a mapping symbol). Ignore STT_SECTION symbols. We will
1662       // synthesize a section symbol if no symbol is defined at offset 0.
1663       //
1664       // For a mapping symbol, store it within both AllSymbols and
1665       // AllMappingSymbols. If --show-all-symbols is unspecified, its label will
1666       // not be printed in disassembly listing.
1667       if (getElfSymbolType(Obj, Symbol) != ELF::STT_SECTION &&
1668           hasMappingSymbols(Obj)) {
1669         section_iterator SecI = unwrapOrError(Symbol.getSection(), FileName);
1670         if (SecI != Obj.section_end()) {
1671           uint64_t SectionAddr = SecI->getAddress();
1672           uint64_t Address = cantFail(Symbol.getAddress());
1673           StringRef Name = *NameOrErr;
1674           if (Name.consume_front("$") && Name.size() &&
1675               strchr("adtx", Name[0])) {
1676             AllMappingSymbols[*SecI].emplace_back(Address - SectionAddr,
1677                                                   Name[0]);
1678             AllSymbols[*SecI].push_back(
1679                 createSymbolInfo(Obj, Symbol, /*MappingSymbol=*/true));
1680           }
1681         }
1682       }
1683       continue;
1684     }
1685 
1686     if (MachO) {
1687       // __mh_(execute|dylib|dylinker|bundle|preload|object)_header are special
1688       // symbols that support MachO header introspection. They do not bind to
1689       // code locations and are irrelevant for disassembly.
1690       if (NameOrErr->starts_with("__mh_") && NameOrErr->ends_with("_header"))
1691         continue;
1692       // Don't ask a Mach-O STAB symbol for its section unless you know that
1693       // STAB symbol's section field refers to a valid section index. Otherwise
1694       // the symbol may error trying to load a section that does not exist.
1695       DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
1696       uint8_t NType = (MachO->is64Bit() ?
1697                        MachO->getSymbol64TableEntry(SymDRI).n_type:
1698                        MachO->getSymbolTableEntry(SymDRI).n_type);
1699       if (NType & MachO::N_STAB)
1700         continue;
1701     }
1702 
1703     section_iterator SecI = unwrapOrError(Symbol.getSection(), FileName);
1704     if (SecI != Obj.section_end())
1705       AllSymbols[*SecI].push_back(createSymbolInfo(Obj, Symbol));
1706     else
1707       AbsoluteSymbols.push_back(createSymbolInfo(Obj, Symbol));
1708   }
1709 
1710   if (AllSymbols.empty() && Obj.isELF())
1711     addDynamicElfSymbols(cast<ELFObjectFileBase>(Obj), AllSymbols);
1712 
1713   if (Obj.isWasm())
1714     addMissingWasmCodeSymbols(cast<WasmObjectFile>(Obj), AllSymbols);
1715 
1716   if (Obj.isELF() && Obj.sections().empty())
1717     createFakeELFSections(Obj);
1718 
1719   BumpPtrAllocator A;
1720   StringSaver Saver(A);
1721   addPltEntries(Obj, AllSymbols, Saver);
1722 
1723   // Create a mapping from virtual address to section. An empty section can
1724   // cause more than one section at the same address. Sort such sections to be
1725   // before same-addressed non-empty sections so that symbol lookups prefer the
1726   // non-empty section.
1727   std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1728   for (SectionRef Sec : Obj.sections())
1729     SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1730   llvm::stable_sort(SectionAddresses, [](const auto &LHS, const auto &RHS) {
1731     if (LHS.first != RHS.first)
1732       return LHS.first < RHS.first;
1733     return LHS.second.getSize() < RHS.second.getSize();
1734   });
1735 
1736   // Linked executables (.exe and .dll files) typically don't include a real
1737   // symbol table but they might contain an export table.
1738   if (const auto *COFFObj = dyn_cast<COFFObjectFile>(&Obj)) {
1739     for (const auto &ExportEntry : COFFObj->export_directories()) {
1740       StringRef Name;
1741       if (Error E = ExportEntry.getSymbolName(Name))
1742         reportError(std::move(E), Obj.getFileName());
1743       if (Name.empty())
1744         continue;
1745 
1746       uint32_t RVA;
1747       if (Error E = ExportEntry.getExportRVA(RVA))
1748         reportError(std::move(E), Obj.getFileName());
1749 
1750       uint64_t VA = COFFObj->getImageBase() + RVA;
1751       auto Sec = partition_point(
1752           SectionAddresses, [VA](const std::pair<uint64_t, SectionRef> &O) {
1753             return O.first <= VA;
1754           });
1755       if (Sec != SectionAddresses.begin()) {
1756         --Sec;
1757         AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
1758       } else
1759         AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
1760     }
1761   }
1762 
1763   // Sort all the symbols, this allows us to use a simple binary search to find
1764   // Multiple symbols can have the same address. Use a stable sort to stabilize
1765   // the output.
1766   StringSet<> FoundDisasmSymbolSet;
1767   for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1768     llvm::stable_sort(SecSyms.second);
1769   llvm::stable_sort(AbsoluteSymbols);
1770 
1771   std::unique_ptr<DWARFContext> DICtx;
1772   LiveVariablePrinter LVP(*DT->Context->getRegisterInfo(), *DT->SubtargetInfo);
1773 
1774   if (DbgVariables != DVDisabled) {
1775     DICtx = DWARFContext::create(DbgObj);
1776     for (const std::unique_ptr<DWARFUnit> &CU : DICtx->compile_units())
1777       LVP.addCompileUnit(CU->getUnitDIE(false));
1778   }
1779 
1780   LLVM_DEBUG(LVP.dump());
1781 
1782   BBAddrMapInfo FullAddrMap;
1783   auto ReadBBAddrMap = [&](std::optional<unsigned> SectionIndex =
1784                                std::nullopt) {
1785     FullAddrMap.clear();
1786     if (const auto *Elf = dyn_cast<ELFObjectFileBase>(&Obj)) {
1787       std::vector<PGOAnalysisMap> PGOAnalyses;
1788       auto BBAddrMapsOrErr = Elf->readBBAddrMap(SectionIndex, &PGOAnalyses);
1789       if (!BBAddrMapsOrErr) {
1790         reportWarning(toString(BBAddrMapsOrErr.takeError()), Obj.getFileName());
1791         return;
1792       }
1793       for (auto &&[FunctionBBAddrMap, FunctionPGOAnalysis] :
1794            zip_equal(*std::move(BBAddrMapsOrErr), std::move(PGOAnalyses))) {
1795         FullAddrMap.AddFunctionEntry(std::move(FunctionBBAddrMap),
1796                                      std::move(FunctionPGOAnalysis));
1797       }
1798     }
1799   };
1800 
1801   // For non-relocatable objects, Read all LLVM_BB_ADDR_MAP sections into a
1802   // single mapping, since they don't have any conflicts.
1803   if (SymbolizeOperands && !Obj.isRelocatableObject())
1804     ReadBBAddrMap();
1805 
1806   std::optional<llvm::BTFParser> BTF;
1807   if (InlineRelocs && BTFParser::hasBTFSections(Obj)) {
1808     BTF.emplace();
1809     BTFParser::ParseOptions Opts = {};
1810     Opts.LoadTypes = true;
1811     Opts.LoadRelocs = true;
1812     if (Error E = BTF->parse(Obj, Opts))
1813       WithColor::defaultErrorHandler(std::move(E));
1814   }
1815 
1816   for (const SectionRef &Section : ToolSectionFilter(Obj)) {
1817     if (FilterSections.empty() && !DisassembleAll &&
1818         (!Section.isText() || Section.isVirtual()))
1819       continue;
1820 
1821     uint64_t SectionAddr = Section.getAddress();
1822     uint64_t SectSize = Section.getSize();
1823     if (!SectSize)
1824       continue;
1825 
1826     // For relocatable object files, read the LLVM_BB_ADDR_MAP section
1827     // corresponding to this section, if present.
1828     if (SymbolizeOperands && Obj.isRelocatableObject())
1829       ReadBBAddrMap(Section.getIndex());
1830 
1831     // Get the list of all the symbols in this section.
1832     SectionSymbolsTy &Symbols = AllSymbols[Section];
1833     auto &MappingSymbols = AllMappingSymbols[Section];
1834     llvm::sort(MappingSymbols);
1835 
1836     ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(
1837         unwrapOrError(Section.getContents(), Obj.getFileName()));
1838 
1839     std::vector<std::unique_ptr<std::string>> SynthesizedLabelNames;
1840     if (Obj.isELF() && Obj.getArch() == Triple::amdgcn) {
1841       // AMDGPU disassembler uses symbolizer for printing labels
1842       addSymbolizer(*DT->Context, DT->TheTarget, TripleName, DT->DisAsm.get(),
1843                     SectionAddr, Bytes, Symbols, SynthesizedLabelNames);
1844     }
1845 
1846     StringRef SegmentName = getSegmentName(MachO, Section);
1847     StringRef SectionName = unwrapOrError(Section.getName(), Obj.getFileName());
1848     // If the section has no symbol at the start, just insert a dummy one.
1849     // Without --show-all-symbols, also insert one if all symbols at the start
1850     // are mapping symbols.
1851     bool CreateDummy = Symbols.empty();
1852     if (!CreateDummy) {
1853       CreateDummy = true;
1854       for (auto &Sym : Symbols) {
1855         if (Sym.Addr != SectionAddr)
1856           break;
1857         if (!Sym.IsMappingSymbol || ShowAllSymbols)
1858           CreateDummy = false;
1859       }
1860     }
1861     if (CreateDummy) {
1862       SymbolInfoTy Sym = createDummySymbolInfo(
1863           Obj, SectionAddr, SectionName,
1864           Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT);
1865       if (Obj.isXCOFF())
1866         Symbols.insert(Symbols.begin(), Sym);
1867       else
1868         Symbols.insert(llvm::lower_bound(Symbols, Sym), Sym);
1869     }
1870 
1871     SmallString<40> Comments;
1872     raw_svector_ostream CommentStream(Comments);
1873 
1874     uint64_t VMAAdjustment = 0;
1875     if (shouldAdjustVA(Section))
1876       VMAAdjustment = AdjustVMA;
1877 
1878     // In executable and shared objects, r_offset holds a virtual address.
1879     // Subtract SectionAddr from the r_offset field of a relocation to get
1880     // the section offset.
1881     uint64_t RelAdjustment = Obj.isRelocatableObject() ? 0 : SectionAddr;
1882     uint64_t Size;
1883     uint64_t Index;
1884     bool PrintedSection = false;
1885     std::vector<RelocationRef> Rels = RelocMap[Section];
1886     std::vector<RelocationRef>::const_iterator RelCur = Rels.begin();
1887     std::vector<RelocationRef>::const_iterator RelEnd = Rels.end();
1888 
1889     // Loop over each chunk of code between two points where at least
1890     // one symbol is defined.
1891     for (size_t SI = 0, SE = Symbols.size(); SI != SE;) {
1892       // Advance SI past all the symbols starting at the same address,
1893       // and make an ArrayRef of them.
1894       unsigned FirstSI = SI;
1895       uint64_t Start = Symbols[SI].Addr;
1896       ArrayRef<SymbolInfoTy> SymbolsHere;
1897       while (SI != SE && Symbols[SI].Addr == Start)
1898         ++SI;
1899       SymbolsHere = ArrayRef<SymbolInfoTy>(&Symbols[FirstSI], SI - FirstSI);
1900 
1901       // Get the demangled names of all those symbols. We end up with a vector
1902       // of StringRef that holds the names we're going to use, and a vector of
1903       // std::string that stores the new strings returned by demangle(), if
1904       // any. If we don't call demangle() then that vector can stay empty.
1905       std::vector<StringRef> SymNamesHere;
1906       std::vector<std::string> DemangledSymNamesHere;
1907       if (Demangle) {
1908         // Fetch the demangled names and store them locally.
1909         for (const SymbolInfoTy &Symbol : SymbolsHere)
1910           DemangledSymNamesHere.push_back(demangle(Symbol.Name));
1911         // Now we've finished modifying that vector, it's safe to make
1912         // a vector of StringRefs pointing into it.
1913         SymNamesHere.insert(SymNamesHere.begin(), DemangledSymNamesHere.begin(),
1914                             DemangledSymNamesHere.end());
1915       } else {
1916         for (const SymbolInfoTy &Symbol : SymbolsHere)
1917           SymNamesHere.push_back(Symbol.Name);
1918       }
1919 
1920       // Distinguish ELF data from code symbols, which will be used later on to
1921       // decide whether to 'disassemble' this chunk as a data declaration via
1922       // dumpELFData(), or whether to treat it as code.
1923       //
1924       // If data _and_ code symbols are defined at the same address, the code
1925       // takes priority, on the grounds that disassembling code is our main
1926       // purpose here, and it would be a worse failure to _not_ interpret
1927       // something that _was_ meaningful as code than vice versa.
1928       //
1929       // Any ELF symbol type that is not clearly data will be regarded as code.
1930       // In particular, one of the uses of STT_NOTYPE is for branch targets
1931       // inside functions, for which STT_FUNC would be inaccurate.
1932       //
1933       // So here, we spot whether there's any non-data symbol present at all,
1934       // and only set the DisassembleAsELFData flag if there isn't. Also, we use
1935       // this distinction to inform the decision of which symbol to print at
1936       // the head of the section, so that if we're printing code, we print a
1937       // code-related symbol name to go with it.
1938       bool DisassembleAsELFData = false;
1939       size_t DisplaySymIndex = SymbolsHere.size() - 1;
1940       if (Obj.isELF() && !DisassembleAll && Section.isText()) {
1941         DisassembleAsELFData = true; // unless we find a code symbol below
1942 
1943         for (size_t i = 0; i < SymbolsHere.size(); ++i) {
1944           uint8_t SymTy = SymbolsHere[i].Type;
1945           if (SymTy != ELF::STT_OBJECT && SymTy != ELF::STT_COMMON) {
1946             DisassembleAsELFData = false;
1947             DisplaySymIndex = i;
1948           }
1949         }
1950       }
1951 
1952       // Decide which symbol(s) from this collection we're going to print.
1953       std::vector<bool> SymsToPrint(SymbolsHere.size(), false);
1954       // If the user has given the --disassemble-symbols option, then we must
1955       // display every symbol in that set, and no others.
1956       if (!DisasmSymbolSet.empty()) {
1957         bool FoundAny = false;
1958         for (size_t i = 0; i < SymbolsHere.size(); ++i) {
1959           if (DisasmSymbolSet.count(SymNamesHere[i])) {
1960             SymsToPrint[i] = true;
1961             FoundAny = true;
1962           }
1963         }
1964 
1965         // And if none of the symbols here is one that the user asked for, skip
1966         // disassembling this entire chunk of code.
1967         if (!FoundAny)
1968           continue;
1969       } else if (!SymbolsHere[DisplaySymIndex].IsMappingSymbol) {
1970         // Otherwise, print whichever symbol at this location is last in the
1971         // Symbols array, because that array is pre-sorted in a way intended to
1972         // correlate with priority of which symbol to display.
1973         SymsToPrint[DisplaySymIndex] = true;
1974       }
1975 
1976       // Now that we know we're disassembling this section, override the choice
1977       // of which symbols to display by printing _all_ of them at this address
1978       // if the user asked for all symbols.
1979       //
1980       // That way, '--show-all-symbols --disassemble-symbol=foo' will print
1981       // only the chunk of code headed by 'foo', but also show any other
1982       // symbols defined at that address, such as aliases for 'foo', or the ARM
1983       // mapping symbol preceding its code.
1984       if (ShowAllSymbols) {
1985         for (size_t i = 0; i < SymbolsHere.size(); ++i)
1986           SymsToPrint[i] = true;
1987       }
1988 
1989       if (Start < SectionAddr || StopAddress <= Start)
1990         continue;
1991 
1992       for (size_t i = 0; i < SymbolsHere.size(); ++i)
1993         FoundDisasmSymbolSet.insert(SymNamesHere[i]);
1994 
1995       // The end is the section end, the beginning of the next symbol, or
1996       // --stop-address.
1997       uint64_t End = std::min<uint64_t>(SectionAddr + SectSize, StopAddress);
1998       if (SI < SE)
1999         End = std::min(End, Symbols[SI].Addr);
2000       if (Start >= End || End <= StartAddress)
2001         continue;
2002       Start -= SectionAddr;
2003       End -= SectionAddr;
2004 
2005       if (!PrintedSection) {
2006         PrintedSection = true;
2007         outs() << "\nDisassembly of section ";
2008         if (!SegmentName.empty())
2009           outs() << SegmentName << ",";
2010         outs() << SectionName << ":\n";
2011       }
2012 
2013       bool PrintedLabel = false;
2014       for (size_t i = 0; i < SymbolsHere.size(); ++i) {
2015         if (!SymsToPrint[i])
2016           continue;
2017 
2018         const SymbolInfoTy &Symbol = SymbolsHere[i];
2019         const StringRef SymbolName = SymNamesHere[i];
2020 
2021         if (!PrintedLabel) {
2022           outs() << '\n';
2023           PrintedLabel = true;
2024         }
2025         if (LeadingAddr)
2026           outs() << format(Is64Bits ? "%016" PRIx64 " " : "%08" PRIx64 " ",
2027                            SectionAddr + Start + VMAAdjustment);
2028         if (Obj.isXCOFF() && SymbolDescription) {
2029           outs() << getXCOFFSymbolDescription(Symbol, SymbolName) << ":\n";
2030         } else
2031           outs() << '<' << SymbolName << ">:\n";
2032       }
2033 
2034       // Don't print raw contents of a virtual section. A virtual section
2035       // doesn't have any contents in the file.
2036       if (Section.isVirtual()) {
2037         outs() << "...\n";
2038         continue;
2039       }
2040 
2041       // See if any of the symbols defined at this location triggers target-
2042       // specific disassembly behavior, e.g. of special descriptors or function
2043       // prelude information.
2044       //
2045       // We stop this loop at the first symbol that triggers some kind of
2046       // interesting behavior (if any), on the assumption that if two symbols
2047       // defined at the same address trigger two conflicting symbol handlers,
2048       // the object file is probably confused anyway, and it would make even
2049       // less sense to present the output of _both_ handlers, because that
2050       // would describe the same data twice.
2051       for (size_t SHI = 0; SHI < SymbolsHere.size(); ++SHI) {
2052         SymbolInfoTy Symbol = SymbolsHere[SHI];
2053 
2054         Expected<bool> RespondedOrErr = DT->DisAsm->onSymbolStart(
2055             Symbol, Size, Bytes.slice(Start, End - Start), SectionAddr + Start);
2056 
2057         if (RespondedOrErr && !*RespondedOrErr) {
2058           // This symbol didn't trigger any interesting handling. Try the other
2059           // symbols defined at this address.
2060           continue;
2061         }
2062 
2063         // If onSymbolStart returned an Error, that means it identified some
2064         // kind of special data at this address, but wasn't able to disassemble
2065         // it meaningfully. So we fall back to printing the error out and
2066         // disassembling the failed region as bytes, assuming that the target
2067         // detected the failure before printing anything.
2068         if (!RespondedOrErr) {
2069           std::string ErrMsgStr = toString(RespondedOrErr.takeError());
2070           StringRef ErrMsg = ErrMsgStr;
2071           do {
2072             StringRef Line;
2073             std::tie(Line, ErrMsg) = ErrMsg.split('\n');
2074             outs() << DT->Context->getAsmInfo()->getCommentString()
2075                    << " error decoding " << SymNamesHere[SHI] << ": " << Line
2076                    << '\n';
2077           } while (!ErrMsg.empty());
2078 
2079           if (Size) {
2080             outs() << DT->Context->getAsmInfo()->getCommentString()
2081                    << " decoding failed region as bytes\n";
2082             for (uint64_t I = 0; I < Size; ++I)
2083               outs() << "\t.byte\t " << format_hex(Bytes[I], 1, /*Upper=*/true)
2084                      << '\n';
2085           }
2086         }
2087 
2088         // Regardless of whether onSymbolStart returned an Error or true, 'Size'
2089         // will have been set to the amount of data covered by whatever prologue
2090         // the target identified. So we advance our own position to beyond that.
2091         // Sometimes that will be the entire distance to the next symbol, and
2092         // sometimes it will be just a prologue and we should start
2093         // disassembling instructions from where it left off.
2094         Start += Size;
2095         break;
2096       }
2097 
2098       Index = Start;
2099       if (SectionAddr < StartAddress)
2100         Index = std::max<uint64_t>(Index, StartAddress - SectionAddr);
2101 
2102       if (DisassembleAsELFData) {
2103         dumpELFData(SectionAddr, Index, End, Bytes);
2104         Index = End;
2105         continue;
2106       }
2107 
2108       // Skip relocations from symbols that are not dumped.
2109       for (; RelCur != RelEnd; ++RelCur) {
2110         uint64_t Offset = RelCur->getOffset() - RelAdjustment;
2111         if (Index <= Offset)
2112           break;
2113       }
2114 
2115       bool DumpARMELFData = false;
2116       bool DumpTracebackTableForXCOFFFunction =
2117           Obj.isXCOFF() && Section.isText() && TracebackTable &&
2118           Symbols[SI - 1].XCOFFSymInfo.StorageMappingClass &&
2119           (*Symbols[SI - 1].XCOFFSymInfo.StorageMappingClass == XCOFF::XMC_PR);
2120 
2121       formatted_raw_ostream FOS(outs());
2122 
2123       std::unordered_map<uint64_t, std::string> AllLabels;
2124       std::unordered_map<uint64_t, std::vector<BBAddrMapLabel>> BBAddrMapLabels;
2125       if (SymbolizeOperands) {
2126         collectLocalBranchTargets(Bytes, DT->InstrAnalysis.get(),
2127                                   DT->DisAsm.get(), DT->InstPrinter.get(),
2128                                   PrimaryTarget.SubtargetInfo.get(),
2129                                   SectionAddr, Index, End, AllLabels);
2130         collectBBAddrMapLabels(FullAddrMap, SectionAddr, Index, End,
2131                                BBAddrMapLabels);
2132       }
2133 
2134       if (DT->InstrAnalysis)
2135         DT->InstrAnalysis->resetState();
2136 
2137       while (Index < End) {
2138         uint64_t RelOffset;
2139 
2140         // ARM and AArch64 ELF binaries can interleave data and text in the
2141         // same section. We rely on the markers introduced to understand what
2142         // we need to dump. If the data marker is within a function, it is
2143         // denoted as a word/short etc.
2144         if (!MappingSymbols.empty()) {
2145           char Kind = getMappingSymbolKind(MappingSymbols, Index);
2146           DumpARMELFData = Kind == 'd';
2147           if (SecondaryTarget) {
2148             if (Kind == 'a') {
2149               DT = PrimaryIsThumb ? &*SecondaryTarget : &PrimaryTarget;
2150             } else if (Kind == 't') {
2151               DT = PrimaryIsThumb ? &PrimaryTarget : &*SecondaryTarget;
2152             }
2153           }
2154         } else if (!CHPECodeMap.empty()) {
2155           uint64_t Address = SectionAddr + Index;
2156           auto It = partition_point(
2157               CHPECodeMap,
2158               [Address](const std::pair<uint64_t, uint64_t> &Entry) {
2159                 return Entry.first <= Address;
2160               });
2161           if (It != CHPECodeMap.begin() && Address < (It - 1)->second) {
2162             DT = &*SecondaryTarget;
2163           } else {
2164             DT = &PrimaryTarget;
2165             // X64 disassembler range may have left Index unaligned, so
2166             // make sure that it's aligned when we switch back to ARM64
2167             // code.
2168             Index = llvm::alignTo(Index, 4);
2169             if (Index >= End)
2170               break;
2171           }
2172         }
2173 
2174         auto findRel = [&]() {
2175           while (RelCur != RelEnd) {
2176             RelOffset = RelCur->getOffset() - RelAdjustment;
2177             // If this relocation is hidden, skip it.
2178             if (getHidden(*RelCur) || SectionAddr + RelOffset < StartAddress) {
2179               ++RelCur;
2180               continue;
2181             }
2182 
2183             // Stop when RelCur's offset is past the disassembled
2184             // instruction/data.
2185             if (RelOffset >= Index + Size)
2186               return false;
2187             if (RelOffset >= Index)
2188               return true;
2189             ++RelCur;
2190           }
2191           return false;
2192         };
2193 
2194         if (DumpARMELFData) {
2195           Size = dumpARMELFData(SectionAddr, Index, End, Obj, Bytes,
2196                                 MappingSymbols, *DT->SubtargetInfo, FOS);
2197         } else {
2198           // When -z or --disassemble-zeroes are given we always dissasemble
2199           // them. Otherwise we might want to skip zero bytes we see.
2200           if (!DisassembleZeroes) {
2201             uint64_t MaxOffset = End - Index;
2202             // For --reloc: print zero blocks patched by relocations, so that
2203             // relocations can be shown in the dump.
2204             if (InlineRelocs && RelCur != RelEnd)
2205               MaxOffset = std::min(RelCur->getOffset() - RelAdjustment - Index,
2206                                    MaxOffset);
2207 
2208             if (size_t N =
2209                     countSkippableZeroBytes(Bytes.slice(Index, MaxOffset))) {
2210               FOS << "\t\t..." << '\n';
2211               Index += N;
2212               continue;
2213             }
2214           }
2215 
2216           if (DumpTracebackTableForXCOFFFunction &&
2217               doesXCOFFTracebackTableBegin(Bytes.slice(Index, 4))) {
2218             dumpTracebackTable(Bytes.slice(Index),
2219                                SectionAddr + Index + VMAAdjustment, FOS,
2220                                SectionAddr + End + VMAAdjustment,
2221                                *DT->SubtargetInfo, cast<XCOFFObjectFile>(&Obj));
2222             Index = End;
2223             continue;
2224           }
2225 
2226           // Print local label if there's any.
2227           auto Iter1 = BBAddrMapLabels.find(SectionAddr + Index);
2228           if (Iter1 != BBAddrMapLabels.end()) {
2229             for (const auto &BBLabel : Iter1->second)
2230               FOS << "<" << BBLabel.BlockLabel << ">" << BBLabel.PGOAnalysis
2231                   << ":\n";
2232           } else {
2233             auto Iter2 = AllLabels.find(SectionAddr + Index);
2234             if (Iter2 != AllLabels.end())
2235               FOS << "<" << Iter2->second << ">:\n";
2236           }
2237 
2238           // Disassemble a real instruction or a data when disassemble all is
2239           // provided
2240           MCInst Inst;
2241           ArrayRef<uint8_t> ThisBytes = Bytes.slice(Index);
2242           uint64_t ThisAddr = SectionAddr + Index;
2243           bool Disassembled = DT->DisAsm->getInstruction(
2244               Inst, Size, ThisBytes, ThisAddr, CommentStream);
2245           if (Size == 0)
2246             Size = std::min<uint64_t>(
2247                 ThisBytes.size(),
2248                 DT->DisAsm->suggestBytesToSkip(ThisBytes, ThisAddr));
2249 
2250           LVP.update({Index, Section.getIndex()},
2251                      {Index + Size, Section.getIndex()}, Index + Size != End);
2252 
2253           DT->InstPrinter->setCommentStream(CommentStream);
2254 
2255           DT->Printer->printInst(
2256               *DT->InstPrinter, Disassembled ? &Inst : nullptr,
2257               Bytes.slice(Index, Size),
2258               {SectionAddr + Index + VMAAdjustment, Section.getIndex()}, FOS,
2259               "", *DT->SubtargetInfo, &SP, Obj.getFileName(), &Rels, LVP);
2260 
2261           DT->InstPrinter->setCommentStream(llvm::nulls());
2262 
2263           // If disassembly succeeds, we try to resolve the target address
2264           // (jump target or memory operand address) and print it to the
2265           // right of the instruction.
2266           //
2267           // Otherwise, we don't print anything else so that we avoid
2268           // analyzing invalid or incomplete instruction information.
2269           if (Disassembled && DT->InstrAnalysis) {
2270             llvm::raw_ostream *TargetOS = &FOS;
2271             uint64_t Target;
2272             bool PrintTarget = DT->InstrAnalysis->evaluateBranch(
2273                 Inst, SectionAddr + Index, Size, Target);
2274 
2275             if (!PrintTarget) {
2276               if (std::optional<uint64_t> MaybeTarget =
2277                       DT->InstrAnalysis->evaluateMemoryOperandAddress(
2278                           Inst, DT->SubtargetInfo.get(), SectionAddr + Index,
2279                           Size)) {
2280                 Target = *MaybeTarget;
2281                 PrintTarget = true;
2282                 // Do not print real address when symbolizing.
2283                 if (!SymbolizeOperands) {
2284                   // Memory operand addresses are printed as comments.
2285                   TargetOS = &CommentStream;
2286                   *TargetOS << "0x" << Twine::utohexstr(Target);
2287                 }
2288               }
2289             }
2290 
2291             if (PrintTarget) {
2292               // In a relocatable object, the target's section must reside in
2293               // the same section as the call instruction or it is accessed
2294               // through a relocation.
2295               //
2296               // In a non-relocatable object, the target may be in any section.
2297               // In that case, locate the section(s) containing the target
2298               // address and find the symbol in one of those, if possible.
2299               //
2300               // N.B. Except for XCOFF, we don't walk the relocations in the
2301               // relocatable case yet.
2302               std::vector<const SectionSymbolsTy *> TargetSectionSymbols;
2303               if (!Obj.isRelocatableObject()) {
2304                 auto It = llvm::partition_point(
2305                     SectionAddresses,
2306                     [=](const std::pair<uint64_t, SectionRef> &O) {
2307                       return O.first <= Target;
2308                     });
2309                 uint64_t TargetSecAddr = 0;
2310                 while (It != SectionAddresses.begin()) {
2311                   --It;
2312                   if (TargetSecAddr == 0)
2313                     TargetSecAddr = It->first;
2314                   if (It->first != TargetSecAddr)
2315                     break;
2316                   TargetSectionSymbols.push_back(&AllSymbols[It->second]);
2317                 }
2318               } else {
2319                 TargetSectionSymbols.push_back(&Symbols);
2320               }
2321               TargetSectionSymbols.push_back(&AbsoluteSymbols);
2322 
2323               // Find the last symbol in the first candidate section whose
2324               // offset is less than or equal to the target. If there are no
2325               // such symbols, try in the next section and so on, before finally
2326               // using the nearest preceding absolute symbol (if any), if there
2327               // are no other valid symbols.
2328               const SymbolInfoTy *TargetSym = nullptr;
2329               for (const SectionSymbolsTy *TargetSymbols :
2330                    TargetSectionSymbols) {
2331                 auto It = llvm::partition_point(
2332                     *TargetSymbols,
2333                     [=](const SymbolInfoTy &O) { return O.Addr <= Target; });
2334                 while (It != TargetSymbols->begin()) {
2335                   --It;
2336                   // Skip mapping symbols to avoid possible ambiguity as they
2337                   // do not allow uniquely identifying the target address.
2338                   if (!It->IsMappingSymbol) {
2339                     TargetSym = &*It;
2340                     break;
2341                   }
2342                 }
2343                 if (TargetSym)
2344                   break;
2345               }
2346 
2347               // Branch targets are printed just after the instructions.
2348               // Print the labels corresponding to the target if there's any.
2349               bool BBAddrMapLabelAvailable = BBAddrMapLabels.count(Target);
2350               bool LabelAvailable = AllLabels.count(Target);
2351 
2352               if (TargetSym != nullptr) {
2353                 uint64_t TargetAddress = TargetSym->Addr;
2354                 uint64_t Disp = Target - TargetAddress;
2355                 std::string TargetName = Demangle ? demangle(TargetSym->Name)
2356                                                   : TargetSym->Name.str();
2357                 bool RelFixedUp = false;
2358                 SmallString<32> Val;
2359 
2360                 *TargetOS << " <";
2361                 // On XCOFF, we use relocations, even without -r, so we
2362                 // can print the correct name for an extern function call.
2363                 if (Obj.isXCOFF() && findRel()) {
2364                   // Check for possible branch relocations and
2365                   // branches to fixup code.
2366                   bool BranchRelocationType = true;
2367                   XCOFF::RelocationType RelocType;
2368                   if (Obj.is64Bit()) {
2369                     const XCOFFRelocation64 *Reloc =
2370                         reinterpret_cast<XCOFFRelocation64 *>(
2371                             RelCur->getRawDataRefImpl().p);
2372                     RelFixedUp = Reloc->isFixupIndicated();
2373                     RelocType = Reloc->Type;
2374                   } else {
2375                     const XCOFFRelocation32 *Reloc =
2376                         reinterpret_cast<XCOFFRelocation32 *>(
2377                             RelCur->getRawDataRefImpl().p);
2378                     RelFixedUp = Reloc->isFixupIndicated();
2379                     RelocType = Reloc->Type;
2380                   }
2381                   BranchRelocationType =
2382                       RelocType == XCOFF::R_BA || RelocType == XCOFF::R_BR ||
2383                       RelocType == XCOFF::R_RBA || RelocType == XCOFF::R_RBR;
2384 
2385                   // If we have a valid relocation, try to print its
2386                   // corresponding symbol name. Multiple relocations on the
2387                   // same instruction are not handled.
2388                   // Branches to fixup code will have the RelFixedUp flag set in
2389                   // the RLD. For these instructions, we print the correct
2390                   // branch target, but print the referenced symbol as a
2391                   // comment.
2392                   if (Error E = getRelocationValueString(*RelCur, false, Val)) {
2393                     // If -r was used, this error will be printed later.
2394                     // Otherwise, we ignore the error and print what
2395                     // would have been printed without using relocations.
2396                     consumeError(std::move(E));
2397                     *TargetOS << TargetName;
2398                     RelFixedUp = false; // Suppress comment for RLD sym name
2399                   } else if (BranchRelocationType && !RelFixedUp)
2400                     *TargetOS << Val;
2401                   else
2402                     *TargetOS << TargetName;
2403                   if (Disp)
2404                     *TargetOS << "+0x" << Twine::utohexstr(Disp);
2405                 } else if (!Disp) {
2406                   *TargetOS << TargetName;
2407                 } else if (BBAddrMapLabelAvailable) {
2408                   *TargetOS << BBAddrMapLabels[Target].front().BlockLabel;
2409                 } else if (LabelAvailable) {
2410                   *TargetOS << AllLabels[Target];
2411                 } else {
2412                   // Always Print the binary symbol plus an offset if there's no
2413                   // local label corresponding to the target address.
2414                   *TargetOS << TargetName << "+0x" << Twine::utohexstr(Disp);
2415                 }
2416                 *TargetOS << ">";
2417                 if (RelFixedUp && !InlineRelocs) {
2418                   // We have fixup code for a relocation. We print the
2419                   // referenced symbol as a comment.
2420                   *TargetOS << "\t# " << Val;
2421                 }
2422 
2423               } else if (BBAddrMapLabelAvailable) {
2424                 *TargetOS << " <" << BBAddrMapLabels[Target].front().BlockLabel
2425                           << ">";
2426               } else if (LabelAvailable) {
2427                 *TargetOS << " <" << AllLabels[Target] << ">";
2428               }
2429               // By convention, each record in the comment stream should be
2430               // terminated.
2431               if (TargetOS == &CommentStream)
2432                 *TargetOS << "\n";
2433             }
2434 
2435             DT->InstrAnalysis->updateState(Inst, SectionAddr + Index);
2436           } else if (!Disassembled && DT->InstrAnalysis) {
2437             DT->InstrAnalysis->resetState();
2438           }
2439         }
2440 
2441         assert(DT->Context->getAsmInfo());
2442         emitPostInstructionInfo(FOS, *DT->Context->getAsmInfo(),
2443                                 *DT->SubtargetInfo, CommentStream.str(), LVP);
2444         Comments.clear();
2445 
2446         if (BTF)
2447           printBTFRelocation(FOS, *BTF, {Index, Section.getIndex()}, LVP);
2448 
2449         // Hexagon handles relocs in pretty printer
2450         if (InlineRelocs && Obj.getArch() != Triple::hexagon) {
2451           while (findRel()) {
2452             // When --adjust-vma is used, update the address printed.
2453             if (RelCur->getSymbol() != Obj.symbol_end()) {
2454               Expected<section_iterator> SymSI =
2455                   RelCur->getSymbol()->getSection();
2456               if (SymSI && *SymSI != Obj.section_end() &&
2457                   shouldAdjustVA(**SymSI))
2458                 RelOffset += AdjustVMA;
2459             }
2460 
2461             printRelocation(FOS, Obj.getFileName(), *RelCur,
2462                             SectionAddr + RelOffset, Is64Bits);
2463             LVP.printAfterOtherLine(FOS, true);
2464             ++RelCur;
2465           }
2466         }
2467 
2468         Index += Size;
2469       }
2470     }
2471   }
2472   StringSet<> MissingDisasmSymbolSet =
2473       set_difference(DisasmSymbolSet, FoundDisasmSymbolSet);
2474   for (StringRef Sym : MissingDisasmSymbolSet.keys())
2475     reportWarning("failed to disassemble missing symbol " + Sym, FileName);
2476 }
2477 
2478 static void disassembleObject(ObjectFile *Obj, bool InlineRelocs) {
2479   // If information useful for showing the disassembly is missing, try to find a
2480   // more complete binary and disassemble that instead.
2481   OwningBinary<Binary> FetchedBinary;
2482   if (Obj->symbols().empty()) {
2483     if (std::optional<OwningBinary<Binary>> FetchedBinaryOpt =
2484             fetchBinaryByBuildID(*Obj)) {
2485       if (auto *O = dyn_cast<ObjectFile>(FetchedBinaryOpt->getBinary())) {
2486         if (!O->symbols().empty() ||
2487             (!O->sections().empty() && Obj->sections().empty())) {
2488           FetchedBinary = std::move(*FetchedBinaryOpt);
2489           Obj = O;
2490         }
2491       }
2492     }
2493   }
2494 
2495   const Target *TheTarget = getTarget(Obj);
2496 
2497   // Package up features to be passed to target/subtarget
2498   Expected<SubtargetFeatures> FeaturesValue = Obj->getFeatures();
2499   if (!FeaturesValue)
2500     reportError(FeaturesValue.takeError(), Obj->getFileName());
2501   SubtargetFeatures Features = *FeaturesValue;
2502   if (!MAttrs.empty()) {
2503     for (unsigned I = 0; I != MAttrs.size(); ++I)
2504       Features.AddFeature(MAttrs[I]);
2505   } else if (MCPU.empty() && Obj->getArch() == llvm::Triple::aarch64) {
2506     Features.AddFeature("+all");
2507   }
2508 
2509   if (MCPU.empty())
2510     MCPU = Obj->tryGetCPUName().value_or("").str();
2511 
2512   if (isArmElf(*Obj)) {
2513     // When disassembling big-endian Arm ELF, the instruction endianness is
2514     // determined in a complex way. In relocatable objects, AAELF32 mandates
2515     // that instruction endianness matches the ELF file endianness; in
2516     // executable images, that's true unless the file header has the EF_ARM_BE8
2517     // flag, in which case instructions are little-endian regardless of data
2518     // endianness.
2519     //
2520     // We must set the big-endian-instructions SubtargetFeature to make the
2521     // disassembler read the instructions the right way round, and also tell
2522     // our own prettyprinter to retrieve the encodings the same way to print in
2523     // hex.
2524     const auto *Elf32BE = dyn_cast<ELF32BEObjectFile>(Obj);
2525 
2526     if (Elf32BE && (Elf32BE->isRelocatableObject() ||
2527                     !(Elf32BE->getPlatformFlags() & ELF::EF_ARM_BE8))) {
2528       Features.AddFeature("+big-endian-instructions");
2529       ARMPrettyPrinterInst.setInstructionEndianness(llvm::endianness::big);
2530     } else {
2531       ARMPrettyPrinterInst.setInstructionEndianness(llvm::endianness::little);
2532     }
2533   }
2534 
2535   DisassemblerTarget PrimaryTarget(TheTarget, *Obj, TripleName, MCPU, Features);
2536 
2537   // If we have an ARM object file, we need a second disassembler, because
2538   // ARM CPUs have two different instruction sets: ARM mode, and Thumb mode.
2539   // We use mapping symbols to switch between the two assemblers, where
2540   // appropriate.
2541   std::optional<DisassemblerTarget> SecondaryTarget;
2542 
2543   if (isArmElf(*Obj)) {
2544     if (!PrimaryTarget.SubtargetInfo->checkFeatures("+mclass")) {
2545       if (PrimaryTarget.SubtargetInfo->checkFeatures("+thumb-mode"))
2546         Features.AddFeature("-thumb-mode");
2547       else
2548         Features.AddFeature("+thumb-mode");
2549       SecondaryTarget.emplace(PrimaryTarget, Features);
2550     }
2551   } else if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
2552     const chpe_metadata *CHPEMetadata = COFFObj->getCHPEMetadata();
2553     if (CHPEMetadata && CHPEMetadata->CodeMapCount) {
2554       // Set up x86_64 disassembler for ARM64EC binaries.
2555       Triple X64Triple(TripleName);
2556       X64Triple.setArch(Triple::ArchType::x86_64);
2557 
2558       std::string Error;
2559       const Target *X64Target =
2560           TargetRegistry::lookupTarget("", X64Triple, Error);
2561       if (X64Target) {
2562         SubtargetFeatures X64Features;
2563         SecondaryTarget.emplace(X64Target, *Obj, X64Triple.getTriple(), "",
2564                                 X64Features);
2565       } else {
2566         reportWarning(Error, Obj->getFileName());
2567       }
2568     }
2569   }
2570 
2571   const ObjectFile *DbgObj = Obj;
2572   if (!FetchedBinary.getBinary() && !Obj->hasDebugInfo()) {
2573     if (std::optional<OwningBinary<Binary>> DebugBinaryOpt =
2574             fetchBinaryByBuildID(*Obj)) {
2575       if (auto *FetchedObj =
2576               dyn_cast<const ObjectFile>(DebugBinaryOpt->getBinary())) {
2577         if (FetchedObj->hasDebugInfo()) {
2578           FetchedBinary = std::move(*DebugBinaryOpt);
2579           DbgObj = FetchedObj;
2580         }
2581       }
2582     }
2583   }
2584 
2585   std::unique_ptr<object::Binary> DSYMBinary;
2586   std::unique_ptr<MemoryBuffer> DSYMBuf;
2587   if (!DbgObj->hasDebugInfo()) {
2588     if (const MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*Obj)) {
2589       DbgObj = objdump::getMachODSymObject(MachOOF, Obj->getFileName(),
2590                                            DSYMBinary, DSYMBuf);
2591       if (!DbgObj)
2592         return;
2593     }
2594   }
2595 
2596   SourcePrinter SP(DbgObj, TheTarget->getName());
2597 
2598   for (StringRef Opt : DisassemblerOptions)
2599     if (!PrimaryTarget.InstPrinter->applyTargetSpecificCLOption(Opt))
2600       reportError(Obj->getFileName(),
2601                   "Unrecognized disassembler option: " + Opt);
2602 
2603   disassembleObject(*Obj, *DbgObj, PrimaryTarget, SecondaryTarget, SP,
2604                     InlineRelocs);
2605 }
2606 
2607 void Dumper::printRelocations() {
2608   StringRef Fmt = O.getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
2609 
2610   // Build a mapping from relocation target to a vector of relocation
2611   // sections. Usually, there is an only one relocation section for
2612   // each relocated section.
2613   MapVector<SectionRef, std::vector<SectionRef>> SecToRelSec;
2614   uint64_t Ndx;
2615   for (const SectionRef &Section : ToolSectionFilter(O, &Ndx)) {
2616     if (O.isELF() && (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC))
2617       continue;
2618     if (Section.relocation_begin() == Section.relocation_end())
2619       continue;
2620     Expected<section_iterator> SecOrErr = Section.getRelocatedSection();
2621     if (!SecOrErr)
2622       reportError(O.getFileName(),
2623                   "section (" + Twine(Ndx) +
2624                       "): unable to get a relocation target: " +
2625                       toString(SecOrErr.takeError()));
2626     SecToRelSec[**SecOrErr].push_back(Section);
2627   }
2628 
2629   for (std::pair<SectionRef, std::vector<SectionRef>> &P : SecToRelSec) {
2630     StringRef SecName = unwrapOrError(P.first.getName(), O.getFileName());
2631     outs() << "\nRELOCATION RECORDS FOR [" << SecName << "]:\n";
2632     uint32_t OffsetPadding = (O.getBytesInAddress() > 4 ? 16 : 8);
2633     uint32_t TypePadding = 24;
2634     outs() << left_justify("OFFSET", OffsetPadding) << " "
2635            << left_justify("TYPE", TypePadding) << " "
2636            << "VALUE\n";
2637 
2638     for (SectionRef Section : P.second) {
2639       for (const RelocationRef &Reloc : Section.relocations()) {
2640         uint64_t Address = Reloc.getOffset();
2641         SmallString<32> RelocName;
2642         SmallString<32> ValueStr;
2643         if (Address < StartAddress || Address > StopAddress || getHidden(Reloc))
2644           continue;
2645         Reloc.getTypeName(RelocName);
2646         if (Error E =
2647                 getRelocationValueString(Reloc, SymbolDescription, ValueStr))
2648           reportUniqueWarning(std::move(E));
2649 
2650         outs() << format(Fmt.data(), Address) << " "
2651                << left_justify(RelocName, TypePadding) << " " << ValueStr
2652                << "\n";
2653       }
2654     }
2655   }
2656 }
2657 
2658 // Returns true if we need to show LMA column when dumping section headers. We
2659 // show it only when the platform is ELF and either we have at least one section
2660 // whose VMA and LMA are different and/or when --show-lma flag is used.
2661 static bool shouldDisplayLMA(const ObjectFile &Obj) {
2662   if (!Obj.isELF())
2663     return false;
2664   for (const SectionRef &S : ToolSectionFilter(Obj))
2665     if (S.getAddress() != getELFSectionLMA(S))
2666       return true;
2667   return ShowLMA;
2668 }
2669 
2670 static size_t getMaxSectionNameWidth(const ObjectFile &Obj) {
2671   // Default column width for names is 13 even if no names are that long.
2672   size_t MaxWidth = 13;
2673   for (const SectionRef &Section : ToolSectionFilter(Obj)) {
2674     StringRef Name = unwrapOrError(Section.getName(), Obj.getFileName());
2675     MaxWidth = std::max(MaxWidth, Name.size());
2676   }
2677   return MaxWidth;
2678 }
2679 
2680 void objdump::printSectionHeaders(ObjectFile &Obj) {
2681   if (Obj.isELF() && Obj.sections().empty())
2682     createFakeELFSections(Obj);
2683 
2684   size_t NameWidth = getMaxSectionNameWidth(Obj);
2685   size_t AddressWidth = 2 * Obj.getBytesInAddress();
2686   bool HasLMAColumn = shouldDisplayLMA(Obj);
2687   outs() << "\nSections:\n";
2688   if (HasLMAColumn)
2689     outs() << "Idx " << left_justify("Name", NameWidth) << " Size     "
2690            << left_justify("VMA", AddressWidth) << " "
2691            << left_justify("LMA", AddressWidth) << " Type\n";
2692   else
2693     outs() << "Idx " << left_justify("Name", NameWidth) << " Size     "
2694            << left_justify("VMA", AddressWidth) << " Type\n";
2695 
2696   uint64_t Idx;
2697   for (const SectionRef &Section : ToolSectionFilter(Obj, &Idx)) {
2698     StringRef Name = unwrapOrError(Section.getName(), Obj.getFileName());
2699     uint64_t VMA = Section.getAddress();
2700     if (shouldAdjustVA(Section))
2701       VMA += AdjustVMA;
2702 
2703     uint64_t Size = Section.getSize();
2704 
2705     std::string Type = Section.isText() ? "TEXT" : "";
2706     if (Section.isData())
2707       Type += Type.empty() ? "DATA" : ", DATA";
2708     if (Section.isBSS())
2709       Type += Type.empty() ? "BSS" : ", BSS";
2710     if (Section.isDebugSection())
2711       Type += Type.empty() ? "DEBUG" : ", DEBUG";
2712 
2713     if (HasLMAColumn)
2714       outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth,
2715                        Name.str().c_str(), Size)
2716              << format_hex_no_prefix(VMA, AddressWidth) << " "
2717              << format_hex_no_prefix(getELFSectionLMA(Section), AddressWidth)
2718              << " " << Type << "\n";
2719     else
2720       outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth,
2721                        Name.str().c_str(), Size)
2722              << format_hex_no_prefix(VMA, AddressWidth) << " " << Type << "\n";
2723   }
2724 }
2725 
2726 void objdump::printSectionContents(const ObjectFile *Obj) {
2727   const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj);
2728 
2729   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
2730     StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName());
2731     uint64_t BaseAddr = Section.getAddress();
2732     uint64_t Size = Section.getSize();
2733     if (!Size)
2734       continue;
2735 
2736     outs() << "Contents of section ";
2737     StringRef SegmentName = getSegmentName(MachO, Section);
2738     if (!SegmentName.empty())
2739       outs() << SegmentName << ",";
2740     outs() << Name << ":\n";
2741     if (Section.isBSS()) {
2742       outs() << format("<skipping contents of bss section at [%04" PRIx64
2743                        ", %04" PRIx64 ")>\n",
2744                        BaseAddr, BaseAddr + Size);
2745       continue;
2746     }
2747 
2748     StringRef Contents = unwrapOrError(Section.getContents(), Obj->getFileName());
2749 
2750     // Dump out the content as hex and printable ascii characters.
2751     for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) {
2752       outs() << format(" %04" PRIx64 " ", BaseAddr + Addr);
2753       // Dump line of hex.
2754       for (std::size_t I = 0; I < 16; ++I) {
2755         if (I != 0 && I % 4 == 0)
2756           outs() << ' ';
2757         if (Addr + I < End)
2758           outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true)
2759                  << hexdigit(Contents[Addr + I] & 0xF, true);
2760         else
2761           outs() << "  ";
2762       }
2763       // Print ascii.
2764       outs() << "  ";
2765       for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) {
2766         if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF))
2767           outs() << Contents[Addr + I];
2768         else
2769           outs() << ".";
2770       }
2771       outs() << "\n";
2772     }
2773   }
2774 }
2775 
2776 void Dumper::printSymbolTable(StringRef ArchiveName, StringRef ArchitectureName,
2777                               bool DumpDynamic) {
2778   if (O.isCOFF() && !DumpDynamic) {
2779     outs() << "\nSYMBOL TABLE:\n";
2780     printCOFFSymbolTable(cast<const COFFObjectFile>(O));
2781     return;
2782   }
2783 
2784   const StringRef FileName = O.getFileName();
2785 
2786   if (!DumpDynamic) {
2787     outs() << "\nSYMBOL TABLE:\n";
2788     for (auto I = O.symbol_begin(); I != O.symbol_end(); ++I)
2789       printSymbol(*I, {}, FileName, ArchiveName, ArchitectureName, DumpDynamic);
2790     return;
2791   }
2792 
2793   outs() << "\nDYNAMIC SYMBOL TABLE:\n";
2794   if (!O.isELF()) {
2795     reportWarning(
2796         "this operation is not currently supported for this file format",
2797         FileName);
2798     return;
2799   }
2800 
2801   const ELFObjectFileBase *ELF = cast<const ELFObjectFileBase>(&O);
2802   auto Symbols = ELF->getDynamicSymbolIterators();
2803   Expected<std::vector<VersionEntry>> SymbolVersionsOrErr =
2804       ELF->readDynsymVersions();
2805   if (!SymbolVersionsOrErr) {
2806     reportWarning(toString(SymbolVersionsOrErr.takeError()), FileName);
2807     SymbolVersionsOrErr = std::vector<VersionEntry>();
2808     (void)!SymbolVersionsOrErr;
2809   }
2810   for (auto &Sym : Symbols)
2811     printSymbol(Sym, *SymbolVersionsOrErr, FileName, ArchiveName,
2812                 ArchitectureName, DumpDynamic);
2813 }
2814 
2815 void Dumper::printSymbol(const SymbolRef &Symbol,
2816                          ArrayRef<VersionEntry> SymbolVersions,
2817                          StringRef FileName, StringRef ArchiveName,
2818                          StringRef ArchitectureName, bool DumpDynamic) {
2819   const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(&O);
2820   Expected<uint64_t> AddrOrErr = Symbol.getAddress();
2821   if (!AddrOrErr) {
2822     reportUniqueWarning(AddrOrErr.takeError());
2823     return;
2824   }
2825   uint64_t Address = *AddrOrErr;
2826   section_iterator SecI = unwrapOrError(Symbol.getSection(), FileName);
2827   if (SecI != O.section_end() && shouldAdjustVA(*SecI))
2828     Address += AdjustVMA;
2829   if ((Address < StartAddress) || (Address > StopAddress))
2830     return;
2831   SymbolRef::Type Type =
2832       unwrapOrError(Symbol.getType(), FileName, ArchiveName, ArchitectureName);
2833   uint32_t Flags =
2834       unwrapOrError(Symbol.getFlags(), FileName, ArchiveName, ArchitectureName);
2835 
2836   // Don't ask a Mach-O STAB symbol for its section unless you know that
2837   // STAB symbol's section field refers to a valid section index. Otherwise
2838   // the symbol may error trying to load a section that does not exist.
2839   bool IsSTAB = false;
2840   if (MachO) {
2841     DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
2842     uint8_t NType =
2843         (MachO->is64Bit() ? MachO->getSymbol64TableEntry(SymDRI).n_type
2844                           : MachO->getSymbolTableEntry(SymDRI).n_type);
2845     if (NType & MachO::N_STAB)
2846       IsSTAB = true;
2847   }
2848   section_iterator Section = IsSTAB
2849                                  ? O.section_end()
2850                                  : unwrapOrError(Symbol.getSection(), FileName,
2851                                                  ArchiveName, ArchitectureName);
2852 
2853   StringRef Name;
2854   if (Type == SymbolRef::ST_Debug && Section != O.section_end()) {
2855     if (Expected<StringRef> NameOrErr = Section->getName())
2856       Name = *NameOrErr;
2857     else
2858       consumeError(NameOrErr.takeError());
2859 
2860   } else {
2861     Name = unwrapOrError(Symbol.getName(), FileName, ArchiveName,
2862                          ArchitectureName);
2863   }
2864 
2865   bool Global = Flags & SymbolRef::SF_Global;
2866   bool Weak = Flags & SymbolRef::SF_Weak;
2867   bool Absolute = Flags & SymbolRef::SF_Absolute;
2868   bool Common = Flags & SymbolRef::SF_Common;
2869   bool Hidden = Flags & SymbolRef::SF_Hidden;
2870 
2871   char GlobLoc = ' ';
2872   if ((Section != O.section_end() || Absolute) && !Weak)
2873     GlobLoc = Global ? 'g' : 'l';
2874   char IFunc = ' ';
2875   if (O.isELF()) {
2876     if (ELFSymbolRef(Symbol).getELFType() == ELF::STT_GNU_IFUNC)
2877       IFunc = 'i';
2878     if (ELFSymbolRef(Symbol).getBinding() == ELF::STB_GNU_UNIQUE)
2879       GlobLoc = 'u';
2880   }
2881 
2882   char Debug = ' ';
2883   if (DumpDynamic)
2884     Debug = 'D';
2885   else if (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
2886     Debug = 'd';
2887 
2888   char FileFunc = ' ';
2889   if (Type == SymbolRef::ST_File)
2890     FileFunc = 'f';
2891   else if (Type == SymbolRef::ST_Function)
2892     FileFunc = 'F';
2893   else if (Type == SymbolRef::ST_Data)
2894     FileFunc = 'O';
2895 
2896   const char *Fmt = O.getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
2897 
2898   outs() << format(Fmt, Address) << " "
2899          << GlobLoc            // Local -> 'l', Global -> 'g', Neither -> ' '
2900          << (Weak ? 'w' : ' ') // Weak?
2901          << ' '                // Constructor. Not supported yet.
2902          << ' '                // Warning. Not supported yet.
2903          << IFunc              // Indirect reference to another symbol.
2904          << Debug              // Debugging (d) or dynamic (D) symbol.
2905          << FileFunc           // Name of function (F), file (f) or object (O).
2906          << ' ';
2907   if (Absolute) {
2908     outs() << "*ABS*";
2909   } else if (Common) {
2910     outs() << "*COM*";
2911   } else if (Section == O.section_end()) {
2912     if (O.isXCOFF()) {
2913       XCOFFSymbolRef XCOFFSym = cast<const XCOFFObjectFile>(O).toSymbolRef(
2914           Symbol.getRawDataRefImpl());
2915       if (XCOFF::N_DEBUG == XCOFFSym.getSectionNumber())
2916         outs() << "*DEBUG*";
2917       else
2918         outs() << "*UND*";
2919     } else
2920       outs() << "*UND*";
2921   } else {
2922     StringRef SegmentName = getSegmentName(MachO, *Section);
2923     if (!SegmentName.empty())
2924       outs() << SegmentName << ",";
2925     StringRef SectionName = unwrapOrError(Section->getName(), FileName);
2926     outs() << SectionName;
2927     if (O.isXCOFF()) {
2928       std::optional<SymbolRef> SymRef =
2929           getXCOFFSymbolContainingSymbolRef(cast<XCOFFObjectFile>(O), Symbol);
2930       if (SymRef) {
2931 
2932         Expected<StringRef> NameOrErr = SymRef->getName();
2933 
2934         if (NameOrErr) {
2935           outs() << " (csect:";
2936           std::string SymName =
2937               Demangle ? demangle(*NameOrErr) : NameOrErr->str();
2938 
2939           if (SymbolDescription)
2940             SymName = getXCOFFSymbolDescription(createSymbolInfo(O, *SymRef),
2941                                                 SymName);
2942 
2943           outs() << ' ' << SymName;
2944           outs() << ") ";
2945         } else
2946           reportWarning(toString(NameOrErr.takeError()), FileName);
2947       }
2948     }
2949   }
2950 
2951   if (Common)
2952     outs() << '\t' << format(Fmt, static_cast<uint64_t>(Symbol.getAlignment()));
2953   else if (O.isXCOFF())
2954     outs() << '\t'
2955            << format(Fmt, cast<XCOFFObjectFile>(O).getSymbolSize(
2956                               Symbol.getRawDataRefImpl()));
2957   else if (O.isELF())
2958     outs() << '\t' << format(Fmt, ELFSymbolRef(Symbol).getSize());
2959   else if (O.isWasm())
2960     outs() << '\t'
2961            << format(Fmt, static_cast<uint64_t>(
2962                               cast<WasmObjectFile>(O).getSymbolSize(Symbol)));
2963 
2964   if (O.isELF()) {
2965     if (!SymbolVersions.empty()) {
2966       const VersionEntry &Ver =
2967           SymbolVersions[Symbol.getRawDataRefImpl().d.b - 1];
2968       std::string Str;
2969       if (!Ver.Name.empty())
2970         Str = Ver.IsVerDef ? ' ' + Ver.Name : '(' + Ver.Name + ')';
2971       outs() << ' ' << left_justify(Str, 12);
2972     }
2973 
2974     uint8_t Other = ELFSymbolRef(Symbol).getOther();
2975     switch (Other) {
2976     case ELF::STV_DEFAULT:
2977       break;
2978     case ELF::STV_INTERNAL:
2979       outs() << " .internal";
2980       break;
2981     case ELF::STV_HIDDEN:
2982       outs() << " .hidden";
2983       break;
2984     case ELF::STV_PROTECTED:
2985       outs() << " .protected";
2986       break;
2987     default:
2988       outs() << format(" 0x%02x", Other);
2989       break;
2990     }
2991   } else if (Hidden) {
2992     outs() << " .hidden";
2993   }
2994 
2995   std::string SymName = Demangle ? demangle(Name) : Name.str();
2996   if (O.isXCOFF() && SymbolDescription)
2997     SymName = getXCOFFSymbolDescription(createSymbolInfo(O, Symbol), SymName);
2998 
2999   outs() << ' ' << SymName << '\n';
3000 }
3001 
3002 static void printUnwindInfo(const ObjectFile *O) {
3003   outs() << "Unwind info:\n\n";
3004 
3005   if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O))
3006     printCOFFUnwindInfo(Coff);
3007   else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O))
3008     printMachOUnwindInfo(MachO);
3009   else
3010     // TODO: Extract DWARF dump tool to objdump.
3011     WithColor::error(errs(), ToolName)
3012         << "This operation is only currently supported "
3013            "for COFF and MachO object files.\n";
3014 }
3015 
3016 /// Dump the raw contents of the __clangast section so the output can be piped
3017 /// into llvm-bcanalyzer.
3018 static void printRawClangAST(const ObjectFile *Obj) {
3019   if (outs().is_displayed()) {
3020     WithColor::error(errs(), ToolName)
3021         << "The -raw-clang-ast option will dump the raw binary contents of "
3022            "the clang ast section.\n"
3023            "Please redirect the output to a file or another program such as "
3024            "llvm-bcanalyzer.\n";
3025     return;
3026   }
3027 
3028   StringRef ClangASTSectionName("__clangast");
3029   if (Obj->isCOFF()) {
3030     ClangASTSectionName = "clangast";
3031   }
3032 
3033   std::optional<object::SectionRef> ClangASTSection;
3034   for (auto Sec : ToolSectionFilter(*Obj)) {
3035     StringRef Name;
3036     if (Expected<StringRef> NameOrErr = Sec.getName())
3037       Name = *NameOrErr;
3038     else
3039       consumeError(NameOrErr.takeError());
3040 
3041     if (Name == ClangASTSectionName) {
3042       ClangASTSection = Sec;
3043       break;
3044     }
3045   }
3046   if (!ClangASTSection)
3047     return;
3048 
3049   StringRef ClangASTContents =
3050       unwrapOrError(ClangASTSection->getContents(), Obj->getFileName());
3051   outs().write(ClangASTContents.data(), ClangASTContents.size());
3052 }
3053 
3054 static void printFaultMaps(const ObjectFile *Obj) {
3055   StringRef FaultMapSectionName;
3056 
3057   if (Obj->isELF()) {
3058     FaultMapSectionName = ".llvm_faultmaps";
3059   } else if (Obj->isMachO()) {
3060     FaultMapSectionName = "__llvm_faultmaps";
3061   } else {
3062     WithColor::error(errs(), ToolName)
3063         << "This operation is only currently supported "
3064            "for ELF and Mach-O executable files.\n";
3065     return;
3066   }
3067 
3068   std::optional<object::SectionRef> FaultMapSection;
3069 
3070   for (auto Sec : ToolSectionFilter(*Obj)) {
3071     StringRef Name;
3072     if (Expected<StringRef> NameOrErr = Sec.getName())
3073       Name = *NameOrErr;
3074     else
3075       consumeError(NameOrErr.takeError());
3076 
3077     if (Name == FaultMapSectionName) {
3078       FaultMapSection = Sec;
3079       break;
3080     }
3081   }
3082 
3083   outs() << "FaultMap table:\n";
3084 
3085   if (!FaultMapSection) {
3086     outs() << "<not found>\n";
3087     return;
3088   }
3089 
3090   StringRef FaultMapContents =
3091       unwrapOrError(FaultMapSection->getContents(), Obj->getFileName());
3092   FaultMapParser FMP(FaultMapContents.bytes_begin(),
3093                      FaultMapContents.bytes_end());
3094 
3095   outs() << FMP;
3096 }
3097 
3098 void Dumper::printPrivateHeaders() {
3099   reportError(O.getFileName(), "Invalid/Unsupported object file format");
3100 }
3101 
3102 static void printFileHeaders(const ObjectFile *O) {
3103   if (!O->isELF() && !O->isCOFF())
3104     reportError(O->getFileName(), "Invalid/Unsupported object file format");
3105 
3106   Triple::ArchType AT = O->getArch();
3107   outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
3108   uint64_t Address = unwrapOrError(O->getStartAddress(), O->getFileName());
3109 
3110   StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
3111   outs() << "start address: "
3112          << "0x" << format(Fmt.data(), Address) << "\n";
3113 }
3114 
3115 static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
3116   Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
3117   if (!ModeOrErr) {
3118     WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n";
3119     consumeError(ModeOrErr.takeError());
3120     return;
3121   }
3122   sys::fs::perms Mode = ModeOrErr.get();
3123   outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
3124   outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
3125   outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
3126   outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
3127   outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
3128   outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
3129   outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
3130   outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
3131   outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
3132 
3133   outs() << " ";
3134 
3135   outs() << format("%d/%d %6" PRId64 " ", unwrapOrError(C.getUID(), Filename),
3136                    unwrapOrError(C.getGID(), Filename),
3137                    unwrapOrError(C.getRawSize(), Filename));
3138 
3139   StringRef RawLastModified = C.getRawLastModified();
3140   unsigned Seconds;
3141   if (RawLastModified.getAsInteger(10, Seconds))
3142     outs() << "(date: \"" << RawLastModified
3143            << "\" contains non-decimal chars) ";
3144   else {
3145     // Since ctime(3) returns a 26 character string of the form:
3146     // "Sun Sep 16 01:03:52 1973\n\0"
3147     // just print 24 characters.
3148     time_t t = Seconds;
3149     outs() << format("%.24s ", ctime(&t));
3150   }
3151 
3152   StringRef Name = "";
3153   Expected<StringRef> NameOrErr = C.getName();
3154   if (!NameOrErr) {
3155     consumeError(NameOrErr.takeError());
3156     Name = unwrapOrError(C.getRawName(), Filename);
3157   } else {
3158     Name = NameOrErr.get();
3159   }
3160   outs() << Name << "\n";
3161 }
3162 
3163 // For ELF only now.
3164 static bool shouldWarnForInvalidStartStopAddress(ObjectFile *Obj) {
3165   if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj)) {
3166     if (Elf->getEType() != ELF::ET_REL)
3167       return true;
3168   }
3169   return false;
3170 }
3171 
3172 static void checkForInvalidStartStopAddress(ObjectFile *Obj,
3173                                             uint64_t Start, uint64_t Stop) {
3174   if (!shouldWarnForInvalidStartStopAddress(Obj))
3175     return;
3176 
3177   for (const SectionRef &Section : Obj->sections())
3178     if (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC) {
3179       uint64_t BaseAddr = Section.getAddress();
3180       uint64_t Size = Section.getSize();
3181       if ((Start < BaseAddr + Size) && Stop > BaseAddr)
3182         return;
3183     }
3184 
3185   if (!HasStartAddressFlag)
3186     reportWarning("no section has address less than 0x" +
3187                       Twine::utohexstr(Stop) + " specified by --stop-address",
3188                   Obj->getFileName());
3189   else if (!HasStopAddressFlag)
3190     reportWarning("no section has address greater than or equal to 0x" +
3191                       Twine::utohexstr(Start) + " specified by --start-address",
3192                   Obj->getFileName());
3193   else
3194     reportWarning("no section overlaps the range [0x" +
3195                       Twine::utohexstr(Start) + ",0x" + Twine::utohexstr(Stop) +
3196                       ") specified by --start-address/--stop-address",
3197                   Obj->getFileName());
3198 }
3199 
3200 static void dumpObject(ObjectFile *O, const Archive *A = nullptr,
3201                        const Archive::Child *C = nullptr) {
3202   Expected<std::unique_ptr<Dumper>> DumperOrErr = createDumper(*O);
3203   if (!DumperOrErr) {
3204     reportError(DumperOrErr.takeError(), O->getFileName(),
3205                 A ? A->getFileName() : "");
3206     return;
3207   }
3208   Dumper &D = **DumperOrErr;
3209 
3210   // Avoid other output when using a raw option.
3211   if (!RawClangAST) {
3212     outs() << '\n';
3213     if (A)
3214       outs() << A->getFileName() << "(" << O->getFileName() << ")";
3215     else
3216       outs() << O->getFileName();
3217     outs() << ":\tfile format " << O->getFileFormatName().lower() << "\n";
3218   }
3219 
3220   if (HasStartAddressFlag || HasStopAddressFlag)
3221     checkForInvalidStartStopAddress(O, StartAddress, StopAddress);
3222 
3223   // TODO: Change print* free functions to Dumper member functions to utilitize
3224   // stateful functions like reportUniqueWarning.
3225 
3226   // Note: the order here matches GNU objdump for compatability.
3227   StringRef ArchiveName = A ? A->getFileName() : "";
3228   if (ArchiveHeaders && !MachOOpt && C)
3229     printArchiveChild(ArchiveName, *C);
3230   if (FileHeaders)
3231     printFileHeaders(O);
3232   if (PrivateHeaders || FirstPrivateHeader)
3233     D.printPrivateHeaders();
3234   if (SectionHeaders)
3235     printSectionHeaders(*O);
3236   if (SymbolTable)
3237     D.printSymbolTable(ArchiveName);
3238   if (DynamicSymbolTable)
3239     D.printSymbolTable(ArchiveName, /*ArchitectureName=*/"",
3240                        /*DumpDynamic=*/true);
3241   if (DwarfDumpType != DIDT_Null) {
3242     std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O);
3243     // Dump the complete DWARF structure.
3244     DIDumpOptions DumpOpts;
3245     DumpOpts.DumpType = DwarfDumpType;
3246     DICtx->dump(outs(), DumpOpts);
3247   }
3248   if (Relocations && !Disassemble)
3249     D.printRelocations();
3250   if (DynamicRelocations)
3251     D.printDynamicRelocations();
3252   if (SectionContents)
3253     printSectionContents(O);
3254   if (Disassemble)
3255     disassembleObject(O, Relocations);
3256   if (UnwindInfo)
3257     printUnwindInfo(O);
3258 
3259   // Mach-O specific options:
3260   if (ExportsTrie)
3261     printExportsTrie(O);
3262   if (Rebase)
3263     printRebaseTable(O);
3264   if (Bind)
3265     printBindTable(O);
3266   if (LazyBind)
3267     printLazyBindTable(O);
3268   if (WeakBind)
3269     printWeakBindTable(O);
3270 
3271   // Other special sections:
3272   if (RawClangAST)
3273     printRawClangAST(O);
3274   if (FaultMapSection)
3275     printFaultMaps(O);
3276   if (Offloading)
3277     dumpOffloadBinary(*O);
3278 }
3279 
3280 static void dumpObject(const COFFImportFile *I, const Archive *A,
3281                        const Archive::Child *C = nullptr) {
3282   StringRef ArchiveName = A ? A->getFileName() : "";
3283 
3284   // Avoid other output when using a raw option.
3285   if (!RawClangAST)
3286     outs() << '\n'
3287            << ArchiveName << "(" << I->getFileName() << ")"
3288            << ":\tfile format COFF-import-file"
3289            << "\n\n";
3290 
3291   if (ArchiveHeaders && !MachOOpt && C)
3292     printArchiveChild(ArchiveName, *C);
3293   if (SymbolTable)
3294     printCOFFSymbolTable(*I);
3295 }
3296 
3297 /// Dump each object file in \a a;
3298 static void dumpArchive(const Archive *A) {
3299   Error Err = Error::success();
3300   unsigned I = -1;
3301   for (auto &C : A->children(Err)) {
3302     ++I;
3303     Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
3304     if (!ChildOrErr) {
3305       if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
3306         reportError(std::move(E), getFileNameForError(C, I), A->getFileName());
3307       continue;
3308     }
3309     if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
3310       dumpObject(O, A, &C);
3311     else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
3312       dumpObject(I, A, &C);
3313     else
3314       reportError(errorCodeToError(object_error::invalid_file_type),
3315                   A->getFileName());
3316   }
3317   if (Err)
3318     reportError(std::move(Err), A->getFileName());
3319 }
3320 
3321 /// Open file and figure out how to dump it.
3322 static void dumpInput(StringRef file) {
3323   // If we are using the Mach-O specific object file parser, then let it parse
3324   // the file and process the command line options.  So the -arch flags can
3325   // be used to select specific slices, etc.
3326   if (MachOOpt) {
3327     parseInputMachO(file);
3328     return;
3329   }
3330 
3331   // Attempt to open the binary.
3332   OwningBinary<Binary> OBinary = unwrapOrError(createBinary(file), file);
3333   Binary &Binary = *OBinary.getBinary();
3334 
3335   if (Archive *A = dyn_cast<Archive>(&Binary))
3336     dumpArchive(A);
3337   else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary))
3338     dumpObject(O);
3339   else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
3340     parseInputMachO(UB);
3341   else if (OffloadBinary *OB = dyn_cast<OffloadBinary>(&Binary))
3342     dumpOffloadSections(*OB);
3343   else
3344     reportError(errorCodeToError(object_error::invalid_file_type), file);
3345 }
3346 
3347 template <typename T>
3348 static void parseIntArg(const llvm::opt::InputArgList &InputArgs, int ID,
3349                         T &Value) {
3350   if (const opt::Arg *A = InputArgs.getLastArg(ID)) {
3351     StringRef V(A->getValue());
3352     if (!llvm::to_integer(V, Value, 0)) {
3353       reportCmdLineError(A->getSpelling() +
3354                          ": expected a non-negative integer, but got '" + V +
3355                          "'");
3356     }
3357   }
3358 }
3359 
3360 static object::BuildID parseBuildIDArg(const opt::Arg *A) {
3361   StringRef V(A->getValue());
3362   object::BuildID BID = parseBuildID(V);
3363   if (BID.empty())
3364     reportCmdLineError(A->getSpelling() + ": expected a build ID, but got '" +
3365                        V + "'");
3366   return BID;
3367 }
3368 
3369 void objdump::invalidArgValue(const opt::Arg *A) {
3370   reportCmdLineError("'" + StringRef(A->getValue()) +
3371                      "' is not a valid value for '" + A->getSpelling() + "'");
3372 }
3373 
3374 static std::vector<std::string>
3375 commaSeparatedValues(const llvm::opt::InputArgList &InputArgs, int ID) {
3376   std::vector<std::string> Values;
3377   for (StringRef Value : InputArgs.getAllArgValues(ID)) {
3378     llvm::SmallVector<StringRef, 2> SplitValues;
3379     llvm::SplitString(Value, SplitValues, ",");
3380     for (StringRef SplitValue : SplitValues)
3381       Values.push_back(SplitValue.str());
3382   }
3383   return Values;
3384 }
3385 
3386 static void parseOtoolOptions(const llvm::opt::InputArgList &InputArgs) {
3387   MachOOpt = true;
3388   FullLeadingAddr = true;
3389   PrintImmHex = true;
3390 
3391   ArchName = InputArgs.getLastArgValue(OTOOL_arch).str();
3392   LinkOptHints = InputArgs.hasArg(OTOOL_C);
3393   if (InputArgs.hasArg(OTOOL_d))
3394     FilterSections.push_back("__DATA,__data");
3395   DylibId = InputArgs.hasArg(OTOOL_D);
3396   UniversalHeaders = InputArgs.hasArg(OTOOL_f);
3397   DataInCode = InputArgs.hasArg(OTOOL_G);
3398   FirstPrivateHeader = InputArgs.hasArg(OTOOL_h);
3399   IndirectSymbols = InputArgs.hasArg(OTOOL_I);
3400   ShowRawInsn = InputArgs.hasArg(OTOOL_j);
3401   PrivateHeaders = InputArgs.hasArg(OTOOL_l);
3402   DylibsUsed = InputArgs.hasArg(OTOOL_L);
3403   MCPU = InputArgs.getLastArgValue(OTOOL_mcpu_EQ).str();
3404   ObjcMetaData = InputArgs.hasArg(OTOOL_o);
3405   DisSymName = InputArgs.getLastArgValue(OTOOL_p).str();
3406   InfoPlist = InputArgs.hasArg(OTOOL_P);
3407   Relocations = InputArgs.hasArg(OTOOL_r);
3408   if (const Arg *A = InputArgs.getLastArg(OTOOL_s)) {
3409     auto Filter = (A->getValue(0) + StringRef(",") + A->getValue(1)).str();
3410     FilterSections.push_back(Filter);
3411   }
3412   if (InputArgs.hasArg(OTOOL_t))
3413     FilterSections.push_back("__TEXT,__text");
3414   Verbose = InputArgs.hasArg(OTOOL_v) || InputArgs.hasArg(OTOOL_V) ||
3415             InputArgs.hasArg(OTOOL_o);
3416   SymbolicOperands = InputArgs.hasArg(OTOOL_V);
3417   if (InputArgs.hasArg(OTOOL_x))
3418     FilterSections.push_back(",__text");
3419   LeadingAddr = LeadingHeaders = !InputArgs.hasArg(OTOOL_X);
3420 
3421   ChainedFixups = InputArgs.hasArg(OTOOL_chained_fixups);
3422   DyldInfo = InputArgs.hasArg(OTOOL_dyld_info);
3423 
3424   InputFilenames = InputArgs.getAllArgValues(OTOOL_INPUT);
3425   if (InputFilenames.empty())
3426     reportCmdLineError("no input file");
3427 
3428   for (const Arg *A : InputArgs) {
3429     const Option &O = A->getOption();
3430     if (O.getGroup().isValid() && O.getGroup().getID() == OTOOL_grp_obsolete) {
3431       reportCmdLineWarning(O.getPrefixedName() +
3432                            " is obsolete and not implemented");
3433     }
3434   }
3435 }
3436 
3437 static void parseObjdumpOptions(const llvm::opt::InputArgList &InputArgs) {
3438   parseIntArg(InputArgs, OBJDUMP_adjust_vma_EQ, AdjustVMA);
3439   AllHeaders = InputArgs.hasArg(OBJDUMP_all_headers);
3440   ArchName = InputArgs.getLastArgValue(OBJDUMP_arch_name_EQ).str();
3441   ArchiveHeaders = InputArgs.hasArg(OBJDUMP_archive_headers);
3442   Demangle = InputArgs.hasArg(OBJDUMP_demangle);
3443   Disassemble = InputArgs.hasArg(OBJDUMP_disassemble);
3444   DisassembleAll = InputArgs.hasArg(OBJDUMP_disassemble_all);
3445   SymbolDescription = InputArgs.hasArg(OBJDUMP_symbol_description);
3446   TracebackTable = InputArgs.hasArg(OBJDUMP_traceback_table);
3447   DisassembleSymbols =
3448       commaSeparatedValues(InputArgs, OBJDUMP_disassemble_symbols_EQ);
3449   DisassembleZeroes = InputArgs.hasArg(OBJDUMP_disassemble_zeroes);
3450   if (const opt::Arg *A = InputArgs.getLastArg(OBJDUMP_dwarf_EQ)) {
3451     DwarfDumpType = StringSwitch<DIDumpType>(A->getValue())
3452                         .Case("frames", DIDT_DebugFrame)
3453                         .Default(DIDT_Null);
3454     if (DwarfDumpType == DIDT_Null)
3455       invalidArgValue(A);
3456   }
3457   DynamicRelocations = InputArgs.hasArg(OBJDUMP_dynamic_reloc);
3458   FaultMapSection = InputArgs.hasArg(OBJDUMP_fault_map_section);
3459   Offloading = InputArgs.hasArg(OBJDUMP_offloading);
3460   FileHeaders = InputArgs.hasArg(OBJDUMP_file_headers);
3461   SectionContents = InputArgs.hasArg(OBJDUMP_full_contents);
3462   PrintLines = InputArgs.hasArg(OBJDUMP_line_numbers);
3463   InputFilenames = InputArgs.getAllArgValues(OBJDUMP_INPUT);
3464   MachOOpt = InputArgs.hasArg(OBJDUMP_macho);
3465   MCPU = InputArgs.getLastArgValue(OBJDUMP_mcpu_EQ).str();
3466   MAttrs = commaSeparatedValues(InputArgs, OBJDUMP_mattr_EQ);
3467   ShowRawInsn = !InputArgs.hasArg(OBJDUMP_no_show_raw_insn);
3468   LeadingAddr = !InputArgs.hasArg(OBJDUMP_no_leading_addr);
3469   RawClangAST = InputArgs.hasArg(OBJDUMP_raw_clang_ast);
3470   Relocations = InputArgs.hasArg(OBJDUMP_reloc);
3471   PrintImmHex =
3472       InputArgs.hasFlag(OBJDUMP_print_imm_hex, OBJDUMP_no_print_imm_hex, true);
3473   PrivateHeaders = InputArgs.hasArg(OBJDUMP_private_headers);
3474   FilterSections = InputArgs.getAllArgValues(OBJDUMP_section_EQ);
3475   SectionHeaders = InputArgs.hasArg(OBJDUMP_section_headers);
3476   ShowAllSymbols = InputArgs.hasArg(OBJDUMP_show_all_symbols);
3477   ShowLMA = InputArgs.hasArg(OBJDUMP_show_lma);
3478   PrintSource = InputArgs.hasArg(OBJDUMP_source);
3479   parseIntArg(InputArgs, OBJDUMP_start_address_EQ, StartAddress);
3480   HasStartAddressFlag = InputArgs.hasArg(OBJDUMP_start_address_EQ);
3481   parseIntArg(InputArgs, OBJDUMP_stop_address_EQ, StopAddress);
3482   HasStopAddressFlag = InputArgs.hasArg(OBJDUMP_stop_address_EQ);
3483   SymbolTable = InputArgs.hasArg(OBJDUMP_syms);
3484   SymbolizeOperands = InputArgs.hasArg(OBJDUMP_symbolize_operands);
3485   PrettyPGOAnalysisMap = InputArgs.hasArg(OBJDUMP_pretty_pgo_analysis_map);
3486   if (PrettyPGOAnalysisMap && !SymbolizeOperands)
3487     reportCmdLineWarning("--symbolize-operands must be enabled for "
3488                          "--pretty-pgo-analysis-map to have an effect");
3489   DynamicSymbolTable = InputArgs.hasArg(OBJDUMP_dynamic_syms);
3490   TripleName = InputArgs.getLastArgValue(OBJDUMP_triple_EQ).str();
3491   UnwindInfo = InputArgs.hasArg(OBJDUMP_unwind_info);
3492   Wide = InputArgs.hasArg(OBJDUMP_wide);
3493   Prefix = InputArgs.getLastArgValue(OBJDUMP_prefix).str();
3494   parseIntArg(InputArgs, OBJDUMP_prefix_strip, PrefixStrip);
3495   if (const opt::Arg *A = InputArgs.getLastArg(OBJDUMP_debug_vars_EQ)) {
3496     DbgVariables = StringSwitch<DebugVarsFormat>(A->getValue())
3497                        .Case("ascii", DVASCII)
3498                        .Case("unicode", DVUnicode)
3499                        .Default(DVInvalid);
3500     if (DbgVariables == DVInvalid)
3501       invalidArgValue(A);
3502   }
3503   if (const opt::Arg *A = InputArgs.getLastArg(OBJDUMP_disassembler_color_EQ)) {
3504     DisassemblyColor = StringSwitch<ColorOutput>(A->getValue())
3505                            .Case("on", ColorOutput::Enable)
3506                            .Case("off", ColorOutput::Disable)
3507                            .Case("terminal", ColorOutput::Auto)
3508                            .Default(ColorOutput::Invalid);
3509     if (DisassemblyColor == ColorOutput::Invalid)
3510       invalidArgValue(A);
3511   }
3512 
3513   parseIntArg(InputArgs, OBJDUMP_debug_vars_indent_EQ, DbgIndent);
3514 
3515   parseMachOOptions(InputArgs);
3516 
3517   // Parse -M (--disassembler-options) and deprecated
3518   // --x86-asm-syntax={att,intel}.
3519   //
3520   // Note, for x86, the asm dialect (AssemblerDialect) is initialized when the
3521   // MCAsmInfo is constructed. MCInstPrinter::applyTargetSpecificCLOption is
3522   // called too late. For now we have to use the internal cl::opt option.
3523   const char *AsmSyntax = nullptr;
3524   for (const auto *A : InputArgs.filtered(OBJDUMP_disassembler_options_EQ,
3525                                           OBJDUMP_x86_asm_syntax_att,
3526                                           OBJDUMP_x86_asm_syntax_intel)) {
3527     switch (A->getOption().getID()) {
3528     case OBJDUMP_x86_asm_syntax_att:
3529       AsmSyntax = "--x86-asm-syntax=att";
3530       continue;
3531     case OBJDUMP_x86_asm_syntax_intel:
3532       AsmSyntax = "--x86-asm-syntax=intel";
3533       continue;
3534     }
3535 
3536     SmallVector<StringRef, 2> Values;
3537     llvm::SplitString(A->getValue(), Values, ",");
3538     for (StringRef V : Values) {
3539       if (V == "att")
3540         AsmSyntax = "--x86-asm-syntax=att";
3541       else if (V == "intel")
3542         AsmSyntax = "--x86-asm-syntax=intel";
3543       else
3544         DisassemblerOptions.push_back(V.str());
3545     }
3546   }
3547   SmallVector<const char *> Args = {"llvm-objdump"};
3548   for (const opt::Arg *A : InputArgs.filtered(OBJDUMP_mllvm))
3549     Args.push_back(A->getValue());
3550   if (AsmSyntax)
3551     Args.push_back(AsmSyntax);
3552   if (Args.size() > 1)
3553     llvm::cl::ParseCommandLineOptions(Args.size(), Args.data());
3554 
3555   // Look up any provided build IDs, then append them to the input filenames.
3556   for (const opt::Arg *A : InputArgs.filtered(OBJDUMP_build_id)) {
3557     object::BuildID BuildID = parseBuildIDArg(A);
3558     std::optional<std::string> Path = BIDFetcher->fetch(BuildID);
3559     if (!Path) {
3560       reportCmdLineError(A->getSpelling() + ": could not find build ID '" +
3561                          A->getValue() + "'");
3562     }
3563     InputFilenames.push_back(std::move(*Path));
3564   }
3565 
3566   // objdump defaults to a.out if no filenames specified.
3567   if (InputFilenames.empty())
3568     InputFilenames.push_back("a.out");
3569 }
3570 
3571 int llvm_objdump_main(int argc, char **argv, const llvm::ToolContext &) {
3572   using namespace llvm;
3573 
3574   ToolName = argv[0];
3575   std::unique_ptr<CommonOptTable> T;
3576   OptSpecifier Unknown, HelpFlag, HelpHiddenFlag, VersionFlag;
3577 
3578   StringRef Stem = sys::path::stem(ToolName);
3579   auto Is = [=](StringRef Tool) {
3580     // We need to recognize the following filenames:
3581     //
3582     // llvm-objdump -> objdump
3583     // llvm-otool-10.exe -> otool
3584     // powerpc64-unknown-freebsd13-objdump -> objdump
3585     auto I = Stem.rfind_insensitive(Tool);
3586     return I != StringRef::npos &&
3587            (I + Tool.size() == Stem.size() || !isAlnum(Stem[I + Tool.size()]));
3588   };
3589   if (Is("otool")) {
3590     T = std::make_unique<OtoolOptTable>();
3591     Unknown = OTOOL_UNKNOWN;
3592     HelpFlag = OTOOL_help;
3593     HelpHiddenFlag = OTOOL_help_hidden;
3594     VersionFlag = OTOOL_version;
3595   } else {
3596     T = std::make_unique<ObjdumpOptTable>();
3597     Unknown = OBJDUMP_UNKNOWN;
3598     HelpFlag = OBJDUMP_help;
3599     HelpHiddenFlag = OBJDUMP_help_hidden;
3600     VersionFlag = OBJDUMP_version;
3601   }
3602 
3603   BumpPtrAllocator A;
3604   StringSaver Saver(A);
3605   opt::InputArgList InputArgs =
3606       T->parseArgs(argc, argv, Unknown, Saver,
3607                    [&](StringRef Msg) { reportCmdLineError(Msg); });
3608 
3609   if (InputArgs.size() == 0 || InputArgs.hasArg(HelpFlag)) {
3610     T->printHelp(ToolName);
3611     return 0;
3612   }
3613   if (InputArgs.hasArg(HelpHiddenFlag)) {
3614     T->printHelp(ToolName, /*ShowHidden=*/true);
3615     return 0;
3616   }
3617 
3618   // Initialize targets and assembly printers/parsers.
3619   InitializeAllTargetInfos();
3620   InitializeAllTargetMCs();
3621   InitializeAllDisassemblers();
3622 
3623   if (InputArgs.hasArg(VersionFlag)) {
3624     cl::PrintVersionMessage();
3625     if (!Is("otool")) {
3626       outs() << '\n';
3627       TargetRegistry::printRegisteredTargetsForVersion(outs());
3628     }
3629     return 0;
3630   }
3631 
3632   // Initialize debuginfod.
3633   const bool ShouldUseDebuginfodByDefault =
3634       InputArgs.hasArg(OBJDUMP_build_id) || canUseDebuginfod();
3635   std::vector<std::string> DebugFileDirectories =
3636       InputArgs.getAllArgValues(OBJDUMP_debug_file_directory);
3637   if (InputArgs.hasFlag(OBJDUMP_debuginfod, OBJDUMP_no_debuginfod,
3638                         ShouldUseDebuginfodByDefault)) {
3639     HTTPClient::initialize();
3640     BIDFetcher =
3641         std::make_unique<DebuginfodFetcher>(std::move(DebugFileDirectories));
3642   } else {
3643     BIDFetcher =
3644         std::make_unique<BuildIDFetcher>(std::move(DebugFileDirectories));
3645   }
3646 
3647   if (Is("otool"))
3648     parseOtoolOptions(InputArgs);
3649   else
3650     parseObjdumpOptions(InputArgs);
3651 
3652   if (StartAddress >= StopAddress)
3653     reportCmdLineError("start address should be less than stop address");
3654 
3655   // Removes trailing separators from prefix.
3656   while (!Prefix.empty() && sys::path::is_separator(Prefix.back()))
3657     Prefix.pop_back();
3658 
3659   if (AllHeaders)
3660     ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations =
3661         SectionHeaders = SymbolTable = true;
3662 
3663   if (DisassembleAll || PrintSource || PrintLines || TracebackTable ||
3664       !DisassembleSymbols.empty())
3665     Disassemble = true;
3666 
3667   if (!ArchiveHeaders && !Disassemble && DwarfDumpType == DIDT_Null &&
3668       !DynamicRelocations && !FileHeaders && !PrivateHeaders && !RawClangAST &&
3669       !Relocations && !SectionHeaders && !SectionContents && !SymbolTable &&
3670       !DynamicSymbolTable && !UnwindInfo && !FaultMapSection && !Offloading &&
3671       !(MachOOpt &&
3672         (Bind || DataInCode || ChainedFixups || DyldInfo || DylibId ||
3673          DylibsUsed || ExportsTrie || FirstPrivateHeader ||
3674          FunctionStartsType != FunctionStartsMode::None || IndirectSymbols ||
3675          InfoPlist || LazyBind || LinkOptHints || ObjcMetaData || Rebase ||
3676          Rpaths || UniversalHeaders || WeakBind || !FilterSections.empty()))) {
3677     T->printHelp(ToolName);
3678     return 2;
3679   }
3680 
3681   DisasmSymbolSet.insert(DisassembleSymbols.begin(), DisassembleSymbols.end());
3682 
3683   llvm::for_each(InputFilenames, dumpInput);
3684 
3685   warnOnNoMatchForSections();
3686 
3687   return EXIT_SUCCESS;
3688 }
3689