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