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