[WebAssembly] Add a EM_WEBASSEMBLY value, and several bits of code that use it.
[oota-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/Triple.h"
24 #include "llvm/CodeGen/FaultMaps.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCDisassembler.h"
28 #include "llvm/MC/MCInst.h"
29 #include "llvm/MC/MCInstPrinter.h"
30 #include "llvm/MC/MCInstrAnalysis.h"
31 #include "llvm/MC/MCInstrInfo.h"
32 #include "llvm/MC/MCObjectFileInfo.h"
33 #include "llvm/MC/MCRegisterInfo.h"
34 #include "llvm/MC/MCRelocationInfo.h"
35 #include "llvm/MC/MCSubtargetInfo.h"
36 #include "llvm/Object/Archive.h"
37 #include "llvm/Object/ELFObjectFile.h"
38 #include "llvm/Object/COFF.h"
39 #include "llvm/Object/MachO.h"
40 #include "llvm/Object/ObjectFile.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/Errc.h"
45 #include "llvm/Support/FileSystem.h"
46 #include "llvm/Support/Format.h"
47 #include "llvm/Support/GraphWriter.h"
48 #include "llvm/Support/Host.h"
49 #include "llvm/Support/ManagedStatic.h"
50 #include "llvm/Support/MemoryBuffer.h"
51 #include "llvm/Support/PrettyStackTrace.h"
52 #include "llvm/Support/Signals.h"
53 #include "llvm/Support/SourceMgr.h"
54 #include "llvm/Support/TargetRegistry.h"
55 #include "llvm/Support/TargetSelect.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include <algorithm>
58 #include <cctype>
59 #include <cstring>
60 #include <system_error>
61
62 using namespace llvm;
63 using namespace object;
64
65 static cl::list<std::string>
66 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
67
68 cl::opt<bool>
69 llvm::Disassemble("disassemble",
70   cl::desc("Display assembler mnemonics for the machine instructions"));
71 static cl::alias
72 Disassembled("d", cl::desc("Alias for --disassemble"),
73              cl::aliasopt(Disassemble));
74
75 cl::opt<bool>
76 llvm::DisassembleAll("disassemble-all",
77   cl::desc("Display assembler mnemonics for the machine instructions"));
78 static cl::alias
79 DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
80              cl::aliasopt(DisassembleAll));
81
82 cl::opt<bool>
83 llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
84
85 cl::opt<bool>
86 llvm::SectionContents("s", cl::desc("Display the content of each section"));
87
88 cl::opt<bool>
89 llvm::SymbolTable("t", cl::desc("Display the symbol table"));
90
91 cl::opt<bool>
92 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
93
94 cl::opt<bool>
95 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
96
97 cl::opt<bool>
98 llvm::Bind("bind", cl::desc("Display mach-o binding info"));
99
100 cl::opt<bool>
101 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
102
103 cl::opt<bool>
104 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
105
106 cl::opt<bool>
107 llvm::RawClangAST("raw-clang-ast",
108     cl::desc("Dump the raw binary contents of the clang AST section"));
109
110 static cl::opt<bool>
111 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
112 static cl::alias
113 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
114
115 cl::opt<std::string>
116 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
117                                     "see -version for available targets"));
118
119 cl::opt<std::string>
120 llvm::MCPU("mcpu",
121      cl::desc("Target a specific cpu type (-mcpu=help for details)"),
122      cl::value_desc("cpu-name"),
123      cl::init(""));
124
125 cl::opt<std::string>
126 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
127                                 "see -version for available targets"));
128
129 cl::opt<bool>
130 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
131                                                  "headers for each section."));
132 static cl::alias
133 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
134                     cl::aliasopt(SectionHeaders));
135 static cl::alias
136 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
137                       cl::aliasopt(SectionHeaders));
138
139 cl::list<std::string>
140 llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
141                                          "With -macho dump segment,section"));
142 cl::alias
143 static FilterSectionsj("j", cl::desc("Alias for --section"),
144                  cl::aliasopt(llvm::FilterSections));
145
146 cl::list<std::string>
147 llvm::MAttrs("mattr",
148   cl::CommaSeparated,
149   cl::desc("Target specific attributes"),
150   cl::value_desc("a1,+a2,-a3,..."));
151
152 cl::opt<bool>
153 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
154                                                  "instructions, do not print "
155                                                  "the instruction bytes."));
156
157 cl::opt<bool>
158 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
159
160 static cl::alias
161 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
162                 cl::aliasopt(UnwindInfo));
163
164 cl::opt<bool>
165 llvm::PrivateHeaders("private-headers",
166                      cl::desc("Display format specific file headers"));
167
168 static cl::alias
169 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
170                     cl::aliasopt(PrivateHeaders));
171
172 cl::opt<bool>
173     llvm::PrintImmHex("print-imm-hex",
174                       cl::desc("Use hex format for immediate values"));
175
176 cl::opt<bool> PrintFaultMaps("fault-map-section",
177                              cl::desc("Display contents of faultmap section"));
178
179 static StringRef ToolName;
180
181 namespace {
182 typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
183
184 class SectionFilterIterator {
185 public:
186   SectionFilterIterator(FilterPredicate P,
187                         llvm::object::section_iterator const &I,
188                         llvm::object::section_iterator const &E)
189       : Predicate(P), Iterator(I), End(E) {
190     ScanPredicate();
191   }
192   const llvm::object::SectionRef &operator*() const { return *Iterator; }
193   SectionFilterIterator &operator++() {
194     ++Iterator;
195     ScanPredicate();
196     return *this;
197   }
198   bool operator!=(SectionFilterIterator const &Other) const {
199     return Iterator != Other.Iterator;
200   }
201
202 private:
203   void ScanPredicate() {
204     while (Iterator != End && !Predicate(*Iterator)) {
205       ++Iterator;
206     }
207   }
208   FilterPredicate Predicate;
209   llvm::object::section_iterator Iterator;
210   llvm::object::section_iterator End;
211 };
212
213 class SectionFilter {
214 public:
215   SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
216       : Predicate(P), Object(O) {}
217   SectionFilterIterator begin() {
218     return SectionFilterIterator(Predicate, Object.section_begin(),
219                                  Object.section_end());
220   }
221   SectionFilterIterator end() {
222     return SectionFilterIterator(Predicate, Object.section_end(),
223                                  Object.section_end());
224   }
225
226 private:
227   FilterPredicate Predicate;
228   llvm::object::ObjectFile const &Object;
229 };
230 SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
231   return SectionFilter([](llvm::object::SectionRef const &S) {
232                          if(FilterSections.empty())
233                            return true;
234                          llvm::StringRef String;
235                          std::error_code error = S.getName(String);
236                          if (error)
237                            return false;
238                          return std::find(FilterSections.begin(),
239                                           FilterSections.end(),
240                                           String) != FilterSections.end();
241                        },
242                        O);
243 }
244 }
245
246 void llvm::error(std::error_code EC) {
247   if (!EC)
248     return;
249
250   errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
251   errs().flush();
252   exit(1);
253 }
254
255 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
256                                                 std::error_code EC) {
257   assert(EC);
258   errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
259   exit(1);
260 }
261
262 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
263   // Figure out the target triple.
264   llvm::Triple TheTriple("unknown-unknown-unknown");
265   if (TripleName.empty()) {
266     if (Obj) {
267       TheTriple.setArch(Triple::ArchType(Obj->getArch()));
268       // TheTriple defaults to ELF, and COFF doesn't have an environment:
269       // the best we can do here is indicate that it is mach-o.
270       if (Obj->isMachO())
271         TheTriple.setObjectFormat(Triple::MachO);
272
273       if (Obj->isCOFF()) {
274         const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
275         if (COFFObj->getArch() == Triple::thumb)
276           TheTriple.setTriple("thumbv7-windows");
277       }
278     }
279   } else
280     TheTriple.setTriple(Triple::normalize(TripleName));
281
282   // Get the target specific parser.
283   std::string Error;
284   const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
285                                                          Error);
286   if (!TheTarget)
287     report_fatal_error("can't find target: " + Error);
288
289   // Update the triple name and return the found target.
290   TripleName = TheTriple.getTriple();
291   return TheTarget;
292 }
293
294 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
295   return a.getOffset() < b.getOffset();
296 }
297
298 namespace {
299 class PrettyPrinter {
300 public:
301   virtual ~PrettyPrinter(){}
302   virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
303                          ArrayRef<uint8_t> Bytes, uint64_t Address,
304                          raw_ostream &OS, StringRef Annot,
305                          MCSubtargetInfo const &STI) {
306     outs() << format("%8" PRIx64 ":", Address);
307     if (!NoShowRawInsn) {
308       outs() << "\t";
309       dumpBytes(Bytes, outs());
310     }
311     IP.printInst(MI, outs(), "", STI);
312   }
313 };
314 PrettyPrinter PrettyPrinterInst;
315 class HexagonPrettyPrinter : public PrettyPrinter {
316 public:
317   void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
318                  raw_ostream &OS) {
319     uint32_t opcode =
320       (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
321     OS << format("%8" PRIx64 ":", Address);
322     if (!NoShowRawInsn) {
323       OS << "\t";
324       dumpBytes(Bytes.slice(0, 4), OS);
325       OS << format("%08" PRIx32, opcode);
326     }
327   }
328   void printInst(MCInstPrinter &IP, const MCInst *MI,
329                  ArrayRef<uint8_t> Bytes, uint64_t Address,
330                  raw_ostream &OS, StringRef Annot,
331                  MCSubtargetInfo const &STI) override {
332     std::string Buffer;
333     {
334       raw_string_ostream TempStream(Buffer);
335       IP.printInst(MI, TempStream, "", STI);
336     }
337     StringRef Contents(Buffer);
338     // Split off bundle attributes
339     auto PacketBundle = Contents.rsplit('\n');
340     // Split off first instruction from the rest
341     auto HeadTail = PacketBundle.first.split('\n');
342     auto Preamble = " { ";
343     auto Separator = "";
344     while(!HeadTail.first.empty()) {
345       OS << Separator;
346       Separator = "\n";
347       printLead(Bytes, Address, OS);
348       OS << Preamble;
349       Preamble = "   ";
350       StringRef Inst;
351       auto Duplex = HeadTail.first.split('\v');
352       if(!Duplex.second.empty()){
353         OS << Duplex.first;
354         OS << "; ";
355         Inst = Duplex.second;
356       }
357       else
358         Inst = HeadTail.first;
359       OS << Inst;
360       Bytes = Bytes.slice(4);
361       Address += 4;
362       HeadTail = HeadTail.second.split('\n');
363     }
364     OS << " } " << PacketBundle.second;
365   }
366 };
367 HexagonPrettyPrinter HexagonPrettyPrinterInst;
368 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
369   switch(Triple.getArch()) {
370   default:
371     return PrettyPrinterInst;
372   case Triple::hexagon:
373     return HexagonPrettyPrinterInst;
374   }
375 }
376 }
377
378 template <class ELFT>
379 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
380                                                 const RelocationRef &RelRef,
381                                                 SmallVectorImpl<char> &Result) {
382   DataRefImpl Rel = RelRef.getRawDataRefImpl();
383
384   typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
385   typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
386   typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
387
388   const ELFFile<ELFT> &EF = *Obj->getELFFile();
389
390   ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
391   if (std::error_code EC = SecOrErr.getError())
392     return EC;
393   const Elf_Shdr *Sec = *SecOrErr;
394   ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
395   if (std::error_code EC = SymTabOrErr.getError())
396     return EC;
397   const Elf_Shdr *SymTab = *SymTabOrErr;
398   assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
399          SymTab->sh_type == ELF::SHT_DYNSYM);
400   ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
401   if (std::error_code EC = StrTabSec.getError())
402     return EC;
403   ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
404   if (std::error_code EC = StrTabOrErr.getError())
405     return EC;
406   StringRef StrTab = *StrTabOrErr;
407   uint8_t type = RelRef.getType();
408   StringRef res;
409   int64_t addend = 0;
410   switch (Sec->sh_type) {
411   default:
412     return object_error::parse_failed;
413   case ELF::SHT_REL: {
414     // TODO: Read implicit addend from section data.
415     break;
416   }
417   case ELF::SHT_RELA: {
418     const Elf_Rela *ERela = Obj->getRela(Rel);
419     addend = ERela->r_addend;
420     break;
421   }
422   }
423   symbol_iterator SI = RelRef.getSymbol();
424   const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
425   StringRef Target;
426   if (symb->getType() == ELF::STT_SECTION) {
427     ErrorOr<section_iterator> SymSI = SI->getSection();
428     if (std::error_code EC = SymSI.getError())
429       return EC;
430     const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
431     ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
432     if (std::error_code EC = SecName.getError())
433       return EC;
434     Target = *SecName;
435   } else {
436     ErrorOr<StringRef> SymName = symb->getName(StrTab);
437     if (!SymName)
438       return SymName.getError();
439     Target = *SymName;
440   }
441   switch (EF.getHeader()->e_machine) {
442   case ELF::EM_X86_64:
443     switch (type) {
444     case ELF::R_X86_64_PC8:
445     case ELF::R_X86_64_PC16:
446     case ELF::R_X86_64_PC32: {
447       std::string fmtbuf;
448       raw_string_ostream fmt(fmtbuf);
449       fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
450       fmt.flush();
451       Result.append(fmtbuf.begin(), fmtbuf.end());
452     } break;
453     case ELF::R_X86_64_8:
454     case ELF::R_X86_64_16:
455     case ELF::R_X86_64_32:
456     case ELF::R_X86_64_32S:
457     case ELF::R_X86_64_64: {
458       std::string fmtbuf;
459       raw_string_ostream fmt(fmtbuf);
460       fmt << Target << (addend < 0 ? "" : "+") << addend;
461       fmt.flush();
462       Result.append(fmtbuf.begin(), fmtbuf.end());
463     } break;
464     default:
465       res = "Unknown";
466     }
467     break;
468   case ELF::EM_AARCH64: {
469     std::string fmtbuf;
470     raw_string_ostream fmt(fmtbuf);
471     fmt << Target;
472     if (addend != 0)
473       fmt << (addend < 0 ? "" : "+") << addend;
474     fmt.flush();
475     Result.append(fmtbuf.begin(), fmtbuf.end());
476     break;
477   }
478   case ELF::EM_386:
479   case ELF::EM_IAMCU:
480   case ELF::EM_ARM:
481   case ELF::EM_HEXAGON:
482   case ELF::EM_MIPS:
483     res = Target;
484     break;
485   case ELF::EM_WEBASSEMBLY:
486     switch (type) {
487     case ELF::R_WEBASSEMBLY_DATA: {
488       std::string fmtbuf;
489       raw_string_ostream fmt(fmtbuf);
490       fmt << Target << (addend < 0 ? "" : "+") << addend;
491       fmt.flush();
492       Result.append(fmtbuf.begin(), fmtbuf.end());
493       break;
494     }
495     case ELF::R_WEBASSEMBLY_FUNCTION:
496       res = Target;
497       break;
498     default:
499       res = "Unknown";
500     }
501     break;
502   default:
503     res = "Unknown";
504   }
505   if (Result.empty())
506     Result.append(res.begin(), res.end());
507   return std::error_code();
508 }
509
510 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
511                                                 const RelocationRef &Rel,
512                                                 SmallVectorImpl<char> &Result) {
513   if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
514     return getRelocationValueString(ELF32LE, Rel, Result);
515   if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
516     return getRelocationValueString(ELF64LE, Rel, Result);
517   if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
518     return getRelocationValueString(ELF32BE, Rel, Result);
519   auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
520   return getRelocationValueString(ELF64BE, Rel, Result);
521 }
522
523 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
524                                                 const RelocationRef &Rel,
525                                                 SmallVectorImpl<char> &Result) {
526   symbol_iterator SymI = Rel.getSymbol();
527   ErrorOr<StringRef> SymNameOrErr = SymI->getName();
528   if (std::error_code EC = SymNameOrErr.getError())
529     return EC;
530   StringRef SymName = *SymNameOrErr;
531   Result.append(SymName.begin(), SymName.end());
532   return std::error_code();
533 }
534
535 static void printRelocationTargetName(const MachOObjectFile *O,
536                                       const MachO::any_relocation_info &RE,
537                                       raw_string_ostream &fmt) {
538   bool IsScattered = O->isRelocationScattered(RE);
539
540   // Target of a scattered relocation is an address.  In the interest of
541   // generating pretty output, scan through the symbol table looking for a
542   // symbol that aligns with that address.  If we find one, print it.
543   // Otherwise, we just print the hex address of the target.
544   if (IsScattered) {
545     uint32_t Val = O->getPlainRelocationSymbolNum(RE);
546
547     for (const SymbolRef &Symbol : O->symbols()) {
548       std::error_code ec;
549       ErrorOr<uint64_t> Addr = Symbol.getAddress();
550       if ((ec = Addr.getError()))
551         report_fatal_error(ec.message());
552       if (*Addr != Val)
553         continue;
554       ErrorOr<StringRef> Name = Symbol.getName();
555       if (std::error_code EC = Name.getError())
556         report_fatal_error(EC.message());
557       fmt << *Name;
558       return;
559     }
560
561     // If we couldn't find a symbol that this relocation refers to, try
562     // to find a section beginning instead.
563     for (const SectionRef &Section : ToolSectionFilter(*O)) {
564       std::error_code ec;
565
566       StringRef Name;
567       uint64_t Addr = Section.getAddress();
568       if (Addr != Val)
569         continue;
570       if ((ec = Section.getName(Name)))
571         report_fatal_error(ec.message());
572       fmt << Name;
573       return;
574     }
575
576     fmt << format("0x%x", Val);
577     return;
578   }
579
580   StringRef S;
581   bool isExtern = O->getPlainRelocationExternal(RE);
582   uint64_t Val = O->getPlainRelocationSymbolNum(RE);
583
584   if (isExtern) {
585     symbol_iterator SI = O->symbol_begin();
586     advance(SI, Val);
587     ErrorOr<StringRef> SOrErr = SI->getName();
588     error(SOrErr.getError());
589     S = *SOrErr;
590   } else {
591     section_iterator SI = O->section_begin();
592     // Adjust for the fact that sections are 1-indexed.
593     advance(SI, Val - 1);
594     SI->getName(S);
595   }
596
597   fmt << S;
598 }
599
600 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
601                                                 const RelocationRef &RelRef,
602                                                 SmallVectorImpl<char> &Result) {
603   DataRefImpl Rel = RelRef.getRawDataRefImpl();
604   MachO::any_relocation_info RE = Obj->getRelocation(Rel);
605
606   unsigned Arch = Obj->getArch();
607
608   std::string fmtbuf;
609   raw_string_ostream fmt(fmtbuf);
610   unsigned Type = Obj->getAnyRelocationType(RE);
611   bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
612
613   // Determine any addends that should be displayed with the relocation.
614   // These require decoding the relocation type, which is triple-specific.
615
616   // X86_64 has entirely custom relocation types.
617   if (Arch == Triple::x86_64) {
618     bool isPCRel = Obj->getAnyRelocationPCRel(RE);
619
620     switch (Type) {
621     case MachO::X86_64_RELOC_GOT_LOAD:
622     case MachO::X86_64_RELOC_GOT: {
623       printRelocationTargetName(Obj, RE, fmt);
624       fmt << "@GOT";
625       if (isPCRel)
626         fmt << "PCREL";
627       break;
628     }
629     case MachO::X86_64_RELOC_SUBTRACTOR: {
630       DataRefImpl RelNext = Rel;
631       Obj->moveRelocationNext(RelNext);
632       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
633
634       // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
635       // X86_64_RELOC_UNSIGNED.
636       // NOTE: Scattered relocations don't exist on x86_64.
637       unsigned RType = Obj->getAnyRelocationType(RENext);
638       if (RType != MachO::X86_64_RELOC_UNSIGNED)
639         report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
640                            "X86_64_RELOC_SUBTRACTOR.");
641
642       // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
643       // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
644       printRelocationTargetName(Obj, RENext, fmt);
645       fmt << "-";
646       printRelocationTargetName(Obj, RE, fmt);
647       break;
648     }
649     case MachO::X86_64_RELOC_TLV:
650       printRelocationTargetName(Obj, RE, fmt);
651       fmt << "@TLV";
652       if (isPCRel)
653         fmt << "P";
654       break;
655     case MachO::X86_64_RELOC_SIGNED_1:
656       printRelocationTargetName(Obj, RE, fmt);
657       fmt << "-1";
658       break;
659     case MachO::X86_64_RELOC_SIGNED_2:
660       printRelocationTargetName(Obj, RE, fmt);
661       fmt << "-2";
662       break;
663     case MachO::X86_64_RELOC_SIGNED_4:
664       printRelocationTargetName(Obj, RE, fmt);
665       fmt << "-4";
666       break;
667     default:
668       printRelocationTargetName(Obj, RE, fmt);
669       break;
670     }
671     // X86 and ARM share some relocation types in common.
672   } else if (Arch == Triple::x86 || Arch == Triple::arm ||
673              Arch == Triple::ppc) {
674     // Generic relocation types...
675     switch (Type) {
676     case MachO::GENERIC_RELOC_PAIR: // prints no info
677       return std::error_code();
678     case MachO::GENERIC_RELOC_SECTDIFF: {
679       DataRefImpl RelNext = Rel;
680       Obj->moveRelocationNext(RelNext);
681       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
682
683       // X86 sect diff's must be followed by a relocation of type
684       // GENERIC_RELOC_PAIR.
685       unsigned RType = Obj->getAnyRelocationType(RENext);
686
687       if (RType != MachO::GENERIC_RELOC_PAIR)
688         report_fatal_error("Expected GENERIC_RELOC_PAIR after "
689                            "GENERIC_RELOC_SECTDIFF.");
690
691       printRelocationTargetName(Obj, RE, fmt);
692       fmt << "-";
693       printRelocationTargetName(Obj, RENext, fmt);
694       break;
695     }
696     }
697
698     if (Arch == Triple::x86 || Arch == Triple::ppc) {
699       switch (Type) {
700       case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
701         DataRefImpl RelNext = Rel;
702         Obj->moveRelocationNext(RelNext);
703         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
704
705         // X86 sect diff's must be followed by a relocation of type
706         // GENERIC_RELOC_PAIR.
707         unsigned RType = Obj->getAnyRelocationType(RENext);
708         if (RType != MachO::GENERIC_RELOC_PAIR)
709           report_fatal_error("Expected GENERIC_RELOC_PAIR after "
710                              "GENERIC_RELOC_LOCAL_SECTDIFF.");
711
712         printRelocationTargetName(Obj, RE, fmt);
713         fmt << "-";
714         printRelocationTargetName(Obj, RENext, fmt);
715         break;
716       }
717       case MachO::GENERIC_RELOC_TLV: {
718         printRelocationTargetName(Obj, RE, fmt);
719         fmt << "@TLV";
720         if (IsPCRel)
721           fmt << "P";
722         break;
723       }
724       default:
725         printRelocationTargetName(Obj, RE, fmt);
726       }
727     } else { // ARM-specific relocations
728       switch (Type) {
729       case MachO::ARM_RELOC_HALF:
730       case MachO::ARM_RELOC_HALF_SECTDIFF: {
731         // Half relocations steal a bit from the length field to encode
732         // whether this is an upper16 or a lower16 relocation.
733         bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
734
735         if (isUpper)
736           fmt << ":upper16:(";
737         else
738           fmt << ":lower16:(";
739         printRelocationTargetName(Obj, RE, fmt);
740
741         DataRefImpl RelNext = Rel;
742         Obj->moveRelocationNext(RelNext);
743         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
744
745         // ARM half relocs must be followed by a relocation of type
746         // ARM_RELOC_PAIR.
747         unsigned RType = Obj->getAnyRelocationType(RENext);
748         if (RType != MachO::ARM_RELOC_PAIR)
749           report_fatal_error("Expected ARM_RELOC_PAIR after "
750                              "ARM_RELOC_HALF");
751
752         // NOTE: The half of the target virtual address is stashed in the
753         // address field of the secondary relocation, but we can't reverse
754         // engineer the constant offset from it without decoding the movw/movt
755         // instruction to find the other half in its immediate field.
756
757         // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
758         // symbol/section pointer of the follow-on relocation.
759         if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
760           fmt << "-";
761           printRelocationTargetName(Obj, RENext, fmt);
762         }
763
764         fmt << ")";
765         break;
766       }
767       default: { printRelocationTargetName(Obj, RE, fmt); }
768       }
769     }
770   } else
771     printRelocationTargetName(Obj, RE, fmt);
772
773   fmt.flush();
774   Result.append(fmtbuf.begin(), fmtbuf.end());
775   return std::error_code();
776 }
777
778 static std::error_code getRelocationValueString(const RelocationRef &Rel,
779                                                 SmallVectorImpl<char> &Result) {
780   const ObjectFile *Obj = Rel.getObject();
781   if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
782     return getRelocationValueString(ELF, Rel, Result);
783   if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
784     return getRelocationValueString(COFF, Rel, Result);
785   auto *MachO = cast<MachOObjectFile>(Obj);
786   return getRelocationValueString(MachO, Rel, Result);
787 }
788
789 /// @brief Indicates whether this relocation should hidden when listing
790 /// relocations, usually because it is the trailing part of a multipart
791 /// relocation that will be printed as part of the leading relocation.
792 static bool getHidden(RelocationRef RelRef) {
793   const ObjectFile *Obj = RelRef.getObject();
794   auto *MachO = dyn_cast<MachOObjectFile>(Obj);
795   if (!MachO)
796     return false;
797
798   unsigned Arch = MachO->getArch();
799   DataRefImpl Rel = RelRef.getRawDataRefImpl();
800   uint64_t Type = MachO->getRelocationType(Rel);
801
802   // On arches that use the generic relocations, GENERIC_RELOC_PAIR
803   // is always hidden.
804   if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
805     if (Type == MachO::GENERIC_RELOC_PAIR)
806       return true;
807   } else if (Arch == Triple::x86_64) {
808     // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
809     // an X86_64_RELOC_SUBTRACTOR.
810     if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
811       DataRefImpl RelPrev = Rel;
812       RelPrev.d.a--;
813       uint64_t PrevType = MachO->getRelocationType(RelPrev);
814       if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
815         return true;
816     }
817   }
818
819   return false;
820 }
821
822 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
823   const Target *TheTarget = getTarget(Obj);
824
825   // Package up features to be passed to target/subtarget
826   std::string FeaturesStr;
827   if (MAttrs.size()) {
828     SubtargetFeatures Features;
829     for (unsigned i = 0; i != MAttrs.size(); ++i)
830       Features.AddFeature(MAttrs[i]);
831     FeaturesStr = Features.getString();
832   }
833
834   std::unique_ptr<const MCRegisterInfo> MRI(
835       TheTarget->createMCRegInfo(TripleName));
836   if (!MRI)
837     report_fatal_error("error: no register info for target " + TripleName);
838
839   // Set up disassembler.
840   std::unique_ptr<const MCAsmInfo> AsmInfo(
841       TheTarget->createMCAsmInfo(*MRI, TripleName));
842   if (!AsmInfo)
843     report_fatal_error("error: no assembly info for target " + TripleName);
844   std::unique_ptr<const MCSubtargetInfo> STI(
845       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
846   if (!STI)
847     report_fatal_error("error: no subtarget info for target " + TripleName);
848   std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
849   if (!MII)
850     report_fatal_error("error: no instruction info for target " + TripleName);
851   std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
852   MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
853
854   std::unique_ptr<MCDisassembler> DisAsm(
855     TheTarget->createMCDisassembler(*STI, Ctx));
856   if (!DisAsm)
857     report_fatal_error("error: no disassembler for target " + TripleName);
858
859   std::unique_ptr<const MCInstrAnalysis> MIA(
860       TheTarget->createMCInstrAnalysis(MII.get()));
861
862   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
863   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
864       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
865   if (!IP)
866     report_fatal_error("error: no instruction printer for target " +
867                        TripleName);
868   IP->setPrintImmHex(PrintImmHex);
869   PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
870
871   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ":  " :
872                                                  "\t\t\t%08" PRIx64 ":  ";
873
874   // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
875   // in RelocSecs contain the relocations for section S.
876   std::error_code EC;
877   std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
878   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
879     section_iterator Sec2 = Section.getRelocatedSection();
880     if (Sec2 != Obj->section_end())
881       SectionRelocMap[*Sec2].push_back(Section);
882   }
883
884   // Create a mapping from virtual address to symbol name.  This is used to
885   // pretty print the symbols while disassembling.
886   typedef std::vector<std::pair<uint64_t, StringRef>> SectionSymbolsTy;
887   std::map<SectionRef, SectionSymbolsTy> AllSymbols;
888   for (const SymbolRef &Symbol : Obj->symbols()) {
889     ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
890     error(AddressOrErr.getError());
891     uint64_t Address = *AddressOrErr;
892
893     ErrorOr<StringRef> Name = Symbol.getName();
894     error(Name.getError());
895     if (Name->empty())
896       continue;
897
898     ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
899     error(SectionOrErr.getError());
900     section_iterator SecI = *SectionOrErr;
901     if (SecI == Obj->section_end())
902       continue;
903
904     AllSymbols[*SecI].emplace_back(Address, *Name);
905   }
906
907   // Create a mapping from virtual address to section.
908   std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
909   for (SectionRef Sec : Obj->sections())
910     SectionAddresses.emplace_back(Sec.getAddress(), Sec);
911   array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
912
913   // Linked executables (.exe and .dll files) typically don't include a real
914   // symbol table but they might contain an export table.
915   if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
916     for (const auto &ExportEntry : COFFObj->export_directories()) {
917       StringRef Name;
918       error(ExportEntry.getSymbolName(Name));
919       if (Name.empty())
920         continue;
921       uint32_t RVA;
922       error(ExportEntry.getExportRVA(RVA));
923
924       uint64_t VA = COFFObj->getImageBase() + RVA;
925       auto Sec = std::upper_bound(
926           SectionAddresses.begin(), SectionAddresses.end(), VA,
927           [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
928             return LHS < RHS.first;
929           });
930       if (Sec != SectionAddresses.begin())
931         --Sec;
932       else
933         Sec = SectionAddresses.end();
934
935       if (Sec != SectionAddresses.end())
936         AllSymbols[Sec->second].emplace_back(VA, Name);
937     }
938   }
939
940   // Sort all the symbols, this allows us to use a simple binary search to find
941   // a symbol near an address.
942   for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
943     array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
944
945   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
946     if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
947       continue;
948
949     uint64_t SectionAddr = Section.getAddress();
950     uint64_t SectSize = Section.getSize();
951     if (!SectSize)
952       continue;
953
954     // Get the list of all the symbols in this section.
955     SectionSymbolsTy &Symbols = AllSymbols[Section];
956     std::vector<uint64_t> DataMappingSymsAddr;
957     std::vector<uint64_t> TextMappingSymsAddr;
958     if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
959       for (const auto &Symb : Symbols) {
960         uint64_t Address = Symb.first;
961         StringRef Name = Symb.second;
962         if (Name.startswith("$d"))
963           DataMappingSymsAddr.push_back(Address - SectionAddr);
964         if (Name.startswith("$x"))
965           TextMappingSymsAddr.push_back(Address - SectionAddr);
966       }
967     }
968
969     std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
970     std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
971
972     // Make a list of all the relocations for this section.
973     std::vector<RelocationRef> Rels;
974     if (InlineRelocs) {
975       for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
976         for (const RelocationRef &Reloc : RelocSec.relocations()) {
977           Rels.push_back(Reloc);
978         }
979       }
980     }
981
982     // Sort relocations by address.
983     std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
984
985     StringRef SegmentName = "";
986     if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
987       DataRefImpl DR = Section.getRawDataRefImpl();
988       SegmentName = MachO->getSectionFinalSegmentName(DR);
989     }
990     StringRef name;
991     error(Section.getName(name));
992     outs() << "Disassembly of section ";
993     if (!SegmentName.empty())
994       outs() << SegmentName << ",";
995     outs() << name << ':';
996
997     // If the section has no symbol at the start, just insert a dummy one.
998     if (Symbols.empty() || Symbols[0].first != 0)
999       Symbols.insert(Symbols.begin(), std::make_pair(SectionAddr, name));
1000
1001     SmallString<40> Comments;
1002     raw_svector_ostream CommentStream(Comments);
1003
1004     StringRef BytesStr;
1005     error(Section.getContents(BytesStr));
1006     ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1007                             BytesStr.size());
1008
1009     uint64_t Size;
1010     uint64_t Index;
1011
1012     std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1013     std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
1014     // Disassemble symbol by symbol.
1015     for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
1016
1017       uint64_t Start = Symbols[si].first - SectionAddr;
1018       // The end is either the section end or the beginning of the next
1019       // symbol.
1020       uint64_t End =
1021           (si == se - 1) ? SectSize : Symbols[si + 1].first - SectionAddr;
1022       // Don't try to disassemble beyond the end of section contents.
1023       if (End > SectSize)
1024         End = SectSize;
1025       // If this symbol has the same address as the next symbol, then skip it.
1026       if (Start >= End)
1027         continue;
1028
1029       outs() << '\n' << Symbols[si].second << ":\n";
1030
1031 #ifndef NDEBUG
1032       raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1033 #else
1034       raw_ostream &DebugOut = nulls();
1035 #endif
1036
1037       for (Index = Start; Index < End; Index += Size) {
1038         MCInst Inst;
1039
1040         // AArch64 ELF binaries can interleave data and text in the
1041         // same section. We rely on the markers introduced to
1042         // understand what we need to dump.
1043         if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1044           uint64_t Stride = 0;
1045
1046           auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1047                                       DataMappingSymsAddr.end(), Index);
1048           if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1049             // Switch to data.
1050             while (Index < End) {
1051               outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1052               outs() << "\t";
1053               if (Index + 4 <= End) {
1054                 Stride = 4;
1055                 dumpBytes(Bytes.slice(Index, 4), outs());
1056                 outs() << "\t.word";
1057               } else if (Index + 2 <= End) {
1058                 Stride = 2;
1059                 dumpBytes(Bytes.slice(Index, 2), outs());
1060                 outs() << "\t.short";
1061               } else {
1062                 Stride = 1;
1063                 dumpBytes(Bytes.slice(Index, 1), outs());
1064                 outs() << "\t.byte";
1065               }
1066               Index += Stride;
1067               outs() << "\n";
1068               auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1069                                           TextMappingSymsAddr.end(), Index);
1070               if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1071                 break;
1072             }
1073           }
1074         }
1075
1076         if (Index >= End)
1077           break;
1078
1079         if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1080                                    SectionAddr + Index, DebugOut,
1081                                    CommentStream)) {
1082           PIP.printInst(*IP, &Inst,
1083                         Bytes.slice(Index, Size),
1084                         SectionAddr + Index, outs(), "", *STI);
1085           outs() << CommentStream.str();
1086           Comments.clear();
1087
1088           // Try to resolve the target of a call, tail call, etc. to a specific
1089           // symbol.
1090           if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1091                       MIA->isConditionalBranch(Inst))) {
1092             uint64_t Target;
1093             if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1094               // In a relocatable object, the target's section must reside in
1095               // the same section as the call instruction or it is accessed
1096               // through a relocation.
1097               //
1098               // In a non-relocatable object, the target may be in any section.
1099               //
1100               // N.B. We don't walk the relocations in the relocatable case yet.
1101               auto *TargetSectionSymbols = &Symbols;
1102               if (!Obj->isRelocatableObject()) {
1103                 auto SectionAddress = std::upper_bound(
1104                     SectionAddresses.begin(), SectionAddresses.end(), Target,
1105                     [](uint64_t LHS,
1106                        const std::pair<uint64_t, SectionRef> &RHS) {
1107                       return LHS < RHS.first;
1108                     });
1109                 if (SectionAddress != SectionAddresses.begin()) {
1110                   --SectionAddress;
1111                   TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1112                 } else {
1113                   TargetSectionSymbols = nullptr;
1114                 }
1115               }
1116
1117               // Find the first symbol in the section whose offset is less than
1118               // or equal to the target.
1119               if (TargetSectionSymbols) {
1120                 auto TargetSym = std::upper_bound(
1121                     TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1122                     Target, [](uint64_t LHS,
1123                                const std::pair<uint64_t, StringRef> &RHS) {
1124                       return LHS < RHS.first;
1125                     });
1126                 if (TargetSym != TargetSectionSymbols->begin()) {
1127                   --TargetSym;
1128                   uint64_t TargetAddress = std::get<0>(*TargetSym);
1129                   StringRef TargetName = std::get<1>(*TargetSym);
1130                   outs() << " <" << TargetName;
1131                   uint64_t Disp = Target - TargetAddress;
1132                   if (Disp)
1133                     outs() << '+' << utohexstr(Disp);
1134                   outs() << '>';
1135                 }
1136               }
1137             }
1138           }
1139           outs() << "\n";
1140         } else {
1141           errs() << ToolName << ": warning: invalid instruction encoding\n";
1142           if (Size == 0)
1143             Size = 1; // skip illegible bytes
1144         }
1145
1146         // Print relocation for instruction.
1147         while (rel_cur != rel_end) {
1148           bool hidden = getHidden(*rel_cur);
1149           uint64_t addr = rel_cur->getOffset();
1150           SmallString<16> name;
1151           SmallString<32> val;
1152
1153           // If this relocation is hidden, skip it.
1154           if (hidden) goto skip_print_rel;
1155
1156           // Stop when rel_cur's address is past the current instruction.
1157           if (addr >= Index + Size) break;
1158           rel_cur->getTypeName(name);
1159           error(getRelocationValueString(*rel_cur, val));
1160           outs() << format(Fmt.data(), SectionAddr + addr) << name
1161                  << "\t" << val << "\n";
1162
1163         skip_print_rel:
1164           ++rel_cur;
1165         }
1166       }
1167     }
1168   }
1169 }
1170
1171 void llvm::PrintRelocations(const ObjectFile *Obj) {
1172   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1173                                                  "%08" PRIx64;
1174   // Regular objdump doesn't print relocations in non-relocatable object
1175   // files.
1176   if (!Obj->isRelocatableObject())
1177     return;
1178
1179   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1180     if (Section.relocation_begin() == Section.relocation_end())
1181       continue;
1182     StringRef secname;
1183     error(Section.getName(secname));
1184     outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
1185     for (const RelocationRef &Reloc : Section.relocations()) {
1186       bool hidden = getHidden(Reloc);
1187       uint64_t address = Reloc.getOffset();
1188       SmallString<32> relocname;
1189       SmallString<32> valuestr;
1190       if (hidden)
1191         continue;
1192       Reloc.getTypeName(relocname);
1193       error(getRelocationValueString(Reloc, valuestr));
1194       outs() << format(Fmt.data(), address) << " " << relocname << " "
1195              << valuestr << "\n";
1196     }
1197     outs() << "\n";
1198   }
1199 }
1200
1201 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
1202   outs() << "Sections:\n"
1203             "Idx Name          Size      Address          Type\n";
1204   unsigned i = 0;
1205   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1206     StringRef Name;
1207     error(Section.getName(Name));
1208     uint64_t Address = Section.getAddress();
1209     uint64_t Size = Section.getSize();
1210     bool Text = Section.isText();
1211     bool Data = Section.isData();
1212     bool BSS = Section.isBSS();
1213     std::string Type = (std::string(Text ? "TEXT " : "") +
1214                         (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1215     outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1216                      Name.str().c_str(), Size, Address, Type.c_str());
1217     ++i;
1218   }
1219 }
1220
1221 void llvm::PrintSectionContents(const ObjectFile *Obj) {
1222   std::error_code EC;
1223   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1224     StringRef Name;
1225     StringRef Contents;
1226     error(Section.getName(Name));
1227     uint64_t BaseAddr = Section.getAddress();
1228     uint64_t Size = Section.getSize();
1229     if (!Size)
1230       continue;
1231
1232     outs() << "Contents of section " << Name << ":\n";
1233     if (Section.isBSS()) {
1234       outs() << format("<skipping contents of bss section at [%04" PRIx64
1235                        ", %04" PRIx64 ")>\n",
1236                        BaseAddr, BaseAddr + Size);
1237       continue;
1238     }
1239
1240     error(Section.getContents(Contents));
1241
1242     // Dump out the content as hex and printable ascii characters.
1243     for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1244       outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1245       // Dump line of hex.
1246       for (std::size_t i = 0; i < 16; ++i) {
1247         if (i != 0 && i % 4 == 0)
1248           outs() << ' ';
1249         if (addr + i < end)
1250           outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1251                  << hexdigit(Contents[addr + i] & 0xF, true);
1252         else
1253           outs() << "  ";
1254       }
1255       // Print ascii.
1256       outs() << "  ";
1257       for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1258         if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1259           outs() << Contents[addr + i];
1260         else
1261           outs() << ".";
1262       }
1263       outs() << "\n";
1264     }
1265   }
1266 }
1267
1268 void llvm::PrintSymbolTable(const ObjectFile *o) {
1269   outs() << "SYMBOL TABLE:\n";
1270
1271   if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1272     printCOFFSymbolTable(coff);
1273     return;
1274   }
1275   for (const SymbolRef &Symbol : o->symbols()) {
1276     ErrorOr<uint64_t> AddressOrError = Symbol.getAddress();
1277     error(AddressOrError.getError());
1278     uint64_t Address = *AddressOrError;
1279     SymbolRef::Type Type = Symbol.getType();
1280     uint32_t Flags = Symbol.getFlags();
1281     ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
1282     error(SectionOrErr.getError());
1283     section_iterator Section = *SectionOrErr;
1284     StringRef Name;
1285     if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1286       Section->getName(Name);
1287     } else {
1288       ErrorOr<StringRef> NameOrErr = Symbol.getName();
1289       error(NameOrErr.getError());
1290       Name = *NameOrErr;
1291     }
1292
1293     bool Global = Flags & SymbolRef::SF_Global;
1294     bool Weak = Flags & SymbolRef::SF_Weak;
1295     bool Absolute = Flags & SymbolRef::SF_Absolute;
1296     bool Common = Flags & SymbolRef::SF_Common;
1297     bool Hidden = Flags & SymbolRef::SF_Hidden;
1298
1299     char GlobLoc = ' ';
1300     if (Type != SymbolRef::ST_Unknown)
1301       GlobLoc = Global ? 'g' : 'l';
1302     char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1303                  ? 'd' : ' ';
1304     char FileFunc = ' ';
1305     if (Type == SymbolRef::ST_File)
1306       FileFunc = 'f';
1307     else if (Type == SymbolRef::ST_Function)
1308       FileFunc = 'F';
1309
1310     const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1311                                                    "%08" PRIx64;
1312
1313     outs() << format(Fmt, Address) << " "
1314            << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1315            << (Weak ? 'w' : ' ') // Weak?
1316            << ' ' // Constructor. Not supported yet.
1317            << ' ' // Warning. Not supported yet.
1318            << ' ' // Indirect reference to another symbol.
1319            << Debug // Debugging (d) or dynamic (D) symbol.
1320            << FileFunc // Name of function (F), file (f) or object (O).
1321            << ' ';
1322     if (Absolute) {
1323       outs() << "*ABS*";
1324     } else if (Common) {
1325       outs() << "*COM*";
1326     } else if (Section == o->section_end()) {
1327       outs() << "*UND*";
1328     } else {
1329       if (const MachOObjectFile *MachO =
1330           dyn_cast<const MachOObjectFile>(o)) {
1331         DataRefImpl DR = Section->getRawDataRefImpl();
1332         StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1333         outs() << SegmentName << ",";
1334       }
1335       StringRef SectionName;
1336       error(Section->getName(SectionName));
1337       outs() << SectionName;
1338     }
1339
1340     outs() << '\t';
1341     if (Common || isa<ELFObjectFileBase>(o)) {
1342       uint64_t Val =
1343           Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1344       outs() << format("\t %08" PRIx64 " ", Val);
1345     }
1346
1347     if (Hidden) {
1348       outs() << ".hidden ";
1349     }
1350     outs() << Name
1351            << '\n';
1352   }
1353 }
1354
1355 static void PrintUnwindInfo(const ObjectFile *o) {
1356   outs() << "Unwind info:\n\n";
1357
1358   if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1359     printCOFFUnwindInfo(coff);
1360   } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1361     printMachOUnwindInfo(MachO);
1362   else {
1363     // TODO: Extract DWARF dump tool to objdump.
1364     errs() << "This operation is only currently supported "
1365               "for COFF and MachO object files.\n";
1366     return;
1367   }
1368 }
1369
1370 void llvm::printExportsTrie(const ObjectFile *o) {
1371   outs() << "Exports trie:\n";
1372   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1373     printMachOExportsTrie(MachO);
1374   else {
1375     errs() << "This operation is only currently supported "
1376               "for Mach-O executable files.\n";
1377     return;
1378   }
1379 }
1380
1381 void llvm::printRebaseTable(const ObjectFile *o) {
1382   outs() << "Rebase table:\n";
1383   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1384     printMachORebaseTable(MachO);
1385   else {
1386     errs() << "This operation is only currently supported "
1387               "for Mach-O executable files.\n";
1388     return;
1389   }
1390 }
1391
1392 void llvm::printBindTable(const ObjectFile *o) {
1393   outs() << "Bind table:\n";
1394   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1395     printMachOBindTable(MachO);
1396   else {
1397     errs() << "This operation is only currently supported "
1398               "for Mach-O executable files.\n";
1399     return;
1400   }
1401 }
1402
1403 void llvm::printLazyBindTable(const ObjectFile *o) {
1404   outs() << "Lazy bind table:\n";
1405   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1406     printMachOLazyBindTable(MachO);
1407   else {
1408     errs() << "This operation is only currently supported "
1409               "for Mach-O executable files.\n";
1410     return;
1411   }
1412 }
1413
1414 void llvm::printWeakBindTable(const ObjectFile *o) {
1415   outs() << "Weak bind table:\n";
1416   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1417     printMachOWeakBindTable(MachO);
1418   else {
1419     errs() << "This operation is only currently supported "
1420               "for Mach-O executable files.\n";
1421     return;
1422   }
1423 }
1424
1425 /// Dump the raw contents of the __clangast section so the output can be piped
1426 /// into llvm-bcanalyzer.
1427 void llvm::printRawClangAST(const ObjectFile *Obj) {
1428   if (outs().is_displayed()) {
1429     errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1430               "the clang ast section.\n"
1431               "Please redirect the output to a file or another program such as "
1432               "llvm-bcanalyzer.\n";
1433     return;
1434   }
1435
1436   StringRef ClangASTSectionName("__clangast");
1437   if (isa<COFFObjectFile>(Obj)) {
1438     ClangASTSectionName = "clangast";
1439   }
1440
1441   Optional<object::SectionRef> ClangASTSection;
1442   for (auto Sec : ToolSectionFilter(*Obj)) {
1443     StringRef Name;
1444     Sec.getName(Name);
1445     if (Name == ClangASTSectionName) {
1446       ClangASTSection = Sec;
1447       break;
1448     }
1449   }
1450   if (!ClangASTSection)
1451     return;
1452
1453   StringRef ClangASTContents;
1454   error(ClangASTSection.getValue().getContents(ClangASTContents));
1455   outs().write(ClangASTContents.data(), ClangASTContents.size());
1456 }
1457
1458 static void printFaultMaps(const ObjectFile *Obj) {
1459   const char *FaultMapSectionName = nullptr;
1460
1461   if (isa<ELFObjectFileBase>(Obj)) {
1462     FaultMapSectionName = ".llvm_faultmaps";
1463   } else if (isa<MachOObjectFile>(Obj)) {
1464     FaultMapSectionName = "__llvm_faultmaps";
1465   } else {
1466     errs() << "This operation is only currently supported "
1467               "for ELF and Mach-O executable files.\n";
1468     return;
1469   }
1470
1471   Optional<object::SectionRef> FaultMapSection;
1472
1473   for (auto Sec : ToolSectionFilter(*Obj)) {
1474     StringRef Name;
1475     Sec.getName(Name);
1476     if (Name == FaultMapSectionName) {
1477       FaultMapSection = Sec;
1478       break;
1479     }
1480   }
1481
1482   outs() << "FaultMap table:\n";
1483
1484   if (!FaultMapSection.hasValue()) {
1485     outs() << "<not found>\n";
1486     return;
1487   }
1488
1489   StringRef FaultMapContents;
1490   error(FaultMapSection.getValue().getContents(FaultMapContents));
1491
1492   FaultMapParser FMP(FaultMapContents.bytes_begin(),
1493                      FaultMapContents.bytes_end());
1494
1495   outs() << FMP;
1496 }
1497
1498 static void printPrivateFileHeader(const ObjectFile *o) {
1499   if (o->isELF())
1500     printELFFileHeader(o);
1501   else if (o->isCOFF())
1502     printCOFFFileHeader(o);
1503   else if (o->isMachO())
1504     printMachOFileHeader(o);
1505   else
1506     report_fatal_error("Invalid/Unsupported object file format");
1507 }
1508
1509 static void DumpObject(const ObjectFile *o) {
1510   // Avoid other output when using a raw option.
1511   if (!RawClangAST) {
1512     outs() << '\n';
1513     outs() << o->getFileName()
1514            << ":\tfile format " << o->getFileFormatName() << "\n\n";
1515   }
1516
1517   if (Disassemble)
1518     DisassembleObject(o, Relocations);
1519   if (Relocations && !Disassemble)
1520     PrintRelocations(o);
1521   if (SectionHeaders)
1522     PrintSectionHeaders(o);
1523   if (SectionContents)
1524     PrintSectionContents(o);
1525   if (SymbolTable)
1526     PrintSymbolTable(o);
1527   if (UnwindInfo)
1528     PrintUnwindInfo(o);
1529   if (PrivateHeaders)
1530     printPrivateFileHeader(o);
1531   if (ExportsTrie)
1532     printExportsTrie(o);
1533   if (Rebase)
1534     printRebaseTable(o);
1535   if (Bind)
1536     printBindTable(o);
1537   if (LazyBind)
1538     printLazyBindTable(o);
1539   if (WeakBind)
1540     printWeakBindTable(o);
1541   if (RawClangAST)
1542     printRawClangAST(o);
1543   if (PrintFaultMaps)
1544     printFaultMaps(o);
1545 }
1546
1547 /// @brief Dump each object file in \a a;
1548 static void DumpArchive(const Archive *a) {
1549   for (auto &ErrorOrChild : a->children()) {
1550     if (std::error_code EC = ErrorOrChild.getError())
1551       report_error(a->getFileName(), EC);
1552     const Archive::Child &C = *ErrorOrChild;
1553     ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1554     if (std::error_code EC = ChildOrErr.getError())
1555       if (EC != object_error::invalid_file_type)
1556         report_error(a->getFileName(), EC);
1557     if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
1558       DumpObject(o);
1559     else
1560       report_error(a->getFileName(), object_error::invalid_file_type);
1561   }
1562 }
1563
1564 /// @brief Open file and figure out how to dump it.
1565 static void DumpInput(StringRef file) {
1566
1567   // If we are using the Mach-O specific object file parser, then let it parse
1568   // the file and process the command line options.  So the -arch flags can
1569   // be used to select specific slices, etc.
1570   if (MachOOpt) {
1571     ParseInputMachO(file);
1572     return;
1573   }
1574
1575   // Attempt to open the binary.
1576   ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1577   if (std::error_code EC = BinaryOrErr.getError())
1578     report_error(file, EC);
1579   Binary &Binary = *BinaryOrErr.get().getBinary();
1580
1581   if (Archive *a = dyn_cast<Archive>(&Binary))
1582     DumpArchive(a);
1583   else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
1584     DumpObject(o);
1585   else
1586     report_error(file, object_error::invalid_file_type);
1587 }
1588
1589 int main(int argc, char **argv) {
1590   // Print a stack trace if we signal out.
1591   sys::PrintStackTraceOnErrorSignal();
1592   PrettyStackTraceProgram X(argc, argv);
1593   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
1594
1595   // Initialize targets and assembly printers/parsers.
1596   llvm::InitializeAllTargetInfos();
1597   llvm::InitializeAllTargetMCs();
1598   llvm::InitializeAllDisassemblers();
1599
1600   // Register the target printer for --version.
1601   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1602
1603   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1604   TripleName = Triple::normalize(TripleName);
1605
1606   ToolName = argv[0];
1607
1608   // Defaults to a.out if no filenames specified.
1609   if (InputFilenames.size() == 0)
1610     InputFilenames.push_back("a.out");
1611
1612   if (DisassembleAll)
1613     Disassemble = true;
1614   if (!Disassemble
1615       && !Relocations
1616       && !SectionHeaders
1617       && !SectionContents
1618       && !SymbolTable
1619       && !UnwindInfo
1620       && !PrivateHeaders
1621       && !ExportsTrie
1622       && !Rebase
1623       && !Bind
1624       && !LazyBind
1625       && !WeakBind
1626       && !RawClangAST
1627       && !(UniversalHeaders && MachOOpt)
1628       && !(ArchiveHeaders && MachOOpt)
1629       && !(IndirectSymbols && MachOOpt)
1630       && !(DataInCode && MachOOpt)
1631       && !(LinkOptHints && MachOOpt)
1632       && !(InfoPlist && MachOOpt)
1633       && !(DylibsUsed && MachOOpt)
1634       && !(DylibId && MachOOpt)
1635       && !(ObjcMetaData && MachOOpt)
1636       && !(FilterSections.size() != 0 && MachOOpt)
1637       && !PrintFaultMaps) {
1638     cl::PrintHelpMessage();
1639     return 2;
1640   }
1641
1642   std::for_each(InputFilenames.begin(), InputFilenames.end(),
1643                 DumpInput);
1644
1645   return EXIT_SUCCESS;
1646 }