xref: /llvm-project/llvm/tools/llvm-objdump/llvm-objdump.cpp (revision 55f1fbf005fef1e4024b2b44db0842f23fc5ea64)
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[Index], 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     ArrayRef<uint8_t> ThisBytes = Bytes.slice(Index - SectionAddr);
1026     bool Disassembled =
1027         DisAsm->getInstruction(Inst, Size, ThisBytes, Index, nulls());
1028     if (Size == 0)
1029       Size = std::min(ThisBytes.size(),
1030                       DisAsm->suggestBytesToSkip(ThisBytes, Index));
1031 
1032     if (Disassembled && MIA) {
1033       uint64_t Target;
1034       bool TargetKnown = MIA->evaluateBranch(Inst, Index, Size, Target);
1035       // On PowerPC, if the address of a branch is the same as the target, it
1036       // means that it's a function call. Do not mark the label for this case.
1037       if (TargetKnown && (Target >= Start && Target < End) &&
1038           !Labels.count(Target) &&
1039           !(STI->getTargetTriple().isPPC() && Target == Index))
1040         Labels[Target] = ("L" + Twine(LabelCount++)).str();
1041     }
1042     Index += Size;
1043   }
1044 }
1045 
1046 // Create an MCSymbolizer for the target and add it to the MCDisassembler.
1047 // This is currently only used on AMDGPU, and assumes the format of the
1048 // void * argument passed to AMDGPU's createMCSymbolizer.
1049 static void addSymbolizer(
1050     MCContext &Ctx, const Target *Target, StringRef TripleName,
1051     MCDisassembler *DisAsm, uint64_t SectionAddr, ArrayRef<uint8_t> Bytes,
1052     SectionSymbolsTy &Symbols,
1053     std::vector<std::unique_ptr<std::string>> &SynthesizedLabelNames) {
1054 
1055   std::unique_ptr<MCRelocationInfo> RelInfo(
1056       Target->createMCRelocationInfo(TripleName, Ctx));
1057   if (!RelInfo)
1058     return;
1059   std::unique_ptr<MCSymbolizer> Symbolizer(Target->createMCSymbolizer(
1060       TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1061   MCSymbolizer *SymbolizerPtr = &*Symbolizer;
1062   DisAsm->setSymbolizer(std::move(Symbolizer));
1063 
1064   if (!SymbolizeOperands)
1065     return;
1066 
1067   // Synthesize labels referenced by branch instructions by
1068   // disassembling, discarding the output, and collecting the referenced
1069   // addresses from the symbolizer.
1070   for (size_t Index = 0; Index != Bytes.size();) {
1071     MCInst Inst;
1072     uint64_t Size;
1073     ArrayRef<uint8_t> ThisBytes = Bytes.slice(Index - SectionAddr);
1074     DisAsm->getInstruction(Inst, Size, ThisBytes, Index, nulls());
1075     if (Size == 0)
1076       Size = std::min(ThisBytes.size(),
1077                       DisAsm->suggestBytesToSkip(ThisBytes, Index));
1078     Index += Size;
1079   }
1080   ArrayRef<uint64_t> LabelAddrsRef = SymbolizerPtr->getReferencedAddresses();
1081   // Copy and sort to remove duplicates.
1082   std::vector<uint64_t> LabelAddrs;
1083   LabelAddrs.insert(LabelAddrs.end(), LabelAddrsRef.begin(),
1084                     LabelAddrsRef.end());
1085   llvm::sort(LabelAddrs);
1086   LabelAddrs.resize(std::unique(LabelAddrs.begin(), LabelAddrs.end()) -
1087                     LabelAddrs.begin());
1088   // Add the labels.
1089   for (unsigned LabelNum = 0; LabelNum != LabelAddrs.size(); ++LabelNum) {
1090     auto Name = std::make_unique<std::string>();
1091     *Name = (Twine("L") + Twine(LabelNum)).str();
1092     SynthesizedLabelNames.push_back(std::move(Name));
1093     Symbols.push_back(SymbolInfoTy(
1094         LabelAddrs[LabelNum], *SynthesizedLabelNames.back(), ELF::STT_NOTYPE));
1095   }
1096   llvm::stable_sort(Symbols);
1097   // Recreate the symbolizer with the new symbols list.
1098   RelInfo.reset(Target->createMCRelocationInfo(TripleName, Ctx));
1099   Symbolizer.reset(Target->createMCSymbolizer(
1100       TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1101   DisAsm->setSymbolizer(std::move(Symbolizer));
1102 }
1103 
1104 static StringRef getSegmentName(const MachOObjectFile *MachO,
1105                                 const SectionRef &Section) {
1106   if (MachO) {
1107     DataRefImpl DR = Section.getRawDataRefImpl();
1108     StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1109     return SegmentName;
1110   }
1111   return "";
1112 }
1113 
1114 static void emitPostInstructionInfo(formatted_raw_ostream &FOS,
1115                                     const MCAsmInfo &MAI,
1116                                     const MCSubtargetInfo &STI,
1117                                     StringRef Comments,
1118                                     LiveVariablePrinter &LVP) {
1119   do {
1120     if (!Comments.empty()) {
1121       // Emit a line of comments.
1122       StringRef Comment;
1123       std::tie(Comment, Comments) = Comments.split('\n');
1124       // MAI.getCommentColumn() assumes that instructions are printed at the
1125       // position of 8, while getInstStartColumn() returns the actual position.
1126       unsigned CommentColumn =
1127           MAI.getCommentColumn() - 8 + getInstStartColumn(STI);
1128       FOS.PadToColumn(CommentColumn);
1129       FOS << MAI.getCommentString() << ' ' << Comment;
1130     }
1131     LVP.printAfterInst(FOS);
1132     FOS << '\n';
1133   } while (!Comments.empty());
1134   FOS.flush();
1135 }
1136 
1137 static void createFakeELFSections(ObjectFile &Obj) {
1138   assert(Obj.isELF());
1139   if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(&Obj))
1140     Elf32LEObj->createFakeSections();
1141   else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(&Obj))
1142     Elf64LEObj->createFakeSections();
1143   else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(&Obj))
1144     Elf32BEObj->createFakeSections();
1145   else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(&Obj))
1146     Elf64BEObj->createFakeSections();
1147   else
1148     llvm_unreachable("Unsupported binary format");
1149 }
1150 
1151 static void disassembleObject(const Target *TheTarget, ObjectFile &Obj,
1152                               MCContext &Ctx, MCDisassembler *PrimaryDisAsm,
1153                               MCDisassembler *SecondaryDisAsm,
1154                               const MCInstrAnalysis *MIA, MCInstPrinter *IP,
1155                               const MCSubtargetInfo *PrimarySTI,
1156                               const MCSubtargetInfo *SecondarySTI,
1157                               PrettyPrinter &PIP, SourcePrinter &SP,
1158                               bool InlineRelocs) {
1159   const MCSubtargetInfo *STI = PrimarySTI;
1160   MCDisassembler *DisAsm = PrimaryDisAsm;
1161   bool PrimaryIsThumb = false;
1162   if (isArmElf(Obj))
1163     PrimaryIsThumb = STI->checkFeatures("+thumb-mode");
1164 
1165   std::map<SectionRef, std::vector<RelocationRef>> RelocMap;
1166   if (InlineRelocs)
1167     RelocMap = getRelocsMap(Obj);
1168   bool Is64Bits = Obj.getBytesInAddress() > 4;
1169 
1170   // Create a mapping from virtual address to symbol name.  This is used to
1171   // pretty print the symbols while disassembling.
1172   std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1173   SectionSymbolsTy AbsoluteSymbols;
1174   const StringRef FileName = Obj.getFileName();
1175   const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(&Obj);
1176   for (const SymbolRef &Symbol : Obj.symbols()) {
1177     Expected<StringRef> NameOrErr = Symbol.getName();
1178     if (!NameOrErr) {
1179       reportWarning(toString(NameOrErr.takeError()), FileName);
1180       continue;
1181     }
1182     if (NameOrErr->empty() && !(Obj.isXCOFF() && SymbolDescription))
1183       continue;
1184 
1185     if (Obj.isELF() && getElfSymbolType(Obj, Symbol) == ELF::STT_SECTION)
1186       continue;
1187 
1188     if (MachO) {
1189       // __mh_(execute|dylib|dylinker|bundle|preload|object)_header are special
1190       // symbols that support MachO header introspection. They do not bind to
1191       // code locations and are irrelevant for disassembly.
1192       if (NameOrErr->startswith("__mh_") && NameOrErr->endswith("_header"))
1193         continue;
1194       // Don't ask a Mach-O STAB symbol for its section unless you know that
1195       // STAB symbol's section field refers to a valid section index. Otherwise
1196       // the symbol may error trying to load a section that does not exist.
1197       DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
1198       uint8_t NType = (MachO->is64Bit() ?
1199                        MachO->getSymbol64TableEntry(SymDRI).n_type:
1200                        MachO->getSymbolTableEntry(SymDRI).n_type);
1201       if (NType & MachO::N_STAB)
1202         continue;
1203     }
1204 
1205     section_iterator SecI = unwrapOrError(Symbol.getSection(), FileName);
1206     if (SecI != Obj.section_end())
1207       AllSymbols[*SecI].push_back(createSymbolInfo(Obj, Symbol));
1208     else
1209       AbsoluteSymbols.push_back(createSymbolInfo(Obj, Symbol));
1210   }
1211 
1212   if (AllSymbols.empty() && Obj.isELF())
1213     addDynamicElfSymbols(cast<ELFObjectFileBase>(Obj), AllSymbols);
1214 
1215   if (Obj.isWasm())
1216     addMissingWasmCodeSymbols(cast<WasmObjectFile>(Obj), AllSymbols);
1217 
1218   if (Obj.isELF() && Obj.sections().empty())
1219     createFakeELFSections(Obj);
1220 
1221   BumpPtrAllocator A;
1222   StringSaver Saver(A);
1223   addPltEntries(Obj, AllSymbols, Saver);
1224 
1225   // Create a mapping from virtual address to section. An empty section can
1226   // cause more than one section at the same address. Sort such sections to be
1227   // before same-addressed non-empty sections so that symbol lookups prefer the
1228   // non-empty section.
1229   std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1230   for (SectionRef Sec : Obj.sections())
1231     SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1232   llvm::stable_sort(SectionAddresses, [](const auto &LHS, const auto &RHS) {
1233     if (LHS.first != RHS.first)
1234       return LHS.first < RHS.first;
1235     return LHS.second.getSize() < RHS.second.getSize();
1236   });
1237 
1238   // Linked executables (.exe and .dll files) typically don't include a real
1239   // symbol table but they might contain an export table.
1240   if (const auto *COFFObj = dyn_cast<COFFObjectFile>(&Obj)) {
1241     for (const auto &ExportEntry : COFFObj->export_directories()) {
1242       StringRef Name;
1243       if (Error E = ExportEntry.getSymbolName(Name))
1244         reportError(std::move(E), Obj.getFileName());
1245       if (Name.empty())
1246         continue;
1247 
1248       uint32_t RVA;
1249       if (Error E = ExportEntry.getExportRVA(RVA))
1250         reportError(std::move(E), Obj.getFileName());
1251 
1252       uint64_t VA = COFFObj->getImageBase() + RVA;
1253       auto Sec = partition_point(
1254           SectionAddresses, [VA](const std::pair<uint64_t, SectionRef> &O) {
1255             return O.first <= VA;
1256           });
1257       if (Sec != SectionAddresses.begin()) {
1258         --Sec;
1259         AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
1260       } else
1261         AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
1262     }
1263   }
1264 
1265   // Sort all the symbols, this allows us to use a simple binary search to find
1266   // Multiple symbols can have the same address. Use a stable sort to stabilize
1267   // the output.
1268   StringSet<> FoundDisasmSymbolSet;
1269   for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1270     llvm::stable_sort(SecSyms.second);
1271   llvm::stable_sort(AbsoluteSymbols);
1272 
1273   std::unique_ptr<DWARFContext> DICtx;
1274   LiveVariablePrinter LVP(*Ctx.getRegisterInfo(), *STI);
1275 
1276   if (DbgVariables != DVDisabled) {
1277     DICtx = DWARFContext::create(Obj);
1278     for (const std::unique_ptr<DWARFUnit> &CU : DICtx->compile_units())
1279       LVP.addCompileUnit(CU->getUnitDIE(false));
1280   }
1281 
1282   LLVM_DEBUG(LVP.dump());
1283 
1284   std::unordered_map<uint64_t, BBAddrMap> AddrToBBAddrMap;
1285   auto ReadBBAddrMap = [&](Optional<unsigned> SectionIndex = None) {
1286     AddrToBBAddrMap.clear();
1287     if (const auto *Elf = dyn_cast<ELFObjectFileBase>(&Obj)) {
1288       auto BBAddrMapsOrErr = Elf->readBBAddrMap(SectionIndex);
1289       if (!BBAddrMapsOrErr)
1290           reportWarning(toString(BBAddrMapsOrErr.takeError()),
1291                         Obj.getFileName());
1292       for (auto &FunctionBBAddrMap : *BBAddrMapsOrErr)
1293         AddrToBBAddrMap.emplace(FunctionBBAddrMap.Addr,
1294                                 std::move(FunctionBBAddrMap));
1295     }
1296   };
1297 
1298   // For non-relocatable objects, Read all LLVM_BB_ADDR_MAP sections into a
1299   // single mapping, since they don't have any conflicts.
1300   if (SymbolizeOperands && !Obj.isRelocatableObject())
1301     ReadBBAddrMap();
1302 
1303   for (const SectionRef &Section : ToolSectionFilter(Obj)) {
1304     if (FilterSections.empty() && !DisassembleAll &&
1305         (!Section.isText() || Section.isVirtual()))
1306       continue;
1307 
1308     uint64_t SectionAddr = Section.getAddress();
1309     uint64_t SectSize = Section.getSize();
1310     if (!SectSize)
1311       continue;
1312 
1313     // For relocatable object files, read the LLVM_BB_ADDR_MAP section
1314     // corresponding to this section, if present.
1315     if (SymbolizeOperands && Obj.isRelocatableObject())
1316       ReadBBAddrMap(Section.getIndex());
1317 
1318     // Get the list of all the symbols in this section.
1319     SectionSymbolsTy &Symbols = AllSymbols[Section];
1320     std::vector<MappingSymbolPair> MappingSymbols;
1321     if (hasMappingSymbols(Obj)) {
1322       for (const auto &Symb : Symbols) {
1323         uint64_t Address = Symb.Addr;
1324         StringRef Name = Symb.Name;
1325         if (Name.startswith("$d"))
1326           MappingSymbols.emplace_back(Address - SectionAddr, 'd');
1327         if (Name.startswith("$x"))
1328           MappingSymbols.emplace_back(Address - SectionAddr, 'x');
1329         if (Name.startswith("$a"))
1330           MappingSymbols.emplace_back(Address - SectionAddr, 'a');
1331         if (Name.startswith("$t"))
1332           MappingSymbols.emplace_back(Address - SectionAddr, 't');
1333       }
1334     }
1335 
1336     llvm::sort(MappingSymbols);
1337 
1338     ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(
1339         unwrapOrError(Section.getContents(), Obj.getFileName()));
1340 
1341     std::vector<std::unique_ptr<std::string>> SynthesizedLabelNames;
1342     if (Obj.isELF() && Obj.getArch() == Triple::amdgcn) {
1343       // AMDGPU disassembler uses symbolizer for printing labels
1344       addSymbolizer(Ctx, TheTarget, TripleName, DisAsm, SectionAddr, Bytes,
1345                     Symbols, SynthesizedLabelNames);
1346     }
1347 
1348     StringRef SegmentName = getSegmentName(MachO, Section);
1349     StringRef SectionName = unwrapOrError(Section.getName(), Obj.getFileName());
1350     // If the section has no symbol at the start, just insert a dummy one.
1351     if (Symbols.empty() || Symbols[0].Addr != 0) {
1352       Symbols.insert(Symbols.begin(),
1353                      createDummySymbolInfo(Obj, SectionAddr, SectionName,
1354                                            Section.isText() ? ELF::STT_FUNC
1355                                                             : ELF::STT_OBJECT));
1356     }
1357 
1358     SmallString<40> Comments;
1359     raw_svector_ostream CommentStream(Comments);
1360 
1361     uint64_t VMAAdjustment = 0;
1362     if (shouldAdjustVA(Section))
1363       VMAAdjustment = AdjustVMA;
1364 
1365     // In executable and shared objects, r_offset holds a virtual address.
1366     // Subtract SectionAddr from the r_offset field of a relocation to get
1367     // the section offset.
1368     uint64_t RelAdjustment = Obj.isRelocatableObject() ? 0 : SectionAddr;
1369     uint64_t Size;
1370     uint64_t Index;
1371     bool PrintedSection = false;
1372     std::vector<RelocationRef> Rels = RelocMap[Section];
1373     std::vector<RelocationRef>::const_iterator RelCur = Rels.begin();
1374     std::vector<RelocationRef>::const_iterator RelEnd = Rels.end();
1375     // Disassemble symbol by symbol.
1376     for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) {
1377       std::string SymbolName = Symbols[SI].Name.str();
1378       if (Demangle)
1379         SymbolName = demangle(SymbolName);
1380 
1381       // Skip if --disassemble-symbols is not empty and the symbol is not in
1382       // the list.
1383       if (!DisasmSymbolSet.empty() && !DisasmSymbolSet.count(SymbolName))
1384         continue;
1385 
1386       uint64_t Start = Symbols[SI].Addr;
1387       if (Start < SectionAddr || StopAddress <= Start)
1388         continue;
1389       else
1390         FoundDisasmSymbolSet.insert(SymbolName);
1391 
1392       // The end is the section end, the beginning of the next symbol, or
1393       // --stop-address.
1394       uint64_t End = std::min<uint64_t>(SectionAddr + SectSize, StopAddress);
1395       if (SI + 1 < SE)
1396         End = std::min(End, Symbols[SI + 1].Addr);
1397       if (Start >= End || End <= StartAddress)
1398         continue;
1399       Start -= SectionAddr;
1400       End -= SectionAddr;
1401 
1402       if (!PrintedSection) {
1403         PrintedSection = true;
1404         outs() << "\nDisassembly of section ";
1405         if (!SegmentName.empty())
1406           outs() << SegmentName << ",";
1407         outs() << SectionName << ":\n";
1408       }
1409 
1410       outs() << '\n';
1411       if (LeadingAddr)
1412         outs() << format(Is64Bits ? "%016" PRIx64 " " : "%08" PRIx64 " ",
1413                          SectionAddr + Start + VMAAdjustment);
1414       if (Obj.isXCOFF() && SymbolDescription) {
1415         outs() << getXCOFFSymbolDescription(Symbols[SI], SymbolName) << ":\n";
1416       } else
1417         outs() << '<' << SymbolName << ">:\n";
1418 
1419       // Don't print raw contents of a virtual section. A virtual section
1420       // doesn't have any contents in the file.
1421       if (Section.isVirtual()) {
1422         outs() << "...\n";
1423         continue;
1424       }
1425 
1426       auto Status = DisAsm->onSymbolStart(Symbols[SI], Size,
1427                                           Bytes.slice(Start, End - Start),
1428                                           SectionAddr + Start, CommentStream);
1429       // To have round trippable disassembly, we fall back to decoding the
1430       // remaining bytes as instructions.
1431       //
1432       // If there is a failure, we disassemble the failed region as bytes before
1433       // falling back. The target is expected to print nothing in this case.
1434       //
1435       // If there is Success or SoftFail i.e no 'real' failure, we go ahead by
1436       // Size bytes before falling back.
1437       // So if the entire symbol is 'eaten' by the target:
1438       //   Start += Size  // Now Start = End and we will never decode as
1439       //                  // instructions
1440       //
1441       // Right now, most targets return None i.e ignore to treat a symbol
1442       // separately. But WebAssembly decodes preludes for some symbols.
1443       //
1444       if (Status) {
1445         if (Status.value() == MCDisassembler::Fail) {
1446           outs() << "// Error in decoding " << SymbolName
1447                  << " : Decoding failed region as bytes.\n";
1448           for (uint64_t I = 0; I < Size; ++I) {
1449             outs() << "\t.byte\t " << format_hex(Bytes[I], 1, /*Upper=*/true)
1450                    << "\n";
1451           }
1452         }
1453       } else {
1454         Size = 0;
1455       }
1456 
1457       Start += Size;
1458 
1459       Index = Start;
1460       if (SectionAddr < StartAddress)
1461         Index = std::max<uint64_t>(Index, StartAddress - SectionAddr);
1462 
1463       // If there is a data/common symbol inside an ELF text section and we are
1464       // only disassembling text (applicable all architectures), we are in a
1465       // situation where we must print the data and not disassemble it.
1466       if (Obj.isELF() && !DisassembleAll && Section.isText()) {
1467         uint8_t SymTy = Symbols[SI].Type;
1468         if (SymTy == ELF::STT_OBJECT || SymTy == ELF::STT_COMMON) {
1469           dumpELFData(SectionAddr, Index, End, Bytes);
1470           Index = End;
1471         }
1472       }
1473 
1474       bool CheckARMELFData = hasMappingSymbols(Obj) &&
1475                              Symbols[SI].Type != ELF::STT_OBJECT &&
1476                              !DisassembleAll;
1477       bool DumpARMELFData = false;
1478       formatted_raw_ostream FOS(outs());
1479 
1480       std::unordered_map<uint64_t, std::string> AllLabels;
1481       std::unordered_map<uint64_t, std::vector<std::string>> BBAddrMapLabels;
1482       if (SymbolizeOperands) {
1483         collectLocalBranchTargets(Bytes, MIA, DisAsm, IP, PrimarySTI,
1484                                   SectionAddr, Index, End, AllLabels);
1485         collectBBAddrMapLabels(AddrToBBAddrMap, SectionAddr, Index, End,
1486                                BBAddrMapLabels);
1487       }
1488 
1489       while (Index < End) {
1490         // ARM and AArch64 ELF binaries can interleave data and text in the
1491         // same section. We rely on the markers introduced to understand what
1492         // we need to dump. If the data marker is within a function, it is
1493         // denoted as a word/short etc.
1494         if (CheckARMELFData) {
1495           char Kind = getMappingSymbolKind(MappingSymbols, Index);
1496           DumpARMELFData = Kind == 'd';
1497           if (SecondarySTI) {
1498             if (Kind == 'a') {
1499               STI = PrimaryIsThumb ? SecondarySTI : PrimarySTI;
1500               DisAsm = PrimaryIsThumb ? SecondaryDisAsm : PrimaryDisAsm;
1501             } else if (Kind == 't') {
1502               STI = PrimaryIsThumb ? PrimarySTI : SecondarySTI;
1503               DisAsm = PrimaryIsThumb ? PrimaryDisAsm : SecondaryDisAsm;
1504             }
1505           }
1506         }
1507 
1508         if (DumpARMELFData) {
1509           Size = dumpARMELFData(SectionAddr, Index, End, Obj, Bytes,
1510                                 MappingSymbols, FOS);
1511         } else {
1512           // When -z or --disassemble-zeroes are given we always dissasemble
1513           // them. Otherwise we might want to skip zero bytes we see.
1514           if (!DisassembleZeroes) {
1515             uint64_t MaxOffset = End - Index;
1516             // For --reloc: print zero blocks patched by relocations, so that
1517             // relocations can be shown in the dump.
1518             if (RelCur != RelEnd)
1519               MaxOffset = std::min(RelCur->getOffset() - RelAdjustment - Index,
1520                                    MaxOffset);
1521 
1522             if (size_t N =
1523                     countSkippableZeroBytes(Bytes.slice(Index, MaxOffset))) {
1524               FOS << "\t\t..." << '\n';
1525               Index += N;
1526               continue;
1527             }
1528           }
1529 
1530           // Print local label if there's any.
1531           auto Iter1 = BBAddrMapLabels.find(SectionAddr + Index);
1532           if (Iter1 != BBAddrMapLabels.end()) {
1533             for (StringRef Label : Iter1->second)
1534               FOS << "<" << Label << ">:\n";
1535           } else {
1536             auto Iter2 = AllLabels.find(SectionAddr + Index);
1537             if (Iter2 != AllLabels.end())
1538               FOS << "<" << Iter2->second << ">:\n";
1539           }
1540 
1541           // Disassemble a real instruction or a data when disassemble all is
1542           // provided
1543           MCInst Inst;
1544           ArrayRef<uint8_t> ThisBytes = Bytes.slice(Index);
1545           uint64_t ThisAddr = SectionAddr + Index;
1546           bool Disassembled = DisAsm->getInstruction(Inst, Size, ThisBytes,
1547                                                      ThisAddr, CommentStream);
1548           if (Size == 0)
1549             Size = std::min(ThisBytes.size(),
1550                             DisAsm->suggestBytesToSkip(ThisBytes, ThisAddr));
1551 
1552           LVP.update({Index, Section.getIndex()},
1553                      {Index + Size, Section.getIndex()}, Index + Size != End);
1554 
1555           IP->setCommentStream(CommentStream);
1556 
1557           PIP.printInst(
1558               *IP, Disassembled ? &Inst : nullptr, Bytes.slice(Index, Size),
1559               {SectionAddr + Index + VMAAdjustment, Section.getIndex()}, FOS,
1560               "", *STI, &SP, Obj.getFileName(), &Rels, LVP);
1561 
1562           IP->setCommentStream(llvm::nulls());
1563 
1564           // If disassembly has failed, avoid analysing invalid/incomplete
1565           // instruction information. Otherwise, try to resolve the target
1566           // address (jump target or memory operand address) and print it on the
1567           // right of the instruction.
1568           if (Disassembled && MIA) {
1569             // Branch targets are printed just after the instructions.
1570             llvm::raw_ostream *TargetOS = &FOS;
1571             uint64_t Target;
1572             bool PrintTarget =
1573                 MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target);
1574             if (!PrintTarget)
1575               if (Optional<uint64_t> MaybeTarget =
1576                       MIA->evaluateMemoryOperandAddress(
1577                           Inst, STI, SectionAddr + Index, Size)) {
1578                 Target = *MaybeTarget;
1579                 PrintTarget = true;
1580                 // Do not print real address when symbolizing.
1581                 if (!SymbolizeOperands) {
1582                   // Memory operand addresses are printed as comments.
1583                   TargetOS = &CommentStream;
1584                   *TargetOS << "0x" << Twine::utohexstr(Target);
1585                 }
1586               }
1587             if (PrintTarget) {
1588               // In a relocatable object, the target's section must reside in
1589               // the same section as the call instruction or it is accessed
1590               // through a relocation.
1591               //
1592               // In a non-relocatable object, the target may be in any section.
1593               // In that case, locate the section(s) containing the target
1594               // address and find the symbol in one of those, if possible.
1595               //
1596               // N.B. We don't walk the relocations in the relocatable case yet.
1597               std::vector<const SectionSymbolsTy *> TargetSectionSymbols;
1598               if (!Obj.isRelocatableObject()) {
1599                 auto It = llvm::partition_point(
1600                     SectionAddresses,
1601                     [=](const std::pair<uint64_t, SectionRef> &O) {
1602                       return O.first <= Target;
1603                     });
1604                 uint64_t TargetSecAddr = 0;
1605                 while (It != SectionAddresses.begin()) {
1606                   --It;
1607                   if (TargetSecAddr == 0)
1608                     TargetSecAddr = It->first;
1609                   if (It->first != TargetSecAddr)
1610                     break;
1611                   TargetSectionSymbols.push_back(&AllSymbols[It->second]);
1612                 }
1613               } else {
1614                 TargetSectionSymbols.push_back(&Symbols);
1615               }
1616               TargetSectionSymbols.push_back(&AbsoluteSymbols);
1617 
1618               // Find the last symbol in the first candidate section whose
1619               // offset is less than or equal to the target. If there are no
1620               // such symbols, try in the next section and so on, before finally
1621               // using the nearest preceding absolute symbol (if any), if there
1622               // are no other valid symbols.
1623               const SymbolInfoTy *TargetSym = nullptr;
1624               for (const SectionSymbolsTy *TargetSymbols :
1625                    TargetSectionSymbols) {
1626                 auto It = llvm::partition_point(
1627                     *TargetSymbols,
1628                     [=](const SymbolInfoTy &O) { return O.Addr <= Target; });
1629                 if (It != TargetSymbols->begin()) {
1630                   TargetSym = &*(It - 1);
1631                   break;
1632                 }
1633               }
1634 
1635               // Print the labels corresponding to the target if there's any.
1636               bool BBAddrMapLabelAvailable = BBAddrMapLabels.count(Target);
1637               bool LabelAvailable = AllLabels.count(Target);
1638               if (TargetSym != nullptr) {
1639                 uint64_t TargetAddress = TargetSym->Addr;
1640                 uint64_t Disp = Target - TargetAddress;
1641                 std::string TargetName = TargetSym->Name.str();
1642                 if (Demangle)
1643                   TargetName = demangle(TargetName);
1644 
1645                 *TargetOS << " <";
1646                 if (!Disp) {
1647                   // Always Print the binary symbol precisely corresponding to
1648                   // the target address.
1649                   *TargetOS << TargetName;
1650                 } else if (BBAddrMapLabelAvailable) {
1651                   *TargetOS << BBAddrMapLabels[Target].front();
1652                 } else if (LabelAvailable) {
1653                   *TargetOS << AllLabels[Target];
1654                 } else {
1655                   // Always Print the binary symbol plus an offset if there's no
1656                   // local label corresponding to the target address.
1657                   *TargetOS << TargetName << "+0x" << Twine::utohexstr(Disp);
1658                 }
1659                 *TargetOS << ">";
1660               } else if (BBAddrMapLabelAvailable) {
1661                 *TargetOS << " <" << BBAddrMapLabels[Target].front() << ">";
1662               } else if (LabelAvailable) {
1663                 *TargetOS << " <" << AllLabels[Target] << ">";
1664               }
1665               // By convention, each record in the comment stream should be
1666               // terminated.
1667               if (TargetOS == &CommentStream)
1668                 *TargetOS << "\n";
1669             }
1670           }
1671         }
1672 
1673         assert(Ctx.getAsmInfo());
1674         emitPostInstructionInfo(FOS, *Ctx.getAsmInfo(), *STI,
1675                                 CommentStream.str(), LVP);
1676         Comments.clear();
1677 
1678         // Hexagon does this in pretty printer
1679         if (Obj.getArch() != Triple::hexagon) {
1680           // Print relocation for instruction and data.
1681           while (RelCur != RelEnd) {
1682             uint64_t Offset = RelCur->getOffset() - RelAdjustment;
1683             // If this relocation is hidden, skip it.
1684             if (getHidden(*RelCur) || SectionAddr + Offset < StartAddress) {
1685               ++RelCur;
1686               continue;
1687             }
1688 
1689             // Stop when RelCur's offset is past the disassembled
1690             // instruction/data. Note that it's possible the disassembled data
1691             // is not the complete data: we might see the relocation printed in
1692             // the middle of the data, but this matches the binutils objdump
1693             // output.
1694             if (Offset >= Index + Size)
1695               break;
1696 
1697             // When --adjust-vma is used, update the address printed.
1698             if (RelCur->getSymbol() != Obj.symbol_end()) {
1699               Expected<section_iterator> SymSI =
1700                   RelCur->getSymbol()->getSection();
1701               if (SymSI && *SymSI != Obj.section_end() &&
1702                   shouldAdjustVA(**SymSI))
1703                 Offset += AdjustVMA;
1704             }
1705 
1706             printRelocation(FOS, Obj.getFileName(), *RelCur,
1707                             SectionAddr + Offset, Is64Bits);
1708             LVP.printAfterOtherLine(FOS, true);
1709             ++RelCur;
1710           }
1711         }
1712 
1713         Index += Size;
1714       }
1715     }
1716   }
1717   StringSet<> MissingDisasmSymbolSet =
1718       set_difference(DisasmSymbolSet, FoundDisasmSymbolSet);
1719   for (StringRef Sym : MissingDisasmSymbolSet.keys())
1720     reportWarning("failed to disassemble missing symbol " + Sym, FileName);
1721 }
1722 
1723 static void disassembleObject(ObjectFile *Obj, bool InlineRelocs) {
1724   const Target *TheTarget = getTarget(Obj);
1725 
1726   // Package up features to be passed to target/subtarget
1727   SubtargetFeatures Features = Obj->getFeatures();
1728   if (!MAttrs.empty()) {
1729     for (unsigned I = 0; I != MAttrs.size(); ++I)
1730       Features.AddFeature(MAttrs[I]);
1731   } else if (MCPU.empty() && Obj->getArch() == llvm::Triple::aarch64) {
1732     Features.AddFeature("+all");
1733   }
1734 
1735   std::unique_ptr<const MCRegisterInfo> MRI(
1736       TheTarget->createMCRegInfo(TripleName));
1737   if (!MRI)
1738     reportError(Obj->getFileName(),
1739                 "no register info for target " + TripleName);
1740 
1741   // Set up disassembler.
1742   MCTargetOptions MCOptions;
1743   std::unique_ptr<const MCAsmInfo> AsmInfo(
1744       TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
1745   if (!AsmInfo)
1746     reportError(Obj->getFileName(),
1747                 "no assembly info for target " + TripleName);
1748 
1749   if (MCPU.empty())
1750     MCPU = Obj->tryGetCPUName().value_or("").str();
1751 
1752   std::unique_ptr<const MCSubtargetInfo> STI(
1753       TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1754   if (!STI)
1755     reportError(Obj->getFileName(),
1756                 "no subtarget info for target " + TripleName);
1757   std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1758   if (!MII)
1759     reportError(Obj->getFileName(),
1760                 "no instruction info for target " + TripleName);
1761   MCContext Ctx(Triple(TripleName), AsmInfo.get(), MRI.get(), STI.get());
1762   // FIXME: for now initialize MCObjectFileInfo with default values
1763   std::unique_ptr<MCObjectFileInfo> MOFI(
1764       TheTarget->createMCObjectFileInfo(Ctx, /*PIC=*/false));
1765   Ctx.setObjectFileInfo(MOFI.get());
1766 
1767   std::unique_ptr<MCDisassembler> DisAsm(
1768       TheTarget->createMCDisassembler(*STI, Ctx));
1769   if (!DisAsm)
1770     reportError(Obj->getFileName(), "no disassembler for target " + TripleName);
1771 
1772   // If we have an ARM object file, we need a second disassembler, because
1773   // ARM CPUs have two different instruction sets: ARM mode, and Thumb mode.
1774   // We use mapping symbols to switch between the two assemblers, where
1775   // appropriate.
1776   std::unique_ptr<MCDisassembler> SecondaryDisAsm;
1777   std::unique_ptr<const MCSubtargetInfo> SecondarySTI;
1778   if (isArmElf(*Obj) && !STI->checkFeatures("+mclass")) {
1779     if (STI->checkFeatures("+thumb-mode"))
1780       Features.AddFeature("-thumb-mode");
1781     else
1782       Features.AddFeature("+thumb-mode");
1783     SecondarySTI.reset(TheTarget->createMCSubtargetInfo(TripleName, MCPU,
1784                                                         Features.getString()));
1785     SecondaryDisAsm.reset(TheTarget->createMCDisassembler(*SecondarySTI, Ctx));
1786   }
1787 
1788   std::unique_ptr<const MCInstrAnalysis> MIA(
1789       TheTarget->createMCInstrAnalysis(MII.get()));
1790 
1791   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1792   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1793       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
1794   if (!IP)
1795     reportError(Obj->getFileName(),
1796                 "no instruction printer for target " + TripleName);
1797   IP->setPrintImmHex(PrintImmHex);
1798   IP->setPrintBranchImmAsAddress(true);
1799   IP->setSymbolizeOperands(SymbolizeOperands);
1800   IP->setMCInstrAnalysis(MIA.get());
1801 
1802   PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
1803   SourcePrinter SP(Obj, TheTarget->getName());
1804 
1805   for (StringRef Opt : DisassemblerOptions)
1806     if (!IP->applyTargetSpecificCLOption(Opt))
1807       reportError(Obj->getFileName(),
1808                   "Unrecognized disassembler option: " + Opt);
1809 
1810   disassembleObject(TheTarget, *Obj, Ctx, DisAsm.get(), SecondaryDisAsm.get(),
1811                     MIA.get(), IP.get(), STI.get(), SecondarySTI.get(), PIP, SP,
1812                     InlineRelocs);
1813 }
1814 
1815 void objdump::printRelocations(const ObjectFile *Obj) {
1816   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1817                                                  "%08" PRIx64;
1818 
1819   // Build a mapping from relocation target to a vector of relocation
1820   // sections. Usually, there is an only one relocation section for
1821   // each relocated section.
1822   MapVector<SectionRef, std::vector<SectionRef>> SecToRelSec;
1823   uint64_t Ndx;
1824   for (const SectionRef &Section : ToolSectionFilter(*Obj, &Ndx)) {
1825     if (Obj->isELF() && (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC))
1826       continue;
1827     if (Section.relocation_begin() == Section.relocation_end())
1828       continue;
1829     Expected<section_iterator> SecOrErr = Section.getRelocatedSection();
1830     if (!SecOrErr)
1831       reportError(Obj->getFileName(),
1832                   "section (" + Twine(Ndx) +
1833                       "): unable to get a relocation target: " +
1834                       toString(SecOrErr.takeError()));
1835     SecToRelSec[**SecOrErr].push_back(Section);
1836   }
1837 
1838   for (std::pair<SectionRef, std::vector<SectionRef>> &P : SecToRelSec) {
1839     StringRef SecName = unwrapOrError(P.first.getName(), Obj->getFileName());
1840     outs() << "\nRELOCATION RECORDS FOR [" << SecName << "]:\n";
1841     uint32_t OffsetPadding = (Obj->getBytesInAddress() > 4 ? 16 : 8);
1842     uint32_t TypePadding = 24;
1843     outs() << left_justify("OFFSET", OffsetPadding) << " "
1844            << left_justify("TYPE", TypePadding) << " "
1845            << "VALUE\n";
1846 
1847     for (SectionRef Section : P.second) {
1848       for (const RelocationRef &Reloc : Section.relocations()) {
1849         uint64_t Address = Reloc.getOffset();
1850         SmallString<32> RelocName;
1851         SmallString<32> ValueStr;
1852         if (Address < StartAddress || Address > StopAddress || getHidden(Reloc))
1853           continue;
1854         Reloc.getTypeName(RelocName);
1855         if (Error E = getRelocationValueString(Reloc, ValueStr))
1856           reportError(std::move(E), Obj->getFileName());
1857 
1858         outs() << format(Fmt.data(), Address) << " "
1859                << left_justify(RelocName, TypePadding) << " " << ValueStr
1860                << "\n";
1861       }
1862     }
1863   }
1864 }
1865 
1866 void objdump::printDynamicRelocations(const ObjectFile *Obj) {
1867   // For the moment, this option is for ELF only
1868   if (!Obj->isELF())
1869     return;
1870 
1871   const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
1872   if (!Elf || !any_of(Elf->sections(), [](const ELFSectionRef Sec) {
1873         return Sec.getType() == ELF::SHT_DYNAMIC;
1874       })) {
1875     reportError(Obj->getFileName(), "not a dynamic object");
1876     return;
1877   }
1878 
1879   std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1880   if (DynRelSec.empty())
1881     return;
1882 
1883   outs() << "\nDYNAMIC RELOCATION RECORDS\n";
1884   const uint32_t OffsetPadding = (Obj->getBytesInAddress() > 4 ? 16 : 8);
1885   const uint32_t TypePadding = 24;
1886   outs() << left_justify("OFFSET", OffsetPadding) << ' '
1887          << left_justify("TYPE", TypePadding) << " VALUE\n";
1888 
1889   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1890   for (const SectionRef &Section : DynRelSec)
1891     for (const RelocationRef &Reloc : Section.relocations()) {
1892       uint64_t Address = Reloc.getOffset();
1893       SmallString<32> RelocName;
1894       SmallString<32> ValueStr;
1895       Reloc.getTypeName(RelocName);
1896       if (Error E = getRelocationValueString(Reloc, ValueStr))
1897         reportError(std::move(E), Obj->getFileName());
1898       outs() << format(Fmt.data(), Address) << ' '
1899              << left_justify(RelocName, TypePadding) << ' ' << ValueStr << '\n';
1900     }
1901 }
1902 
1903 // Returns true if we need to show LMA column when dumping section headers. We
1904 // show it only when the platform is ELF and either we have at least one section
1905 // whose VMA and LMA are different and/or when --show-lma flag is used.
1906 static bool shouldDisplayLMA(const ObjectFile &Obj) {
1907   if (!Obj.isELF())
1908     return false;
1909   for (const SectionRef &S : ToolSectionFilter(Obj))
1910     if (S.getAddress() != getELFSectionLMA(S))
1911       return true;
1912   return ShowLMA;
1913 }
1914 
1915 static size_t getMaxSectionNameWidth(const ObjectFile &Obj) {
1916   // Default column width for names is 13 even if no names are that long.
1917   size_t MaxWidth = 13;
1918   for (const SectionRef &Section : ToolSectionFilter(Obj)) {
1919     StringRef Name = unwrapOrError(Section.getName(), Obj.getFileName());
1920     MaxWidth = std::max(MaxWidth, Name.size());
1921   }
1922   return MaxWidth;
1923 }
1924 
1925 void objdump::printSectionHeaders(ObjectFile &Obj) {
1926   size_t NameWidth = getMaxSectionNameWidth(Obj);
1927   size_t AddressWidth = 2 * Obj.getBytesInAddress();
1928   bool HasLMAColumn = shouldDisplayLMA(Obj);
1929   outs() << "\nSections:\n";
1930   if (HasLMAColumn)
1931     outs() << "Idx " << left_justify("Name", NameWidth) << " Size     "
1932            << left_justify("VMA", AddressWidth) << " "
1933            << left_justify("LMA", AddressWidth) << " Type\n";
1934   else
1935     outs() << "Idx " << left_justify("Name", NameWidth) << " Size     "
1936            << left_justify("VMA", AddressWidth) << " Type\n";
1937 
1938   if (Obj.isELF() && Obj.sections().empty())
1939     createFakeELFSections(Obj);
1940 
1941   uint64_t Idx;
1942   for (const SectionRef &Section : ToolSectionFilter(Obj, &Idx)) {
1943     StringRef Name = unwrapOrError(Section.getName(), Obj.getFileName());
1944     uint64_t VMA = Section.getAddress();
1945     if (shouldAdjustVA(Section))
1946       VMA += AdjustVMA;
1947 
1948     uint64_t Size = Section.getSize();
1949 
1950     std::string Type = Section.isText() ? "TEXT" : "";
1951     if (Section.isData())
1952       Type += Type.empty() ? "DATA" : ", DATA";
1953     if (Section.isBSS())
1954       Type += Type.empty() ? "BSS" : ", BSS";
1955     if (Section.isDebugSection())
1956       Type += Type.empty() ? "DEBUG" : ", DEBUG";
1957 
1958     if (HasLMAColumn)
1959       outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth,
1960                        Name.str().c_str(), Size)
1961              << format_hex_no_prefix(VMA, AddressWidth) << " "
1962              << format_hex_no_prefix(getELFSectionLMA(Section), AddressWidth)
1963              << " " << Type << "\n";
1964     else
1965       outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth,
1966                        Name.str().c_str(), Size)
1967              << format_hex_no_prefix(VMA, AddressWidth) << " " << Type << "\n";
1968   }
1969 }
1970 
1971 void objdump::printSectionContents(const ObjectFile *Obj) {
1972   const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj);
1973 
1974   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1975     StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName());
1976     uint64_t BaseAddr = Section.getAddress();
1977     uint64_t Size = Section.getSize();
1978     if (!Size)
1979       continue;
1980 
1981     outs() << "Contents of section ";
1982     StringRef SegmentName = getSegmentName(MachO, Section);
1983     if (!SegmentName.empty())
1984       outs() << SegmentName << ",";
1985     outs() << Name << ":\n";
1986     if (Section.isBSS()) {
1987       outs() << format("<skipping contents of bss section at [%04" PRIx64
1988                        ", %04" PRIx64 ")>\n",
1989                        BaseAddr, BaseAddr + Size);
1990       continue;
1991     }
1992 
1993     StringRef Contents = unwrapOrError(Section.getContents(), Obj->getFileName());
1994 
1995     // Dump out the content as hex and printable ascii characters.
1996     for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) {
1997       outs() << format(" %04" PRIx64 " ", BaseAddr + Addr);
1998       // Dump line of hex.
1999       for (std::size_t I = 0; I < 16; ++I) {
2000         if (I != 0 && I % 4 == 0)
2001           outs() << ' ';
2002         if (Addr + I < End)
2003           outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true)
2004                  << hexdigit(Contents[Addr + I] & 0xF, true);
2005         else
2006           outs() << "  ";
2007       }
2008       // Print ascii.
2009       outs() << "  ";
2010       for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) {
2011         if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF))
2012           outs() << Contents[Addr + I];
2013         else
2014           outs() << ".";
2015       }
2016       outs() << "\n";
2017     }
2018   }
2019 }
2020 
2021 void objdump::printSymbolTable(const ObjectFile &O, StringRef ArchiveName,
2022                                StringRef ArchitectureName, bool DumpDynamic) {
2023   if (O.isCOFF() && !DumpDynamic) {
2024     outs() << "\nSYMBOL TABLE:\n";
2025     printCOFFSymbolTable(cast<const COFFObjectFile>(O));
2026     return;
2027   }
2028 
2029   const StringRef FileName = O.getFileName();
2030 
2031   if (!DumpDynamic) {
2032     outs() << "\nSYMBOL TABLE:\n";
2033     for (auto I = O.symbol_begin(); I != O.symbol_end(); ++I)
2034       printSymbol(O, *I, {}, FileName, ArchiveName, ArchitectureName,
2035                   DumpDynamic);
2036     return;
2037   }
2038 
2039   outs() << "\nDYNAMIC SYMBOL TABLE:\n";
2040   if (!O.isELF()) {
2041     reportWarning(
2042         "this operation is not currently supported for this file format",
2043         FileName);
2044     return;
2045   }
2046 
2047   const ELFObjectFileBase *ELF = cast<const ELFObjectFileBase>(&O);
2048   auto Symbols = ELF->getDynamicSymbolIterators();
2049   Expected<std::vector<VersionEntry>> SymbolVersionsOrErr =
2050       ELF->readDynsymVersions();
2051   if (!SymbolVersionsOrErr) {
2052     reportWarning(toString(SymbolVersionsOrErr.takeError()), FileName);
2053     SymbolVersionsOrErr = std::vector<VersionEntry>();
2054     (void)!SymbolVersionsOrErr;
2055   }
2056   for (auto &Sym : Symbols)
2057     printSymbol(O, Sym, *SymbolVersionsOrErr, FileName, ArchiveName,
2058                 ArchitectureName, DumpDynamic);
2059 }
2060 
2061 void objdump::printSymbol(const ObjectFile &O, const SymbolRef &Symbol,
2062                           ArrayRef<VersionEntry> SymbolVersions,
2063                           StringRef FileName, StringRef ArchiveName,
2064                           StringRef ArchitectureName, bool DumpDynamic) {
2065   const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(&O);
2066   uint64_t Address = unwrapOrError(Symbol.getAddress(), FileName, ArchiveName,
2067                                    ArchitectureName);
2068   if ((Address < StartAddress) || (Address > StopAddress))
2069     return;
2070   SymbolRef::Type Type =
2071       unwrapOrError(Symbol.getType(), FileName, ArchiveName, ArchitectureName);
2072   uint32_t Flags =
2073       unwrapOrError(Symbol.getFlags(), FileName, ArchiveName, ArchitectureName);
2074 
2075   // Don't ask a Mach-O STAB symbol for its section unless you know that
2076   // STAB symbol's section field refers to a valid section index. Otherwise
2077   // the symbol may error trying to load a section that does not exist.
2078   bool IsSTAB = false;
2079   if (MachO) {
2080     DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
2081     uint8_t NType =
2082         (MachO->is64Bit() ? MachO->getSymbol64TableEntry(SymDRI).n_type
2083                           : MachO->getSymbolTableEntry(SymDRI).n_type);
2084     if (NType & MachO::N_STAB)
2085       IsSTAB = true;
2086   }
2087   section_iterator Section = IsSTAB
2088                                  ? O.section_end()
2089                                  : unwrapOrError(Symbol.getSection(), FileName,
2090                                                  ArchiveName, ArchitectureName);
2091 
2092   StringRef Name;
2093   if (Type == SymbolRef::ST_Debug && Section != O.section_end()) {
2094     if (Expected<StringRef> NameOrErr = Section->getName())
2095       Name = *NameOrErr;
2096     else
2097       consumeError(NameOrErr.takeError());
2098 
2099   } else {
2100     Name = unwrapOrError(Symbol.getName(), FileName, ArchiveName,
2101                          ArchitectureName);
2102   }
2103 
2104   bool Global = Flags & SymbolRef::SF_Global;
2105   bool Weak = Flags & SymbolRef::SF_Weak;
2106   bool Absolute = Flags & SymbolRef::SF_Absolute;
2107   bool Common = Flags & SymbolRef::SF_Common;
2108   bool Hidden = Flags & SymbolRef::SF_Hidden;
2109 
2110   char GlobLoc = ' ';
2111   if ((Section != O.section_end() || Absolute) && !Weak)
2112     GlobLoc = Global ? 'g' : 'l';
2113   char IFunc = ' ';
2114   if (O.isELF()) {
2115     if (ELFSymbolRef(Symbol).getELFType() == ELF::STT_GNU_IFUNC)
2116       IFunc = 'i';
2117     if (ELFSymbolRef(Symbol).getBinding() == ELF::STB_GNU_UNIQUE)
2118       GlobLoc = 'u';
2119   }
2120 
2121   char Debug = ' ';
2122   if (DumpDynamic)
2123     Debug = 'D';
2124   else if (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
2125     Debug = 'd';
2126 
2127   char FileFunc = ' ';
2128   if (Type == SymbolRef::ST_File)
2129     FileFunc = 'f';
2130   else if (Type == SymbolRef::ST_Function)
2131     FileFunc = 'F';
2132   else if (Type == SymbolRef::ST_Data)
2133     FileFunc = 'O';
2134 
2135   const char *Fmt = O.getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
2136 
2137   outs() << format(Fmt, Address) << " "
2138          << GlobLoc            // Local -> 'l', Global -> 'g', Neither -> ' '
2139          << (Weak ? 'w' : ' ') // Weak?
2140          << ' '                // Constructor. Not supported yet.
2141          << ' '                // Warning. Not supported yet.
2142          << IFunc              // Indirect reference to another symbol.
2143          << Debug              // Debugging (d) or dynamic (D) symbol.
2144          << FileFunc           // Name of function (F), file (f) or object (O).
2145          << ' ';
2146   if (Absolute) {
2147     outs() << "*ABS*";
2148   } else if (Common) {
2149     outs() << "*COM*";
2150   } else if (Section == O.section_end()) {
2151     if (O.isXCOFF()) {
2152       XCOFFSymbolRef XCOFFSym = cast<const XCOFFObjectFile>(O).toSymbolRef(
2153           Symbol.getRawDataRefImpl());
2154       if (XCOFF::N_DEBUG == XCOFFSym.getSectionNumber())
2155         outs() << "*DEBUG*";
2156       else
2157         outs() << "*UND*";
2158     } else
2159       outs() << "*UND*";
2160   } else {
2161     StringRef SegmentName = getSegmentName(MachO, *Section);
2162     if (!SegmentName.empty())
2163       outs() << SegmentName << ",";
2164     StringRef SectionName = unwrapOrError(Section->getName(), FileName);
2165     outs() << SectionName;
2166     if (O.isXCOFF()) {
2167       Optional<SymbolRef> SymRef =
2168           getXCOFFSymbolContainingSymbolRef(cast<XCOFFObjectFile>(O), Symbol);
2169       if (SymRef) {
2170 
2171         Expected<StringRef> NameOrErr = SymRef->getName();
2172 
2173         if (NameOrErr) {
2174           outs() << " (csect:";
2175           std::string SymName(NameOrErr.get());
2176 
2177           if (Demangle)
2178             SymName = demangle(SymName);
2179 
2180           if (SymbolDescription)
2181             SymName = getXCOFFSymbolDescription(
2182                 createSymbolInfo(O, SymRef.value()), SymName);
2183 
2184           outs() << ' ' << SymName;
2185           outs() << ") ";
2186         } else
2187           reportWarning(toString(NameOrErr.takeError()), FileName);
2188       }
2189     }
2190   }
2191 
2192   if (Common)
2193     outs() << '\t' << format(Fmt, static_cast<uint64_t>(Symbol.getAlignment()));
2194   else if (O.isXCOFF())
2195     outs() << '\t'
2196            << format(Fmt, cast<XCOFFObjectFile>(O).getSymbolSize(
2197                               Symbol.getRawDataRefImpl()));
2198   else if (O.isELF())
2199     outs() << '\t' << format(Fmt, ELFSymbolRef(Symbol).getSize());
2200 
2201   if (O.isELF()) {
2202     if (!SymbolVersions.empty()) {
2203       const VersionEntry &Ver =
2204           SymbolVersions[Symbol.getRawDataRefImpl().d.b - 1];
2205       std::string Str;
2206       if (!Ver.Name.empty())
2207         Str = Ver.IsVerDef ? ' ' + Ver.Name : '(' + Ver.Name + ')';
2208       outs() << ' ' << left_justify(Str, 12);
2209     }
2210 
2211     uint8_t Other = ELFSymbolRef(Symbol).getOther();
2212     switch (Other) {
2213     case ELF::STV_DEFAULT:
2214       break;
2215     case ELF::STV_INTERNAL:
2216       outs() << " .internal";
2217       break;
2218     case ELF::STV_HIDDEN:
2219       outs() << " .hidden";
2220       break;
2221     case ELF::STV_PROTECTED:
2222       outs() << " .protected";
2223       break;
2224     default:
2225       outs() << format(" 0x%02x", Other);
2226       break;
2227     }
2228   } else if (Hidden) {
2229     outs() << " .hidden";
2230   }
2231 
2232   std::string SymName(Name);
2233   if (Demangle)
2234     SymName = demangle(SymName);
2235 
2236   if (O.isXCOFF() && SymbolDescription)
2237     SymName = getXCOFFSymbolDescription(createSymbolInfo(O, Symbol), SymName);
2238 
2239   outs() << ' ' << SymName << '\n';
2240 }
2241 
2242 static void printUnwindInfo(const ObjectFile *O) {
2243   outs() << "Unwind info:\n\n";
2244 
2245   if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O))
2246     printCOFFUnwindInfo(Coff);
2247   else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O))
2248     printMachOUnwindInfo(MachO);
2249   else
2250     // TODO: Extract DWARF dump tool to objdump.
2251     WithColor::error(errs(), ToolName)
2252         << "This operation is only currently supported "
2253            "for COFF and MachO object files.\n";
2254 }
2255 
2256 /// Dump the raw contents of the __clangast section so the output can be piped
2257 /// into llvm-bcanalyzer.
2258 static void printRawClangAST(const ObjectFile *Obj) {
2259   if (outs().is_displayed()) {
2260     WithColor::error(errs(), ToolName)
2261         << "The -raw-clang-ast option will dump the raw binary contents of "
2262            "the clang ast section.\n"
2263            "Please redirect the output to a file or another program such as "
2264            "llvm-bcanalyzer.\n";
2265     return;
2266   }
2267 
2268   StringRef ClangASTSectionName("__clangast");
2269   if (Obj->isCOFF()) {
2270     ClangASTSectionName = "clangast";
2271   }
2272 
2273   Optional<object::SectionRef> ClangASTSection;
2274   for (auto Sec : ToolSectionFilter(*Obj)) {
2275     StringRef Name;
2276     if (Expected<StringRef> NameOrErr = Sec.getName())
2277       Name = *NameOrErr;
2278     else
2279       consumeError(NameOrErr.takeError());
2280 
2281     if (Name == ClangASTSectionName) {
2282       ClangASTSection = Sec;
2283       break;
2284     }
2285   }
2286   if (!ClangASTSection)
2287     return;
2288 
2289   StringRef ClangASTContents =
2290       unwrapOrError(ClangASTSection.value().getContents(), Obj->getFileName());
2291   outs().write(ClangASTContents.data(), ClangASTContents.size());
2292 }
2293 
2294 static void printFaultMaps(const ObjectFile *Obj) {
2295   StringRef FaultMapSectionName;
2296 
2297   if (Obj->isELF()) {
2298     FaultMapSectionName = ".llvm_faultmaps";
2299   } else if (Obj->isMachO()) {
2300     FaultMapSectionName = "__llvm_faultmaps";
2301   } else {
2302     WithColor::error(errs(), ToolName)
2303         << "This operation is only currently supported "
2304            "for ELF and Mach-O executable files.\n";
2305     return;
2306   }
2307 
2308   Optional<object::SectionRef> FaultMapSection;
2309 
2310   for (auto Sec : ToolSectionFilter(*Obj)) {
2311     StringRef Name;
2312     if (Expected<StringRef> NameOrErr = Sec.getName())
2313       Name = *NameOrErr;
2314     else
2315       consumeError(NameOrErr.takeError());
2316 
2317     if (Name == FaultMapSectionName) {
2318       FaultMapSection = Sec;
2319       break;
2320     }
2321   }
2322 
2323   outs() << "FaultMap table:\n";
2324 
2325   if (!FaultMapSection) {
2326     outs() << "<not found>\n";
2327     return;
2328   }
2329 
2330   StringRef FaultMapContents =
2331       unwrapOrError(FaultMapSection->getContents(), Obj->getFileName());
2332   FaultMapParser FMP(FaultMapContents.bytes_begin(),
2333                      FaultMapContents.bytes_end());
2334 
2335   outs() << FMP;
2336 }
2337 
2338 static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) {
2339   if (O->isELF()) {
2340     printELFFileHeader(O);
2341     printELFDynamicSection(O);
2342     printELFSymbolVersionInfo(O);
2343     return;
2344   }
2345   if (O->isCOFF())
2346     return printCOFFFileHeader(cast<object::COFFObjectFile>(*O));
2347   if (O->isWasm())
2348     return printWasmFileHeader(O);
2349   if (O->isMachO()) {
2350     printMachOFileHeader(O);
2351     if (!OnlyFirst)
2352       printMachOLoadCommands(O);
2353     return;
2354   }
2355   reportError(O->getFileName(), "Invalid/Unsupported object file format");
2356 }
2357 
2358 static void printFileHeaders(const ObjectFile *O) {
2359   if (!O->isELF() && !O->isCOFF())
2360     reportError(O->getFileName(), "Invalid/Unsupported object file format");
2361 
2362   Triple::ArchType AT = O->getArch();
2363   outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
2364   uint64_t Address = unwrapOrError(O->getStartAddress(), O->getFileName());
2365 
2366   StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
2367   outs() << "start address: "
2368          << "0x" << format(Fmt.data(), Address) << "\n";
2369 }
2370 
2371 static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
2372   Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
2373   if (!ModeOrErr) {
2374     WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n";
2375     consumeError(ModeOrErr.takeError());
2376     return;
2377   }
2378   sys::fs::perms Mode = ModeOrErr.get();
2379   outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2380   outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2381   outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2382   outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2383   outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2384   outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2385   outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2386   outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2387   outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2388 
2389   outs() << " ";
2390 
2391   outs() << format("%d/%d %6" PRId64 " ", unwrapOrError(C.getUID(), Filename),
2392                    unwrapOrError(C.getGID(), Filename),
2393                    unwrapOrError(C.getRawSize(), Filename));
2394 
2395   StringRef RawLastModified = C.getRawLastModified();
2396   unsigned Seconds;
2397   if (RawLastModified.getAsInteger(10, Seconds))
2398     outs() << "(date: \"" << RawLastModified
2399            << "\" contains non-decimal chars) ";
2400   else {
2401     // Since ctime(3) returns a 26 character string of the form:
2402     // "Sun Sep 16 01:03:52 1973\n\0"
2403     // just print 24 characters.
2404     time_t t = Seconds;
2405     outs() << format("%.24s ", ctime(&t));
2406   }
2407 
2408   StringRef Name = "";
2409   Expected<StringRef> NameOrErr = C.getName();
2410   if (!NameOrErr) {
2411     consumeError(NameOrErr.takeError());
2412     Name = unwrapOrError(C.getRawName(), Filename);
2413   } else {
2414     Name = NameOrErr.get();
2415   }
2416   outs() << Name << "\n";
2417 }
2418 
2419 // For ELF only now.
2420 static bool shouldWarnForInvalidStartStopAddress(ObjectFile *Obj) {
2421   if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj)) {
2422     if (Elf->getEType() != ELF::ET_REL)
2423       return true;
2424   }
2425   return false;
2426 }
2427 
2428 static void checkForInvalidStartStopAddress(ObjectFile *Obj,
2429                                             uint64_t Start, uint64_t Stop) {
2430   if (!shouldWarnForInvalidStartStopAddress(Obj))
2431     return;
2432 
2433   for (const SectionRef &Section : Obj->sections())
2434     if (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC) {
2435       uint64_t BaseAddr = Section.getAddress();
2436       uint64_t Size = Section.getSize();
2437       if ((Start < BaseAddr + Size) && Stop > BaseAddr)
2438         return;
2439     }
2440 
2441   if (!HasStartAddressFlag)
2442     reportWarning("no section has address less than 0x" +
2443                       Twine::utohexstr(Stop) + " specified by --stop-address",
2444                   Obj->getFileName());
2445   else if (!HasStopAddressFlag)
2446     reportWarning("no section has address greater than or equal to 0x" +
2447                       Twine::utohexstr(Start) + " specified by --start-address",
2448                   Obj->getFileName());
2449   else
2450     reportWarning("no section overlaps the range [0x" +
2451                       Twine::utohexstr(Start) + ",0x" + Twine::utohexstr(Stop) +
2452                       ") specified by --start-address/--stop-address",
2453                   Obj->getFileName());
2454 }
2455 
2456 static void dumpObject(ObjectFile *O, const Archive *A = nullptr,
2457                        const Archive::Child *C = nullptr) {
2458   // Avoid other output when using a raw option.
2459   if (!RawClangAST) {
2460     outs() << '\n';
2461     if (A)
2462       outs() << A->getFileName() << "(" << O->getFileName() << ")";
2463     else
2464       outs() << O->getFileName();
2465     outs() << ":\tfile format " << O->getFileFormatName().lower() << "\n";
2466   }
2467 
2468   if (HasStartAddressFlag || HasStopAddressFlag)
2469     checkForInvalidStartStopAddress(O, StartAddress, StopAddress);
2470 
2471   // Note: the order here matches GNU objdump for compatability.
2472   StringRef ArchiveName = A ? A->getFileName() : "";
2473   if (ArchiveHeaders && !MachOOpt && C)
2474     printArchiveChild(ArchiveName, *C);
2475   if (FileHeaders)
2476     printFileHeaders(O);
2477   if (PrivateHeaders || FirstPrivateHeader)
2478     printPrivateFileHeaders(O, FirstPrivateHeader);
2479   if (SectionHeaders)
2480     printSectionHeaders(*O);
2481   if (SymbolTable)
2482     printSymbolTable(*O, ArchiveName);
2483   if (DynamicSymbolTable)
2484     printSymbolTable(*O, ArchiveName, /*ArchitectureName=*/"",
2485                      /*DumpDynamic=*/true);
2486   if (DwarfDumpType != DIDT_Null) {
2487     std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O);
2488     // Dump the complete DWARF structure.
2489     DIDumpOptions DumpOpts;
2490     DumpOpts.DumpType = DwarfDumpType;
2491     DICtx->dump(outs(), DumpOpts);
2492   }
2493   if (Relocations && !Disassemble)
2494     printRelocations(O);
2495   if (DynamicRelocations)
2496     printDynamicRelocations(O);
2497   if (SectionContents)
2498     printSectionContents(O);
2499   if (Disassemble)
2500     disassembleObject(O, Relocations);
2501   if (UnwindInfo)
2502     printUnwindInfo(O);
2503 
2504   // Mach-O specific options:
2505   if (ExportsTrie)
2506     printExportsTrie(O);
2507   if (Rebase)
2508     printRebaseTable(O);
2509   if (Bind)
2510     printBindTable(O);
2511   if (LazyBind)
2512     printLazyBindTable(O);
2513   if (WeakBind)
2514     printWeakBindTable(O);
2515 
2516   // Other special sections:
2517   if (RawClangAST)
2518     printRawClangAST(O);
2519   if (FaultMapSection)
2520     printFaultMaps(O);
2521   if (Offloading)
2522     dumpOffloadBinary(*O);
2523 }
2524 
2525 static void dumpObject(const COFFImportFile *I, const Archive *A,
2526                        const Archive::Child *C = nullptr) {
2527   StringRef ArchiveName = A ? A->getFileName() : "";
2528 
2529   // Avoid other output when using a raw option.
2530   if (!RawClangAST)
2531     outs() << '\n'
2532            << ArchiveName << "(" << I->getFileName() << ")"
2533            << ":\tfile format COFF-import-file"
2534            << "\n\n";
2535 
2536   if (ArchiveHeaders && !MachOOpt && C)
2537     printArchiveChild(ArchiveName, *C);
2538   if (SymbolTable)
2539     printCOFFSymbolTable(*I);
2540 }
2541 
2542 /// Dump each object file in \a a;
2543 static void dumpArchive(const Archive *A) {
2544   Error Err = Error::success();
2545   unsigned I = -1;
2546   for (auto &C : A->children(Err)) {
2547     ++I;
2548     Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2549     if (!ChildOrErr) {
2550       if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2551         reportError(std::move(E), getFileNameForError(C, I), A->getFileName());
2552       continue;
2553     }
2554     if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2555       dumpObject(O, A, &C);
2556     else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2557       dumpObject(I, A, &C);
2558     else
2559       reportError(errorCodeToError(object_error::invalid_file_type),
2560                   A->getFileName());
2561   }
2562   if (Err)
2563     reportError(std::move(Err), A->getFileName());
2564 }
2565 
2566 /// Open file and figure out how to dump it.
2567 static void dumpInput(StringRef file) {
2568   // If we are using the Mach-O specific object file parser, then let it parse
2569   // the file and process the command line options.  So the -arch flags can
2570   // be used to select specific slices, etc.
2571   if (MachOOpt) {
2572     parseInputMachO(file);
2573     return;
2574   }
2575 
2576   // Attempt to open the binary.
2577   OwningBinary<Binary> OBinary = unwrapOrError(createBinary(file), file);
2578   Binary &Binary = *OBinary.getBinary();
2579 
2580   if (Archive *A = dyn_cast<Archive>(&Binary))
2581     dumpArchive(A);
2582   else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary))
2583     dumpObject(O);
2584   else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
2585     parseInputMachO(UB);
2586   else if (OffloadBinary *OB = dyn_cast<OffloadBinary>(&Binary))
2587     dumpOffloadSections(*OB);
2588   else
2589     reportError(errorCodeToError(object_error::invalid_file_type), file);
2590 }
2591 
2592 template <typename T>
2593 static void parseIntArg(const llvm::opt::InputArgList &InputArgs, int ID,
2594                         T &Value) {
2595   if (const opt::Arg *A = InputArgs.getLastArg(ID)) {
2596     StringRef V(A->getValue());
2597     if (!llvm::to_integer(V, Value, 0)) {
2598       reportCmdLineError(A->getSpelling() +
2599                          ": expected a non-negative integer, but got '" + V +
2600                          "'");
2601     }
2602   }
2603 }
2604 
2605 static void invalidArgValue(const opt::Arg *A) {
2606   reportCmdLineError("'" + StringRef(A->getValue()) +
2607                      "' is not a valid value for '" + A->getSpelling() + "'");
2608 }
2609 
2610 static std::vector<std::string>
2611 commaSeparatedValues(const llvm::opt::InputArgList &InputArgs, int ID) {
2612   std::vector<std::string> Values;
2613   for (StringRef Value : InputArgs.getAllArgValues(ID)) {
2614     llvm::SmallVector<StringRef, 2> SplitValues;
2615     llvm::SplitString(Value, SplitValues, ",");
2616     for (StringRef SplitValue : SplitValues)
2617       Values.push_back(SplitValue.str());
2618   }
2619   return Values;
2620 }
2621 
2622 static void parseOtoolOptions(const llvm::opt::InputArgList &InputArgs) {
2623   MachOOpt = true;
2624   FullLeadingAddr = true;
2625   PrintImmHex = true;
2626 
2627   ArchName = InputArgs.getLastArgValue(OTOOL_arch).str();
2628   LinkOptHints = InputArgs.hasArg(OTOOL_C);
2629   if (InputArgs.hasArg(OTOOL_d))
2630     FilterSections.push_back("__DATA,__data");
2631   DylibId = InputArgs.hasArg(OTOOL_D);
2632   UniversalHeaders = InputArgs.hasArg(OTOOL_f);
2633   DataInCode = InputArgs.hasArg(OTOOL_G);
2634   FirstPrivateHeader = InputArgs.hasArg(OTOOL_h);
2635   IndirectSymbols = InputArgs.hasArg(OTOOL_I);
2636   ShowRawInsn = InputArgs.hasArg(OTOOL_j);
2637   PrivateHeaders = InputArgs.hasArg(OTOOL_l);
2638   DylibsUsed = InputArgs.hasArg(OTOOL_L);
2639   MCPU = InputArgs.getLastArgValue(OTOOL_mcpu_EQ).str();
2640   ObjcMetaData = InputArgs.hasArg(OTOOL_o);
2641   DisSymName = InputArgs.getLastArgValue(OTOOL_p).str();
2642   InfoPlist = InputArgs.hasArg(OTOOL_P);
2643   Relocations = InputArgs.hasArg(OTOOL_r);
2644   if (const Arg *A = InputArgs.getLastArg(OTOOL_s)) {
2645     auto Filter = (A->getValue(0) + StringRef(",") + A->getValue(1)).str();
2646     FilterSections.push_back(Filter);
2647   }
2648   if (InputArgs.hasArg(OTOOL_t))
2649     FilterSections.push_back("__TEXT,__text");
2650   Verbose = InputArgs.hasArg(OTOOL_v) || InputArgs.hasArg(OTOOL_V) ||
2651             InputArgs.hasArg(OTOOL_o);
2652   SymbolicOperands = InputArgs.hasArg(OTOOL_V);
2653   if (InputArgs.hasArg(OTOOL_x))
2654     FilterSections.push_back(",__text");
2655   LeadingAddr = LeadingHeaders = !InputArgs.hasArg(OTOOL_X);
2656 
2657   InputFilenames = InputArgs.getAllArgValues(OTOOL_INPUT);
2658   if (InputFilenames.empty())
2659     reportCmdLineError("no input file");
2660 
2661   for (const Arg *A : InputArgs) {
2662     const Option &O = A->getOption();
2663     if (O.getGroup().isValid() && O.getGroup().getID() == OTOOL_grp_obsolete) {
2664       reportCmdLineWarning(O.getPrefixedName() +
2665                            " is obsolete and not implemented");
2666     }
2667   }
2668 }
2669 
2670 static void parseObjdumpOptions(const llvm::opt::InputArgList &InputArgs) {
2671   parseIntArg(InputArgs, OBJDUMP_adjust_vma_EQ, AdjustVMA);
2672   AllHeaders = InputArgs.hasArg(OBJDUMP_all_headers);
2673   ArchName = InputArgs.getLastArgValue(OBJDUMP_arch_name_EQ).str();
2674   ArchiveHeaders = InputArgs.hasArg(OBJDUMP_archive_headers);
2675   Demangle = InputArgs.hasArg(OBJDUMP_demangle);
2676   Disassemble = InputArgs.hasArg(OBJDUMP_disassemble);
2677   DisassembleAll = InputArgs.hasArg(OBJDUMP_disassemble_all);
2678   SymbolDescription = InputArgs.hasArg(OBJDUMP_symbol_description);
2679   DisassembleSymbols =
2680       commaSeparatedValues(InputArgs, OBJDUMP_disassemble_symbols_EQ);
2681   DisassembleZeroes = InputArgs.hasArg(OBJDUMP_disassemble_zeroes);
2682   if (const opt::Arg *A = InputArgs.getLastArg(OBJDUMP_dwarf_EQ)) {
2683     DwarfDumpType = StringSwitch<DIDumpType>(A->getValue())
2684                         .Case("frames", DIDT_DebugFrame)
2685                         .Default(DIDT_Null);
2686     if (DwarfDumpType == DIDT_Null)
2687       invalidArgValue(A);
2688   }
2689   DynamicRelocations = InputArgs.hasArg(OBJDUMP_dynamic_reloc);
2690   FaultMapSection = InputArgs.hasArg(OBJDUMP_fault_map_section);
2691   Offloading = InputArgs.hasArg(OBJDUMP_offloading);
2692   FileHeaders = InputArgs.hasArg(OBJDUMP_file_headers);
2693   SectionContents = InputArgs.hasArg(OBJDUMP_full_contents);
2694   PrintLines = InputArgs.hasArg(OBJDUMP_line_numbers);
2695   InputFilenames = InputArgs.getAllArgValues(OBJDUMP_INPUT);
2696   MachOOpt = InputArgs.hasArg(OBJDUMP_macho);
2697   MCPU = InputArgs.getLastArgValue(OBJDUMP_mcpu_EQ).str();
2698   MAttrs = commaSeparatedValues(InputArgs, OBJDUMP_mattr_EQ);
2699   ShowRawInsn = !InputArgs.hasArg(OBJDUMP_no_show_raw_insn);
2700   LeadingAddr = !InputArgs.hasArg(OBJDUMP_no_leading_addr);
2701   RawClangAST = InputArgs.hasArg(OBJDUMP_raw_clang_ast);
2702   Relocations = InputArgs.hasArg(OBJDUMP_reloc);
2703   PrintImmHex =
2704       InputArgs.hasFlag(OBJDUMP_print_imm_hex, OBJDUMP_no_print_imm_hex, false);
2705   PrivateHeaders = InputArgs.hasArg(OBJDUMP_private_headers);
2706   FilterSections = InputArgs.getAllArgValues(OBJDUMP_section_EQ);
2707   SectionHeaders = InputArgs.hasArg(OBJDUMP_section_headers);
2708   ShowLMA = InputArgs.hasArg(OBJDUMP_show_lma);
2709   PrintSource = InputArgs.hasArg(OBJDUMP_source);
2710   parseIntArg(InputArgs, OBJDUMP_start_address_EQ, StartAddress);
2711   HasStartAddressFlag = InputArgs.hasArg(OBJDUMP_start_address_EQ);
2712   parseIntArg(InputArgs, OBJDUMP_stop_address_EQ, StopAddress);
2713   HasStopAddressFlag = InputArgs.hasArg(OBJDUMP_stop_address_EQ);
2714   SymbolTable = InputArgs.hasArg(OBJDUMP_syms);
2715   SymbolizeOperands = InputArgs.hasArg(OBJDUMP_symbolize_operands);
2716   DynamicSymbolTable = InputArgs.hasArg(OBJDUMP_dynamic_syms);
2717   TripleName = InputArgs.getLastArgValue(OBJDUMP_triple_EQ).str();
2718   UnwindInfo = InputArgs.hasArg(OBJDUMP_unwind_info);
2719   Wide = InputArgs.hasArg(OBJDUMP_wide);
2720   Prefix = InputArgs.getLastArgValue(OBJDUMP_prefix).str();
2721   parseIntArg(InputArgs, OBJDUMP_prefix_strip, PrefixStrip);
2722   if (const opt::Arg *A = InputArgs.getLastArg(OBJDUMP_debug_vars_EQ)) {
2723     DbgVariables = StringSwitch<DebugVarsFormat>(A->getValue())
2724                        .Case("ascii", DVASCII)
2725                        .Case("unicode", DVUnicode)
2726                        .Default(DVInvalid);
2727     if (DbgVariables == DVInvalid)
2728       invalidArgValue(A);
2729   }
2730   parseIntArg(InputArgs, OBJDUMP_debug_vars_indent_EQ, DbgIndent);
2731 
2732   parseMachOOptions(InputArgs);
2733 
2734   // Parse -M (--disassembler-options) and deprecated
2735   // --x86-asm-syntax={att,intel}.
2736   //
2737   // Note, for x86, the asm dialect (AssemblerDialect) is initialized when the
2738   // MCAsmInfo is constructed. MCInstPrinter::applyTargetSpecificCLOption is
2739   // called too late. For now we have to use the internal cl::opt option.
2740   const char *AsmSyntax = nullptr;
2741   for (const auto *A : InputArgs.filtered(OBJDUMP_disassembler_options_EQ,
2742                                           OBJDUMP_x86_asm_syntax_att,
2743                                           OBJDUMP_x86_asm_syntax_intel)) {
2744     switch (A->getOption().getID()) {
2745     case OBJDUMP_x86_asm_syntax_att:
2746       AsmSyntax = "--x86-asm-syntax=att";
2747       continue;
2748     case OBJDUMP_x86_asm_syntax_intel:
2749       AsmSyntax = "--x86-asm-syntax=intel";
2750       continue;
2751     }
2752 
2753     SmallVector<StringRef, 2> Values;
2754     llvm::SplitString(A->getValue(), Values, ",");
2755     for (StringRef V : Values) {
2756       if (V == "att")
2757         AsmSyntax = "--x86-asm-syntax=att";
2758       else if (V == "intel")
2759         AsmSyntax = "--x86-asm-syntax=intel";
2760       else
2761         DisassemblerOptions.push_back(V.str());
2762     }
2763   }
2764   if (AsmSyntax) {
2765     const char *Argv[] = {"llvm-objdump", AsmSyntax};
2766     llvm::cl::ParseCommandLineOptions(2, Argv);
2767   }
2768 
2769   // objdump defaults to a.out if no filenames specified.
2770   if (InputFilenames.empty())
2771     InputFilenames.push_back("a.out");
2772 }
2773 
2774 int main(int argc, char **argv) {
2775   using namespace llvm;
2776   InitLLVM X(argc, argv);
2777 
2778   ToolName = argv[0];
2779   std::unique_ptr<CommonOptTable> T;
2780   OptSpecifier Unknown, HelpFlag, HelpHiddenFlag, VersionFlag;
2781 
2782   StringRef Stem = sys::path::stem(ToolName);
2783   auto Is = [=](StringRef Tool) {
2784     // We need to recognize the following filenames:
2785     //
2786     // llvm-objdump -> objdump
2787     // llvm-otool-10.exe -> otool
2788     // powerpc64-unknown-freebsd13-objdump -> objdump
2789     auto I = Stem.rfind_insensitive(Tool);
2790     return I != StringRef::npos &&
2791            (I + Tool.size() == Stem.size() || !isAlnum(Stem[I + Tool.size()]));
2792   };
2793   if (Is("otool")) {
2794     T = std::make_unique<OtoolOptTable>();
2795     Unknown = OTOOL_UNKNOWN;
2796     HelpFlag = OTOOL_help;
2797     HelpHiddenFlag = OTOOL_help_hidden;
2798     VersionFlag = OTOOL_version;
2799   } else {
2800     T = std::make_unique<ObjdumpOptTable>();
2801     Unknown = OBJDUMP_UNKNOWN;
2802     HelpFlag = OBJDUMP_help;
2803     HelpHiddenFlag = OBJDUMP_help_hidden;
2804     VersionFlag = OBJDUMP_version;
2805   }
2806 
2807   BumpPtrAllocator A;
2808   StringSaver Saver(A);
2809   opt::InputArgList InputArgs =
2810       T->parseArgs(argc, argv, Unknown, Saver,
2811                    [&](StringRef Msg) { reportCmdLineError(Msg); });
2812 
2813   if (InputArgs.size() == 0 || InputArgs.hasArg(HelpFlag)) {
2814     T->printHelp(ToolName);
2815     return 0;
2816   }
2817   if (InputArgs.hasArg(HelpHiddenFlag)) {
2818     T->printHelp(ToolName, /*ShowHidden=*/true);
2819     return 0;
2820   }
2821 
2822   // Initialize targets and assembly printers/parsers.
2823   InitializeAllTargetInfos();
2824   InitializeAllTargetMCs();
2825   InitializeAllDisassemblers();
2826 
2827   if (InputArgs.hasArg(VersionFlag)) {
2828     cl::PrintVersionMessage();
2829     if (!Is("otool")) {
2830       outs() << '\n';
2831       TargetRegistry::printRegisteredTargetsForVersion(outs());
2832     }
2833     return 0;
2834   }
2835 
2836   if (Is("otool"))
2837     parseOtoolOptions(InputArgs);
2838   else
2839     parseObjdumpOptions(InputArgs);
2840 
2841   if (StartAddress >= StopAddress)
2842     reportCmdLineError("start address should be less than stop address");
2843 
2844   // Removes trailing separators from prefix.
2845   while (!Prefix.empty() && sys::path::is_separator(Prefix.back()))
2846     Prefix.pop_back();
2847 
2848   if (AllHeaders)
2849     ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations =
2850         SectionHeaders = SymbolTable = true;
2851 
2852   if (DisassembleAll || PrintSource || PrintLines ||
2853       !DisassembleSymbols.empty())
2854     Disassemble = true;
2855 
2856   if (!ArchiveHeaders && !Disassemble && DwarfDumpType == DIDT_Null &&
2857       !DynamicRelocations && !FileHeaders && !PrivateHeaders && !RawClangAST &&
2858       !Relocations && !SectionHeaders && !SectionContents && !SymbolTable &&
2859       !DynamicSymbolTable && !UnwindInfo && !FaultMapSection && !Offloading &&
2860       !(MachOOpt && (Bind || DataInCode || DyldInfo || DylibId || DylibsUsed ||
2861                      ExportsTrie || FirstPrivateHeader || FunctionStarts ||
2862                      IndirectSymbols || InfoPlist || LazyBind || LinkOptHints ||
2863                      ObjcMetaData || Rebase || Rpaths || UniversalHeaders ||
2864                      WeakBind || !FilterSections.empty()))) {
2865     T->printHelp(ToolName);
2866     return 2;
2867   }
2868 
2869   DisasmSymbolSet.insert(DisassembleSymbols.begin(), DisassembleSymbols.end());
2870 
2871   llvm::for_each(InputFilenames, dumpInput);
2872 
2873   warnOnNoMatchForSections();
2874 
2875   return EXIT_SUCCESS;
2876 }
2877