160fe5b73cb9d0f918abc8d70bb997e68c8ad47a
[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   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_ARM:
481   case ELF::EM_HEXAGON:
482   case ELF::EM_MIPS:
483     res = Target;
484     break;
485   default:
486     res = "Unknown";
487   }
488   if (Result.empty())
489     Result.append(res.begin(), res.end());
490   return std::error_code();
491 }
492
493 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
494                                                 const RelocationRef &Rel,
495                                                 SmallVectorImpl<char> &Result) {
496   if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
497     return getRelocationValueString(ELF32LE, Rel, Result);
498   if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
499     return getRelocationValueString(ELF64LE, Rel, Result);
500   if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
501     return getRelocationValueString(ELF32BE, Rel, Result);
502   auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
503   return getRelocationValueString(ELF64BE, Rel, Result);
504 }
505
506 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
507                                                 const RelocationRef &Rel,
508                                                 SmallVectorImpl<char> &Result) {
509   symbol_iterator SymI = Rel.getSymbol();
510   ErrorOr<StringRef> SymNameOrErr = SymI->getName();
511   if (std::error_code EC = SymNameOrErr.getError())
512     return EC;
513   StringRef SymName = *SymNameOrErr;
514   Result.append(SymName.begin(), SymName.end());
515   return std::error_code();
516 }
517
518 static void printRelocationTargetName(const MachOObjectFile *O,
519                                       const MachO::any_relocation_info &RE,
520                                       raw_string_ostream &fmt) {
521   bool IsScattered = O->isRelocationScattered(RE);
522
523   // Target of a scattered relocation is an address.  In the interest of
524   // generating pretty output, scan through the symbol table looking for a
525   // symbol that aligns with that address.  If we find one, print it.
526   // Otherwise, we just print the hex address of the target.
527   if (IsScattered) {
528     uint32_t Val = O->getPlainRelocationSymbolNum(RE);
529
530     for (const SymbolRef &Symbol : O->symbols()) {
531       std::error_code ec;
532       ErrorOr<uint64_t> Addr = Symbol.getAddress();
533       if ((ec = Addr.getError()))
534         report_fatal_error(ec.message());
535       if (*Addr != Val)
536         continue;
537       ErrorOr<StringRef> Name = Symbol.getName();
538       if (std::error_code EC = Name.getError())
539         report_fatal_error(EC.message());
540       fmt << *Name;
541       return;
542     }
543
544     // If we couldn't find a symbol that this relocation refers to, try
545     // to find a section beginning instead.
546     for (const SectionRef &Section : ToolSectionFilter(*O)) {
547       std::error_code ec;
548
549       StringRef Name;
550       uint64_t Addr = Section.getAddress();
551       if (Addr != Val)
552         continue;
553       if ((ec = Section.getName(Name)))
554         report_fatal_error(ec.message());
555       fmt << Name;
556       return;
557     }
558
559     fmt << format("0x%x", Val);
560     return;
561   }
562
563   StringRef S;
564   bool isExtern = O->getPlainRelocationExternal(RE);
565   uint64_t Val = O->getPlainRelocationSymbolNum(RE);
566
567   if (isExtern) {
568     symbol_iterator SI = O->symbol_begin();
569     advance(SI, Val);
570     ErrorOr<StringRef> SOrErr = SI->getName();
571     error(SOrErr.getError());
572     S = *SOrErr;
573   } else {
574     section_iterator SI = O->section_begin();
575     // Adjust for the fact that sections are 1-indexed.
576     advance(SI, Val - 1);
577     SI->getName(S);
578   }
579
580   fmt << S;
581 }
582
583 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
584                                                 const RelocationRef &RelRef,
585                                                 SmallVectorImpl<char> &Result) {
586   DataRefImpl Rel = RelRef.getRawDataRefImpl();
587   MachO::any_relocation_info RE = Obj->getRelocation(Rel);
588
589   unsigned Arch = Obj->getArch();
590
591   std::string fmtbuf;
592   raw_string_ostream fmt(fmtbuf);
593   unsigned Type = Obj->getAnyRelocationType(RE);
594   bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
595
596   // Determine any addends that should be displayed with the relocation.
597   // These require decoding the relocation type, which is triple-specific.
598
599   // X86_64 has entirely custom relocation types.
600   if (Arch == Triple::x86_64) {
601     bool isPCRel = Obj->getAnyRelocationPCRel(RE);
602
603     switch (Type) {
604     case MachO::X86_64_RELOC_GOT_LOAD:
605     case MachO::X86_64_RELOC_GOT: {
606       printRelocationTargetName(Obj, RE, fmt);
607       fmt << "@GOT";
608       if (isPCRel)
609         fmt << "PCREL";
610       break;
611     }
612     case MachO::X86_64_RELOC_SUBTRACTOR: {
613       DataRefImpl RelNext = Rel;
614       Obj->moveRelocationNext(RelNext);
615       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
616
617       // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
618       // X86_64_RELOC_UNSIGNED.
619       // NOTE: Scattered relocations don't exist on x86_64.
620       unsigned RType = Obj->getAnyRelocationType(RENext);
621       if (RType != MachO::X86_64_RELOC_UNSIGNED)
622         report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
623                            "X86_64_RELOC_SUBTRACTOR.");
624
625       // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
626       // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
627       printRelocationTargetName(Obj, RENext, fmt);
628       fmt << "-";
629       printRelocationTargetName(Obj, RE, fmt);
630       break;
631     }
632     case MachO::X86_64_RELOC_TLV:
633       printRelocationTargetName(Obj, RE, fmt);
634       fmt << "@TLV";
635       if (isPCRel)
636         fmt << "P";
637       break;
638     case MachO::X86_64_RELOC_SIGNED_1:
639       printRelocationTargetName(Obj, RE, fmt);
640       fmt << "-1";
641       break;
642     case MachO::X86_64_RELOC_SIGNED_2:
643       printRelocationTargetName(Obj, RE, fmt);
644       fmt << "-2";
645       break;
646     case MachO::X86_64_RELOC_SIGNED_4:
647       printRelocationTargetName(Obj, RE, fmt);
648       fmt << "-4";
649       break;
650     default:
651       printRelocationTargetName(Obj, RE, fmt);
652       break;
653     }
654     // X86 and ARM share some relocation types in common.
655   } else if (Arch == Triple::x86 || Arch == Triple::arm ||
656              Arch == Triple::ppc) {
657     // Generic relocation types...
658     switch (Type) {
659     case MachO::GENERIC_RELOC_PAIR: // prints no info
660       return std::error_code();
661     case MachO::GENERIC_RELOC_SECTDIFF: {
662       DataRefImpl RelNext = Rel;
663       Obj->moveRelocationNext(RelNext);
664       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
665
666       // X86 sect diff's must be followed by a relocation of type
667       // GENERIC_RELOC_PAIR.
668       unsigned RType = Obj->getAnyRelocationType(RENext);
669
670       if (RType != MachO::GENERIC_RELOC_PAIR)
671         report_fatal_error("Expected GENERIC_RELOC_PAIR after "
672                            "GENERIC_RELOC_SECTDIFF.");
673
674       printRelocationTargetName(Obj, RE, fmt);
675       fmt << "-";
676       printRelocationTargetName(Obj, RENext, fmt);
677       break;
678     }
679     }
680
681     if (Arch == Triple::x86 || Arch == Triple::ppc) {
682       switch (Type) {
683       case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
684         DataRefImpl RelNext = Rel;
685         Obj->moveRelocationNext(RelNext);
686         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
687
688         // X86 sect diff's must be followed by a relocation of type
689         // GENERIC_RELOC_PAIR.
690         unsigned RType = Obj->getAnyRelocationType(RENext);
691         if (RType != MachO::GENERIC_RELOC_PAIR)
692           report_fatal_error("Expected GENERIC_RELOC_PAIR after "
693                              "GENERIC_RELOC_LOCAL_SECTDIFF.");
694
695         printRelocationTargetName(Obj, RE, fmt);
696         fmt << "-";
697         printRelocationTargetName(Obj, RENext, fmt);
698         break;
699       }
700       case MachO::GENERIC_RELOC_TLV: {
701         printRelocationTargetName(Obj, RE, fmt);
702         fmt << "@TLV";
703         if (IsPCRel)
704           fmt << "P";
705         break;
706       }
707       default:
708         printRelocationTargetName(Obj, RE, fmt);
709       }
710     } else { // ARM-specific relocations
711       switch (Type) {
712       case MachO::ARM_RELOC_HALF:
713       case MachO::ARM_RELOC_HALF_SECTDIFF: {
714         // Half relocations steal a bit from the length field to encode
715         // whether this is an upper16 or a lower16 relocation.
716         bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
717
718         if (isUpper)
719           fmt << ":upper16:(";
720         else
721           fmt << ":lower16:(";
722         printRelocationTargetName(Obj, RE, fmt);
723
724         DataRefImpl RelNext = Rel;
725         Obj->moveRelocationNext(RelNext);
726         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
727
728         // ARM half relocs must be followed by a relocation of type
729         // ARM_RELOC_PAIR.
730         unsigned RType = Obj->getAnyRelocationType(RENext);
731         if (RType != MachO::ARM_RELOC_PAIR)
732           report_fatal_error("Expected ARM_RELOC_PAIR after "
733                              "ARM_RELOC_HALF");
734
735         // NOTE: The half of the target virtual address is stashed in the
736         // address field of the secondary relocation, but we can't reverse
737         // engineer the constant offset from it without decoding the movw/movt
738         // instruction to find the other half in its immediate field.
739
740         // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
741         // symbol/section pointer of the follow-on relocation.
742         if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
743           fmt << "-";
744           printRelocationTargetName(Obj, RENext, fmt);
745         }
746
747         fmt << ")";
748         break;
749       }
750       default: { printRelocationTargetName(Obj, RE, fmt); }
751       }
752     }
753   } else
754     printRelocationTargetName(Obj, RE, fmt);
755
756   fmt.flush();
757   Result.append(fmtbuf.begin(), fmtbuf.end());
758   return std::error_code();
759 }
760
761 static std::error_code getRelocationValueString(const RelocationRef &Rel,
762                                                 SmallVectorImpl<char> &Result) {
763   const ObjectFile *Obj = Rel.getObject();
764   if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
765     return getRelocationValueString(ELF, Rel, Result);
766   if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
767     return getRelocationValueString(COFF, Rel, Result);
768   auto *MachO = cast<MachOObjectFile>(Obj);
769   return getRelocationValueString(MachO, Rel, Result);
770 }
771
772 /// @brief Indicates whether this relocation should hidden when listing
773 /// relocations, usually because it is the trailing part of a multipart
774 /// relocation that will be printed as part of the leading relocation.
775 static bool getHidden(RelocationRef RelRef) {
776   const ObjectFile *Obj = RelRef.getObject();
777   auto *MachO = dyn_cast<MachOObjectFile>(Obj);
778   if (!MachO)
779     return false;
780
781   unsigned Arch = MachO->getArch();
782   DataRefImpl Rel = RelRef.getRawDataRefImpl();
783   uint64_t Type = MachO->getRelocationType(Rel);
784
785   // On arches that use the generic relocations, GENERIC_RELOC_PAIR
786   // is always hidden.
787   if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
788     if (Type == MachO::GENERIC_RELOC_PAIR)
789       return true;
790   } else if (Arch == Triple::x86_64) {
791     // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
792     // an X86_64_RELOC_SUBTRACTOR.
793     if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
794       DataRefImpl RelPrev = Rel;
795       RelPrev.d.a--;
796       uint64_t PrevType = MachO->getRelocationType(RelPrev);
797       if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
798         return true;
799     }
800   }
801
802   return false;
803 }
804
805 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
806   const Target *TheTarget = getTarget(Obj);
807   // getTarget() will have already issued a diagnostic if necessary, so
808   // just bail here if it failed.
809   if (!TheTarget)
810     return;
811
812   // Package up features to be passed to target/subtarget
813   std::string FeaturesStr;
814   if (MAttrs.size()) {
815     SubtargetFeatures Features;
816     for (unsigned i = 0; i != MAttrs.size(); ++i)
817       Features.AddFeature(MAttrs[i]);
818     FeaturesStr = Features.getString();
819   }
820
821   std::unique_ptr<const MCRegisterInfo> MRI(
822       TheTarget->createMCRegInfo(TripleName));
823   if (!MRI) {
824     errs() << "error: no register info for target " << TripleName << "\n";
825     return;
826   }
827
828   // Set up disassembler.
829   std::unique_ptr<const MCAsmInfo> AsmInfo(
830       TheTarget->createMCAsmInfo(*MRI, TripleName));
831   if (!AsmInfo) {
832     errs() << "error: no assembly info for target " << TripleName << "\n";
833     return;
834   }
835
836   std::unique_ptr<const MCSubtargetInfo> STI(
837       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
838   if (!STI) {
839     errs() << "error: no subtarget info for target " << TripleName << "\n";
840     return;
841   }
842
843   std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
844   if (!MII) {
845     errs() << "error: no instruction info for target " << TripleName << "\n";
846     return;
847   }
848
849   std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
850   MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
851
852   std::unique_ptr<MCDisassembler> DisAsm(
853     TheTarget->createMCDisassembler(*STI, Ctx));
854
855   if (!DisAsm) {
856     errs() << "error: no disassembler for target " << TripleName << "\n";
857     return;
858   }
859
860   std::unique_ptr<const MCInstrAnalysis> MIA(
861       TheTarget->createMCInstrAnalysis(MII.get()));
862
863   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
864   std::unique_ptr<MCInstPrinter> IP(
865       TheTarget->createMCInstPrinter(TargetTuple(Triple(TripleName)),
866                                      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     for (const SymbolRef &Symbol : Obj->symbols()) {
922       if (Section.containsSymbol(Symbol)) {
923         ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
924         error(AddressOrErr.getError());
925         uint64_t Address = *AddressOrErr;
926         Address -= SectionAddr;
927         if (Address >= SectSize)
928           continue;
929
930         ErrorOr<StringRef> Name = Symbol.getName();
931         error(Name.getError());
932         Symbols.push_back(std::make_pair(Address, *Name));
933       }
934     }
935
936     // Sort the symbols by address, just in case they didn't come in that way.
937     array_pod_sort(Symbols.begin(), Symbols.end());
938
939     // Make a list of all the relocations for this section.
940     std::vector<RelocationRef> Rels;
941     if (InlineRelocs) {
942       for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
943         for (const RelocationRef &Reloc : RelocSec.relocations()) {
944           Rels.push_back(Reloc);
945         }
946       }
947     }
948
949     // Sort relocations by address.
950     std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
951
952     StringRef SegmentName = "";
953     if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
954       DataRefImpl DR = Section.getRawDataRefImpl();
955       SegmentName = MachO->getSectionFinalSegmentName(DR);
956     }
957     StringRef name;
958     error(Section.getName(name));
959     outs() << "Disassembly of section ";
960     if (!SegmentName.empty())
961       outs() << SegmentName << ",";
962     outs() << name << ':';
963
964     // If the section has no symbol at the start, just insert a dummy one.
965     if (Symbols.empty() || Symbols[0].first != 0)
966       Symbols.insert(Symbols.begin(), std::make_pair(0, name));
967
968     SmallString<40> Comments;
969     raw_svector_ostream CommentStream(Comments);
970
971     StringRef BytesStr;
972     error(Section.getContents(BytesStr));
973     ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
974                             BytesStr.size());
975
976     uint64_t Size;
977     uint64_t Index;
978
979     std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
980     std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
981     // Disassemble symbol by symbol.
982     for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
983
984       uint64_t Start = Symbols[si].first;
985       // The end is either the section end or the beginning of the next symbol.
986       uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
987       // If this symbol has the same address as the next symbol, then skip it.
988       if (Start == End)
989         continue;
990
991       outs() << '\n' << Symbols[si].second << ":\n";
992
993 #ifndef NDEBUG
994       raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
995 #else
996       raw_ostream &DebugOut = nulls();
997 #endif
998
999       for (Index = Start; Index < End; Index += Size) {
1000         MCInst Inst;
1001
1002         if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1003                                    SectionAddr + Index, DebugOut,
1004                                    CommentStream)) {
1005           PIP.printInst(*IP, &Inst,
1006                         Bytes.slice(Index, Size),
1007                         SectionAddr + Index, outs(), "", *STI);
1008           outs() << CommentStream.str();
1009           Comments.clear();
1010           if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1011                       MIA->isConditionalBranch(Inst))) {
1012             uint64_t Target;
1013             if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1014               auto TargetSym = std::upper_bound(
1015                   AllSymbols.begin(), AllSymbols.end(), Target,
1016                   [](uint64_t LHS, const std::pair<uint64_t, StringRef> &RHS) {
1017                     return LHS < RHS.first;
1018                   });
1019               if (TargetSym != AllSymbols.begin())
1020                 --TargetSym;
1021               else
1022                 TargetSym = AllSymbols.end();
1023
1024               if (TargetSym != AllSymbols.end()) {
1025                 outs() << " <" << TargetSym->second;
1026                 uint64_t Disp = Target - TargetSym->first;
1027                 if (Disp)
1028                   outs() << '+' << utohexstr(Disp);
1029                 outs() << '>';
1030               }
1031             }
1032           }
1033           outs() << "\n";
1034         } else {
1035           errs() << ToolName << ": warning: invalid instruction encoding\n";
1036           if (Size == 0)
1037             Size = 1; // skip illegible bytes
1038         }
1039
1040         // Print relocation for instruction.
1041         while (rel_cur != rel_end) {
1042           bool hidden = getHidden(*rel_cur);
1043           uint64_t addr = rel_cur->getOffset();
1044           SmallString<16> name;
1045           SmallString<32> val;
1046
1047           // If this relocation is hidden, skip it.
1048           if (hidden) goto skip_print_rel;
1049
1050           // Stop when rel_cur's address is past the current instruction.
1051           if (addr >= Index + Size) break;
1052           rel_cur->getTypeName(name);
1053           error(getRelocationValueString(*rel_cur, val));
1054           outs() << format(Fmt.data(), SectionAddr + addr) << name
1055                  << "\t" << val << "\n";
1056
1057         skip_print_rel:
1058           ++rel_cur;
1059         }
1060       }
1061     }
1062   }
1063 }
1064
1065 void llvm::PrintRelocations(const ObjectFile *Obj) {
1066   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1067                                                  "%08" PRIx64;
1068   // Regular objdump doesn't print relocations in non-relocatable object
1069   // files.
1070   if (!Obj->isRelocatableObject())
1071     return;
1072
1073   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1074     if (Section.relocation_begin() == Section.relocation_end())
1075       continue;
1076     StringRef secname;
1077     error(Section.getName(secname));
1078     outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
1079     for (const RelocationRef &Reloc : Section.relocations()) {
1080       bool hidden = getHidden(Reloc);
1081       uint64_t address = Reloc.getOffset();
1082       SmallString<32> relocname;
1083       SmallString<32> valuestr;
1084       if (hidden)
1085         continue;
1086       Reloc.getTypeName(relocname);
1087       error(getRelocationValueString(Reloc, valuestr));
1088       outs() << format(Fmt.data(), address) << " " << relocname << " "
1089              << valuestr << "\n";
1090     }
1091     outs() << "\n";
1092   }
1093 }
1094
1095 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
1096   outs() << "Sections:\n"
1097             "Idx Name          Size      Address          Type\n";
1098   unsigned i = 0;
1099   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1100     StringRef Name;
1101     error(Section.getName(Name));
1102     uint64_t Address = Section.getAddress();
1103     uint64_t Size = Section.getSize();
1104     bool Text = Section.isText();
1105     bool Data = Section.isData();
1106     bool BSS = Section.isBSS();
1107     std::string Type = (std::string(Text ? "TEXT " : "") +
1108                         (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1109     outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1110                      Name.str().c_str(), Size, Address, Type.c_str());
1111     ++i;
1112   }
1113 }
1114
1115 void llvm::PrintSectionContents(const ObjectFile *Obj) {
1116   std::error_code EC;
1117   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1118     StringRef Name;
1119     StringRef Contents;
1120     error(Section.getName(Name));
1121     uint64_t BaseAddr = Section.getAddress();
1122     uint64_t Size = Section.getSize();
1123     if (!Size)
1124       continue;
1125
1126     outs() << "Contents of section " << Name << ":\n";
1127     if (Section.isBSS()) {
1128       outs() << format("<skipping contents of bss section at [%04" PRIx64
1129                        ", %04" PRIx64 ")>\n",
1130                        BaseAddr, BaseAddr + Size);
1131       continue;
1132     }
1133
1134     error(Section.getContents(Contents));
1135
1136     // Dump out the content as hex and printable ascii characters.
1137     for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1138       outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1139       // Dump line of hex.
1140       for (std::size_t i = 0; i < 16; ++i) {
1141         if (i != 0 && i % 4 == 0)
1142           outs() << ' ';
1143         if (addr + i < end)
1144           outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1145                  << hexdigit(Contents[addr + i] & 0xF, true);
1146         else
1147           outs() << "  ";
1148       }
1149       // Print ascii.
1150       outs() << "  ";
1151       for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1152         if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1153           outs() << Contents[addr + i];
1154         else
1155           outs() << ".";
1156       }
1157       outs() << "\n";
1158     }
1159   }
1160 }
1161
1162 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
1163   for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1164     ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
1165     StringRef Name;
1166     error(Symbol.getError());
1167     error(coff->getSymbolName(*Symbol, Name));
1168
1169     outs() << "[" << format("%2d", SI) << "]"
1170            << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
1171            << "(fl 0x00)" // Flag bits, which COFF doesn't have.
1172            << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1173            << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1174            << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1175            << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
1176            << Name << "\n";
1177
1178     for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
1179       if (Symbol->isSectionDefinition()) {
1180         const coff_aux_section_definition *asd;
1181         error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd));
1182
1183         int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1184
1185         outs() << "AUX "
1186                << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1187                          , unsigned(asd->Length)
1188                          , unsigned(asd->NumberOfRelocations)
1189                          , unsigned(asd->NumberOfLinenumbers)
1190                          , unsigned(asd->CheckSum))
1191                << format("assoc %d comdat %d\n"
1192                          , unsigned(AuxNumber)
1193                          , unsigned(asd->Selection));
1194       } else if (Symbol->isFileRecord()) {
1195         const char *FileName;
1196         error(coff->getAuxSymbol<char>(SI + 1, FileName));
1197
1198         StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1199                                      coff->getSymbolTableEntrySize());
1200         outs() << "AUX " << Name.rtrim(StringRef("\0", 1))  << '\n';
1201
1202         SI = SI + Symbol->getNumberOfAuxSymbols();
1203         break;
1204       } else {
1205         outs() << "AUX Unknown\n";
1206       }
1207     }
1208   }
1209 }
1210
1211 void llvm::PrintSymbolTable(const ObjectFile *o) {
1212   outs() << "SYMBOL TABLE:\n";
1213
1214   if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1215     PrintCOFFSymbolTable(coff);
1216     return;
1217   }
1218   for (const SymbolRef &Symbol : o->symbols()) {
1219     ErrorOr<uint64_t> AddressOrError = Symbol.getAddress();
1220     error(AddressOrError.getError());
1221     uint64_t Address = *AddressOrError;
1222     SymbolRef::Type Type = Symbol.getType();
1223     uint32_t Flags = Symbol.getFlags();
1224     ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
1225     error(SectionOrErr.getError());
1226     section_iterator Section = *SectionOrErr;
1227     StringRef Name;
1228     if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1229       Section->getName(Name);
1230     } else {
1231       ErrorOr<StringRef> NameOrErr = Symbol.getName();
1232       error(NameOrErr.getError());
1233       Name = *NameOrErr;
1234     }
1235
1236     bool Global = Flags & SymbolRef::SF_Global;
1237     bool Weak = Flags & SymbolRef::SF_Weak;
1238     bool Absolute = Flags & SymbolRef::SF_Absolute;
1239     bool Common = Flags & SymbolRef::SF_Common;
1240     bool Hidden = Flags & SymbolRef::SF_Hidden;
1241
1242     char GlobLoc = ' ';
1243     if (Type != SymbolRef::ST_Unknown)
1244       GlobLoc = Global ? 'g' : 'l';
1245     char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1246                  ? 'd' : ' ';
1247     char FileFunc = ' ';
1248     if (Type == SymbolRef::ST_File)
1249       FileFunc = 'f';
1250     else if (Type == SymbolRef::ST_Function)
1251       FileFunc = 'F';
1252
1253     const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1254                                                    "%08" PRIx64;
1255
1256     outs() << format(Fmt, Address) << " "
1257            << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1258            << (Weak ? 'w' : ' ') // Weak?
1259            << ' ' // Constructor. Not supported yet.
1260            << ' ' // Warning. Not supported yet.
1261            << ' ' // Indirect reference to another symbol.
1262            << Debug // Debugging (d) or dynamic (D) symbol.
1263            << FileFunc // Name of function (F), file (f) or object (O).
1264            << ' ';
1265     if (Absolute) {
1266       outs() << "*ABS*";
1267     } else if (Common) {
1268       outs() << "*COM*";
1269     } else if (Section == o->section_end()) {
1270       outs() << "*UND*";
1271     } else {
1272       if (const MachOObjectFile *MachO =
1273           dyn_cast<const MachOObjectFile>(o)) {
1274         DataRefImpl DR = Section->getRawDataRefImpl();
1275         StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1276         outs() << SegmentName << ",";
1277       }
1278       StringRef SectionName;
1279       error(Section->getName(SectionName));
1280       outs() << SectionName;
1281     }
1282
1283     outs() << '\t';
1284     if (Common || isa<ELFObjectFileBase>(o)) {
1285       uint64_t Val =
1286           Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1287       outs() << format("\t %08" PRIx64 " ", Val);
1288     }
1289
1290     if (Hidden) {
1291       outs() << ".hidden ";
1292     }
1293     outs() << Name
1294            << '\n';
1295   }
1296 }
1297
1298 static void PrintUnwindInfo(const ObjectFile *o) {
1299   outs() << "Unwind info:\n\n";
1300
1301   if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1302     printCOFFUnwindInfo(coff);
1303   } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1304     printMachOUnwindInfo(MachO);
1305   else {
1306     // TODO: Extract DWARF dump tool to objdump.
1307     errs() << "This operation is only currently supported "
1308               "for COFF and MachO object files.\n";
1309     return;
1310   }
1311 }
1312
1313 void llvm::printExportsTrie(const ObjectFile *o) {
1314   outs() << "Exports trie:\n";
1315   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1316     printMachOExportsTrie(MachO);
1317   else {
1318     errs() << "This operation is only currently supported "
1319               "for Mach-O executable files.\n";
1320     return;
1321   }
1322 }
1323
1324 void llvm::printRebaseTable(const ObjectFile *o) {
1325   outs() << "Rebase table:\n";
1326   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1327     printMachORebaseTable(MachO);
1328   else {
1329     errs() << "This operation is only currently supported "
1330               "for Mach-O executable files.\n";
1331     return;
1332   }
1333 }
1334
1335 void llvm::printBindTable(const ObjectFile *o) {
1336   outs() << "Bind table:\n";
1337   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1338     printMachOBindTable(MachO);
1339   else {
1340     errs() << "This operation is only currently supported "
1341               "for Mach-O executable files.\n";
1342     return;
1343   }
1344 }
1345
1346 void llvm::printLazyBindTable(const ObjectFile *o) {
1347   outs() << "Lazy bind table:\n";
1348   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1349     printMachOLazyBindTable(MachO);
1350   else {
1351     errs() << "This operation is only currently supported "
1352               "for Mach-O executable files.\n";
1353     return;
1354   }
1355 }
1356
1357 void llvm::printWeakBindTable(const ObjectFile *o) {
1358   outs() << "Weak bind table:\n";
1359   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1360     printMachOWeakBindTable(MachO);
1361   else {
1362     errs() << "This operation is only currently supported "
1363               "for Mach-O executable files.\n";
1364     return;
1365   }
1366 }
1367
1368 /// Dump the raw contents of the __clangast section so the output can be piped
1369 /// into llvm-bcanalyzer.
1370 void llvm::printRawClangAST(const ObjectFile *Obj) {
1371   if (outs().is_displayed()) {
1372     errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1373               "the clang ast section.\n"
1374               "Please redirect the output to a file or another program such as "
1375               "llvm-bcanalyzer.\n";
1376     return;
1377   }
1378
1379   StringRef ClangASTSectionName("__clangast");
1380   if (isa<COFFObjectFile>(Obj)) {
1381     ClangASTSectionName = "clangast";
1382   }
1383
1384   Optional<object::SectionRef> ClangASTSection;
1385   for (auto Sec : ToolSectionFilter(*Obj)) {
1386     StringRef Name;
1387     Sec.getName(Name);
1388     if (Name == ClangASTSectionName) {
1389       ClangASTSection = Sec;
1390       break;
1391     }
1392   }
1393   if (!ClangASTSection)
1394     return;
1395
1396   StringRef ClangASTContents;
1397   error(ClangASTSection.getValue().getContents(ClangASTContents));
1398   outs().write(ClangASTContents.data(), ClangASTContents.size());
1399 }
1400
1401 static void printFaultMaps(const ObjectFile *Obj) {
1402   const char *FaultMapSectionName = nullptr;
1403
1404   if (isa<ELFObjectFileBase>(Obj)) {
1405     FaultMapSectionName = ".llvm_faultmaps";
1406   } else if (isa<MachOObjectFile>(Obj)) {
1407     FaultMapSectionName = "__llvm_faultmaps";
1408   } else {
1409     errs() << "This operation is only currently supported "
1410               "for ELF and Mach-O executable files.\n";
1411     return;
1412   }
1413
1414   Optional<object::SectionRef> FaultMapSection;
1415
1416   for (auto Sec : ToolSectionFilter(*Obj)) {
1417     StringRef Name;
1418     Sec.getName(Name);
1419     if (Name == FaultMapSectionName) {
1420       FaultMapSection = Sec;
1421       break;
1422     }
1423   }
1424
1425   outs() << "FaultMap table:\n";
1426
1427   if (!FaultMapSection.hasValue()) {
1428     outs() << "<not found>\n";
1429     return;
1430   }
1431
1432   StringRef FaultMapContents;
1433   error(FaultMapSection.getValue().getContents(FaultMapContents));
1434
1435   FaultMapParser FMP(FaultMapContents.bytes_begin(),
1436                      FaultMapContents.bytes_end());
1437
1438   outs() << FMP;
1439 }
1440
1441 static void printPrivateFileHeader(const ObjectFile *o) {
1442   if (o->isELF()) {
1443     printELFFileHeader(o);
1444   } else if (o->isCOFF()) {
1445     printCOFFFileHeader(o);
1446   } else if (o->isMachO()) {
1447     printMachOFileHeader(o);
1448   }
1449 }
1450
1451 static void DumpObject(const ObjectFile *o) {
1452   // Avoid other output when using a raw option.
1453   if (!RawClangAST) {
1454     outs() << '\n';
1455     outs() << o->getFileName()
1456            << ":\tfile format " << o->getFileFormatName() << "\n\n";
1457   }
1458
1459   if (Disassemble)
1460     DisassembleObject(o, Relocations);
1461   if (Relocations && !Disassemble)
1462     PrintRelocations(o);
1463   if (SectionHeaders)
1464     PrintSectionHeaders(o);
1465   if (SectionContents)
1466     PrintSectionContents(o);
1467   if (SymbolTable)
1468     PrintSymbolTable(o);
1469   if (UnwindInfo)
1470     PrintUnwindInfo(o);
1471   if (PrivateHeaders)
1472     printPrivateFileHeader(o);
1473   if (ExportsTrie)
1474     printExportsTrie(o);
1475   if (Rebase)
1476     printRebaseTable(o);
1477   if (Bind)
1478     printBindTable(o);
1479   if (LazyBind)
1480     printLazyBindTable(o);
1481   if (WeakBind)
1482     printWeakBindTable(o);
1483   if (RawClangAST)
1484     printRawClangAST(o);
1485   if (PrintFaultMaps)
1486     printFaultMaps(o);
1487 }
1488
1489 /// @brief Dump each object file in \a a;
1490 static void DumpArchive(const Archive *a) {
1491   for (const Archive::Child &C : a->children()) {
1492     ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1493     if (std::error_code EC = ChildOrErr.getError())
1494       if (EC != object_error::invalid_file_type)
1495         report_error(a->getFileName(), EC);
1496     if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
1497       DumpObject(o);
1498     else
1499       report_error(a->getFileName(), object_error::invalid_file_type);
1500   }
1501 }
1502
1503 /// @brief Open file and figure out how to dump it.
1504 static void DumpInput(StringRef file) {
1505   // If file isn't stdin, check that it exists.
1506   if (file != "-" && !sys::fs::exists(file))
1507     report_error(file, errc::no_such_file_or_directory);
1508
1509   // If we are using the Mach-O specific object file parser, then let it parse
1510   // the file and process the command line options.  So the -arch flags can
1511   // be used to select specific slices, etc.
1512   if (MachOOpt) {
1513     ParseInputMachO(file);
1514     return;
1515   }
1516
1517   // Attempt to open the binary.
1518   ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1519   if (std::error_code EC = BinaryOrErr.getError())
1520     report_error(file, EC);
1521   Binary &Binary = *BinaryOrErr.get().getBinary();
1522
1523   if (Archive *a = dyn_cast<Archive>(&Binary))
1524     DumpArchive(a);
1525   else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
1526     DumpObject(o);
1527   else
1528     report_error(file, object_error::invalid_file_type);
1529 }
1530
1531 int main(int argc, char **argv) {
1532   // Print a stack trace if we signal out.
1533   sys::PrintStackTraceOnErrorSignal();
1534   PrettyStackTraceProgram X(argc, argv);
1535   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
1536
1537   // Initialize targets and assembly printers/parsers.
1538   llvm::InitializeAllTargetInfos();
1539   llvm::InitializeAllTargetMCs();
1540   llvm::InitializeAllAsmParsers();
1541   llvm::InitializeAllDisassemblers();
1542
1543   // Register the target printer for --version.
1544   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1545
1546   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1547   TripleName = Triple::normalize(TripleName);
1548
1549   ToolName = argv[0];
1550
1551   // Defaults to a.out if no filenames specified.
1552   if (InputFilenames.size() == 0)
1553     InputFilenames.push_back("a.out");
1554
1555   if (DisassembleAll)
1556     Disassemble = true;
1557   if (!Disassemble
1558       && !Relocations
1559       && !SectionHeaders
1560       && !SectionContents
1561       && !SymbolTable
1562       && !UnwindInfo
1563       && !PrivateHeaders
1564       && !ExportsTrie
1565       && !Rebase
1566       && !Bind
1567       && !LazyBind
1568       && !WeakBind
1569       && !RawClangAST
1570       && !(UniversalHeaders && MachOOpt)
1571       && !(ArchiveHeaders && MachOOpt)
1572       && !(IndirectSymbols && MachOOpt)
1573       && !(DataInCode && MachOOpt)
1574       && !(LinkOptHints && MachOOpt)
1575       && !(InfoPlist && MachOOpt)
1576       && !(DylibsUsed && MachOOpt)
1577       && !(DylibId && MachOOpt)
1578       && !(ObjcMetaData && MachOOpt)
1579       && !(FilterSections.size() != 0 && MachOOpt)
1580       && !PrintFaultMaps) {
1581     cl::PrintHelpMessage();
1582     return 2;
1583   }
1584
1585   std::for_each(InputFilenames.begin(), InputFilenames.end(),
1586                 DumpInput);
1587
1588   return EXIT_SUCCESS;
1589 }