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