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