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