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