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