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