xref: /llvm-project/llvm/tools/llvm-objdump/llvm-objdump.cpp (revision e35e6448f99d69c40f7073794abbd75b9a0a75c0)
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   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1819     StringRef Name;
1820     error(Section.getName(Name));
1821     uint64_t Address = Section.getAddress();
1822     uint64_t Size = Section.getSize();
1823     bool Text = Section.isText();
1824     bool Data = Section.isData();
1825     bool BSS = Section.isBSS();
1826     std::string Type = (std::string(Text ? "TEXT " : "") +
1827                         (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1828     outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
1829                      Section.getIndex(), Name.str().c_str(), Size, Address,
1830                      Type.c_str());
1831   }
1832 }
1833 
1834 void llvm::PrintSectionContents(const ObjectFile *Obj) {
1835   std::error_code EC;
1836   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1837     StringRef Name;
1838     StringRef Contents;
1839     error(Section.getName(Name));
1840     uint64_t BaseAddr = Section.getAddress();
1841     uint64_t Size = Section.getSize();
1842     if (!Size)
1843       continue;
1844 
1845     outs() << "Contents of section " << Name << ":\n";
1846     if (Section.isBSS()) {
1847       outs() << format("<skipping contents of bss section at [%04" PRIx64
1848                        ", %04" PRIx64 ")>\n",
1849                        BaseAddr, BaseAddr + Size);
1850       continue;
1851     }
1852 
1853     error(Section.getContents(Contents));
1854 
1855     // Dump out the content as hex and printable ascii characters.
1856     for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1857       outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1858       // Dump line of hex.
1859       for (std::size_t i = 0; i < 16; ++i) {
1860         if (i != 0 && i % 4 == 0)
1861           outs() << ' ';
1862         if (addr + i < end)
1863           outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1864                  << hexdigit(Contents[addr + i] & 0xF, true);
1865         else
1866           outs() << "  ";
1867       }
1868       // Print ascii.
1869       outs() << "  ";
1870       for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1871         if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1872           outs() << Contents[addr + i];
1873         else
1874           outs() << ".";
1875       }
1876       outs() << "\n";
1877     }
1878   }
1879 }
1880 
1881 void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1882                             StringRef ArchitectureName) {
1883   outs() << "SYMBOL TABLE:\n";
1884 
1885   if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1886     printCOFFSymbolTable(coff);
1887     return;
1888   }
1889   for (const SymbolRef &Symbol : o->symbols()) {
1890     Expected<uint64_t> AddressOrError = Symbol.getAddress();
1891     if (!AddressOrError)
1892       report_error(ArchiveName, o->getFileName(), AddressOrError.takeError(),
1893                    ArchitectureName);
1894     uint64_t Address = *AddressOrError;
1895     if ((Address < StartAddress) || (Address > StopAddress))
1896       continue;
1897     Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1898     if (!TypeOrError)
1899       report_error(ArchiveName, o->getFileName(), TypeOrError.takeError(),
1900                    ArchitectureName);
1901     SymbolRef::Type Type = *TypeOrError;
1902     uint32_t Flags = Symbol.getFlags();
1903     Expected<section_iterator> SectionOrErr = Symbol.getSection();
1904     if (!SectionOrErr)
1905       report_error(ArchiveName, o->getFileName(), SectionOrErr.takeError(),
1906                    ArchitectureName);
1907     section_iterator Section = *SectionOrErr;
1908     StringRef Name;
1909     if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1910       Section->getName(Name);
1911     } else {
1912       Expected<StringRef> NameOrErr = Symbol.getName();
1913       if (!NameOrErr)
1914         report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1915                      ArchitectureName);
1916       Name = *NameOrErr;
1917     }
1918 
1919     bool Global = Flags & SymbolRef::SF_Global;
1920     bool Weak = Flags & SymbolRef::SF_Weak;
1921     bool Absolute = Flags & SymbolRef::SF_Absolute;
1922     bool Common = Flags & SymbolRef::SF_Common;
1923     bool Hidden = Flags & SymbolRef::SF_Hidden;
1924 
1925     char GlobLoc = ' ';
1926     if (Type != SymbolRef::ST_Unknown)
1927       GlobLoc = Global ? 'g' : 'l';
1928     char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1929                  ? 'd' : ' ';
1930     char FileFunc = ' ';
1931     if (Type == SymbolRef::ST_File)
1932       FileFunc = 'f';
1933     else if (Type == SymbolRef::ST_Function)
1934       FileFunc = 'F';
1935 
1936     const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1937                                                    "%08" PRIx64;
1938 
1939     outs() << format(Fmt, Address) << " "
1940            << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1941            << (Weak ? 'w' : ' ') // Weak?
1942            << ' ' // Constructor. Not supported yet.
1943            << ' ' // Warning. Not supported yet.
1944            << ' ' // Indirect reference to another symbol.
1945            << Debug // Debugging (d) or dynamic (D) symbol.
1946            << FileFunc // Name of function (F), file (f) or object (O).
1947            << ' ';
1948     if (Absolute) {
1949       outs() << "*ABS*";
1950     } else if (Common) {
1951       outs() << "*COM*";
1952     } else if (Section == o->section_end()) {
1953       outs() << "*UND*";
1954     } else {
1955       if (const MachOObjectFile *MachO =
1956           dyn_cast<const MachOObjectFile>(o)) {
1957         DataRefImpl DR = Section->getRawDataRefImpl();
1958         StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1959         outs() << SegmentName << ",";
1960       }
1961       StringRef SectionName;
1962       error(Section->getName(SectionName));
1963       outs() << SectionName;
1964     }
1965 
1966     outs() << '\t';
1967     if (Common || isa<ELFObjectFileBase>(o)) {
1968       uint64_t Val =
1969           Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1970       outs() << format("\t %08" PRIx64 " ", Val);
1971     }
1972 
1973     if (Hidden) {
1974       outs() << ".hidden ";
1975     }
1976     outs() << Name
1977            << '\n';
1978   }
1979 }
1980 
1981 static void PrintUnwindInfo(const ObjectFile *o) {
1982   outs() << "Unwind info:\n\n";
1983 
1984   if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1985     printCOFFUnwindInfo(coff);
1986   } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1987     printMachOUnwindInfo(MachO);
1988   else {
1989     // TODO: Extract DWARF dump tool to objdump.
1990     errs() << "This operation is only currently supported "
1991               "for COFF and MachO object files.\n";
1992     return;
1993   }
1994 }
1995 
1996 void llvm::printExportsTrie(const ObjectFile *o) {
1997   outs() << "Exports trie:\n";
1998   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1999     printMachOExportsTrie(MachO);
2000   else {
2001     errs() << "This operation is only currently supported "
2002               "for Mach-O executable files.\n";
2003     return;
2004   }
2005 }
2006 
2007 void llvm::printRebaseTable(ObjectFile *o) {
2008   outs() << "Rebase table:\n";
2009   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2010     printMachORebaseTable(MachO);
2011   else {
2012     errs() << "This operation is only currently supported "
2013               "for Mach-O executable files.\n";
2014     return;
2015   }
2016 }
2017 
2018 void llvm::printBindTable(ObjectFile *o) {
2019   outs() << "Bind table:\n";
2020   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2021     printMachOBindTable(MachO);
2022   else {
2023     errs() << "This operation is only currently supported "
2024               "for Mach-O executable files.\n";
2025     return;
2026   }
2027 }
2028 
2029 void llvm::printLazyBindTable(ObjectFile *o) {
2030   outs() << "Lazy bind table:\n";
2031   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2032     printMachOLazyBindTable(MachO);
2033   else {
2034     errs() << "This operation is only currently supported "
2035               "for Mach-O executable files.\n";
2036     return;
2037   }
2038 }
2039 
2040 void llvm::printWeakBindTable(ObjectFile *o) {
2041   outs() << "Weak bind table:\n";
2042   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2043     printMachOWeakBindTable(MachO);
2044   else {
2045     errs() << "This operation is only currently supported "
2046               "for Mach-O executable files.\n";
2047     return;
2048   }
2049 }
2050 
2051 /// Dump the raw contents of the __clangast section so the output can be piped
2052 /// into llvm-bcanalyzer.
2053 void llvm::printRawClangAST(const ObjectFile *Obj) {
2054   if (outs().is_displayed()) {
2055     errs() << "The -raw-clang-ast option will dump the raw binary contents of "
2056               "the clang ast section.\n"
2057               "Please redirect the output to a file or another program such as "
2058               "llvm-bcanalyzer.\n";
2059     return;
2060   }
2061 
2062   StringRef ClangASTSectionName("__clangast");
2063   if (isa<COFFObjectFile>(Obj)) {
2064     ClangASTSectionName = "clangast";
2065   }
2066 
2067   Optional<object::SectionRef> ClangASTSection;
2068   for (auto Sec : ToolSectionFilter(*Obj)) {
2069     StringRef Name;
2070     Sec.getName(Name);
2071     if (Name == ClangASTSectionName) {
2072       ClangASTSection = Sec;
2073       break;
2074     }
2075   }
2076   if (!ClangASTSection)
2077     return;
2078 
2079   StringRef ClangASTContents;
2080   error(ClangASTSection.getValue().getContents(ClangASTContents));
2081   outs().write(ClangASTContents.data(), ClangASTContents.size());
2082 }
2083 
2084 static void printFaultMaps(const ObjectFile *Obj) {
2085   const char *FaultMapSectionName = nullptr;
2086 
2087   if (isa<ELFObjectFileBase>(Obj)) {
2088     FaultMapSectionName = ".llvm_faultmaps";
2089   } else if (isa<MachOObjectFile>(Obj)) {
2090     FaultMapSectionName = "__llvm_faultmaps";
2091   } else {
2092     errs() << "This operation is only currently supported "
2093               "for ELF and Mach-O executable files.\n";
2094     return;
2095   }
2096 
2097   Optional<object::SectionRef> FaultMapSection;
2098 
2099   for (auto Sec : ToolSectionFilter(*Obj)) {
2100     StringRef Name;
2101     Sec.getName(Name);
2102     if (Name == FaultMapSectionName) {
2103       FaultMapSection = Sec;
2104       break;
2105     }
2106   }
2107 
2108   outs() << "FaultMap table:\n";
2109 
2110   if (!FaultMapSection.hasValue()) {
2111     outs() << "<not found>\n";
2112     return;
2113   }
2114 
2115   StringRef FaultMapContents;
2116   error(FaultMapSection.getValue().getContents(FaultMapContents));
2117 
2118   FaultMapParser FMP(FaultMapContents.bytes_begin(),
2119                      FaultMapContents.bytes_end());
2120 
2121   outs() << FMP;
2122 }
2123 
2124 static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) {
2125   if (o->isELF())
2126     return printELFFileHeader(o);
2127   if (o->isCOFF())
2128     return printCOFFFileHeader(o);
2129   if (o->isWasm())
2130     return printWasmFileHeader(o);
2131   if (o->isMachO()) {
2132     printMachOFileHeader(o);
2133     if (!onlyFirst)
2134       printMachOLoadCommands(o);
2135     return;
2136   }
2137   report_error(o->getFileName(), "Invalid/Unsupported object file format");
2138 }
2139 
2140 static void printFileHeaders(const ObjectFile *o) {
2141   if (!o->isELF() && !o->isCOFF())
2142     report_error(o->getFileName(), "Invalid/Unsupported object file format");
2143 
2144   Triple::ArchType AT = o->getArch();
2145   outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
2146   Expected<uint64_t> StartAddrOrErr = o->getStartAddress();
2147   if (!StartAddrOrErr)
2148     report_error(o->getFileName(), StartAddrOrErr.takeError());
2149   outs() << "start address: "
2150          << format("0x%0*x", o->getBytesInAddress(), StartAddrOrErr.get())
2151          << "\n";
2152 }
2153 
2154 static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
2155   Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
2156   if (!ModeOrErr) {
2157     errs() << "ill-formed archive entry.\n";
2158     consumeError(ModeOrErr.takeError());
2159     return;
2160   }
2161   sys::fs::perms Mode = ModeOrErr.get();
2162   outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2163   outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2164   outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2165   outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2166   outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2167   outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2168   outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2169   outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2170   outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2171 
2172   outs() << " ";
2173 
2174   Expected<unsigned> UIDOrErr = C.getUID();
2175   if (!UIDOrErr)
2176     report_error(Filename, UIDOrErr.takeError());
2177   unsigned UID = UIDOrErr.get();
2178   outs() << format("%d/", UID);
2179 
2180   Expected<unsigned> GIDOrErr = C.getGID();
2181   if (!GIDOrErr)
2182     report_error(Filename, GIDOrErr.takeError());
2183   unsigned GID = GIDOrErr.get();
2184   outs() << format("%-d ", GID);
2185 
2186   Expected<uint64_t> Size = C.getRawSize();
2187   if (!Size)
2188     report_error(Filename, Size.takeError());
2189   outs() << format("%6" PRId64, Size.get()) << " ";
2190 
2191   StringRef RawLastModified = C.getRawLastModified();
2192   unsigned Seconds;
2193   if (RawLastModified.getAsInteger(10, Seconds))
2194     outs() << "(date: \"" << RawLastModified
2195            << "\" contains non-decimal chars) ";
2196   else {
2197     // Since ctime(3) returns a 26 character string of the form:
2198     // "Sun Sep 16 01:03:52 1973\n\0"
2199     // just print 24 characters.
2200     time_t t = Seconds;
2201     outs() << format("%.24s ", ctime(&t));
2202   }
2203 
2204   StringRef Name = "";
2205   Expected<StringRef> NameOrErr = C.getName();
2206   if (!NameOrErr) {
2207     consumeError(NameOrErr.takeError());
2208     Expected<StringRef> RawNameOrErr = C.getRawName();
2209     if (!RawNameOrErr)
2210       report_error(Filename, NameOrErr.takeError());
2211     Name = RawNameOrErr.get();
2212   } else {
2213     Name = NameOrErr.get();
2214   }
2215   outs() << Name << "\n";
2216 }
2217 
2218 static void DumpObject(ObjectFile *o, const Archive *a = nullptr,
2219                        const Archive::Child *c = nullptr) {
2220   StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
2221   // Avoid other output when using a raw option.
2222   if (!RawClangAST) {
2223     outs() << '\n';
2224     if (a)
2225       outs() << a->getFileName() << "(" << o->getFileName() << ")";
2226     else
2227       outs() << o->getFileName();
2228     outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
2229   }
2230 
2231   if (ArchiveHeaders && !MachOOpt)
2232     printArchiveChild(a->getFileName(), *c);
2233   if (Disassemble)
2234     DisassembleObject(o, Relocations);
2235   if (Relocations && !Disassemble)
2236     PrintRelocations(o);
2237   if (DynamicRelocations)
2238     PrintDynamicRelocations(o);
2239   if (SectionHeaders)
2240     PrintSectionHeaders(o);
2241   if (SectionContents)
2242     PrintSectionContents(o);
2243   if (SymbolTable)
2244     PrintSymbolTable(o, ArchiveName);
2245   if (UnwindInfo)
2246     PrintUnwindInfo(o);
2247   if (PrivateHeaders || FirstPrivateHeader)
2248     printPrivateFileHeaders(o, FirstPrivateHeader);
2249   if (FileHeaders)
2250     printFileHeaders(o);
2251   if (ExportsTrie)
2252     printExportsTrie(o);
2253   if (Rebase)
2254     printRebaseTable(o);
2255   if (Bind)
2256     printBindTable(o);
2257   if (LazyBind)
2258     printLazyBindTable(o);
2259   if (WeakBind)
2260     printWeakBindTable(o);
2261   if (RawClangAST)
2262     printRawClangAST(o);
2263   if (PrintFaultMaps)
2264     printFaultMaps(o);
2265   if (DwarfDumpType != DIDT_Null) {
2266     std::unique_ptr<DIContext> DICtx = DWARFContext::create(*o);
2267     // Dump the complete DWARF structure.
2268     DIDumpOptions DumpOpts;
2269     DumpOpts.DumpType = DwarfDumpType;
2270     DICtx->dump(outs(), DumpOpts);
2271   }
2272 }
2273 
2274 static void DumpObject(const COFFImportFile *I, const Archive *A,
2275                        const Archive::Child *C = nullptr) {
2276   StringRef ArchiveName = A ? A->getFileName() : "";
2277 
2278   // Avoid other output when using a raw option.
2279   if (!RawClangAST)
2280     outs() << '\n'
2281            << ArchiveName << "(" << I->getFileName() << ")"
2282            << ":\tfile format COFF-import-file"
2283            << "\n\n";
2284 
2285   if (ArchiveHeaders && !MachOOpt)
2286     printArchiveChild(A->getFileName(), *C);
2287   if (SymbolTable)
2288     printCOFFSymbolTable(I);
2289 }
2290 
2291 /// Dump each object file in \a a;
2292 static void DumpArchive(const Archive *a) {
2293   Error Err = Error::success();
2294   for (auto &C : a->children(Err)) {
2295     Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2296     if (!ChildOrErr) {
2297       if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2298         report_error(a->getFileName(), C, std::move(E));
2299       continue;
2300     }
2301     if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2302       DumpObject(o, a, &C);
2303     else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2304       DumpObject(I, a, &C);
2305     else
2306       report_error(a->getFileName(), object_error::invalid_file_type);
2307   }
2308   if (Err)
2309     report_error(a->getFileName(), std::move(Err));
2310 }
2311 
2312 /// Open file and figure out how to dump it.
2313 static void DumpInput(StringRef file) {
2314 
2315   // If we are using the Mach-O specific object file parser, then let it parse
2316   // the file and process the command line options.  So the -arch flags can
2317   // be used to select specific slices, etc.
2318   if (MachOOpt) {
2319     ParseInputMachO(file);
2320     return;
2321   }
2322 
2323   // Attempt to open the binary.
2324   Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2325   if (!BinaryOrErr)
2326     report_error(file, BinaryOrErr.takeError());
2327   Binary &Binary = *BinaryOrErr.get().getBinary();
2328 
2329   if (Archive *a = dyn_cast<Archive>(&Binary))
2330     DumpArchive(a);
2331   else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
2332     DumpObject(o);
2333   else
2334     report_error(file, object_error::invalid_file_type);
2335 }
2336 
2337 int main(int argc, char **argv) {
2338   InitLLVM X(argc, argv);
2339 
2340   // Initialize targets and assembly printers/parsers.
2341   llvm::InitializeAllTargetInfos();
2342   llvm::InitializeAllTargetMCs();
2343   llvm::InitializeAllDisassemblers();
2344 
2345   // Register the target printer for --version.
2346   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2347 
2348   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2349   TripleName = Triple::normalize(TripleName);
2350 
2351   ToolName = argv[0];
2352 
2353   // Defaults to a.out if no filenames specified.
2354   if (InputFilenames.size() == 0)
2355     InputFilenames.push_back("a.out");
2356 
2357   if (AllHeaders)
2358     PrivateHeaders = Relocations = SectionHeaders = SymbolTable = true;
2359 
2360   if (DisassembleAll || PrintSource || PrintLines)
2361     Disassemble = true;
2362   if (!Disassemble
2363       && !Relocations
2364       && !DynamicRelocations
2365       && !SectionHeaders
2366       && !SectionContents
2367       && !SymbolTable
2368       && !UnwindInfo
2369       && !PrivateHeaders
2370       && !FileHeaders
2371       && !FirstPrivateHeader
2372       && !ExportsTrie
2373       && !Rebase
2374       && !Bind
2375       && !LazyBind
2376       && !WeakBind
2377       && !RawClangAST
2378       && !(UniversalHeaders && MachOOpt)
2379       && !ArchiveHeaders
2380       && !(IndirectSymbols && MachOOpt)
2381       && !(DataInCode && MachOOpt)
2382       && !(LinkOptHints && MachOOpt)
2383       && !(InfoPlist && MachOOpt)
2384       && !(DylibsUsed && MachOOpt)
2385       && !(DylibId && MachOOpt)
2386       && !(ObjcMetaData && MachOOpt)
2387       && !(FilterSections.size() != 0 && MachOOpt)
2388       && !PrintFaultMaps
2389       && DwarfDumpType == DIDT_Null) {
2390     cl::PrintHelpMessage();
2391     return 2;
2392   }
2393 
2394   DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2395                         DisassembleFunctions.end());
2396 
2397   llvm::for_each(InputFilenames, DumpInput);
2398 
2399   return EXIT_SUCCESS;
2400 }
2401