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