Add support to llvm-objdump for Mach-O universal files and archives with -macho.
[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/COFF.h"
36 #include "llvm/Object/MachO.h"
37 #include "llvm/Object/ObjectFile.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/FileSystem.h"
42 #include "llvm/Support/Format.h"
43 #include "llvm/Support/GraphWriter.h"
44 #include "llvm/Support/Host.h"
45 #include "llvm/Support/ManagedStatic.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/MemoryObject.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 static cl::opt<bool>
66 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 static cl::opt<bool>
73 Relocations("r", cl::desc("Display the relocation entries in the file"));
74
75 static cl::opt<bool>
76 SectionContents("s", cl::desc("Display the content of each section"));
77
78 static cl::opt<bool>
79 SymbolTable("t", cl::desc("Display the symbol table"));
80
81 static cl::opt<bool>
82 ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
83
84 static cl::opt<bool>
85 Rebase("rebase", cl::desc("Display mach-o rebasing info"));
86
87 static cl::opt<bool>
88 Bind("bind", cl::desc("Display mach-o binding info"));
89
90 static cl::opt<bool>
91 LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
92
93 static cl::opt<bool>
94 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 static cl::opt<bool>
116 SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
117                                            "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 static cl::opt<bool>
137 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 static cl::opt<bool>
144 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 void llvm::DumpBytes(StringRef bytes) {
199   static const char hex_rep[] = "0123456789abcdef";
200   // FIXME: The real way to do this is to figure out the longest instruction
201   //        and align to that size before printing. I'll fix this when I get
202   //        around to outputting relocations.
203   // 15 is the longest x86 instruction
204   // 3 is for the hex rep of a byte + a space.
205   // 1 is for the null terminator.
206   enum { OutputSize = (15 * 3) + 1 };
207   char output[OutputSize];
208
209   assert(bytes.size() <= 15
210     && "DumpBytes only supports instructions of up to 15 bytes");
211   memset(output, ' ', sizeof(output));
212   unsigned index = 0;
213   for (StringRef::iterator i = bytes.begin(),
214                            e = bytes.end(); i != e; ++i) {
215     output[index] = hex_rep[(*i & 0xF0) >> 4];
216     output[index + 1] = hex_rep[*i & 0xF];
217     index += 3;
218   }
219
220   output[sizeof(output) - 1] = 0;
221   outs() << output;
222 }
223
224 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
225   uint64_t a_addr, b_addr;
226   if (error(a.getOffset(a_addr))) return false;
227   if (error(b.getOffset(b_addr))) return false;
228   return a_addr < b_addr;
229 }
230
231 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
232   const Target *TheTarget = getTarget(Obj);
233   // getTarget() will have already issued a diagnostic if necessary, so
234   // just bail here if it failed.
235   if (!TheTarget)
236     return;
237
238   // Package up features to be passed to target/subtarget
239   std::string FeaturesStr;
240   if (MAttrs.size()) {
241     SubtargetFeatures Features;
242     for (unsigned i = 0; i != MAttrs.size(); ++i)
243       Features.AddFeature(MAttrs[i]);
244     FeaturesStr = Features.getString();
245   }
246
247   std::unique_ptr<const MCRegisterInfo> MRI(
248       TheTarget->createMCRegInfo(TripleName));
249   if (!MRI) {
250     errs() << "error: no register info for target " << TripleName << "\n";
251     return;
252   }
253
254   // Set up disassembler.
255   std::unique_ptr<const MCAsmInfo> AsmInfo(
256       TheTarget->createMCAsmInfo(*MRI, TripleName));
257   if (!AsmInfo) {
258     errs() << "error: no assembly info for target " << TripleName << "\n";
259     return;
260   }
261
262   std::unique_ptr<const MCSubtargetInfo> STI(
263       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
264   if (!STI) {
265     errs() << "error: no subtarget info for target " << TripleName << "\n";
266     return;
267   }
268
269   std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
270   if (!MII) {
271     errs() << "error: no instruction info for target " << TripleName << "\n";
272     return;
273   }
274
275   std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
276   MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
277
278   std::unique_ptr<MCDisassembler> DisAsm(
279     TheTarget->createMCDisassembler(*STI, Ctx));
280
281   if (!DisAsm) {
282     errs() << "error: no disassembler for target " << TripleName << "\n";
283     return;
284   }
285
286   std::unique_ptr<const MCInstrAnalysis> MIA(
287       TheTarget->createMCInstrAnalysis(MII.get()));
288
289   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
290   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
291       AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
292   if (!IP) {
293     errs() << "error: no instruction printer for target " << TripleName
294       << '\n';
295     return;
296   }
297
298   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ":  " :
299                                                  "\t\t\t%08" PRIx64 ":  ";
300
301   // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
302   // in RelocSecs contain the relocations for section S.
303   std::error_code EC;
304   std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
305   for (const SectionRef &Section : Obj->sections()) {
306     section_iterator Sec2 = Section.getRelocatedSection();
307     if (Sec2 != Obj->section_end())
308       SectionRelocMap[*Sec2].push_back(Section);
309   }
310
311   for (const SectionRef &Section : Obj->sections()) {
312     if (!Section.isText() || Section.isVirtual())
313       continue;
314
315     uint64_t SectionAddr = Section.getAddress();
316     uint64_t SectSize = Section.getSize();
317     if (!SectSize)
318       continue;
319
320     // Make a list of all the symbols in this section.
321     std::vector<std::pair<uint64_t, StringRef>> Symbols;
322     for (const SymbolRef &Symbol : Obj->symbols()) {
323       if (Section.containsSymbol(Symbol)) {
324         uint64_t Address;
325         if (error(Symbol.getAddress(Address)))
326           break;
327         if (Address == UnknownAddressOrSize)
328           continue;
329         Address -= SectionAddr;
330         if (Address >= SectSize)
331           continue;
332
333         StringRef Name;
334         if (error(Symbol.getName(Name)))
335           break;
336         Symbols.push_back(std::make_pair(Address, Name));
337       }
338     }
339
340     // Sort the symbols by address, just in case they didn't come in that way.
341     array_pod_sort(Symbols.begin(), Symbols.end());
342
343     // Make a list of all the relocations for this section.
344     std::vector<RelocationRef> Rels;
345     if (InlineRelocs) {
346       for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
347         for (const RelocationRef &Reloc : RelocSec.relocations()) {
348           Rels.push_back(Reloc);
349         }
350       }
351     }
352
353     // Sort relocations by address.
354     std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
355
356     StringRef SegmentName = "";
357     if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
358       DataRefImpl DR = Section.getRawDataRefImpl();
359       SegmentName = MachO->getSectionFinalSegmentName(DR);
360     }
361     StringRef name;
362     if (error(Section.getName(name)))
363       break;
364     outs() << "Disassembly of section ";
365     if (!SegmentName.empty())
366       outs() << SegmentName << ",";
367     outs() << name << ':';
368
369     // If the section has no symbols just insert a dummy one and disassemble
370     // the whole section.
371     if (Symbols.empty())
372       Symbols.push_back(std::make_pair(0, name));
373
374
375     SmallString<40> Comments;
376     raw_svector_ostream CommentStream(Comments);
377
378     StringRef BytesStr;
379     if (error(Section.getContents(BytesStr)))
380       break;
381     ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
382                             BytesStr.size());
383
384     uint64_t Size;
385     uint64_t Index;
386
387     std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
388     std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
389     // Disassemble symbol by symbol.
390     for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
391
392       uint64_t Start = Symbols[si].first;
393       // The end is either the section end or the beginning of the next symbol.
394       uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
395       // If this symbol has the same address as the next symbol, then skip it.
396       if (Start == End)
397         continue;
398
399       outs() << '\n' << Symbols[si].second << ":\n";
400
401 #ifndef NDEBUG
402       raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
403 #else
404       raw_ostream &DebugOut = nulls();
405 #endif
406
407       for (Index = Start; Index < End; Index += Size) {
408         MCInst Inst;
409
410         if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
411                                    SectionAddr + Index, DebugOut,
412                                    CommentStream)) {
413           outs() << format("%8" PRIx64 ":", SectionAddr + Index);
414           if (!NoShowRawInsn) {
415             outs() << "\t";
416             DumpBytes(StringRef(
417                 reinterpret_cast<const char *>(Bytes.data()) + Index, Size));
418           }
419           IP->printInst(&Inst, outs(), "");
420           outs() << CommentStream.str();
421           Comments.clear();
422           outs() << "\n";
423         } else {
424           errs() << ToolName << ": warning: invalid instruction encoding\n";
425           if (Size == 0)
426             Size = 1; // skip illegible bytes
427         }
428
429         // Print relocation for instruction.
430         while (rel_cur != rel_end) {
431           bool hidden = false;
432           uint64_t addr;
433           SmallString<16> name;
434           SmallString<32> val;
435
436           // If this relocation is hidden, skip it.
437           if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
438           if (hidden) goto skip_print_rel;
439
440           if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
441           // Stop when rel_cur's address is past the current instruction.
442           if (addr >= Index + Size) break;
443           if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
444           if (error(rel_cur->getValueString(val))) goto skip_print_rel;
445
446           outs() << format(Fmt.data(), SectionAddr + addr) << name
447                  << "\t" << val << "\n";
448
449         skip_print_rel:
450           ++rel_cur;
451         }
452       }
453     }
454   }
455 }
456
457 static void PrintRelocations(const ObjectFile *Obj) {
458   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
459                                                  "%08" PRIx64;
460   // Regular objdump doesn't print relocations in non-relocatable object
461   // files.
462   if (!Obj->isRelocatableObject())
463     return;
464
465   for (const SectionRef &Section : Obj->sections()) {
466     if (Section.relocation_begin() == Section.relocation_end())
467       continue;
468     StringRef secname;
469     if (error(Section.getName(secname)))
470       continue;
471     outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
472     for (const RelocationRef &Reloc : Section.relocations()) {
473       bool hidden;
474       uint64_t address;
475       SmallString<32> relocname;
476       SmallString<32> valuestr;
477       if (error(Reloc.getHidden(hidden)))
478         continue;
479       if (hidden)
480         continue;
481       if (error(Reloc.getTypeName(relocname)))
482         continue;
483       if (error(Reloc.getOffset(address)))
484         continue;
485       if (error(Reloc.getValueString(valuestr)))
486         continue;
487       outs() << format(Fmt.data(), address) << " " << relocname << " "
488              << valuestr << "\n";
489     }
490     outs() << "\n";
491   }
492 }
493
494 static void PrintSectionHeaders(const ObjectFile *Obj) {
495   outs() << "Sections:\n"
496             "Idx Name          Size      Address          Type\n";
497   unsigned i = 0;
498   for (const SectionRef &Section : Obj->sections()) {
499     StringRef Name;
500     if (error(Section.getName(Name)))
501       return;
502     uint64_t Address = Section.getAddress();
503     uint64_t Size = Section.getSize();
504     bool Text = Section.isText();
505     bool Data = Section.isData();
506     bool BSS = Section.isBSS();
507     std::string Type = (std::string(Text ? "TEXT " : "") +
508                         (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
509     outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
510                      Name.str().c_str(), Size, Address, Type.c_str());
511     ++i;
512   }
513 }
514
515 static void PrintSectionContents(const ObjectFile *Obj) {
516   std::error_code EC;
517   for (const SectionRef &Section : Obj->sections()) {
518     StringRef Name;
519     StringRef Contents;
520     if (error(Section.getName(Name)))
521       continue;
522     uint64_t BaseAddr = Section.getAddress();
523     uint64_t Size = Section.getSize();
524     if (!Size)
525       continue;
526
527     outs() << "Contents of section " << Name << ":\n";
528     if (Section.isBSS()) {
529       outs() << format("<skipping contents of bss section at [%04" PRIx64
530                        ", %04" PRIx64 ")>\n",
531                        BaseAddr, BaseAddr + Size);
532       continue;
533     }
534
535     if (error(Section.getContents(Contents)))
536       continue;
537
538     // Dump out the content as hex and printable ascii characters.
539     for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
540       outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
541       // Dump line of hex.
542       for (std::size_t i = 0; i < 16; ++i) {
543         if (i != 0 && i % 4 == 0)
544           outs() << ' ';
545         if (addr + i < end)
546           outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
547                  << hexdigit(Contents[addr + i] & 0xF, true);
548         else
549           outs() << "  ";
550       }
551       // Print ascii.
552       outs() << "  ";
553       for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
554         if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
555           outs() << Contents[addr + i];
556         else
557           outs() << ".";
558       }
559       outs() << "\n";
560     }
561   }
562 }
563
564 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
565   for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
566     ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
567     StringRef Name;
568     if (error(Symbol.getError()))
569       return;
570
571     if (error(coff->getSymbolName(*Symbol, Name)))
572       return;
573
574     outs() << "[" << format("%2d", SI) << "]"
575            << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
576            << "(fl 0x00)" // Flag bits, which COFF doesn't have.
577            << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
578            << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
579            << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
580            << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
581            << Name << "\n";
582
583     for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
584       if (Symbol->isSectionDefinition()) {
585         const coff_aux_section_definition *asd;
586         if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
587           return;
588
589         int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
590
591         outs() << "AUX "
592                << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
593                          , unsigned(asd->Length)
594                          , unsigned(asd->NumberOfRelocations)
595                          , unsigned(asd->NumberOfLinenumbers)
596                          , unsigned(asd->CheckSum))
597                << format("assoc %d comdat %d\n"
598                          , unsigned(AuxNumber)
599                          , unsigned(asd->Selection));
600       } else if (Symbol->isFileRecord()) {
601         const char *FileName;
602         if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
603           return;
604
605         StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
606                                      coff->getSymbolTableEntrySize());
607         outs() << "AUX " << Name.rtrim(StringRef("\0", 1))  << '\n';
608
609         SI = SI + Symbol->getNumberOfAuxSymbols();
610         break;
611       } else {
612         outs() << "AUX Unknown\n";
613       }
614     }
615   }
616 }
617
618 static void PrintSymbolTable(const ObjectFile *o) {
619   outs() << "SYMBOL TABLE:\n";
620
621   if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
622     PrintCOFFSymbolTable(coff);
623     return;
624   }
625   for (const SymbolRef &Symbol : o->symbols()) {
626     StringRef Name;
627     uint64_t Address;
628     SymbolRef::Type Type;
629     uint64_t Size;
630     uint32_t Flags = Symbol.getFlags();
631     section_iterator Section = o->section_end();
632     if (error(Symbol.getName(Name)))
633       continue;
634     if (error(Symbol.getAddress(Address)))
635       continue;
636     if (error(Symbol.getType(Type)))
637       continue;
638     if (error(Symbol.getSize(Size)))
639       continue;
640     if (error(Symbol.getSection(Section)))
641       continue;
642
643     bool Global = Flags & SymbolRef::SF_Global;
644     bool Weak = Flags & SymbolRef::SF_Weak;
645     bool Absolute = Flags & SymbolRef::SF_Absolute;
646
647     if (Address == UnknownAddressOrSize)
648       Address = 0;
649     if (Size == UnknownAddressOrSize)
650       Size = 0;
651     char GlobLoc = ' ';
652     if (Type != SymbolRef::ST_Unknown)
653       GlobLoc = Global ? 'g' : 'l';
654     char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
655                  ? 'd' : ' ';
656     char FileFunc = ' ';
657     if (Type == SymbolRef::ST_File)
658       FileFunc = 'f';
659     else if (Type == SymbolRef::ST_Function)
660       FileFunc = 'F';
661
662     const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
663                                                    "%08" PRIx64;
664
665     outs() << format(Fmt, Address) << " "
666            << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
667            << (Weak ? 'w' : ' ') // Weak?
668            << ' ' // Constructor. Not supported yet.
669            << ' ' // Warning. Not supported yet.
670            << ' ' // Indirect reference to another symbol.
671            << Debug // Debugging (d) or dynamic (D) symbol.
672            << FileFunc // Name of function (F), file (f) or object (O).
673            << ' ';
674     if (Absolute) {
675       outs() << "*ABS*";
676     } else if (Section == o->section_end()) {
677       outs() << "*UND*";
678     } else {
679       if (const MachOObjectFile *MachO =
680           dyn_cast<const MachOObjectFile>(o)) {
681         DataRefImpl DR = Section->getRawDataRefImpl();
682         StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
683         outs() << SegmentName << ",";
684       }
685       StringRef SectionName;
686       if (error(Section->getName(SectionName)))
687         SectionName = "";
688       outs() << SectionName;
689     }
690     outs() << '\t'
691            << format("%08" PRIx64 " ", Size)
692            << Name
693            << '\n';
694   }
695 }
696
697 static void PrintUnwindInfo(const ObjectFile *o) {
698   outs() << "Unwind info:\n\n";
699
700   if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
701     printCOFFUnwindInfo(coff);
702   } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
703     printMachOUnwindInfo(MachO);
704   else {
705     // TODO: Extract DWARF dump tool to objdump.
706     errs() << "This operation is only currently supported "
707               "for COFF and MachO object files.\n";
708     return;
709   }
710 }
711
712 static void printExportsTrie(const ObjectFile *o) {
713   outs() << "Exports trie:\n";
714   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
715     printMachOExportsTrie(MachO);
716   else {
717     errs() << "This operation is only currently supported "
718               "for Mach-O executable files.\n";
719     return;
720   }
721 }
722
723 static void printRebaseTable(const ObjectFile *o) {
724   outs() << "Rebase table:\n";
725   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
726     printMachORebaseTable(MachO);
727   else {
728     errs() << "This operation is only currently supported "
729               "for Mach-O executable files.\n";
730     return;
731   }
732 }
733
734 static void printBindTable(const ObjectFile *o) {
735   outs() << "Bind table:\n";
736   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
737     printMachOBindTable(MachO);
738   else {
739     errs() << "This operation is only currently supported "
740               "for Mach-O executable files.\n";
741     return;
742   }
743 }
744
745 static void printLazyBindTable(const ObjectFile *o) {
746   outs() << "Lazy bind table:\n";
747   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
748     printMachOLazyBindTable(MachO);
749   else {
750     errs() << "This operation is only currently supported "
751               "for Mach-O executable files.\n";
752     return;
753   }
754 }
755
756 static void printWeakBindTable(const ObjectFile *o) {
757   outs() << "Weak bind table:\n";
758   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
759     printMachOWeakBindTable(MachO);
760   else {
761     errs() << "This operation is only currently supported "
762               "for Mach-O executable files.\n";
763     return;
764   }
765 }
766
767 static void printPrivateFileHeader(const ObjectFile *o) {
768   if (o->isELF()) {
769     printELFFileHeader(o);
770   } else if (o->isCOFF()) {
771     printCOFFFileHeader(o);
772   } else if (o->isMachO()) {
773     printMachOFileHeader(o);
774   }
775 }
776
777 static void DumpObject(const ObjectFile *o) {
778   outs() << '\n';
779   outs() << o->getFileName()
780          << ":\tfile format " << o->getFileFormatName() << "\n\n";
781
782   if (Disassemble)
783     DisassembleObject(o, Relocations);
784   if (Relocations && !Disassemble)
785     PrintRelocations(o);
786   if (SectionHeaders)
787     PrintSectionHeaders(o);
788   if (SectionContents)
789     PrintSectionContents(o);
790   if (SymbolTable)
791     PrintSymbolTable(o);
792   if (UnwindInfo)
793     PrintUnwindInfo(o);
794   if (PrivateHeaders)
795     printPrivateFileHeader(o);
796   if (ExportsTrie)
797     printExportsTrie(o);
798   if (Rebase)
799     printRebaseTable(o);
800   if (Bind)
801     printBindTable(o);
802   if (LazyBind)
803     printLazyBindTable(o);
804   if (WeakBind)
805     printWeakBindTable(o);
806 }
807
808 /// @brief Dump each object file in \a a;
809 static void DumpArchive(const Archive *a) {
810   for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
811        ++i) {
812     ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
813     if (std::error_code EC = ChildOrErr.getError()) {
814       // Ignore non-object files.
815       if (EC != object_error::invalid_file_type)
816         errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
817                << ".\n";
818       continue;
819     }
820     if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
821       DumpObject(o);
822     else
823       errs() << ToolName << ": '" << a->getFileName() << "': "
824               << "Unrecognized file type.\n";
825   }
826 }
827
828 /// @brief Open file and figure out how to dump it.
829 static void DumpInput(StringRef file) {
830   // If file isn't stdin, check that it exists.
831   if (file != "-" && !sys::fs::exists(file)) {
832     errs() << ToolName << ": '" << file << "': " << "No such file\n";
833     return;
834   }
835
836   if (MachOOpt && Disassemble) {
837     DisassembleInputMachO(file);
838     return;
839   }
840
841   // Attempt to open the binary.
842   ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
843   if (std::error_code EC = BinaryOrErr.getError()) {
844     errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
845     return;
846   }
847   Binary &Binary = *BinaryOrErr.get().getBinary();
848
849   if (Archive *a = dyn_cast<Archive>(&Binary))
850     DumpArchive(a);
851   else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
852     DumpObject(o);
853   else
854     errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
855 }
856
857 int main(int argc, char **argv) {
858   // Print a stack trace if we signal out.
859   sys::PrintStackTraceOnErrorSignal();
860   PrettyStackTraceProgram X(argc, argv);
861   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
862
863   // Initialize targets and assembly printers/parsers.
864   llvm::InitializeAllTargetInfos();
865   llvm::InitializeAllTargetMCs();
866   llvm::InitializeAllAsmParsers();
867   llvm::InitializeAllDisassemblers();
868
869   // Register the target printer for --version.
870   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
871
872   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
873   TripleName = Triple::normalize(TripleName);
874
875   ToolName = argv[0];
876
877   // Defaults to a.out if no filenames specified.
878   if (InputFilenames.size() == 0)
879     InputFilenames.push_back("a.out");
880
881   if (!Disassemble
882       && !Relocations
883       && !SectionHeaders
884       && !SectionContents
885       && !SymbolTable
886       && !UnwindInfo
887       && !PrivateHeaders
888       && !ExportsTrie
889       && !Rebase
890       && !Bind
891       && !LazyBind
892       && !WeakBind) {
893     cl::PrintHelpMessage();
894     return 2;
895   }
896
897   std::for_each(InputFilenames.begin(), InputFilenames.end(),
898                 DumpInput);
899
900   return ReturnValue;
901 }