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