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