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