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