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