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