xref: /llvm-project/llvm/tools/llvm-objdump/llvm-objdump.cpp (revision 31579e9d1932a6052f31abc30cab2ea8c1872e80)
1 //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This program is a utility that works like binutils "objdump", that is, it
11 // dumps out a plethora of information about an object file depending on the
12 // flags.
13 //
14 // The flags and output of this program should be near identical to those of
15 // binutils objdump.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm-objdump.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringSet.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/CodeGen/FaultMaps.h"
26 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
27 #include "llvm/DebugInfo/Symbolize/Symbolize.h"
28 #include "llvm/Demangle/Demangle.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/MC/MCContext.h"
31 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
32 #include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
33 #include "llvm/MC/MCInst.h"
34 #include "llvm/MC/MCInstPrinter.h"
35 #include "llvm/MC/MCInstrAnalysis.h"
36 #include "llvm/MC/MCInstrInfo.h"
37 #include "llvm/MC/MCObjectFileInfo.h"
38 #include "llvm/MC/MCRegisterInfo.h"
39 #include "llvm/MC/MCSubtargetInfo.h"
40 #include "llvm/Object/Archive.h"
41 #include "llvm/Object/COFF.h"
42 #include "llvm/Object/COFFImportFile.h"
43 #include "llvm/Object/ELFObjectFile.h"
44 #include "llvm/Object/MachO.h"
45 #include "llvm/Object/MachOUniversal.h"
46 #include "llvm/Object/ObjectFile.h"
47 #include "llvm/Object/Wasm.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/Errc.h"
52 #include "llvm/Support/FileSystem.h"
53 #include "llvm/Support/Format.h"
54 #include "llvm/Support/GraphWriter.h"
55 #include "llvm/Support/Host.h"
56 #include "llvm/Support/InitLLVM.h"
57 #include "llvm/Support/MemoryBuffer.h"
58 #include "llvm/Support/SourceMgr.h"
59 #include "llvm/Support/StringSaver.h"
60 #include "llvm/Support/TargetRegistry.h"
61 #include "llvm/Support/TargetSelect.h"
62 #include "llvm/Support/raw_ostream.h"
63 #include <algorithm>
64 #include <cctype>
65 #include <cstring>
66 #include <system_error>
67 #include <unordered_map>
68 #include <utility>
69 
70 using namespace llvm;
71 using namespace object;
72 
73 cl::opt<bool>
74     llvm::AllHeaders("all-headers",
75                      cl::desc("Display all available header information"));
76 static cl::alias AllHeadersShort("x", cl::desc("Alias for --all-headers"),
77                                  cl::aliasopt(AllHeaders));
78 
79 static cl::list<std::string>
80 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
81 
82 cl::opt<bool>
83 llvm::Disassemble("disassemble",
84   cl::desc("Display assembler mnemonics for the machine instructions"));
85 static cl::alias
86 Disassembled("d", cl::desc("Alias for --disassemble"),
87              cl::aliasopt(Disassemble));
88 
89 cl::opt<bool>
90 llvm::DisassembleAll("disassemble-all",
91   cl::desc("Display assembler mnemonics for the machine instructions"));
92 static cl::alias
93 DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
94              cl::aliasopt(DisassembleAll));
95 
96 cl::opt<bool> llvm::Demangle("demangle", cl::desc("Demangle symbols names"),
97                              cl::init(false));
98 
99 static cl::alias DemangleShort("C", cl::desc("Alias for --demangle"),
100                                cl::aliasopt(llvm::Demangle));
101 
102 static cl::list<std::string>
103 DisassembleFunctions("df",
104                      cl::CommaSeparated,
105                      cl::desc("List of functions to disassemble"));
106 static StringSet<> DisasmFuncsSet;
107 
108 cl::opt<bool>
109 llvm::Relocations("reloc",
110                   cl::desc("Display the relocation entries in the file"));
111 static cl::alias RelocationsShort("r", cl::desc("Alias for --reloc"),
112                                   cl::NotHidden,
113                                   cl::aliasopt(llvm::Relocations));
114 
115 cl::opt<bool>
116 llvm::DynamicRelocations("dynamic-reloc",
117   cl::desc("Display the dynamic relocation entries in the file"));
118 static cl::alias
119 DynamicRelocationsd("R", cl::desc("Alias for --dynamic-reloc"),
120              cl::aliasopt(DynamicRelocations));
121 
122 cl::opt<bool>
123     llvm::SectionContents("full-contents",
124                           cl::desc("Display the content of each section"));
125 static cl::alias SectionContentsShort("s",
126                                       cl::desc("Alias for --full-contents"),
127                                       cl::aliasopt(SectionContents));
128 
129 cl::opt<bool> llvm::SymbolTable("syms", cl::desc("Display the symbol table"));
130 static cl::alias SymbolTableShort("t", cl::desc("Alias for --syms"),
131                                   cl::aliasopt(llvm::SymbolTable));
132 
133 cl::opt<bool>
134 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
135 
136 cl::opt<bool>
137 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
138 
139 cl::opt<bool>
140 llvm::Bind("bind", cl::desc("Display mach-o binding info"));
141 
142 cl::opt<bool>
143 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
144 
145 cl::opt<bool>
146 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
147 
148 cl::opt<bool>
149 llvm::RawClangAST("raw-clang-ast",
150     cl::desc("Dump the raw binary contents of the clang AST section"));
151 
152 static cl::opt<bool>
153 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
154 static cl::alias
155 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
156 
157 cl::opt<std::string>
158 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
159                                     "see -version for available targets"));
160 
161 cl::opt<std::string>
162 llvm::MCPU("mcpu",
163      cl::desc("Target a specific cpu type (-mcpu=help for details)"),
164      cl::value_desc("cpu-name"),
165      cl::init(""));
166 
167 cl::opt<std::string>
168 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
169                                 "see -version for available targets"));
170 
171 cl::opt<bool>
172 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
173                                                  "headers for each section."));
174 static cl::alias
175 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
176                     cl::aliasopt(SectionHeaders));
177 static cl::alias
178 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
179                       cl::aliasopt(SectionHeaders));
180 
181 cl::list<std::string>
182 llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
183                                          "With -macho dump segment,section"));
184 cl::alias
185 static FilterSectionsj("j", cl::desc("Alias for --section"),
186                  cl::aliasopt(llvm::FilterSections));
187 
188 cl::list<std::string>
189 llvm::MAttrs("mattr",
190   cl::CommaSeparated,
191   cl::desc("Target specific attributes"),
192   cl::value_desc("a1,+a2,-a3,..."));
193 
194 cl::opt<bool>
195 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
196                                                  "instructions, do not print "
197                                                  "the instruction bytes."));
198 cl::opt<bool>
199 llvm::NoLeadingAddr("no-leading-addr", cl::desc("Print no leading address"));
200 
201 cl::opt<bool>
202 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
203 
204 static cl::alias
205 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
206                 cl::aliasopt(UnwindInfo));
207 
208 cl::opt<bool>
209 llvm::PrivateHeaders("private-headers",
210                      cl::desc("Display format specific file headers"));
211 
212 cl::opt<bool>
213 llvm::FirstPrivateHeader("private-header",
214                          cl::desc("Display only the first format specific file "
215                                   "header"));
216 
217 static cl::alias
218 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
219                     cl::aliasopt(PrivateHeaders));
220 
221 cl::opt<bool> llvm::FileHeaders(
222     "file-headers",
223     cl::desc("Display the contents of the overall file header"));
224 
225 static cl::alias FileHeadersShort("f", cl::desc("Alias for --file-headers"),
226                                   cl::aliasopt(FileHeaders));
227 
228 cl::opt<bool>
229     llvm::ArchiveHeaders("archive-headers",
230                          cl::desc("Display archive header information"));
231 
232 cl::alias
233 ArchiveHeadersShort("a", cl::desc("Alias for --archive-headers"),
234                     cl::aliasopt(ArchiveHeaders));
235 
236 cl::opt<bool>
237     llvm::PrintImmHex("print-imm-hex",
238                       cl::desc("Use hex format for immediate values"));
239 
240 cl::opt<bool> PrintFaultMaps("fault-map-section",
241                              cl::desc("Display contents of faultmap section"));
242 
243 cl::opt<DIDumpType> llvm::DwarfDumpType(
244     "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
245     cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")));
246 
247 cl::opt<bool> PrintSource(
248     "source",
249     cl::desc(
250         "Display source inlined with disassembly. Implies disassemble object"));
251 
252 cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
253                            cl::aliasopt(PrintSource));
254 
255 cl::opt<bool> PrintLines("line-numbers",
256                          cl::desc("Display source line numbers with "
257                                   "disassembly. Implies disassemble object"));
258 
259 cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"),
260                           cl::aliasopt(PrintLines));
261 
262 cl::opt<unsigned long long>
263     StartAddress("start-address", cl::desc("Disassemble beginning at address"),
264                  cl::value_desc("address"), cl::init(0));
265 cl::opt<unsigned long long>
266     StopAddress("stop-address", cl::desc("Stop disassembly at address"),
267                 cl::value_desc("address"), cl::init(UINT64_MAX));
268 static StringRef ToolName;
269 
270 typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
271 
272 namespace {
273 typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
274 
275 class SectionFilterIterator {
276 public:
277   SectionFilterIterator(FilterPredicate P,
278                         llvm::object::section_iterator const &I,
279                         llvm::object::section_iterator const &E)
280       : Predicate(std::move(P)), Iterator(I), End(E) {
281     ScanPredicate();
282   }
283   const llvm::object::SectionRef &operator*() const { return *Iterator; }
284   SectionFilterIterator &operator++() {
285     ++Iterator;
286     ScanPredicate();
287     return *this;
288   }
289   bool operator!=(SectionFilterIterator const &Other) const {
290     return Iterator != Other.Iterator;
291   }
292 
293 private:
294   void ScanPredicate() {
295     while (Iterator != End && !Predicate(*Iterator)) {
296       ++Iterator;
297     }
298   }
299   FilterPredicate Predicate;
300   llvm::object::section_iterator Iterator;
301   llvm::object::section_iterator End;
302 };
303 
304 class SectionFilter {
305 public:
306   SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
307       : Predicate(std::move(P)), Object(O) {}
308   SectionFilterIterator begin() {
309     return SectionFilterIterator(Predicate, Object.section_begin(),
310                                  Object.section_end());
311   }
312   SectionFilterIterator end() {
313     return SectionFilterIterator(Predicate, Object.section_end(),
314                                  Object.section_end());
315   }
316 
317 private:
318   FilterPredicate Predicate;
319   llvm::object::ObjectFile const &Object;
320 };
321 SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
322   return SectionFilter(
323       [](llvm::object::SectionRef const &S) {
324         if (FilterSections.empty())
325           return true;
326         llvm::StringRef String;
327         std::error_code error = S.getName(String);
328         if (error)
329           return false;
330         return is_contained(FilterSections, String);
331       },
332       O);
333 }
334 }
335 
336 void llvm::error(std::error_code EC) {
337   if (!EC)
338     return;
339 
340   errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
341   errs().flush();
342   exit(1);
343 }
344 
345 LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
346   errs() << ToolName << ": " << Message << ".\n";
347   errs().flush();
348   exit(1);
349 }
350 
351 void llvm::warn(StringRef Message) {
352   errs() << ToolName << ": warning: " << Message << ".\n";
353   errs().flush();
354 }
355 
356 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
357                                                 Twine Message) {
358   errs() << ToolName << ": '" << File << "': " << Message << ".\n";
359   exit(1);
360 }
361 
362 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
363                                                 std::error_code EC) {
364   assert(EC);
365   errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
366   exit(1);
367 }
368 
369 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
370                                                 llvm::Error E) {
371   assert(E);
372   std::string Buf;
373   raw_string_ostream OS(Buf);
374   logAllUnhandledErrors(std::move(E), OS, "");
375   OS.flush();
376   errs() << ToolName << ": '" << File << "': " << Buf;
377   exit(1);
378 }
379 
380 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
381                                                 StringRef FileName,
382                                                 llvm::Error E,
383                                                 StringRef ArchitectureName) {
384   assert(E);
385   errs() << ToolName << ": ";
386   if (ArchiveName != "")
387     errs() << ArchiveName << "(" << FileName << ")";
388   else
389     errs() << "'" << FileName << "'";
390   if (!ArchitectureName.empty())
391     errs() << " (for architecture " << ArchitectureName << ")";
392   std::string Buf;
393   raw_string_ostream OS(Buf);
394   logAllUnhandledErrors(std::move(E), OS, "");
395   OS.flush();
396   errs() << ": " << Buf;
397   exit(1);
398 }
399 
400 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
401                                                 const object::Archive::Child &C,
402                                                 llvm::Error E,
403                                                 StringRef ArchitectureName) {
404   Expected<StringRef> NameOrErr = C.getName();
405   // TODO: if we have a error getting the name then it would be nice to print
406   // the index of which archive member this is and or its offset in the
407   // archive instead of "???" as the name.
408   if (!NameOrErr) {
409     consumeError(NameOrErr.takeError());
410     llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
411   } else
412     llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
413                        ArchitectureName);
414 }
415 
416 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
417   // Figure out the target triple.
418   llvm::Triple TheTriple("unknown-unknown-unknown");
419   if (TripleName.empty()) {
420     if (Obj) {
421       TheTriple = Obj->makeTriple();
422     }
423   } else {
424     TheTriple.setTriple(Triple::normalize(TripleName));
425 
426     // Use the triple, but also try to combine with ARM build attributes.
427     if (Obj) {
428       auto Arch = Obj->getArch();
429       if (Arch == Triple::arm || Arch == Triple::armeb) {
430         Obj->setARMSubArch(TheTriple);
431       }
432     }
433   }
434 
435   // Get the target specific parser.
436   std::string Error;
437   const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
438                                                          Error);
439   if (!TheTarget) {
440     if (Obj)
441       report_error(Obj->getFileName(), "can't find target: " + Error);
442     else
443       error("can't find target: " + Error);
444   }
445 
446   // Update the triple name and return the found target.
447   TripleName = TheTriple.getTriple();
448   return TheTarget;
449 }
450 
451 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
452   return a.getOffset() < b.getOffset();
453 }
454 
455 template <class ELFT>
456 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
457                                                 const RelocationRef &RelRef,
458                                                 SmallVectorImpl<char> &Result) {
459   DataRefImpl Rel = RelRef.getRawDataRefImpl();
460 
461   typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
462   typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
463   typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
464 
465   const ELFFile<ELFT> &EF = *Obj->getELFFile();
466 
467   auto SecOrErr = EF.getSection(Rel.d.a);
468   if (!SecOrErr)
469     return errorToErrorCode(SecOrErr.takeError());
470   const Elf_Shdr *Sec = *SecOrErr;
471   auto SymTabOrErr = EF.getSection(Sec->sh_link);
472   if (!SymTabOrErr)
473     return errorToErrorCode(SymTabOrErr.takeError());
474   const Elf_Shdr *SymTab = *SymTabOrErr;
475   assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
476          SymTab->sh_type == ELF::SHT_DYNSYM);
477   auto StrTabSec = EF.getSection(SymTab->sh_link);
478   if (!StrTabSec)
479     return errorToErrorCode(StrTabSec.takeError());
480   auto StrTabOrErr = EF.getStringTable(*StrTabSec);
481   if (!StrTabOrErr)
482     return errorToErrorCode(StrTabOrErr.takeError());
483   StringRef StrTab = *StrTabOrErr;
484   int64_t addend = 0;
485   // If there is no Symbol associated with the relocation, we set the undef
486   // boolean value to 'true'. This will prevent us from calling functions that
487   // requires the relocation to be associated with a symbol.
488   bool undef = false;
489   switch (Sec->sh_type) {
490   default:
491     return object_error::parse_failed;
492   case ELF::SHT_REL: {
493     // TODO: Read implicit addend from section data.
494     break;
495   }
496   case ELF::SHT_RELA: {
497     const Elf_Rela *ERela = Obj->getRela(Rel);
498     addend = ERela->r_addend;
499     undef = ERela->getSymbol(false) == 0;
500     break;
501   }
502   }
503   StringRef Target;
504   if (!undef) {
505     symbol_iterator SI = RelRef.getSymbol();
506     const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
507     if (symb->getType() == ELF::STT_SECTION) {
508       Expected<section_iterator> SymSI = SI->getSection();
509       if (!SymSI)
510         return errorToErrorCode(SymSI.takeError());
511       const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
512       auto SecName = EF.getSectionName(SymSec);
513       if (!SecName)
514         return errorToErrorCode(SecName.takeError());
515       Target = *SecName;
516     } else {
517       Expected<StringRef> SymName = symb->getName(StrTab);
518       if (!SymName)
519         return errorToErrorCode(SymName.takeError());
520       Target = *SymName;
521     }
522   } else
523     Target = "*ABS*";
524 
525   // Default scheme is to print Target, as well as "+ <addend>" for nonzero
526   // addend. Should be acceptable for all normal purposes.
527   std::string fmtbuf;
528   raw_string_ostream fmt(fmtbuf);
529   fmt << Target;
530   if (addend != 0)
531     fmt << (addend < 0 ? "" : "+") << addend;
532   fmt.flush();
533   Result.append(fmtbuf.begin(), fmtbuf.end());
534   return std::error_code();
535 }
536 
537 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
538                                                 const RelocationRef &Rel,
539                                                 SmallVectorImpl<char> &Result) {
540   if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
541     return getRelocationValueString(ELF32LE, Rel, Result);
542   if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
543     return getRelocationValueString(ELF64LE, Rel, Result);
544   if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
545     return getRelocationValueString(ELF32BE, Rel, Result);
546   auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
547   return getRelocationValueString(ELF64BE, Rel, Result);
548 }
549 
550 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
551                                                 const RelocationRef &Rel,
552                                                 SmallVectorImpl<char> &Result) {
553   symbol_iterator SymI = Rel.getSymbol();
554   Expected<StringRef> SymNameOrErr = SymI->getName();
555   if (!SymNameOrErr)
556     return errorToErrorCode(SymNameOrErr.takeError());
557   StringRef SymName = *SymNameOrErr;
558   Result.append(SymName.begin(), SymName.end());
559   return std::error_code();
560 }
561 
562 static void printRelocationTargetName(const MachOObjectFile *O,
563                                       const MachO::any_relocation_info &RE,
564                                       raw_string_ostream &fmt) {
565   bool IsScattered = O->isRelocationScattered(RE);
566 
567   // Target of a scattered relocation is an address.  In the interest of
568   // generating pretty output, scan through the symbol table looking for a
569   // symbol that aligns with that address.  If we find one, print it.
570   // Otherwise, we just print the hex address of the target.
571   if (IsScattered) {
572     uint32_t Val = O->getPlainRelocationSymbolNum(RE);
573 
574     for (const SymbolRef &Symbol : O->symbols()) {
575       std::error_code ec;
576       Expected<uint64_t> Addr = Symbol.getAddress();
577       if (!Addr)
578         report_error(O->getFileName(), Addr.takeError());
579       if (*Addr != Val)
580         continue;
581       Expected<StringRef> Name = Symbol.getName();
582       if (!Name)
583         report_error(O->getFileName(), Name.takeError());
584       fmt << *Name;
585       return;
586     }
587 
588     // If we couldn't find a symbol that this relocation refers to, try
589     // to find a section beginning instead.
590     for (const SectionRef &Section : ToolSectionFilter(*O)) {
591       std::error_code ec;
592 
593       StringRef Name;
594       uint64_t Addr = Section.getAddress();
595       if (Addr != Val)
596         continue;
597       if ((ec = Section.getName(Name)))
598         report_error(O->getFileName(), ec);
599       fmt << Name;
600       return;
601     }
602 
603     fmt << format("0x%x", Val);
604     return;
605   }
606 
607   StringRef S;
608   bool isExtern = O->getPlainRelocationExternal(RE);
609   uint64_t Val = O->getPlainRelocationSymbolNum(RE);
610 
611   if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
612     fmt << format("0x%0" PRIx64, Val);
613     return;
614   } else if (isExtern) {
615     symbol_iterator SI = O->symbol_begin();
616     advance(SI, Val);
617     Expected<StringRef> SOrErr = SI->getName();
618     if (!SOrErr)
619       report_error(O->getFileName(), SOrErr.takeError());
620     S = *SOrErr;
621   } else {
622     section_iterator SI = O->section_begin();
623     // Adjust for the fact that sections are 1-indexed.
624     if (Val == 0) {
625       fmt << "0 (?,?)";
626       return;
627     }
628     uint32_t i = Val - 1;
629     while (i != 0 && SI != O->section_end()) {
630       i--;
631       advance(SI, 1);
632     }
633     if (SI == O->section_end())
634       fmt << Val << " (?,?)";
635     else
636       SI->getName(S);
637   }
638 
639   fmt << S;
640 }
641 
642 static std::error_code getRelocationValueString(const WasmObjectFile *Obj,
643                                                 const RelocationRef &RelRef,
644                                                 SmallVectorImpl<char> &Result) {
645   const wasm::WasmRelocation& Rel = Obj->getWasmRelocation(RelRef);
646   symbol_iterator SI = RelRef.getSymbol();
647   std::string fmtbuf;
648   raw_string_ostream fmt(fmtbuf);
649   if (SI == Obj->symbol_end()) {
650     // Not all wasm relocations have symbols associated with them.
651     // In particular R_WEBASSEMBLY_TYPE_INDEX_LEB.
652     fmt << Rel.Index;
653   } else {
654     Expected<StringRef> SymNameOrErr = SI->getName();
655     if (!SymNameOrErr)
656       return errorToErrorCode(SymNameOrErr.takeError());
657     StringRef SymName = *SymNameOrErr;
658     Result.append(SymName.begin(), SymName.end());
659   }
660   fmt << (Rel.Addend < 0 ? "" : "+") << Rel.Addend;
661   fmt.flush();
662   Result.append(fmtbuf.begin(), fmtbuf.end());
663   return std::error_code();
664 }
665 
666 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
667                                                 const RelocationRef &RelRef,
668                                                 SmallVectorImpl<char> &Result) {
669   DataRefImpl Rel = RelRef.getRawDataRefImpl();
670   MachO::any_relocation_info RE = Obj->getRelocation(Rel);
671 
672   unsigned Arch = Obj->getArch();
673 
674   std::string fmtbuf;
675   raw_string_ostream fmt(fmtbuf);
676   unsigned Type = Obj->getAnyRelocationType(RE);
677   bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
678 
679   // Determine any addends that should be displayed with the relocation.
680   // These require decoding the relocation type, which is triple-specific.
681 
682   // X86_64 has entirely custom relocation types.
683   if (Arch == Triple::x86_64) {
684     bool isPCRel = Obj->getAnyRelocationPCRel(RE);
685 
686     switch (Type) {
687     case MachO::X86_64_RELOC_GOT_LOAD:
688     case MachO::X86_64_RELOC_GOT: {
689       printRelocationTargetName(Obj, RE, fmt);
690       fmt << "@GOT";
691       if (isPCRel)
692         fmt << "PCREL";
693       break;
694     }
695     case MachO::X86_64_RELOC_SUBTRACTOR: {
696       DataRefImpl RelNext = Rel;
697       Obj->moveRelocationNext(RelNext);
698       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
699 
700       // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
701       // X86_64_RELOC_UNSIGNED.
702       // NOTE: Scattered relocations don't exist on x86_64.
703       unsigned RType = Obj->getAnyRelocationType(RENext);
704       if (RType != MachO::X86_64_RELOC_UNSIGNED)
705         report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
706                      "X86_64_RELOC_SUBTRACTOR.");
707 
708       // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
709       // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
710       printRelocationTargetName(Obj, RENext, fmt);
711       fmt << "-";
712       printRelocationTargetName(Obj, RE, fmt);
713       break;
714     }
715     case MachO::X86_64_RELOC_TLV:
716       printRelocationTargetName(Obj, RE, fmt);
717       fmt << "@TLV";
718       if (isPCRel)
719         fmt << "P";
720       break;
721     case MachO::X86_64_RELOC_SIGNED_1:
722       printRelocationTargetName(Obj, RE, fmt);
723       fmt << "-1";
724       break;
725     case MachO::X86_64_RELOC_SIGNED_2:
726       printRelocationTargetName(Obj, RE, fmt);
727       fmt << "-2";
728       break;
729     case MachO::X86_64_RELOC_SIGNED_4:
730       printRelocationTargetName(Obj, RE, fmt);
731       fmt << "-4";
732       break;
733     default:
734       printRelocationTargetName(Obj, RE, fmt);
735       break;
736     }
737     // X86 and ARM share some relocation types in common.
738   } else if (Arch == Triple::x86 || Arch == Triple::arm ||
739              Arch == Triple::ppc) {
740     // Generic relocation types...
741     switch (Type) {
742     case MachO::GENERIC_RELOC_PAIR: // prints no info
743       return std::error_code();
744     case MachO::GENERIC_RELOC_SECTDIFF: {
745       DataRefImpl RelNext = Rel;
746       Obj->moveRelocationNext(RelNext);
747       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
748 
749       // X86 sect diff's must be followed by a relocation of type
750       // GENERIC_RELOC_PAIR.
751       unsigned RType = Obj->getAnyRelocationType(RENext);
752 
753       if (RType != MachO::GENERIC_RELOC_PAIR)
754         report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
755                      "GENERIC_RELOC_SECTDIFF.");
756 
757       printRelocationTargetName(Obj, RE, fmt);
758       fmt << "-";
759       printRelocationTargetName(Obj, RENext, fmt);
760       break;
761     }
762     }
763 
764     if (Arch == Triple::x86 || Arch == Triple::ppc) {
765       switch (Type) {
766       case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
767         DataRefImpl RelNext = Rel;
768         Obj->moveRelocationNext(RelNext);
769         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
770 
771         // X86 sect diff's must be followed by a relocation of type
772         // GENERIC_RELOC_PAIR.
773         unsigned RType = Obj->getAnyRelocationType(RENext);
774         if (RType != MachO::GENERIC_RELOC_PAIR)
775           report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
776                        "GENERIC_RELOC_LOCAL_SECTDIFF.");
777 
778         printRelocationTargetName(Obj, RE, fmt);
779         fmt << "-";
780         printRelocationTargetName(Obj, RENext, fmt);
781         break;
782       }
783       case MachO::GENERIC_RELOC_TLV: {
784         printRelocationTargetName(Obj, RE, fmt);
785         fmt << "@TLV";
786         if (IsPCRel)
787           fmt << "P";
788         break;
789       }
790       default:
791         printRelocationTargetName(Obj, RE, fmt);
792       }
793     } else { // ARM-specific relocations
794       switch (Type) {
795       case MachO::ARM_RELOC_HALF:
796       case MachO::ARM_RELOC_HALF_SECTDIFF: {
797         // Half relocations steal a bit from the length field to encode
798         // whether this is an upper16 or a lower16 relocation.
799         bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
800 
801         if (isUpper)
802           fmt << ":upper16:(";
803         else
804           fmt << ":lower16:(";
805         printRelocationTargetName(Obj, RE, fmt);
806 
807         DataRefImpl RelNext = Rel;
808         Obj->moveRelocationNext(RelNext);
809         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
810 
811         // ARM half relocs must be followed by a relocation of type
812         // ARM_RELOC_PAIR.
813         unsigned RType = Obj->getAnyRelocationType(RENext);
814         if (RType != MachO::ARM_RELOC_PAIR)
815           report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
816                        "ARM_RELOC_HALF");
817 
818         // NOTE: The half of the target virtual address is stashed in the
819         // address field of the secondary relocation, but we can't reverse
820         // engineer the constant offset from it without decoding the movw/movt
821         // instruction to find the other half in its immediate field.
822 
823         // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
824         // symbol/section pointer of the follow-on relocation.
825         if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
826           fmt << "-";
827           printRelocationTargetName(Obj, RENext, fmt);
828         }
829 
830         fmt << ")";
831         break;
832       }
833       default: { printRelocationTargetName(Obj, RE, fmt); }
834       }
835     }
836   } else
837     printRelocationTargetName(Obj, RE, fmt);
838 
839   fmt.flush();
840   Result.append(fmtbuf.begin(), fmtbuf.end());
841   return std::error_code();
842 }
843 
844 static std::error_code getRelocationValueString(const RelocationRef &Rel,
845                                                 SmallVectorImpl<char> &Result) {
846   const ObjectFile *Obj = Rel.getObject();
847   if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
848     return getRelocationValueString(ELF, Rel, Result);
849   if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
850     return getRelocationValueString(COFF, Rel, Result);
851   if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
852     return getRelocationValueString(Wasm, Rel, Result);
853   if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
854     return getRelocationValueString(MachO, Rel, Result);
855   llvm_unreachable("unknown object file format");
856 }
857 
858 /// Indicates whether this relocation should hidden when listing
859 /// relocations, usually because it is the trailing part of a multipart
860 /// relocation that will be printed as part of the leading relocation.
861 static bool getHidden(RelocationRef RelRef) {
862   const ObjectFile *Obj = RelRef.getObject();
863   auto *MachO = dyn_cast<MachOObjectFile>(Obj);
864   if (!MachO)
865     return false;
866 
867   unsigned Arch = MachO->getArch();
868   DataRefImpl Rel = RelRef.getRawDataRefImpl();
869   uint64_t Type = MachO->getRelocationType(Rel);
870 
871   // On arches that use the generic relocations, GENERIC_RELOC_PAIR
872   // is always hidden.
873   if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
874     if (Type == MachO::GENERIC_RELOC_PAIR)
875       return true;
876   } else if (Arch == Triple::x86_64) {
877     // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
878     // an X86_64_RELOC_SUBTRACTOR.
879     if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
880       DataRefImpl RelPrev = Rel;
881       RelPrev.d.a--;
882       uint64_t PrevType = MachO->getRelocationType(RelPrev);
883       if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
884         return true;
885     }
886   }
887 
888   return false;
889 }
890 
891 namespace {
892 class SourcePrinter {
893 protected:
894   DILineInfo OldLineInfo;
895   const ObjectFile *Obj = nullptr;
896   std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
897   // File name to file contents of source
898   std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
899   // Mark the line endings of the cached source
900   std::unordered_map<std::string, std::vector<StringRef>> LineCache;
901 
902 private:
903   bool cacheSource(const DILineInfo& LineInfoFile);
904 
905 public:
906   SourcePrinter() = default;
907   SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
908     symbolize::LLVMSymbolizer::Options SymbolizerOpts(
909         DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
910         DefaultArch);
911     Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
912   }
913   virtual ~SourcePrinter() = default;
914   virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
915                                StringRef Delimiter = "; ");
916 };
917 
918 bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
919   std::unique_ptr<MemoryBuffer> Buffer;
920   if (LineInfo.Source) {
921     Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);
922   } else {
923     auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName);
924     if (!BufferOrError)
925       return false;
926     Buffer = std::move(*BufferOrError);
927   }
928   // Chomp the file to get lines
929   size_t BufferSize = Buffer->getBufferSize();
930   const char *BufferStart = Buffer->getBufferStart();
931   for (const char *Start = BufferStart, *End = BufferStart;
932        End < BufferStart + BufferSize; End++)
933     if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
934         (*End == '\r' && *(End + 1) == '\n')) {
935       LineCache[LineInfo.FileName].push_back(StringRef(Start, End - Start));
936       if (*End == '\r')
937         End++;
938       Start = End + 1;
939     }
940   SourceCache[LineInfo.FileName] = std::move(Buffer);
941   return true;
942 }
943 
944 void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
945                                     StringRef Delimiter) {
946   if (!Symbolizer)
947     return;
948   DILineInfo LineInfo = DILineInfo();
949   auto ExpectecLineInfo =
950       Symbolizer->symbolizeCode(Obj->getFileName(), Address);
951   if (!ExpectecLineInfo)
952     consumeError(ExpectecLineInfo.takeError());
953   else
954     LineInfo = *ExpectecLineInfo;
955 
956   if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
957       LineInfo.Line == 0)
958     return;
959 
960   if (PrintLines)
961     OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
962   if (PrintSource) {
963     if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
964       if (!cacheSource(LineInfo))
965         return;
966     auto FileBuffer = SourceCache.find(LineInfo.FileName);
967     if (FileBuffer != SourceCache.end()) {
968       auto LineBuffer = LineCache.find(LineInfo.FileName);
969       if (LineBuffer != LineCache.end()) {
970         if (LineInfo.Line > LineBuffer->second.size())
971           return;
972         // Vector begins at 0, line numbers are non-zero
973         OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
974            << "\n";
975       }
976     }
977   }
978   OldLineInfo = LineInfo;
979 }
980 
981 static bool isArmElf(const ObjectFile *Obj) {
982   return (Obj->isELF() &&
983           (Obj->getArch() == Triple::aarch64 ||
984            Obj->getArch() == Triple::aarch64_be ||
985            Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
986            Obj->getArch() == Triple::thumb ||
987            Obj->getArch() == Triple::thumbeb));
988 }
989 
990 class PrettyPrinter {
991 public:
992   virtual ~PrettyPrinter() = default;
993   virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
994                          ArrayRef<uint8_t> Bytes, uint64_t Address,
995                          raw_ostream &OS, StringRef Annot,
996                          MCSubtargetInfo const &STI, SourcePrinter *SP,
997                          std::vector<RelocationRef> *Rels = nullptr) {
998     if (SP && (PrintSource || PrintLines))
999       SP->printSourceLine(OS, Address);
1000     if (!NoLeadingAddr)
1001       OS << format("%8" PRIx64 ":", Address);
1002     if (!NoShowRawInsn) {
1003       OS << "\t";
1004       dumpBytes(Bytes, OS);
1005     }
1006     if (MI)
1007       IP.printInst(MI, OS, "", STI);
1008     else
1009       OS << " <unknown>";
1010   }
1011 };
1012 PrettyPrinter PrettyPrinterInst;
1013 class HexagonPrettyPrinter : public PrettyPrinter {
1014 public:
1015   void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
1016                  raw_ostream &OS) {
1017     uint32_t opcode =
1018       (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
1019     if (!NoLeadingAddr)
1020       OS << format("%8" PRIx64 ":", Address);
1021     if (!NoShowRawInsn) {
1022       OS << "\t";
1023       dumpBytes(Bytes.slice(0, 4), OS);
1024       OS << format("%08" PRIx32, opcode);
1025     }
1026   }
1027   void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1028                  uint64_t Address, raw_ostream &OS, StringRef Annot,
1029                  MCSubtargetInfo const &STI, SourcePrinter *SP,
1030                  std::vector<RelocationRef> *Rels) override {
1031     if (SP && (PrintSource || PrintLines))
1032       SP->printSourceLine(OS, Address, "");
1033     if (!MI) {
1034       printLead(Bytes, Address, OS);
1035       OS << " <unknown>";
1036       return;
1037     }
1038     std::string Buffer;
1039     {
1040       raw_string_ostream TempStream(Buffer);
1041       IP.printInst(MI, TempStream, "", STI);
1042     }
1043     StringRef Contents(Buffer);
1044     // Split off bundle attributes
1045     auto PacketBundle = Contents.rsplit('\n');
1046     // Split off first instruction from the rest
1047     auto HeadTail = PacketBundle.first.split('\n');
1048     auto Preamble = " { ";
1049     auto Separator = "";
1050     StringRef Fmt = "\t\t\t%08" PRIx64 ":  ";
1051     std::vector<RelocationRef>::const_iterator rel_cur = Rels->begin();
1052     std::vector<RelocationRef>::const_iterator rel_end = Rels->end();
1053 
1054     // Hexagon's packets require relocations to be inline rather than
1055     // clustered at the end of the packet.
1056     auto PrintReloc = [&]() -> void {
1057       while ((rel_cur != rel_end) && (rel_cur->getOffset() <= Address)) {
1058         if (rel_cur->getOffset() == Address) {
1059           SmallString<16> name;
1060           SmallString<32> val;
1061           rel_cur->getTypeName(name);
1062           error(getRelocationValueString(*rel_cur, val));
1063           OS << Separator << format(Fmt.data(), Address) << name << "\t" << val
1064                 << "\n";
1065           return;
1066         }
1067         rel_cur++;
1068       }
1069     };
1070 
1071     while(!HeadTail.first.empty()) {
1072       OS << Separator;
1073       Separator = "\n";
1074       if (SP && (PrintSource || PrintLines))
1075         SP->printSourceLine(OS, Address, "");
1076       printLead(Bytes, Address, OS);
1077       OS << Preamble;
1078       Preamble = "   ";
1079       StringRef Inst;
1080       auto Duplex = HeadTail.first.split('\v');
1081       if(!Duplex.second.empty()){
1082         OS << Duplex.first;
1083         OS << "; ";
1084         Inst = Duplex.second;
1085       }
1086       else
1087         Inst = HeadTail.first;
1088       OS << Inst;
1089       HeadTail = HeadTail.second.split('\n');
1090       if (HeadTail.first.empty())
1091         OS << " } " << PacketBundle.second;
1092       PrintReloc();
1093       Bytes = Bytes.slice(4);
1094       Address += 4;
1095     }
1096   }
1097 };
1098 HexagonPrettyPrinter HexagonPrettyPrinterInst;
1099 
1100 class AMDGCNPrettyPrinter : public PrettyPrinter {
1101 public:
1102   void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1103                  uint64_t Address, raw_ostream &OS, StringRef Annot,
1104                  MCSubtargetInfo const &STI, SourcePrinter *SP,
1105                  std::vector<RelocationRef> *Rels) override {
1106     if (SP && (PrintSource || PrintLines))
1107       SP->printSourceLine(OS, Address);
1108 
1109     typedef support::ulittle32_t U32;
1110 
1111     if (MI) {
1112       SmallString<40> InstStr;
1113       raw_svector_ostream IS(InstStr);
1114 
1115       IP.printInst(MI, IS, "", STI);
1116 
1117       OS << left_justify(IS.str(), 60);
1118     } else {
1119       // an unrecognized encoding - this is probably data so represent it
1120       // using the .long directive, or .byte directive if fewer than 4 bytes
1121       // remaining
1122       if (Bytes.size() >= 4) {
1123         OS << format("\t.long 0x%08" PRIx32 " ",
1124                      static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data())));
1125         OS.indent(42);
1126       } else {
1127           OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
1128           for (unsigned int i = 1; i < Bytes.size(); i++)
1129             OS << format(", 0x%02" PRIx8, Bytes[i]);
1130           OS.indent(55 - (6 * Bytes.size()));
1131       }
1132     }
1133 
1134     OS << format("// %012" PRIX64 ": ", Address);
1135     if (Bytes.size() >=4) {
1136       for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
1137                                  Bytes.size() / sizeof(U32)))
1138         // D should be explicitly casted to uint32_t here as it is passed
1139         // by format to snprintf as vararg.
1140         OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
1141     } else {
1142       for (unsigned int i = 0; i < Bytes.size(); i++)
1143         OS << format("%02" PRIX8 " ", Bytes[i]);
1144     }
1145 
1146     if (!Annot.empty())
1147       OS << "// " << Annot;
1148   }
1149 };
1150 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
1151 
1152 class BPFPrettyPrinter : public PrettyPrinter {
1153 public:
1154   void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1155                  uint64_t Address, raw_ostream &OS, StringRef Annot,
1156                  MCSubtargetInfo const &STI, SourcePrinter *SP,
1157                  std::vector<RelocationRef> *Rels) override {
1158     if (SP && (PrintSource || PrintLines))
1159       SP->printSourceLine(OS, Address);
1160     if (!NoLeadingAddr)
1161       OS << format("%8" PRId64 ":", Address / 8);
1162     if (!NoShowRawInsn) {
1163       OS << "\t";
1164       dumpBytes(Bytes, OS);
1165     }
1166     if (MI)
1167       IP.printInst(MI, OS, "", STI);
1168     else
1169       OS << " <unknown>";
1170   }
1171 };
1172 BPFPrettyPrinter BPFPrettyPrinterInst;
1173 
1174 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
1175   switch(Triple.getArch()) {
1176   default:
1177     return PrettyPrinterInst;
1178   case Triple::hexagon:
1179     return HexagonPrettyPrinterInst;
1180   case Triple::amdgcn:
1181     return AMDGCNPrettyPrinterInst;
1182   case Triple::bpfel:
1183   case Triple::bpfeb:
1184     return BPFPrettyPrinterInst;
1185   }
1186 }
1187 }
1188 
1189 static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1190   assert(Obj->isELF());
1191   if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1192     return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1193   if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1194     return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1195   if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1196     return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1197   if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1198     return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1199   llvm_unreachable("Unsupported binary format");
1200 }
1201 
1202 template <class ELFT> static void
1203 addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
1204                      std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1205   for (auto Symbol : Obj->getDynamicSymbolIterators()) {
1206     uint8_t SymbolType = Symbol.getELFType();
1207     if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
1208       continue;
1209 
1210     Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1211     if (!AddressOrErr)
1212       report_error(Obj->getFileName(), AddressOrErr.takeError());
1213     uint64_t Address = *AddressOrErr;
1214 
1215     Expected<StringRef> Name = Symbol.getName();
1216     if (!Name)
1217       report_error(Obj->getFileName(), Name.takeError());
1218     if (Name->empty())
1219       continue;
1220 
1221     Expected<section_iterator> SectionOrErr = Symbol.getSection();
1222     if (!SectionOrErr)
1223       report_error(Obj->getFileName(), SectionOrErr.takeError());
1224     section_iterator SecI = *SectionOrErr;
1225     if (SecI == Obj->section_end())
1226       continue;
1227 
1228     AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1229   }
1230 }
1231 
1232 static void
1233 addDynamicElfSymbols(const ObjectFile *Obj,
1234                      std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1235   assert(Obj->isELF());
1236   if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1237     addDynamicElfSymbols(Elf32LEObj, AllSymbols);
1238   else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1239     addDynamicElfSymbols(Elf64LEObj, AllSymbols);
1240   else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1241     addDynamicElfSymbols(Elf32BEObj, AllSymbols);
1242   else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1243     addDynamicElfSymbols(Elf64BEObj, AllSymbols);
1244   else
1245     llvm_unreachable("Unsupported binary format");
1246 }
1247 
1248 static void addPltEntries(const ObjectFile *Obj,
1249                           std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
1250                           StringSaver &Saver) {
1251   Optional<SectionRef> Plt = None;
1252   for (const SectionRef &Section : Obj->sections()) {
1253     StringRef Name;
1254     if (Section.getName(Name))
1255       continue;
1256     if (Name == ".plt")
1257       Plt = Section;
1258   }
1259   if (!Plt)
1260     return;
1261   if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) {
1262     for (auto PltEntry : ElfObj->getPltAddresses()) {
1263       SymbolRef Symbol(PltEntry.first, ElfObj);
1264 
1265       uint8_t SymbolType = getElfSymbolType(Obj, Symbol);
1266 
1267       Expected<StringRef> NameOrErr = Symbol.getName();
1268       if (!NameOrErr)
1269         report_error(Obj->getFileName(), NameOrErr.takeError());
1270       if (NameOrErr->empty())
1271         continue;
1272       StringRef Name = Saver.save((*NameOrErr + "@plt").str());
1273 
1274       AllSymbols[*Plt].emplace_back(PltEntry.second, Name, SymbolType);
1275     }
1276   }
1277 }
1278 
1279 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
1280   if (StartAddress > StopAddress)
1281     error("Start address should be less than stop address");
1282 
1283   const Target *TheTarget = getTarget(Obj);
1284 
1285   // Package up features to be passed to target/subtarget
1286   SubtargetFeatures Features = Obj->getFeatures();
1287   if (MAttrs.size()) {
1288     for (unsigned i = 0; i != MAttrs.size(); ++i)
1289       Features.AddFeature(MAttrs[i]);
1290   }
1291 
1292   std::unique_ptr<const MCRegisterInfo> MRI(
1293       TheTarget->createMCRegInfo(TripleName));
1294   if (!MRI)
1295     report_error(Obj->getFileName(), "no register info for target " +
1296                  TripleName);
1297 
1298   // Set up disassembler.
1299   std::unique_ptr<const MCAsmInfo> AsmInfo(
1300       TheTarget->createMCAsmInfo(*MRI, TripleName));
1301   if (!AsmInfo)
1302     report_error(Obj->getFileName(), "no assembly info for target " +
1303                  TripleName);
1304   std::unique_ptr<const MCSubtargetInfo> STI(
1305       TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1306   if (!STI)
1307     report_error(Obj->getFileName(), "no subtarget info for target " +
1308                  TripleName);
1309   std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1310   if (!MII)
1311     report_error(Obj->getFileName(), "no instruction info for target " +
1312                  TripleName);
1313   MCObjectFileInfo MOFI;
1314   MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1315   // FIXME: for now initialize MCObjectFileInfo with default values
1316   MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
1317 
1318   std::unique_ptr<MCDisassembler> DisAsm(
1319     TheTarget->createMCDisassembler(*STI, Ctx));
1320   if (!DisAsm)
1321     report_error(Obj->getFileName(), "no disassembler for target " +
1322                  TripleName);
1323 
1324   std::unique_ptr<const MCInstrAnalysis> MIA(
1325       TheTarget->createMCInstrAnalysis(MII.get()));
1326 
1327   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1328   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1329       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
1330   if (!IP)
1331     report_error(Obj->getFileName(), "no instruction printer for target " +
1332                  TripleName);
1333   IP->setPrintImmHex(PrintImmHex);
1334   PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
1335 
1336   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ":  " :
1337                                                  "\t\t\t%08" PRIx64 ":  ";
1338 
1339   SourcePrinter SP(Obj, TheTarget->getName());
1340 
1341   // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1342   // in RelocSecs contain the relocations for section S.
1343   std::error_code EC;
1344   std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
1345   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1346     section_iterator Sec2 = Section.getRelocatedSection();
1347     if (Sec2 != Obj->section_end())
1348       SectionRelocMap[*Sec2].push_back(Section);
1349   }
1350 
1351   // Create a mapping from virtual address to symbol name.  This is used to
1352   // pretty print the symbols while disassembling.
1353   std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1354   SectionSymbolsTy AbsoluteSymbols;
1355   for (const SymbolRef &Symbol : Obj->symbols()) {
1356     Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1357     if (!AddressOrErr)
1358       report_error(Obj->getFileName(), AddressOrErr.takeError());
1359     uint64_t Address = *AddressOrErr;
1360 
1361     Expected<StringRef> Name = Symbol.getName();
1362     if (!Name)
1363       report_error(Obj->getFileName(), Name.takeError());
1364     if (Name->empty())
1365       continue;
1366 
1367     Expected<section_iterator> SectionOrErr = Symbol.getSection();
1368     if (!SectionOrErr)
1369       report_error(Obj->getFileName(), SectionOrErr.takeError());
1370 
1371     uint8_t SymbolType = ELF::STT_NOTYPE;
1372     if (Obj->isELF())
1373       SymbolType = getElfSymbolType(Obj, Symbol);
1374 
1375     section_iterator SecI = *SectionOrErr;
1376     if (SecI != Obj->section_end())
1377       AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1378     else
1379       AbsoluteSymbols.emplace_back(Address, *Name, SymbolType);
1380 
1381 
1382   }
1383   if (AllSymbols.empty() && Obj->isELF())
1384     addDynamicElfSymbols(Obj, AllSymbols);
1385 
1386   BumpPtrAllocator A;
1387   StringSaver Saver(A);
1388   addPltEntries(Obj, AllSymbols, Saver);
1389 
1390   // Create a mapping from virtual address to section.
1391   std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1392   for (SectionRef Sec : Obj->sections())
1393     SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1394   array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1395 
1396   // Linked executables (.exe and .dll files) typically don't include a real
1397   // symbol table but they might contain an export table.
1398   if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1399     for (const auto &ExportEntry : COFFObj->export_directories()) {
1400       StringRef Name;
1401       error(ExportEntry.getSymbolName(Name));
1402       if (Name.empty())
1403         continue;
1404       uint32_t RVA;
1405       error(ExportEntry.getExportRVA(RVA));
1406 
1407       uint64_t VA = COFFObj->getImageBase() + RVA;
1408       auto Sec = std::upper_bound(
1409           SectionAddresses.begin(), SectionAddresses.end(), VA,
1410           [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1411             return LHS < RHS.first;
1412           });
1413       if (Sec != SectionAddresses.begin())
1414         --Sec;
1415       else
1416         Sec = SectionAddresses.end();
1417 
1418       if (Sec != SectionAddresses.end())
1419         AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
1420       else
1421         AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
1422     }
1423   }
1424 
1425   // Sort all the symbols, this allows us to use a simple binary search to find
1426   // a symbol near an address.
1427   for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1428     array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1429   array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
1430 
1431   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1432     if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
1433       continue;
1434 
1435     uint64_t SectionAddr = Section.getAddress();
1436     uint64_t SectSize = Section.getSize();
1437     if (!SectSize)
1438       continue;
1439 
1440     // Get the list of all the symbols in this section.
1441     SectionSymbolsTy &Symbols = AllSymbols[Section];
1442     std::vector<uint64_t> DataMappingSymsAddr;
1443     std::vector<uint64_t> TextMappingSymsAddr;
1444     if (isArmElf(Obj)) {
1445       for (const auto &Symb : Symbols) {
1446         uint64_t Address = std::get<0>(Symb);
1447         StringRef Name = std::get<1>(Symb);
1448         if (Name.startswith("$d"))
1449           DataMappingSymsAddr.push_back(Address - SectionAddr);
1450         if (Name.startswith("$x"))
1451           TextMappingSymsAddr.push_back(Address - SectionAddr);
1452         if (Name.startswith("$a"))
1453           TextMappingSymsAddr.push_back(Address - SectionAddr);
1454         if (Name.startswith("$t"))
1455           TextMappingSymsAddr.push_back(Address - SectionAddr);
1456       }
1457     }
1458 
1459     llvm::sort(DataMappingSymsAddr);
1460     llvm::sort(TextMappingSymsAddr);
1461 
1462     if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1463       // AMDGPU disassembler uses symbolizer for printing labels
1464       std::unique_ptr<MCRelocationInfo> RelInfo(
1465         TheTarget->createMCRelocationInfo(TripleName, Ctx));
1466       if (RelInfo) {
1467         std::unique_ptr<MCSymbolizer> Symbolizer(
1468           TheTarget->createMCSymbolizer(
1469             TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1470         DisAsm->setSymbolizer(std::move(Symbolizer));
1471       }
1472     }
1473 
1474     // Make a list of all the relocations for this section.
1475     std::vector<RelocationRef> Rels;
1476     if (InlineRelocs) {
1477       for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1478         for (const RelocationRef &Reloc : RelocSec.relocations()) {
1479           Rels.push_back(Reloc);
1480         }
1481       }
1482     }
1483 
1484     // Sort relocations by address.
1485     llvm::sort(Rels, RelocAddressLess);
1486 
1487     StringRef SegmentName = "";
1488     if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
1489       DataRefImpl DR = Section.getRawDataRefImpl();
1490       SegmentName = MachO->getSectionFinalSegmentName(DR);
1491     }
1492     StringRef SectionName;
1493     error(Section.getName(SectionName));
1494 
1495     // If the section has no symbol at the start, just insert a dummy one.
1496     if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
1497       Symbols.insert(
1498           Symbols.begin(),
1499           std::make_tuple(SectionAddr, SectionName,
1500                           Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
1501     }
1502 
1503     SmallString<40> Comments;
1504     raw_svector_ostream CommentStream(Comments);
1505 
1506     StringRef BytesStr;
1507     error(Section.getContents(BytesStr));
1508     ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1509                             BytesStr.size());
1510 
1511     uint64_t Size;
1512     uint64_t Index;
1513     bool PrintedSection = false;
1514 
1515     std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1516     std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
1517     // Disassemble symbol by symbol.
1518     for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
1519       uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr;
1520       // The end is either the section end or the beginning of the next
1521       // symbol.
1522       uint64_t End =
1523           (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr;
1524       // Don't try to disassemble beyond the end of section contents.
1525       if (End > SectSize)
1526         End = SectSize;
1527       // If this symbol has the same address as the next symbol, then skip it.
1528       if (Start >= End)
1529         continue;
1530 
1531       // Check if we need to skip symbol
1532       // Skip if the symbol's data is not between StartAddress and StopAddress
1533       if (End + SectionAddr < StartAddress ||
1534           Start + SectionAddr > StopAddress) {
1535         continue;
1536       }
1537 
1538       /// Skip if user requested specific symbols and this is not in the list
1539       if (!DisasmFuncsSet.empty() &&
1540           !DisasmFuncsSet.count(std::get<1>(Symbols[si])))
1541         continue;
1542 
1543       if (!PrintedSection) {
1544         PrintedSection = true;
1545         outs() << "Disassembly of section ";
1546         if (!SegmentName.empty())
1547           outs() << SegmentName << ",";
1548         outs() << SectionName << ':';
1549       }
1550 
1551       // Stop disassembly at the stop address specified
1552       if (End + SectionAddr > StopAddress)
1553         End = StopAddress - SectionAddr;
1554 
1555       if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1556         if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1557           // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1558           Start += 256;
1559         }
1560         if (si == se - 1 ||
1561             std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1562           // cut trailing zeroes at the end of kernel
1563           // cut up to 256 bytes
1564           const uint64_t EndAlign = 256;
1565           const auto Limit = End - (std::min)(EndAlign, End - Start);
1566           while (End > Limit &&
1567             *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1568             End -= 4;
1569         }
1570       }
1571 
1572       auto PrintSymbol = [](StringRef Name) {
1573         outs() << '\n' << Name << ":\n";
1574       };
1575       StringRef SymbolName = std::get<1>(Symbols[si]);
1576       if (Demangle) {
1577         char *DemangledSymbol = nullptr;
1578         size_t Size = 0;
1579         int Status = -1;
1580         if (SymbolName.startswith("_Z"))
1581           DemangledSymbol = itaniumDemangle(SymbolName.data(), DemangledSymbol,
1582                                             &Size, &Status);
1583         else if (SymbolName.startswith("?"))
1584           DemangledSymbol = microsoftDemangle(SymbolName.data(),
1585                                               DemangledSymbol, &Size, &Status);
1586 
1587         if (Status == 0 && DemangledSymbol)
1588           PrintSymbol(StringRef(DemangledSymbol));
1589         else
1590           PrintSymbol(SymbolName);
1591 
1592         if (DemangledSymbol)
1593           free(DemangledSymbol);
1594       } else
1595         PrintSymbol(SymbolName);
1596 
1597       // Don't print raw contents of a virtual section. A virtual section
1598       // doesn't have any contents in the file.
1599       if (Section.isVirtual()) {
1600         outs() << "...\n";
1601         continue;
1602       }
1603 
1604 #ifndef NDEBUG
1605       raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1606 #else
1607       raw_ostream &DebugOut = nulls();
1608 #endif
1609 
1610       for (Index = Start; Index < End; Index += Size) {
1611         MCInst Inst;
1612 
1613         if (Index + SectionAddr < StartAddress ||
1614             Index + SectionAddr > StopAddress) {
1615           // skip byte by byte till StartAddress is reached
1616           Size = 1;
1617           continue;
1618         }
1619         // AArch64 ELF binaries can interleave data and text in the
1620         // same section. We rely on the markers introduced to
1621         // understand what we need to dump. If the data marker is within a
1622         // function, it is denoted as a word/short etc
1623         if (isArmElf(Obj) && std::get<2>(Symbols[si]) != ELF::STT_OBJECT &&
1624             !DisassembleAll) {
1625           uint64_t Stride = 0;
1626 
1627           auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1628                                       DataMappingSymsAddr.end(), Index);
1629           if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1630             // Switch to data.
1631             while (Index < End) {
1632               outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1633               outs() << "\t";
1634               if (Index + 4 <= End) {
1635                 Stride = 4;
1636                 dumpBytes(Bytes.slice(Index, 4), outs());
1637                 outs() << "\t.word\t";
1638                 uint32_t Data = 0;
1639                 if (Obj->isLittleEndian()) {
1640                   const auto Word =
1641                       reinterpret_cast<const support::ulittle32_t *>(
1642                           Bytes.data() + Index);
1643                   Data = *Word;
1644                 } else {
1645                   const auto Word = reinterpret_cast<const support::ubig32_t *>(
1646                       Bytes.data() + Index);
1647                   Data = *Word;
1648                 }
1649                 outs() << "0x" << format("%08" PRIx32, Data);
1650               } else if (Index + 2 <= End) {
1651                 Stride = 2;
1652                 dumpBytes(Bytes.slice(Index, 2), outs());
1653                 outs() << "\t\t.short\t";
1654                 uint16_t Data = 0;
1655                 if (Obj->isLittleEndian()) {
1656                   const auto Short =
1657                       reinterpret_cast<const support::ulittle16_t *>(
1658                           Bytes.data() + Index);
1659                   Data = *Short;
1660                 } else {
1661                   const auto Short =
1662                       reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1663                                                                   Index);
1664                   Data = *Short;
1665                 }
1666                 outs() << "0x" << format("%04" PRIx16, Data);
1667               } else {
1668                 Stride = 1;
1669                 dumpBytes(Bytes.slice(Index, 1), outs());
1670                 outs() << "\t\t.byte\t";
1671                 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
1672               }
1673               Index += Stride;
1674               outs() << "\n";
1675               auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1676                                           TextMappingSymsAddr.end(), Index);
1677               if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1678                 break;
1679             }
1680           }
1681         }
1682 
1683         // If there is a data symbol inside an ELF text section and we are only
1684         // disassembling text (applicable all architectures),
1685         // we are in a situation where we must print the data and not
1686         // disassemble it.
1687         if (Obj->isELF() && std::get<2>(Symbols[si]) == ELF::STT_OBJECT &&
1688             !DisassembleAll && Section.isText()) {
1689           // print out data up to 8 bytes at a time in hex and ascii
1690           uint8_t AsciiData[9] = {'\0'};
1691           uint8_t Byte;
1692           int NumBytes = 0;
1693 
1694           for (Index = Start; Index < End; Index += 1) {
1695             if (((SectionAddr + Index) < StartAddress) ||
1696                 ((SectionAddr + Index) > StopAddress))
1697               continue;
1698             if (NumBytes == 0) {
1699               outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1700               outs() << "\t";
1701             }
1702             Byte = Bytes.slice(Index)[0];
1703             outs() << format(" %02x", Byte);
1704             AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
1705 
1706             uint8_t IndentOffset = 0;
1707             NumBytes++;
1708             if (Index == End - 1 || NumBytes > 8) {
1709               // Indent the space for less than 8 bytes data.
1710               // 2 spaces for byte and one for space between bytes
1711               IndentOffset = 3 * (8 - NumBytes);
1712               for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1713                 AsciiData[Excess] = '\0';
1714               NumBytes = 8;
1715             }
1716             if (NumBytes == 8) {
1717               AsciiData[8] = '\0';
1718               outs() << std::string(IndentOffset, ' ') << "         ";
1719               outs() << reinterpret_cast<char *>(AsciiData);
1720               outs() << '\n';
1721               NumBytes = 0;
1722             }
1723           }
1724         }
1725         if (Index >= End)
1726           break;
1727 
1728         // Disassemble a real instruction or a data when disassemble all is
1729         // provided
1730         bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1731                                                    SectionAddr + Index, DebugOut,
1732                                                    CommentStream);
1733         if (Size == 0)
1734           Size = 1;
1735 
1736         PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
1737                       Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
1738                       *STI, &SP, &Rels);
1739         outs() << CommentStream.str();
1740         Comments.clear();
1741 
1742         // Try to resolve the target of a call, tail call, etc. to a specific
1743         // symbol.
1744         if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1745                     MIA->isConditionalBranch(Inst))) {
1746           uint64_t Target;
1747           if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1748             // In a relocatable object, the target's section must reside in
1749             // the same section as the call instruction or it is accessed
1750             // through a relocation.
1751             //
1752             // In a non-relocatable object, the target may be in any section.
1753             //
1754             // N.B. We don't walk the relocations in the relocatable case yet.
1755             auto *TargetSectionSymbols = &Symbols;
1756             if (!Obj->isRelocatableObject()) {
1757               auto SectionAddress = std::upper_bound(
1758                   SectionAddresses.begin(), SectionAddresses.end(), Target,
1759                   [](uint64_t LHS,
1760                       const std::pair<uint64_t, SectionRef> &RHS) {
1761                     return LHS < RHS.first;
1762                   });
1763               if (SectionAddress != SectionAddresses.begin()) {
1764                 --SectionAddress;
1765                 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1766               } else {
1767                 TargetSectionSymbols = &AbsoluteSymbols;
1768               }
1769             }
1770 
1771             // Find the first symbol in the section whose offset is less than
1772             // or equal to the target. If there isn't a section that contains
1773             // the target, find the nearest preceding absolute symbol.
1774             auto TargetSym = std::upper_bound(
1775                 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1776                 Target, [](uint64_t LHS,
1777                            const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1778                   return LHS < std::get<0>(RHS);
1779                 });
1780             if (TargetSym == TargetSectionSymbols->begin()) {
1781               TargetSectionSymbols = &AbsoluteSymbols;
1782               TargetSym = std::upper_bound(
1783                   AbsoluteSymbols.begin(), AbsoluteSymbols.end(),
1784                   Target, [](uint64_t LHS,
1785                              const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1786                             return LHS < std::get<0>(RHS);
1787                           });
1788             }
1789             if (TargetSym != TargetSectionSymbols->begin()) {
1790               --TargetSym;
1791               uint64_t TargetAddress = std::get<0>(*TargetSym);
1792               StringRef TargetName = std::get<1>(*TargetSym);
1793               outs() << " <" << TargetName;
1794               uint64_t Disp = Target - TargetAddress;
1795               if (Disp)
1796                 outs() << "+0x" << Twine::utohexstr(Disp);
1797               outs() << '>';
1798             }
1799           }
1800         }
1801         outs() << "\n";
1802 
1803         // Hexagon does this in pretty printer
1804         if (Obj->getArch() != Triple::hexagon)
1805           // Print relocation for instruction.
1806           while (rel_cur != rel_end) {
1807             bool hidden = getHidden(*rel_cur);
1808             uint64_t addr = rel_cur->getOffset();
1809             SmallString<16> name;
1810             SmallString<32> val;
1811 
1812             // If this relocation is hidden, skip it.
1813             if (hidden || ((SectionAddr + addr) < StartAddress)) {
1814               ++rel_cur;
1815               continue;
1816             }
1817 
1818             // Stop when rel_cur's address is past the current instruction.
1819             if (addr >= Index + Size) break;
1820             rel_cur->getTypeName(name);
1821             error(getRelocationValueString(*rel_cur, val));
1822             outs() << format(Fmt.data(), SectionAddr + addr) << name
1823                    << "\t" << val << "\n";
1824             ++rel_cur;
1825           }
1826       }
1827     }
1828   }
1829 }
1830 
1831 void llvm::PrintRelocations(const ObjectFile *Obj) {
1832   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1833                                                  "%08" PRIx64;
1834   // Regular objdump doesn't print relocations in non-relocatable object
1835   // files.
1836   if (!Obj->isRelocatableObject())
1837     return;
1838 
1839   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1840     if (Section.relocation_begin() == Section.relocation_end())
1841       continue;
1842     StringRef secname;
1843     error(Section.getName(secname));
1844     outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
1845     for (const RelocationRef &Reloc : Section.relocations()) {
1846       bool hidden = getHidden(Reloc);
1847       uint64_t address = Reloc.getOffset();
1848       SmallString<32> relocname;
1849       SmallString<32> valuestr;
1850       if (address < StartAddress || address > StopAddress || hidden)
1851         continue;
1852       Reloc.getTypeName(relocname);
1853       error(getRelocationValueString(Reloc, valuestr));
1854       outs() << format(Fmt.data(), address) << " " << relocname << " "
1855              << valuestr << "\n";
1856     }
1857     outs() << "\n";
1858   }
1859 }
1860 
1861 void llvm::PrintDynamicRelocations(const ObjectFile *Obj) {
1862 
1863   // For the moment, this option is for ELF only
1864   if (!Obj->isELF())
1865     return;
1866 
1867   const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
1868 
1869   if (!Elf || Elf->getEType() != ELF::ET_DYN) {
1870     error("not a dynamic object");
1871     return;
1872   }
1873 
1874   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1875 
1876   std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1877   if (DynRelSec.empty())
1878     return;
1879 
1880   outs() << "DYNAMIC RELOCATION RECORDS\n";
1881   for (const SectionRef &Section : DynRelSec) {
1882     if (Section.relocation_begin() == Section.relocation_end())
1883       continue;
1884     for (const RelocationRef &Reloc : Section.relocations()) {
1885       uint64_t address = Reloc.getOffset();
1886       SmallString<32> relocname;
1887       SmallString<32> valuestr;
1888       Reloc.getTypeName(relocname);
1889       error(getRelocationValueString(Reloc, valuestr));
1890       outs() << format(Fmt.data(), address) << " " << relocname << " "
1891              << valuestr << "\n";
1892     }
1893   }
1894 }
1895 
1896 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
1897   outs() << "Sections:\n"
1898             "Idx Name          Size      Address          Type\n";
1899   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1900     StringRef Name;
1901     error(Section.getName(Name));
1902     uint64_t Address = Section.getAddress();
1903     uint64_t Size = Section.getSize();
1904     bool Text = Section.isText();
1905     bool Data = Section.isData();
1906     bool BSS = Section.isBSS();
1907     std::string Type = (std::string(Text ? "TEXT " : "") +
1908                         (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1909     outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
1910                      (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1911                      Address, Type.c_str());
1912   }
1913 }
1914 
1915 void llvm::PrintSectionContents(const ObjectFile *Obj) {
1916   std::error_code EC;
1917   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1918     StringRef Name;
1919     StringRef Contents;
1920     error(Section.getName(Name));
1921     uint64_t BaseAddr = Section.getAddress();
1922     uint64_t Size = Section.getSize();
1923     if (!Size)
1924       continue;
1925 
1926     outs() << "Contents of section " << Name << ":\n";
1927     if (Section.isBSS()) {
1928       outs() << format("<skipping contents of bss section at [%04" PRIx64
1929                        ", %04" PRIx64 ")>\n",
1930                        BaseAddr, BaseAddr + Size);
1931       continue;
1932     }
1933 
1934     error(Section.getContents(Contents));
1935 
1936     // Dump out the content as hex and printable ascii characters.
1937     for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1938       outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1939       // Dump line of hex.
1940       for (std::size_t i = 0; i < 16; ++i) {
1941         if (i != 0 && i % 4 == 0)
1942           outs() << ' ';
1943         if (addr + i < end)
1944           outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1945                  << hexdigit(Contents[addr + i] & 0xF, true);
1946         else
1947           outs() << "  ";
1948       }
1949       // Print ascii.
1950       outs() << "  ";
1951       for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1952         if (isPrint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1953           outs() << Contents[addr + i];
1954         else
1955           outs() << ".";
1956       }
1957       outs() << "\n";
1958     }
1959   }
1960 }
1961 
1962 void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1963                             StringRef ArchitectureName) {
1964   outs() << "SYMBOL TABLE:\n";
1965 
1966   if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1967     printCOFFSymbolTable(coff);
1968     return;
1969   }
1970   for (const SymbolRef &Symbol : o->symbols()) {
1971     Expected<uint64_t> AddressOrError = Symbol.getAddress();
1972     if (!AddressOrError)
1973       report_error(ArchiveName, o->getFileName(), AddressOrError.takeError(),
1974                    ArchitectureName);
1975     uint64_t Address = *AddressOrError;
1976     if ((Address < StartAddress) || (Address > StopAddress))
1977       continue;
1978     Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1979     if (!TypeOrError)
1980       report_error(ArchiveName, o->getFileName(), TypeOrError.takeError(),
1981                    ArchitectureName);
1982     SymbolRef::Type Type = *TypeOrError;
1983     uint32_t Flags = Symbol.getFlags();
1984     Expected<section_iterator> SectionOrErr = Symbol.getSection();
1985     if (!SectionOrErr)
1986       report_error(ArchiveName, o->getFileName(), SectionOrErr.takeError(),
1987                    ArchitectureName);
1988     section_iterator Section = *SectionOrErr;
1989     StringRef Name;
1990     if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1991       Section->getName(Name);
1992     } else {
1993       Expected<StringRef> NameOrErr = Symbol.getName();
1994       if (!NameOrErr)
1995         report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1996                      ArchitectureName);
1997       Name = *NameOrErr;
1998     }
1999 
2000     bool Global = Flags & SymbolRef::SF_Global;
2001     bool Weak = Flags & SymbolRef::SF_Weak;
2002     bool Absolute = Flags & SymbolRef::SF_Absolute;
2003     bool Common = Flags & SymbolRef::SF_Common;
2004     bool Hidden = Flags & SymbolRef::SF_Hidden;
2005 
2006     char GlobLoc = ' ';
2007     if (Type != SymbolRef::ST_Unknown)
2008       GlobLoc = Global ? 'g' : 'l';
2009     char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
2010                  ? 'd' : ' ';
2011     char FileFunc = ' ';
2012     if (Type == SymbolRef::ST_File)
2013       FileFunc = 'f';
2014     else if (Type == SymbolRef::ST_Function)
2015       FileFunc = 'F';
2016 
2017     const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
2018                                                    "%08" PRIx64;
2019 
2020     outs() << format(Fmt, Address) << " "
2021            << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
2022            << (Weak ? 'w' : ' ') // Weak?
2023            << ' ' // Constructor. Not supported yet.
2024            << ' ' // Warning. Not supported yet.
2025            << ' ' // Indirect reference to another symbol.
2026            << Debug // Debugging (d) or dynamic (D) symbol.
2027            << FileFunc // Name of function (F), file (f) or object (O).
2028            << ' ';
2029     if (Absolute) {
2030       outs() << "*ABS*";
2031     } else if (Common) {
2032       outs() << "*COM*";
2033     } else if (Section == o->section_end()) {
2034       outs() << "*UND*";
2035     } else {
2036       if (const MachOObjectFile *MachO =
2037           dyn_cast<const MachOObjectFile>(o)) {
2038         DataRefImpl DR = Section->getRawDataRefImpl();
2039         StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
2040         outs() << SegmentName << ",";
2041       }
2042       StringRef SectionName;
2043       error(Section->getName(SectionName));
2044       outs() << SectionName;
2045     }
2046 
2047     outs() << '\t';
2048     if (Common || isa<ELFObjectFileBase>(o)) {
2049       uint64_t Val =
2050           Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
2051       outs() << format("\t %08" PRIx64 " ", Val);
2052     }
2053 
2054     if (Hidden) {
2055       outs() << ".hidden ";
2056     }
2057     outs() << Name
2058            << '\n';
2059   }
2060 }
2061 
2062 static void PrintUnwindInfo(const ObjectFile *o) {
2063   outs() << "Unwind info:\n\n";
2064 
2065   if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
2066     printCOFFUnwindInfo(coff);
2067   } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2068     printMachOUnwindInfo(MachO);
2069   else {
2070     // TODO: Extract DWARF dump tool to objdump.
2071     errs() << "This operation is only currently supported "
2072               "for COFF and MachO object files.\n";
2073     return;
2074   }
2075 }
2076 
2077 void llvm::printExportsTrie(const ObjectFile *o) {
2078   outs() << "Exports trie:\n";
2079   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2080     printMachOExportsTrie(MachO);
2081   else {
2082     errs() << "This operation is only currently supported "
2083               "for Mach-O executable files.\n";
2084     return;
2085   }
2086 }
2087 
2088 void llvm::printRebaseTable(ObjectFile *o) {
2089   outs() << "Rebase table:\n";
2090   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2091     printMachORebaseTable(MachO);
2092   else {
2093     errs() << "This operation is only currently supported "
2094               "for Mach-O executable files.\n";
2095     return;
2096   }
2097 }
2098 
2099 void llvm::printBindTable(ObjectFile *o) {
2100   outs() << "Bind table:\n";
2101   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2102     printMachOBindTable(MachO);
2103   else {
2104     errs() << "This operation is only currently supported "
2105               "for Mach-O executable files.\n";
2106     return;
2107   }
2108 }
2109 
2110 void llvm::printLazyBindTable(ObjectFile *o) {
2111   outs() << "Lazy bind table:\n";
2112   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2113     printMachOLazyBindTable(MachO);
2114   else {
2115     errs() << "This operation is only currently supported "
2116               "for Mach-O executable files.\n";
2117     return;
2118   }
2119 }
2120 
2121 void llvm::printWeakBindTable(ObjectFile *o) {
2122   outs() << "Weak bind table:\n";
2123   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2124     printMachOWeakBindTable(MachO);
2125   else {
2126     errs() << "This operation is only currently supported "
2127               "for Mach-O executable files.\n";
2128     return;
2129   }
2130 }
2131 
2132 /// Dump the raw contents of the __clangast section so the output can be piped
2133 /// into llvm-bcanalyzer.
2134 void llvm::printRawClangAST(const ObjectFile *Obj) {
2135   if (outs().is_displayed()) {
2136     errs() << "The -raw-clang-ast option will dump the raw binary contents of "
2137               "the clang ast section.\n"
2138               "Please redirect the output to a file or another program such as "
2139               "llvm-bcanalyzer.\n";
2140     return;
2141   }
2142 
2143   StringRef ClangASTSectionName("__clangast");
2144   if (isa<COFFObjectFile>(Obj)) {
2145     ClangASTSectionName = "clangast";
2146   }
2147 
2148   Optional<object::SectionRef> ClangASTSection;
2149   for (auto Sec : ToolSectionFilter(*Obj)) {
2150     StringRef Name;
2151     Sec.getName(Name);
2152     if (Name == ClangASTSectionName) {
2153       ClangASTSection = Sec;
2154       break;
2155     }
2156   }
2157   if (!ClangASTSection)
2158     return;
2159 
2160   StringRef ClangASTContents;
2161   error(ClangASTSection.getValue().getContents(ClangASTContents));
2162   outs().write(ClangASTContents.data(), ClangASTContents.size());
2163 }
2164 
2165 static void printFaultMaps(const ObjectFile *Obj) {
2166   const char *FaultMapSectionName = nullptr;
2167 
2168   if (isa<ELFObjectFileBase>(Obj)) {
2169     FaultMapSectionName = ".llvm_faultmaps";
2170   } else if (isa<MachOObjectFile>(Obj)) {
2171     FaultMapSectionName = "__llvm_faultmaps";
2172   } else {
2173     errs() << "This operation is only currently supported "
2174               "for ELF and Mach-O executable files.\n";
2175     return;
2176   }
2177 
2178   Optional<object::SectionRef> FaultMapSection;
2179 
2180   for (auto Sec : ToolSectionFilter(*Obj)) {
2181     StringRef Name;
2182     Sec.getName(Name);
2183     if (Name == FaultMapSectionName) {
2184       FaultMapSection = Sec;
2185       break;
2186     }
2187   }
2188 
2189   outs() << "FaultMap table:\n";
2190 
2191   if (!FaultMapSection.hasValue()) {
2192     outs() << "<not found>\n";
2193     return;
2194   }
2195 
2196   StringRef FaultMapContents;
2197   error(FaultMapSection.getValue().getContents(FaultMapContents));
2198 
2199   FaultMapParser FMP(FaultMapContents.bytes_begin(),
2200                      FaultMapContents.bytes_end());
2201 
2202   outs() << FMP;
2203 }
2204 
2205 static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) {
2206   if (o->isELF()) {
2207     printELFFileHeader(o);
2208     return printELFDynamicSection(o);
2209   }
2210   if (o->isCOFF())
2211     return printCOFFFileHeader(o);
2212   if (o->isWasm())
2213     return printWasmFileHeader(o);
2214   if (o->isMachO()) {
2215     printMachOFileHeader(o);
2216     if (!onlyFirst)
2217       printMachOLoadCommands(o);
2218     return;
2219   }
2220   report_error(o->getFileName(), "Invalid/Unsupported object file format");
2221 }
2222 
2223 static void printFileHeaders(const ObjectFile *o) {
2224   if (!o->isELF() && !o->isCOFF())
2225     report_error(o->getFileName(), "Invalid/Unsupported object file format");
2226 
2227   Triple::ArchType AT = o->getArch();
2228   outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
2229   Expected<uint64_t> StartAddrOrErr = o->getStartAddress();
2230   if (!StartAddrOrErr)
2231     report_error(o->getFileName(), StartAddrOrErr.takeError());
2232 
2233   StringRef Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
2234   uint64_t Address = StartAddrOrErr.get();
2235   outs() << "start address: "
2236          << "0x" << format(Fmt.data(), Address)
2237          << "\n";
2238 }
2239 
2240 static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
2241   Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
2242   if (!ModeOrErr) {
2243     errs() << "ill-formed archive entry.\n";
2244     consumeError(ModeOrErr.takeError());
2245     return;
2246   }
2247   sys::fs::perms Mode = ModeOrErr.get();
2248   outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2249   outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2250   outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2251   outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2252   outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2253   outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2254   outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2255   outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2256   outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2257 
2258   outs() << " ";
2259 
2260   Expected<unsigned> UIDOrErr = C.getUID();
2261   if (!UIDOrErr)
2262     report_error(Filename, UIDOrErr.takeError());
2263   unsigned UID = UIDOrErr.get();
2264   outs() << format("%d/", UID);
2265 
2266   Expected<unsigned> GIDOrErr = C.getGID();
2267   if (!GIDOrErr)
2268     report_error(Filename, GIDOrErr.takeError());
2269   unsigned GID = GIDOrErr.get();
2270   outs() << format("%-d ", GID);
2271 
2272   Expected<uint64_t> Size = C.getRawSize();
2273   if (!Size)
2274     report_error(Filename, Size.takeError());
2275   outs() << format("%6" PRId64, Size.get()) << " ";
2276 
2277   StringRef RawLastModified = C.getRawLastModified();
2278   unsigned Seconds;
2279   if (RawLastModified.getAsInteger(10, Seconds))
2280     outs() << "(date: \"" << RawLastModified
2281            << "\" contains non-decimal chars) ";
2282   else {
2283     // Since ctime(3) returns a 26 character string of the form:
2284     // "Sun Sep 16 01:03:52 1973\n\0"
2285     // just print 24 characters.
2286     time_t t = Seconds;
2287     outs() << format("%.24s ", ctime(&t));
2288   }
2289 
2290   StringRef Name = "";
2291   Expected<StringRef> NameOrErr = C.getName();
2292   if (!NameOrErr) {
2293     consumeError(NameOrErr.takeError());
2294     Expected<StringRef> RawNameOrErr = C.getRawName();
2295     if (!RawNameOrErr)
2296       report_error(Filename, NameOrErr.takeError());
2297     Name = RawNameOrErr.get();
2298   } else {
2299     Name = NameOrErr.get();
2300   }
2301   outs() << Name << "\n";
2302 }
2303 
2304 static void DumpObject(ObjectFile *o, const Archive *a = nullptr,
2305                        const Archive::Child *c = nullptr) {
2306   StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
2307   // Avoid other output when using a raw option.
2308   if (!RawClangAST) {
2309     outs() << '\n';
2310     if (a)
2311       outs() << a->getFileName() << "(" << o->getFileName() << ")";
2312     else
2313       outs() << o->getFileName();
2314     outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
2315   }
2316 
2317   if (ArchiveHeaders && !MachOOpt && c)
2318     printArchiveChild(ArchiveName, *c);
2319   if (Disassemble)
2320     DisassembleObject(o, Relocations);
2321   if (Relocations && !Disassemble)
2322     PrintRelocations(o);
2323   if (DynamicRelocations)
2324     PrintDynamicRelocations(o);
2325   if (SectionHeaders)
2326     PrintSectionHeaders(o);
2327   if (SectionContents)
2328     PrintSectionContents(o);
2329   if (SymbolTable)
2330     PrintSymbolTable(o, ArchiveName);
2331   if (UnwindInfo)
2332     PrintUnwindInfo(o);
2333   if (PrivateHeaders || FirstPrivateHeader)
2334     printPrivateFileHeaders(o, FirstPrivateHeader);
2335   if (FileHeaders)
2336     printFileHeaders(o);
2337   if (ExportsTrie)
2338     printExportsTrie(o);
2339   if (Rebase)
2340     printRebaseTable(o);
2341   if (Bind)
2342     printBindTable(o);
2343   if (LazyBind)
2344     printLazyBindTable(o);
2345   if (WeakBind)
2346     printWeakBindTable(o);
2347   if (RawClangAST)
2348     printRawClangAST(o);
2349   if (PrintFaultMaps)
2350     printFaultMaps(o);
2351   if (DwarfDumpType != DIDT_Null) {
2352     std::unique_ptr<DIContext> DICtx = DWARFContext::create(*o);
2353     // Dump the complete DWARF structure.
2354     DIDumpOptions DumpOpts;
2355     DumpOpts.DumpType = DwarfDumpType;
2356     DICtx->dump(outs(), DumpOpts);
2357   }
2358 }
2359 
2360 static void DumpObject(const COFFImportFile *I, const Archive *A,
2361                        const Archive::Child *C = nullptr) {
2362   StringRef ArchiveName = A ? A->getFileName() : "";
2363 
2364   // Avoid other output when using a raw option.
2365   if (!RawClangAST)
2366     outs() << '\n'
2367            << ArchiveName << "(" << I->getFileName() << ")"
2368            << ":\tfile format COFF-import-file"
2369            << "\n\n";
2370 
2371   if (ArchiveHeaders && !MachOOpt && C)
2372     printArchiveChild(ArchiveName, *C);
2373   if (SymbolTable)
2374     printCOFFSymbolTable(I);
2375 }
2376 
2377 /// Dump each object file in \a a;
2378 static void DumpArchive(const Archive *a) {
2379   Error Err = Error::success();
2380   for (auto &C : a->children(Err)) {
2381     Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2382     if (!ChildOrErr) {
2383       if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2384         report_error(a->getFileName(), C, std::move(E));
2385       continue;
2386     }
2387     if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2388       DumpObject(o, a, &C);
2389     else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2390       DumpObject(I, a, &C);
2391     else
2392       report_error(a->getFileName(), object_error::invalid_file_type);
2393   }
2394   if (Err)
2395     report_error(a->getFileName(), std::move(Err));
2396 }
2397 
2398 /// Open file and figure out how to dump it.
2399 static void DumpInput(StringRef file) {
2400 
2401   // If we are using the Mach-O specific object file parser, then let it parse
2402   // the file and process the command line options.  So the -arch flags can
2403   // be used to select specific slices, etc.
2404   if (MachOOpt) {
2405     ParseInputMachO(file);
2406     return;
2407   }
2408 
2409   // Attempt to open the binary.
2410   Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2411   if (!BinaryOrErr)
2412     report_error(file, BinaryOrErr.takeError());
2413   Binary &Binary = *BinaryOrErr.get().getBinary();
2414 
2415   if (Archive *a = dyn_cast<Archive>(&Binary))
2416     DumpArchive(a);
2417   else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
2418     DumpObject(o);
2419   else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
2420     ParseInputMachO(UB);
2421   else
2422     report_error(file, object_error::invalid_file_type);
2423 }
2424 
2425 int main(int argc, char **argv) {
2426   InitLLVM X(argc, argv);
2427 
2428   // Initialize targets and assembly printers/parsers.
2429   llvm::InitializeAllTargetInfos();
2430   llvm::InitializeAllTargetMCs();
2431   llvm::InitializeAllDisassemblers();
2432 
2433   // Register the target printer for --version.
2434   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2435 
2436   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2437 
2438   ToolName = argv[0];
2439 
2440   // Defaults to a.out if no filenames specified.
2441   if (InputFilenames.size() == 0)
2442     InputFilenames.push_back("a.out");
2443 
2444   if (AllHeaders)
2445     PrivateHeaders = Relocations = SectionHeaders = SymbolTable = true;
2446 
2447   if (DisassembleAll || PrintSource || PrintLines)
2448     Disassemble = true;
2449 
2450   if (!Disassemble
2451       && !Relocations
2452       && !DynamicRelocations
2453       && !SectionHeaders
2454       && !SectionContents
2455       && !SymbolTable
2456       && !UnwindInfo
2457       && !PrivateHeaders
2458       && !FileHeaders
2459       && !FirstPrivateHeader
2460       && !ExportsTrie
2461       && !Rebase
2462       && !Bind
2463       && !LazyBind
2464       && !WeakBind
2465       && !RawClangAST
2466       && !(UniversalHeaders && MachOOpt)
2467       && !ArchiveHeaders
2468       && !(IndirectSymbols && MachOOpt)
2469       && !(DataInCode && MachOOpt)
2470       && !(LinkOptHints && MachOOpt)
2471       && !(InfoPlist && MachOOpt)
2472       && !(DylibsUsed && MachOOpt)
2473       && !(DylibId && MachOOpt)
2474       && !(ObjcMetaData && MachOOpt)
2475       && !(FilterSections.size() != 0 && MachOOpt)
2476       && !PrintFaultMaps
2477       && DwarfDumpType == DIDT_Null) {
2478     cl::PrintHelpMessage();
2479     return 2;
2480   }
2481 
2482   DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2483                         DisassembleFunctions.end());
2484 
2485   llvm::for_each(InputFilenames, DumpInput);
2486 
2487   return EXIT_SUCCESS;
2488 }
2489