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