OSDN Git Service

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