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