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