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