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