xref: /llvm-project/llvm/tools/llvm-objdump/llvm-objdump.cpp (revision a7938c74f16379704fbd38a3d82dfcb9345651ab)
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 
1697   std::unique_ptr<const MCRegisterInfo> MRI(
1698       TheTarget->createMCRegInfo(TripleName));
1699   if (!MRI)
1700     reportError(Obj->getFileName(),
1701                 "no register info for target " + TripleName);
1702 
1703   // Set up disassembler.
1704   MCTargetOptions MCOptions;
1705   std::unique_ptr<const MCAsmInfo> AsmInfo(
1706       TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
1707   if (!AsmInfo)
1708     reportError(Obj->getFileName(),
1709                 "no assembly info for target " + TripleName);
1710 
1711   if (MCPU.empty())
1712     MCPU = Obj->tryGetCPUName().value_or("").str();
1713 
1714   std::unique_ptr<const MCSubtargetInfo> STI(
1715       TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1716   if (!STI)
1717     reportError(Obj->getFileName(),
1718                 "no subtarget info for target " + TripleName);
1719   std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1720   if (!MII)
1721     reportError(Obj->getFileName(),
1722                 "no instruction info for target " + TripleName);
1723   MCContext Ctx(Triple(TripleName), AsmInfo.get(), MRI.get(), STI.get());
1724   // FIXME: for now initialize MCObjectFileInfo with default values
1725   std::unique_ptr<MCObjectFileInfo> MOFI(
1726       TheTarget->createMCObjectFileInfo(Ctx, /*PIC=*/false));
1727   Ctx.setObjectFileInfo(MOFI.get());
1728 
1729   std::unique_ptr<MCDisassembler> DisAsm(
1730       TheTarget->createMCDisassembler(*STI, Ctx));
1731   if (!DisAsm)
1732     reportError(Obj->getFileName(), "no disassembler for target " + TripleName);
1733 
1734   // If we have an ARM object file, we need a second disassembler, because
1735   // ARM CPUs have two different instruction sets: ARM mode, and Thumb mode.
1736   // We use mapping symbols to switch between the two assemblers, where
1737   // appropriate.
1738   std::unique_ptr<MCDisassembler> SecondaryDisAsm;
1739   std::unique_ptr<const MCSubtargetInfo> SecondarySTI;
1740   if (isArmElf(Obj) && !STI->checkFeatures("+mclass")) {
1741     if (STI->checkFeatures("+thumb-mode"))
1742       Features.AddFeature("-thumb-mode");
1743     else
1744       Features.AddFeature("+thumb-mode");
1745     SecondarySTI.reset(TheTarget->createMCSubtargetInfo(TripleName, MCPU,
1746                                                         Features.getString()));
1747     SecondaryDisAsm.reset(TheTarget->createMCDisassembler(*SecondarySTI, Ctx));
1748   }
1749 
1750   std::unique_ptr<const MCInstrAnalysis> MIA(
1751       TheTarget->createMCInstrAnalysis(MII.get()));
1752 
1753   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1754   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1755       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
1756   if (!IP)
1757     reportError(Obj->getFileName(),
1758                 "no instruction printer for target " + TripleName);
1759   IP->setPrintImmHex(PrintImmHex);
1760   IP->setPrintBranchImmAsAddress(true);
1761   IP->setSymbolizeOperands(SymbolizeOperands);
1762   IP->setMCInstrAnalysis(MIA.get());
1763 
1764   PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
1765   SourcePrinter SP(Obj, TheTarget->getName());
1766 
1767   for (StringRef Opt : DisassemblerOptions)
1768     if (!IP->applyTargetSpecificCLOption(Opt))
1769       reportError(Obj->getFileName(),
1770                   "Unrecognized disassembler option: " + Opt);
1771 
1772   disassembleObject(TheTarget, Obj, Ctx, DisAsm.get(), SecondaryDisAsm.get(),
1773                     MIA.get(), IP.get(), STI.get(), SecondarySTI.get(), PIP,
1774                     SP, InlineRelocs);
1775 }
1776 
1777 void objdump::printRelocations(const ObjectFile *Obj) {
1778   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1779                                                  "%08" PRIx64;
1780   // Regular objdump doesn't print relocations in non-relocatable object
1781   // files.
1782   if (!Obj->isRelocatableObject())
1783     return;
1784 
1785   // Build a mapping from relocation target to a vector of relocation
1786   // sections. Usually, there is an only one relocation section for
1787   // each relocated section.
1788   MapVector<SectionRef, std::vector<SectionRef>> SecToRelSec;
1789   uint64_t Ndx;
1790   for (const SectionRef &Section : ToolSectionFilter(*Obj, &Ndx)) {
1791     if (Section.relocation_begin() == Section.relocation_end())
1792       continue;
1793     Expected<section_iterator> SecOrErr = Section.getRelocatedSection();
1794     if (!SecOrErr)
1795       reportError(Obj->getFileName(),
1796                   "section (" + Twine(Ndx) +
1797                       "): unable to get a relocation target: " +
1798                       toString(SecOrErr.takeError()));
1799     SecToRelSec[**SecOrErr].push_back(Section);
1800   }
1801 
1802   for (std::pair<SectionRef, std::vector<SectionRef>> &P : SecToRelSec) {
1803     StringRef SecName = unwrapOrError(P.first.getName(), Obj->getFileName());
1804     outs() << "\nRELOCATION RECORDS FOR [" << SecName << "]:\n";
1805     uint32_t OffsetPadding = (Obj->getBytesInAddress() > 4 ? 16 : 8);
1806     uint32_t TypePadding = 24;
1807     outs() << left_justify("OFFSET", OffsetPadding) << " "
1808            << left_justify("TYPE", TypePadding) << " "
1809            << "VALUE\n";
1810 
1811     for (SectionRef Section : P.second) {
1812       for (const RelocationRef &Reloc : Section.relocations()) {
1813         uint64_t Address = Reloc.getOffset();
1814         SmallString<32> RelocName;
1815         SmallString<32> ValueStr;
1816         if (Address < StartAddress || Address > StopAddress || getHidden(Reloc))
1817           continue;
1818         Reloc.getTypeName(RelocName);
1819         if (Error E = getRelocationValueString(Reloc, ValueStr))
1820           reportError(std::move(E), Obj->getFileName());
1821 
1822         outs() << format(Fmt.data(), Address) << " "
1823                << left_justify(RelocName, TypePadding) << " " << ValueStr
1824                << "\n";
1825       }
1826     }
1827   }
1828 }
1829 
1830 void objdump::printDynamicRelocations(const ObjectFile *Obj) {
1831   // For the moment, this option is for ELF only
1832   if (!Obj->isELF())
1833     return;
1834 
1835   const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
1836   if (!Elf || !any_of(Elf->sections(), [](const ELFSectionRef Sec) {
1837         return Sec.getType() == ELF::SHT_DYNAMIC;
1838       })) {
1839     reportError(Obj->getFileName(), "not a dynamic object");
1840     return;
1841   }
1842 
1843   std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1844   if (DynRelSec.empty())
1845     return;
1846 
1847   outs() << "\nDYNAMIC RELOCATION RECORDS\n";
1848   const uint32_t OffsetPadding = (Obj->getBytesInAddress() > 4 ? 16 : 8);
1849   const uint32_t TypePadding = 24;
1850   outs() << left_justify("OFFSET", OffsetPadding) << ' '
1851          << left_justify("TYPE", TypePadding) << " VALUE\n";
1852 
1853   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1854   for (const SectionRef &Section : DynRelSec)
1855     for (const RelocationRef &Reloc : Section.relocations()) {
1856       uint64_t Address = Reloc.getOffset();
1857       SmallString<32> RelocName;
1858       SmallString<32> ValueStr;
1859       Reloc.getTypeName(RelocName);
1860       if (Error E = getRelocationValueString(Reloc, ValueStr))
1861         reportError(std::move(E), Obj->getFileName());
1862       outs() << format(Fmt.data(), Address) << ' '
1863              << left_justify(RelocName, TypePadding) << ' ' << ValueStr << '\n';
1864     }
1865 }
1866 
1867 // Returns true if we need to show LMA column when dumping section headers. We
1868 // show it only when the platform is ELF and either we have at least one section
1869 // whose VMA and LMA are different and/or when --show-lma flag is used.
1870 static bool shouldDisplayLMA(const ObjectFile *Obj) {
1871   if (!Obj->isELF())
1872     return false;
1873   for (const SectionRef &S : ToolSectionFilter(*Obj))
1874     if (S.getAddress() != getELFSectionLMA(S))
1875       return true;
1876   return ShowLMA;
1877 }
1878 
1879 static size_t getMaxSectionNameWidth(const ObjectFile *Obj) {
1880   // Default column width for names is 13 even if no names are that long.
1881   size_t MaxWidth = 13;
1882   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1883     StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName());
1884     MaxWidth = std::max(MaxWidth, Name.size());
1885   }
1886   return MaxWidth;
1887 }
1888 
1889 void objdump::printSectionHeaders(const ObjectFile *Obj) {
1890   size_t NameWidth = getMaxSectionNameWidth(Obj);
1891   size_t AddressWidth = 2 * Obj->getBytesInAddress();
1892   bool HasLMAColumn = shouldDisplayLMA(Obj);
1893   outs() << "\nSections:\n";
1894   if (HasLMAColumn)
1895     outs() << "Idx " << left_justify("Name", NameWidth) << " Size     "
1896            << left_justify("VMA", AddressWidth) << " "
1897            << left_justify("LMA", AddressWidth) << " Type\n";
1898   else
1899     outs() << "Idx " << left_justify("Name", NameWidth) << " Size     "
1900            << left_justify("VMA", AddressWidth) << " Type\n";
1901 
1902   uint64_t Idx;
1903   for (const SectionRef &Section : ToolSectionFilter(*Obj, &Idx)) {
1904     StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName());
1905     uint64_t VMA = Section.getAddress();
1906     if (shouldAdjustVA(Section))
1907       VMA += AdjustVMA;
1908 
1909     uint64_t Size = Section.getSize();
1910 
1911     std::string Type = Section.isText() ? "TEXT" : "";
1912     if (Section.isData())
1913       Type += Type.empty() ? "DATA" : ", DATA";
1914     if (Section.isBSS())
1915       Type += Type.empty() ? "BSS" : ", BSS";
1916     if (Section.isDebugSection())
1917       Type += Type.empty() ? "DEBUG" : ", DEBUG";
1918 
1919     if (HasLMAColumn)
1920       outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth,
1921                        Name.str().c_str(), Size)
1922              << format_hex_no_prefix(VMA, AddressWidth) << " "
1923              << format_hex_no_prefix(getELFSectionLMA(Section), AddressWidth)
1924              << " " << Type << "\n";
1925     else
1926       outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth,
1927                        Name.str().c_str(), Size)
1928              << format_hex_no_prefix(VMA, AddressWidth) << " " << Type << "\n";
1929   }
1930 }
1931 
1932 void objdump::printSectionContents(const ObjectFile *Obj) {
1933   const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj);
1934 
1935   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1936     StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName());
1937     uint64_t BaseAddr = Section.getAddress();
1938     uint64_t Size = Section.getSize();
1939     if (!Size)
1940       continue;
1941 
1942     outs() << "Contents of section ";
1943     StringRef SegmentName = getSegmentName(MachO, Section);
1944     if (!SegmentName.empty())
1945       outs() << SegmentName << ",";
1946     outs() << Name << ":\n";
1947     if (Section.isBSS()) {
1948       outs() << format("<skipping contents of bss section at [%04" PRIx64
1949                        ", %04" PRIx64 ")>\n",
1950                        BaseAddr, BaseAddr + Size);
1951       continue;
1952     }
1953 
1954     StringRef Contents = unwrapOrError(Section.getContents(), Obj->getFileName());
1955 
1956     // Dump out the content as hex and printable ascii characters.
1957     for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) {
1958       outs() << format(" %04" PRIx64 " ", BaseAddr + Addr);
1959       // Dump line of hex.
1960       for (std::size_t I = 0; I < 16; ++I) {
1961         if (I != 0 && I % 4 == 0)
1962           outs() << ' ';
1963         if (Addr + I < End)
1964           outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true)
1965                  << hexdigit(Contents[Addr + I] & 0xF, true);
1966         else
1967           outs() << "  ";
1968       }
1969       // Print ascii.
1970       outs() << "  ";
1971       for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) {
1972         if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF))
1973           outs() << Contents[Addr + I];
1974         else
1975           outs() << ".";
1976       }
1977       outs() << "\n";
1978     }
1979   }
1980 }
1981 
1982 void objdump::printSymbolTable(const ObjectFile *O, StringRef ArchiveName,
1983                                StringRef ArchitectureName, bool DumpDynamic) {
1984   if (O->isCOFF() && !DumpDynamic) {
1985     outs() << "\nSYMBOL TABLE:\n";
1986     printCOFFSymbolTable(cast<const COFFObjectFile>(O));
1987     return;
1988   }
1989 
1990   const StringRef FileName = O->getFileName();
1991 
1992   if (!DumpDynamic) {
1993     outs() << "\nSYMBOL TABLE:\n";
1994     for (auto I = O->symbol_begin(); I != O->symbol_end(); ++I)
1995       printSymbol(O, *I, {}, FileName, ArchiveName, ArchitectureName,
1996                   DumpDynamic);
1997     return;
1998   }
1999 
2000   outs() << "\nDYNAMIC SYMBOL TABLE:\n";
2001   if (!O->isELF()) {
2002     reportWarning(
2003         "this operation is not currently supported for this file format",
2004         FileName);
2005     return;
2006   }
2007 
2008   const ELFObjectFileBase *ELF = cast<const ELFObjectFileBase>(O);
2009   auto Symbols = ELF->getDynamicSymbolIterators();
2010   Expected<std::vector<VersionEntry>> SymbolVersionsOrErr =
2011       ELF->readDynsymVersions();
2012   if (!SymbolVersionsOrErr) {
2013     reportWarning(toString(SymbolVersionsOrErr.takeError()), FileName);
2014     SymbolVersionsOrErr = std::vector<VersionEntry>();
2015     (void)!SymbolVersionsOrErr;
2016   }
2017   for (auto &Sym : Symbols)
2018     printSymbol(O, Sym, *SymbolVersionsOrErr, FileName, ArchiveName,
2019                 ArchitectureName, DumpDynamic);
2020 }
2021 
2022 void objdump::printSymbol(const ObjectFile *O, const SymbolRef &Symbol,
2023                           ArrayRef<VersionEntry> SymbolVersions,
2024                           StringRef FileName, StringRef ArchiveName,
2025                           StringRef ArchitectureName, bool DumpDynamic) {
2026   const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(O);
2027   uint64_t Address = unwrapOrError(Symbol.getAddress(), FileName, ArchiveName,
2028                                    ArchitectureName);
2029   if ((Address < StartAddress) || (Address > StopAddress))
2030     return;
2031   SymbolRef::Type Type =
2032       unwrapOrError(Symbol.getType(), FileName, ArchiveName, ArchitectureName);
2033   uint32_t Flags =
2034       unwrapOrError(Symbol.getFlags(), FileName, ArchiveName, ArchitectureName);
2035 
2036   // Don't ask a Mach-O STAB symbol for its section unless you know that
2037   // STAB symbol's section field refers to a valid section index. Otherwise
2038   // the symbol may error trying to load a section that does not exist.
2039   bool IsSTAB = false;
2040   if (MachO) {
2041     DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
2042     uint8_t NType =
2043         (MachO->is64Bit() ? MachO->getSymbol64TableEntry(SymDRI).n_type
2044                           : MachO->getSymbolTableEntry(SymDRI).n_type);
2045     if (NType & MachO::N_STAB)
2046       IsSTAB = true;
2047   }
2048   section_iterator Section = IsSTAB
2049                                  ? O->section_end()
2050                                  : unwrapOrError(Symbol.getSection(), FileName,
2051                                                  ArchiveName, ArchitectureName);
2052 
2053   StringRef Name;
2054   if (Type == SymbolRef::ST_Debug && Section != O->section_end()) {
2055     if (Expected<StringRef> NameOrErr = Section->getName())
2056       Name = *NameOrErr;
2057     else
2058       consumeError(NameOrErr.takeError());
2059 
2060   } else {
2061     Name = unwrapOrError(Symbol.getName(), FileName, ArchiveName,
2062                          ArchitectureName);
2063   }
2064 
2065   bool Global = Flags & SymbolRef::SF_Global;
2066   bool Weak = Flags & SymbolRef::SF_Weak;
2067   bool Absolute = Flags & SymbolRef::SF_Absolute;
2068   bool Common = Flags & SymbolRef::SF_Common;
2069   bool Hidden = Flags & SymbolRef::SF_Hidden;
2070 
2071   char GlobLoc = ' ';
2072   if ((Section != O->section_end() || Absolute) && !Weak)
2073     GlobLoc = Global ? 'g' : 'l';
2074   char IFunc = ' ';
2075   if (O->isELF()) {
2076     if (ELFSymbolRef(Symbol).getELFType() == ELF::STT_GNU_IFUNC)
2077       IFunc = 'i';
2078     if (ELFSymbolRef(Symbol).getBinding() == ELF::STB_GNU_UNIQUE)
2079       GlobLoc = 'u';
2080   }
2081 
2082   char Debug = ' ';
2083   if (DumpDynamic)
2084     Debug = 'D';
2085   else if (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
2086     Debug = 'd';
2087 
2088   char FileFunc = ' ';
2089   if (Type == SymbolRef::ST_File)
2090     FileFunc = 'f';
2091   else if (Type == SymbolRef::ST_Function)
2092     FileFunc = 'F';
2093   else if (Type == SymbolRef::ST_Data)
2094     FileFunc = 'O';
2095 
2096   const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
2097 
2098   outs() << format(Fmt, Address) << " "
2099          << GlobLoc            // Local -> 'l', Global -> 'g', Neither -> ' '
2100          << (Weak ? 'w' : ' ') // Weak?
2101          << ' '                // Constructor. Not supported yet.
2102          << ' '                // Warning. Not supported yet.
2103          << IFunc              // Indirect reference to another symbol.
2104          << Debug              // Debugging (d) or dynamic (D) symbol.
2105          << FileFunc           // Name of function (F), file (f) or object (O).
2106          << ' ';
2107   if (Absolute) {
2108     outs() << "*ABS*";
2109   } else if (Common) {
2110     outs() << "*COM*";
2111   } else if (Section == O->section_end()) {
2112     if (O->isXCOFF()) {
2113       XCOFFSymbolRef XCOFFSym = dyn_cast<const XCOFFObjectFile>(O)->toSymbolRef(
2114           Symbol.getRawDataRefImpl());
2115       if (XCOFF::N_DEBUG == XCOFFSym.getSectionNumber())
2116         outs() << "*DEBUG*";
2117       else
2118         outs() << "*UND*";
2119     } else
2120       outs() << "*UND*";
2121   } else {
2122     StringRef SegmentName = getSegmentName(MachO, *Section);
2123     if (!SegmentName.empty())
2124       outs() << SegmentName << ",";
2125     StringRef SectionName = unwrapOrError(Section->getName(), FileName);
2126     outs() << SectionName;
2127     if (O->isXCOFF()) {
2128       Optional<SymbolRef> SymRef = getXCOFFSymbolContainingSymbolRef(
2129           dyn_cast<const XCOFFObjectFile>(O), Symbol);
2130       if (SymRef) {
2131 
2132         Expected<StringRef> NameOrErr = SymRef->getName();
2133 
2134         if (NameOrErr) {
2135           outs() << " (csect:";
2136           std::string SymName(NameOrErr.get());
2137 
2138           if (Demangle)
2139             SymName = demangle(SymName);
2140 
2141           if (SymbolDescription)
2142             SymName = getXCOFFSymbolDescription(
2143                 createSymbolInfo(O, SymRef.getValue()), SymName);
2144 
2145           outs() << ' ' << SymName;
2146           outs() << ") ";
2147         } else
2148           reportWarning(toString(NameOrErr.takeError()), FileName);
2149       }
2150     }
2151   }
2152 
2153   if (Common)
2154     outs() << '\t' << format(Fmt, static_cast<uint64_t>(Symbol.getAlignment()));
2155   else if (O->isXCOFF())
2156     outs() << '\t'
2157            << format(Fmt, dyn_cast<const XCOFFObjectFile>(O)->getSymbolSize(
2158                               Symbol.getRawDataRefImpl()));
2159   else if (O->isELF())
2160     outs() << '\t' << format(Fmt, ELFSymbolRef(Symbol).getSize());
2161 
2162   if (O->isELF()) {
2163     if (!SymbolVersions.empty()) {
2164       const VersionEntry &Ver =
2165           SymbolVersions[Symbol.getRawDataRefImpl().d.b - 1];
2166       std::string Str;
2167       if (!Ver.Name.empty())
2168         Str = Ver.IsVerDef ? ' ' + Ver.Name : '(' + Ver.Name + ')';
2169       outs() << ' ' << left_justify(Str, 12);
2170     }
2171 
2172     uint8_t Other = ELFSymbolRef(Symbol).getOther();
2173     switch (Other) {
2174     case ELF::STV_DEFAULT:
2175       break;
2176     case ELF::STV_INTERNAL:
2177       outs() << " .internal";
2178       break;
2179     case ELF::STV_HIDDEN:
2180       outs() << " .hidden";
2181       break;
2182     case ELF::STV_PROTECTED:
2183       outs() << " .protected";
2184       break;
2185     default:
2186       outs() << format(" 0x%02x", Other);
2187       break;
2188     }
2189   } else if (Hidden) {
2190     outs() << " .hidden";
2191   }
2192 
2193   std::string SymName(Name);
2194   if (Demangle)
2195     SymName = demangle(SymName);
2196 
2197   if (O->isXCOFF() && SymbolDescription)
2198     SymName = getXCOFFSymbolDescription(createSymbolInfo(O, Symbol), SymName);
2199 
2200   outs() << ' ' << SymName << '\n';
2201 }
2202 
2203 static void printUnwindInfo(const ObjectFile *O) {
2204   outs() << "Unwind info:\n\n";
2205 
2206   if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O))
2207     printCOFFUnwindInfo(Coff);
2208   else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O))
2209     printMachOUnwindInfo(MachO);
2210   else
2211     // TODO: Extract DWARF dump tool to objdump.
2212     WithColor::error(errs(), ToolName)
2213         << "This operation is only currently supported "
2214            "for COFF and MachO object files.\n";
2215 }
2216 
2217 /// Dump the raw contents of the __clangast section so the output can be piped
2218 /// into llvm-bcanalyzer.
2219 static void printRawClangAST(const ObjectFile *Obj) {
2220   if (outs().is_displayed()) {
2221     WithColor::error(errs(), ToolName)
2222         << "The -raw-clang-ast option will dump the raw binary contents of "
2223            "the clang ast section.\n"
2224            "Please redirect the output to a file or another program such as "
2225            "llvm-bcanalyzer.\n";
2226     return;
2227   }
2228 
2229   StringRef ClangASTSectionName("__clangast");
2230   if (Obj->isCOFF()) {
2231     ClangASTSectionName = "clangast";
2232   }
2233 
2234   Optional<object::SectionRef> ClangASTSection;
2235   for (auto Sec : ToolSectionFilter(*Obj)) {
2236     StringRef Name;
2237     if (Expected<StringRef> NameOrErr = Sec.getName())
2238       Name = *NameOrErr;
2239     else
2240       consumeError(NameOrErr.takeError());
2241 
2242     if (Name == ClangASTSectionName) {
2243       ClangASTSection = Sec;
2244       break;
2245     }
2246   }
2247   if (!ClangASTSection)
2248     return;
2249 
2250   StringRef ClangASTContents = unwrapOrError(
2251       ClangASTSection.getValue().getContents(), Obj->getFileName());
2252   outs().write(ClangASTContents.data(), ClangASTContents.size());
2253 }
2254 
2255 static void printFaultMaps(const ObjectFile *Obj) {
2256   StringRef FaultMapSectionName;
2257 
2258   if (Obj->isELF()) {
2259     FaultMapSectionName = ".llvm_faultmaps";
2260   } else if (Obj->isMachO()) {
2261     FaultMapSectionName = "__llvm_faultmaps";
2262   } else {
2263     WithColor::error(errs(), ToolName)
2264         << "This operation is only currently supported "
2265            "for ELF and Mach-O executable files.\n";
2266     return;
2267   }
2268 
2269   Optional<object::SectionRef> FaultMapSection;
2270 
2271   for (auto Sec : ToolSectionFilter(*Obj)) {
2272     StringRef Name;
2273     if (Expected<StringRef> NameOrErr = Sec.getName())
2274       Name = *NameOrErr;
2275     else
2276       consumeError(NameOrErr.takeError());
2277 
2278     if (Name == FaultMapSectionName) {
2279       FaultMapSection = Sec;
2280       break;
2281     }
2282   }
2283 
2284   outs() << "FaultMap table:\n";
2285 
2286   if (!FaultMapSection) {
2287     outs() << "<not found>\n";
2288     return;
2289   }
2290 
2291   StringRef FaultMapContents =
2292       unwrapOrError(FaultMapSection->getContents(), Obj->getFileName());
2293   FaultMapParser FMP(FaultMapContents.bytes_begin(),
2294                      FaultMapContents.bytes_end());
2295 
2296   outs() << FMP;
2297 }
2298 
2299 static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) {
2300   if (O->isELF()) {
2301     printELFFileHeader(O);
2302     printELFDynamicSection(O);
2303     printELFSymbolVersionInfo(O);
2304     return;
2305   }
2306   if (O->isCOFF())
2307     return printCOFFFileHeader(cast<object::COFFObjectFile>(*O));
2308   if (O->isWasm())
2309     return printWasmFileHeader(O);
2310   if (O->isMachO()) {
2311     printMachOFileHeader(O);
2312     if (!OnlyFirst)
2313       printMachOLoadCommands(O);
2314     return;
2315   }
2316   reportError(O->getFileName(), "Invalid/Unsupported object file format");
2317 }
2318 
2319 static void printFileHeaders(const ObjectFile *O) {
2320   if (!O->isELF() && !O->isCOFF())
2321     reportError(O->getFileName(), "Invalid/Unsupported object file format");
2322 
2323   Triple::ArchType AT = O->getArch();
2324   outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
2325   uint64_t Address = unwrapOrError(O->getStartAddress(), O->getFileName());
2326 
2327   StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
2328   outs() << "start address: "
2329          << "0x" << format(Fmt.data(), Address) << "\n";
2330 }
2331 
2332 static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
2333   Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
2334   if (!ModeOrErr) {
2335     WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n";
2336     consumeError(ModeOrErr.takeError());
2337     return;
2338   }
2339   sys::fs::perms Mode = ModeOrErr.get();
2340   outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2341   outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2342   outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2343   outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2344   outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2345   outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2346   outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2347   outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2348   outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2349 
2350   outs() << " ";
2351 
2352   outs() << format("%d/%d %6" PRId64 " ", unwrapOrError(C.getUID(), Filename),
2353                    unwrapOrError(C.getGID(), Filename),
2354                    unwrapOrError(C.getRawSize(), Filename));
2355 
2356   StringRef RawLastModified = C.getRawLastModified();
2357   unsigned Seconds;
2358   if (RawLastModified.getAsInteger(10, Seconds))
2359     outs() << "(date: \"" << RawLastModified
2360            << "\" contains non-decimal chars) ";
2361   else {
2362     // Since ctime(3) returns a 26 character string of the form:
2363     // "Sun Sep 16 01:03:52 1973\n\0"
2364     // just print 24 characters.
2365     time_t t = Seconds;
2366     outs() << format("%.24s ", ctime(&t));
2367   }
2368 
2369   StringRef Name = "";
2370   Expected<StringRef> NameOrErr = C.getName();
2371   if (!NameOrErr) {
2372     consumeError(NameOrErr.takeError());
2373     Name = unwrapOrError(C.getRawName(), Filename);
2374   } else {
2375     Name = NameOrErr.get();
2376   }
2377   outs() << Name << "\n";
2378 }
2379 
2380 // For ELF only now.
2381 static bool shouldWarnForInvalidStartStopAddress(ObjectFile *Obj) {
2382   if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj)) {
2383     if (Elf->getEType() != ELF::ET_REL)
2384       return true;
2385   }
2386   return false;
2387 }
2388 
2389 static void checkForInvalidStartStopAddress(ObjectFile *Obj,
2390                                             uint64_t Start, uint64_t Stop) {
2391   if (!shouldWarnForInvalidStartStopAddress(Obj))
2392     return;
2393 
2394   for (const SectionRef &Section : Obj->sections())
2395     if (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC) {
2396       uint64_t BaseAddr = Section.getAddress();
2397       uint64_t Size = Section.getSize();
2398       if ((Start < BaseAddr + Size) && Stop > BaseAddr)
2399         return;
2400     }
2401 
2402   if (!HasStartAddressFlag)
2403     reportWarning("no section has address less than 0x" +
2404                       Twine::utohexstr(Stop) + " specified by --stop-address",
2405                   Obj->getFileName());
2406   else if (!HasStopAddressFlag)
2407     reportWarning("no section has address greater than or equal to 0x" +
2408                       Twine::utohexstr(Start) + " specified by --start-address",
2409                   Obj->getFileName());
2410   else
2411     reportWarning("no section overlaps the range [0x" +
2412                       Twine::utohexstr(Start) + ",0x" + Twine::utohexstr(Stop) +
2413                       ") specified by --start-address/--stop-address",
2414                   Obj->getFileName());
2415 }
2416 
2417 static void dumpObject(ObjectFile *O, const Archive *A = nullptr,
2418                        const Archive::Child *C = nullptr) {
2419   // Avoid other output when using a raw option.
2420   if (!RawClangAST) {
2421     outs() << '\n';
2422     if (A)
2423       outs() << A->getFileName() << "(" << O->getFileName() << ")";
2424     else
2425       outs() << O->getFileName();
2426     outs() << ":\tfile format " << O->getFileFormatName().lower() << "\n";
2427   }
2428 
2429   if (HasStartAddressFlag || HasStopAddressFlag)
2430     checkForInvalidStartStopAddress(O, StartAddress, StopAddress);
2431 
2432   // Note: the order here matches GNU objdump for compatability.
2433   StringRef ArchiveName = A ? A->getFileName() : "";
2434   if (ArchiveHeaders && !MachOOpt && C)
2435     printArchiveChild(ArchiveName, *C);
2436   if (FileHeaders)
2437     printFileHeaders(O);
2438   if (PrivateHeaders || FirstPrivateHeader)
2439     printPrivateFileHeaders(O, FirstPrivateHeader);
2440   if (SectionHeaders)
2441     printSectionHeaders(O);
2442   if (SymbolTable)
2443     printSymbolTable(O, ArchiveName);
2444   if (DynamicSymbolTable)
2445     printSymbolTable(O, ArchiveName, /*ArchitectureName=*/"",
2446                      /*DumpDynamic=*/true);
2447   if (DwarfDumpType != DIDT_Null) {
2448     std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O);
2449     // Dump the complete DWARF structure.
2450     DIDumpOptions DumpOpts;
2451     DumpOpts.DumpType = DwarfDumpType;
2452     DICtx->dump(outs(), DumpOpts);
2453   }
2454   if (Relocations && !Disassemble)
2455     printRelocations(O);
2456   if (DynamicRelocations)
2457     printDynamicRelocations(O);
2458   if (SectionContents)
2459     printSectionContents(O);
2460   if (Disassemble)
2461     disassembleObject(O, Relocations);
2462   if (UnwindInfo)
2463     printUnwindInfo(O);
2464 
2465   // Mach-O specific options:
2466   if (ExportsTrie)
2467     printExportsTrie(O);
2468   if (Rebase)
2469     printRebaseTable(O);
2470   if (Bind)
2471     printBindTable(O);
2472   if (LazyBind)
2473     printLazyBindTable(O);
2474   if (WeakBind)
2475     printWeakBindTable(O);
2476 
2477   // Other special sections:
2478   if (RawClangAST)
2479     printRawClangAST(O);
2480   if (FaultMapSection)
2481     printFaultMaps(O);
2482 }
2483 
2484 static void dumpObject(const COFFImportFile *I, const Archive *A,
2485                        const Archive::Child *C = nullptr) {
2486   StringRef ArchiveName = A ? A->getFileName() : "";
2487 
2488   // Avoid other output when using a raw option.
2489   if (!RawClangAST)
2490     outs() << '\n'
2491            << ArchiveName << "(" << I->getFileName() << ")"
2492            << ":\tfile format COFF-import-file"
2493            << "\n\n";
2494 
2495   if (ArchiveHeaders && !MachOOpt && C)
2496     printArchiveChild(ArchiveName, *C);
2497   if (SymbolTable)
2498     printCOFFSymbolTable(I);
2499 }
2500 
2501 /// Dump each object file in \a a;
2502 static void dumpArchive(const Archive *A) {
2503   Error Err = Error::success();
2504   unsigned I = -1;
2505   for (auto &C : A->children(Err)) {
2506     ++I;
2507     Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2508     if (!ChildOrErr) {
2509       if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2510         reportError(std::move(E), getFileNameForError(C, I), A->getFileName());
2511       continue;
2512     }
2513     if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2514       dumpObject(O, A, &C);
2515     else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2516       dumpObject(I, A, &C);
2517     else
2518       reportError(errorCodeToError(object_error::invalid_file_type),
2519                   A->getFileName());
2520   }
2521   if (Err)
2522     reportError(std::move(Err), A->getFileName());
2523 }
2524 
2525 /// Open file and figure out how to dump it.
2526 static void dumpInput(StringRef file) {
2527   // If we are using the Mach-O specific object file parser, then let it parse
2528   // the file and process the command line options.  So the -arch flags can
2529   // be used to select specific slices, etc.
2530   if (MachOOpt) {
2531     parseInputMachO(file);
2532     return;
2533   }
2534 
2535   // Attempt to open the binary.
2536   OwningBinary<Binary> OBinary = unwrapOrError(createBinary(file), file);
2537   Binary &Binary = *OBinary.getBinary();
2538 
2539   if (Archive *A = dyn_cast<Archive>(&Binary))
2540     dumpArchive(A);
2541   else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary))
2542     dumpObject(O);
2543   else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
2544     parseInputMachO(UB);
2545   else
2546     reportError(errorCodeToError(object_error::invalid_file_type), file);
2547 }
2548 
2549 template <typename T>
2550 static void parseIntArg(const llvm::opt::InputArgList &InputArgs, int ID,
2551                         T &Value) {
2552   if (const opt::Arg *A = InputArgs.getLastArg(ID)) {
2553     StringRef V(A->getValue());
2554     if (!llvm::to_integer(V, Value, 0)) {
2555       reportCmdLineError(A->getSpelling() +
2556                          ": expected a non-negative integer, but got '" + V +
2557                          "'");
2558     }
2559   }
2560 }
2561 
2562 static void invalidArgValue(const opt::Arg *A) {
2563   reportCmdLineError("'" + StringRef(A->getValue()) +
2564                      "' is not a valid value for '" + A->getSpelling() + "'");
2565 }
2566 
2567 static std::vector<std::string>
2568 commaSeparatedValues(const llvm::opt::InputArgList &InputArgs, int ID) {
2569   std::vector<std::string> Values;
2570   for (StringRef Value : InputArgs.getAllArgValues(ID)) {
2571     llvm::SmallVector<StringRef, 2> SplitValues;
2572     llvm::SplitString(Value, SplitValues, ",");
2573     for (StringRef SplitValue : SplitValues)
2574       Values.push_back(SplitValue.str());
2575   }
2576   return Values;
2577 }
2578 
2579 static void parseOtoolOptions(const llvm::opt::InputArgList &InputArgs) {
2580   MachOOpt = true;
2581   FullLeadingAddr = true;
2582   PrintImmHex = true;
2583 
2584   ArchName = InputArgs.getLastArgValue(OTOOL_arch).str();
2585   LinkOptHints = InputArgs.hasArg(OTOOL_C);
2586   if (InputArgs.hasArg(OTOOL_d))
2587     FilterSections.push_back("__DATA,__data");
2588   DylibId = InputArgs.hasArg(OTOOL_D);
2589   UniversalHeaders = InputArgs.hasArg(OTOOL_f);
2590   DataInCode = InputArgs.hasArg(OTOOL_G);
2591   FirstPrivateHeader = InputArgs.hasArg(OTOOL_h);
2592   IndirectSymbols = InputArgs.hasArg(OTOOL_I);
2593   ShowRawInsn = InputArgs.hasArg(OTOOL_j);
2594   PrivateHeaders = InputArgs.hasArg(OTOOL_l);
2595   DylibsUsed = InputArgs.hasArg(OTOOL_L);
2596   MCPU = InputArgs.getLastArgValue(OTOOL_mcpu_EQ).str();
2597   ObjcMetaData = InputArgs.hasArg(OTOOL_o);
2598   DisSymName = InputArgs.getLastArgValue(OTOOL_p).str();
2599   InfoPlist = InputArgs.hasArg(OTOOL_P);
2600   Relocations = InputArgs.hasArg(OTOOL_r);
2601   if (const Arg *A = InputArgs.getLastArg(OTOOL_s)) {
2602     auto Filter = (A->getValue(0) + StringRef(",") + A->getValue(1)).str();
2603     FilterSections.push_back(Filter);
2604   }
2605   if (InputArgs.hasArg(OTOOL_t))
2606     FilterSections.push_back("__TEXT,__text");
2607   Verbose = InputArgs.hasArg(OTOOL_v) || InputArgs.hasArg(OTOOL_V) ||
2608             InputArgs.hasArg(OTOOL_o);
2609   SymbolicOperands = InputArgs.hasArg(OTOOL_V);
2610   if (InputArgs.hasArg(OTOOL_x))
2611     FilterSections.push_back(",__text");
2612   LeadingAddr = LeadingHeaders = !InputArgs.hasArg(OTOOL_X);
2613 
2614   InputFilenames = InputArgs.getAllArgValues(OTOOL_INPUT);
2615   if (InputFilenames.empty())
2616     reportCmdLineError("no input file");
2617 
2618   for (const Arg *A : InputArgs) {
2619     const Option &O = A->getOption();
2620     if (O.getGroup().isValid() && O.getGroup().getID() == OTOOL_grp_obsolete) {
2621       reportCmdLineWarning(O.getPrefixedName() +
2622                            " is obsolete and not implemented");
2623     }
2624   }
2625 }
2626 
2627 static void parseObjdumpOptions(const llvm::opt::InputArgList &InputArgs) {
2628   parseIntArg(InputArgs, OBJDUMP_adjust_vma_EQ, AdjustVMA);
2629   AllHeaders = InputArgs.hasArg(OBJDUMP_all_headers);
2630   ArchName = InputArgs.getLastArgValue(OBJDUMP_arch_name_EQ).str();
2631   ArchiveHeaders = InputArgs.hasArg(OBJDUMP_archive_headers);
2632   Demangle = InputArgs.hasArg(OBJDUMP_demangle);
2633   Disassemble = InputArgs.hasArg(OBJDUMP_disassemble);
2634   DisassembleAll = InputArgs.hasArg(OBJDUMP_disassemble_all);
2635   SymbolDescription = InputArgs.hasArg(OBJDUMP_symbol_description);
2636   DisassembleSymbols =
2637       commaSeparatedValues(InputArgs, OBJDUMP_disassemble_symbols_EQ);
2638   DisassembleZeroes = InputArgs.hasArg(OBJDUMP_disassemble_zeroes);
2639   if (const opt::Arg *A = InputArgs.getLastArg(OBJDUMP_dwarf_EQ)) {
2640     DwarfDumpType = StringSwitch<DIDumpType>(A->getValue())
2641                         .Case("frames", DIDT_DebugFrame)
2642                         .Default(DIDT_Null);
2643     if (DwarfDumpType == DIDT_Null)
2644       invalidArgValue(A);
2645   }
2646   DynamicRelocations = InputArgs.hasArg(OBJDUMP_dynamic_reloc);
2647   FaultMapSection = InputArgs.hasArg(OBJDUMP_fault_map_section);
2648   FileHeaders = InputArgs.hasArg(OBJDUMP_file_headers);
2649   SectionContents = InputArgs.hasArg(OBJDUMP_full_contents);
2650   PrintLines = InputArgs.hasArg(OBJDUMP_line_numbers);
2651   InputFilenames = InputArgs.getAllArgValues(OBJDUMP_INPUT);
2652   MachOOpt = InputArgs.hasArg(OBJDUMP_macho);
2653   MCPU = InputArgs.getLastArgValue(OBJDUMP_mcpu_EQ).str();
2654   MAttrs = commaSeparatedValues(InputArgs, OBJDUMP_mattr_EQ);
2655   ShowRawInsn = !InputArgs.hasArg(OBJDUMP_no_show_raw_insn);
2656   LeadingAddr = !InputArgs.hasArg(OBJDUMP_no_leading_addr);
2657   RawClangAST = InputArgs.hasArg(OBJDUMP_raw_clang_ast);
2658   Relocations = InputArgs.hasArg(OBJDUMP_reloc);
2659   PrintImmHex =
2660       InputArgs.hasFlag(OBJDUMP_print_imm_hex, OBJDUMP_no_print_imm_hex, false);
2661   PrivateHeaders = InputArgs.hasArg(OBJDUMP_private_headers);
2662   FilterSections = InputArgs.getAllArgValues(OBJDUMP_section_EQ);
2663   SectionHeaders = InputArgs.hasArg(OBJDUMP_section_headers);
2664   ShowLMA = InputArgs.hasArg(OBJDUMP_show_lma);
2665   PrintSource = InputArgs.hasArg(OBJDUMP_source);
2666   parseIntArg(InputArgs, OBJDUMP_start_address_EQ, StartAddress);
2667   HasStartAddressFlag = InputArgs.hasArg(OBJDUMP_start_address_EQ);
2668   parseIntArg(InputArgs, OBJDUMP_stop_address_EQ, StopAddress);
2669   HasStopAddressFlag = InputArgs.hasArg(OBJDUMP_stop_address_EQ);
2670   SymbolTable = InputArgs.hasArg(OBJDUMP_syms);
2671   SymbolizeOperands = InputArgs.hasArg(OBJDUMP_symbolize_operands);
2672   DynamicSymbolTable = InputArgs.hasArg(OBJDUMP_dynamic_syms);
2673   TripleName = InputArgs.getLastArgValue(OBJDUMP_triple_EQ).str();
2674   UnwindInfo = InputArgs.hasArg(OBJDUMP_unwind_info);
2675   Wide = InputArgs.hasArg(OBJDUMP_wide);
2676   Prefix = InputArgs.getLastArgValue(OBJDUMP_prefix).str();
2677   parseIntArg(InputArgs, OBJDUMP_prefix_strip, PrefixStrip);
2678   if (const opt::Arg *A = InputArgs.getLastArg(OBJDUMP_debug_vars_EQ)) {
2679     DbgVariables = StringSwitch<DebugVarsFormat>(A->getValue())
2680                        .Case("ascii", DVASCII)
2681                        .Case("unicode", DVUnicode)
2682                        .Default(DVInvalid);
2683     if (DbgVariables == DVInvalid)
2684       invalidArgValue(A);
2685   }
2686   parseIntArg(InputArgs, OBJDUMP_debug_vars_indent_EQ, DbgIndent);
2687 
2688   parseMachOOptions(InputArgs);
2689 
2690   // Parse -M (--disassembler-options) and deprecated
2691   // --x86-asm-syntax={att,intel}.
2692   //
2693   // Note, for x86, the asm dialect (AssemblerDialect) is initialized when the
2694   // MCAsmInfo is constructed. MCInstPrinter::applyTargetSpecificCLOption is
2695   // called too late. For now we have to use the internal cl::opt option.
2696   const char *AsmSyntax = nullptr;
2697   for (const auto *A : InputArgs.filtered(OBJDUMP_disassembler_options_EQ,
2698                                           OBJDUMP_x86_asm_syntax_att,
2699                                           OBJDUMP_x86_asm_syntax_intel)) {
2700     switch (A->getOption().getID()) {
2701     case OBJDUMP_x86_asm_syntax_att:
2702       AsmSyntax = "--x86-asm-syntax=att";
2703       continue;
2704     case OBJDUMP_x86_asm_syntax_intel:
2705       AsmSyntax = "--x86-asm-syntax=intel";
2706       continue;
2707     }
2708 
2709     SmallVector<StringRef, 2> Values;
2710     llvm::SplitString(A->getValue(), Values, ",");
2711     for (StringRef V : Values) {
2712       if (V == "att")
2713         AsmSyntax = "--x86-asm-syntax=att";
2714       else if (V == "intel")
2715         AsmSyntax = "--x86-asm-syntax=intel";
2716       else
2717         DisassemblerOptions.push_back(V.str());
2718     }
2719   }
2720   if (AsmSyntax) {
2721     const char *Argv[] = {"llvm-objdump", AsmSyntax};
2722     llvm::cl::ParseCommandLineOptions(2, Argv);
2723   }
2724 
2725   // objdump defaults to a.out if no filenames specified.
2726   if (InputFilenames.empty())
2727     InputFilenames.push_back("a.out");
2728 }
2729 
2730 int main(int argc, char **argv) {
2731   using namespace llvm;
2732   InitLLVM X(argc, argv);
2733 
2734   ToolName = argv[0];
2735   std::unique_ptr<CommonOptTable> T;
2736   OptSpecifier Unknown, HelpFlag, HelpHiddenFlag, VersionFlag;
2737 
2738   StringRef Stem = sys::path::stem(ToolName);
2739   auto Is = [=](StringRef Tool) {
2740     // We need to recognize the following filenames:
2741     //
2742     // llvm-objdump -> objdump
2743     // llvm-otool-10.exe -> otool
2744     // powerpc64-unknown-freebsd13-objdump -> objdump
2745     auto I = Stem.rfind_insensitive(Tool);
2746     return I != StringRef::npos &&
2747            (I + Tool.size() == Stem.size() || !isAlnum(Stem[I + Tool.size()]));
2748   };
2749   if (Is("otool")) {
2750     T = std::make_unique<OtoolOptTable>();
2751     Unknown = OTOOL_UNKNOWN;
2752     HelpFlag = OTOOL_help;
2753     HelpHiddenFlag = OTOOL_help_hidden;
2754     VersionFlag = OTOOL_version;
2755   } else {
2756     T = std::make_unique<ObjdumpOptTable>();
2757     Unknown = OBJDUMP_UNKNOWN;
2758     HelpFlag = OBJDUMP_help;
2759     HelpHiddenFlag = OBJDUMP_help_hidden;
2760     VersionFlag = OBJDUMP_version;
2761   }
2762 
2763   BumpPtrAllocator A;
2764   StringSaver Saver(A);
2765   opt::InputArgList InputArgs =
2766       T->parseArgs(argc, argv, Unknown, Saver,
2767                    [&](StringRef Msg) { reportCmdLineError(Msg); });
2768 
2769   if (InputArgs.size() == 0 || InputArgs.hasArg(HelpFlag)) {
2770     T->printHelp(ToolName);
2771     return 0;
2772   }
2773   if (InputArgs.hasArg(HelpHiddenFlag)) {
2774     T->printHelp(ToolName, /*ShowHidden=*/true);
2775     return 0;
2776   }
2777 
2778   // Initialize targets and assembly printers/parsers.
2779   InitializeAllTargetInfos();
2780   InitializeAllTargetMCs();
2781   InitializeAllDisassemblers();
2782 
2783   if (InputArgs.hasArg(VersionFlag)) {
2784     cl::PrintVersionMessage();
2785     if (!Is("otool")) {
2786       outs() << '\n';
2787       TargetRegistry::printRegisteredTargetsForVersion(outs());
2788     }
2789     return 0;
2790   }
2791 
2792   if (Is("otool"))
2793     parseOtoolOptions(InputArgs);
2794   else
2795     parseObjdumpOptions(InputArgs);
2796 
2797   if (StartAddress >= StopAddress)
2798     reportCmdLineError("start address should be less than stop address");
2799 
2800   // Removes trailing separators from prefix.
2801   while (!Prefix.empty() && sys::path::is_separator(Prefix.back()))
2802     Prefix.pop_back();
2803 
2804   if (AllHeaders)
2805     ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations =
2806         SectionHeaders = SymbolTable = true;
2807 
2808   if (DisassembleAll || PrintSource || PrintLines ||
2809       !DisassembleSymbols.empty())
2810     Disassemble = true;
2811 
2812   if (!ArchiveHeaders && !Disassemble && DwarfDumpType == DIDT_Null &&
2813       !DynamicRelocations && !FileHeaders && !PrivateHeaders && !RawClangAST &&
2814       !Relocations && !SectionHeaders && !SectionContents && !SymbolTable &&
2815       !DynamicSymbolTable && !UnwindInfo && !FaultMapSection &&
2816       !(MachOOpt && (Bind || DataInCode || DyldInfo || DylibId || DylibsUsed ||
2817                      ExportsTrie || FirstPrivateHeader || FunctionStarts ||
2818                      IndirectSymbols || InfoPlist || LazyBind || LinkOptHints ||
2819                      ObjcMetaData || Rebase || Rpaths || UniversalHeaders ||
2820                      WeakBind || !FilterSections.empty()))) {
2821     T->printHelp(ToolName);
2822     return 2;
2823   }
2824 
2825   DisasmSymbolSet.insert(DisassembleSymbols.begin(), DisassembleSymbols.end());
2826 
2827   llvm::for_each(InputFilenames, dumpInput);
2828 
2829   warnOnNoMatchForSections();
2830 
2831   return EXIT_SUCCESS;
2832 }
2833