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