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