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