Object: Add support for bigobj
[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 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
86 static cl::alias
87 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
88
89 cl::opt<std::string>
90 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
91                                     "see -version for available targets"));
92
93 cl::opt<std::string>
94 llvm::MCPU("mcpu",
95      cl::desc("Target a specific cpu type (-mcpu=help for details)"),
96      cl::value_desc("cpu-name"),
97      cl::init(""));
98
99 cl::opt<std::string>
100 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
101                                 "see -version for available targets"));
102
103 static cl::opt<bool>
104 SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
105                                            "for each section."));
106 static cl::alias
107 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
108                     cl::aliasopt(SectionHeaders));
109 static cl::alias
110 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
111                       cl::aliasopt(SectionHeaders));
112
113 cl::list<std::string>
114 llvm::MAttrs("mattr",
115   cl::CommaSeparated,
116   cl::desc("Target specific attributes"),
117   cl::value_desc("a1,+a2,-a3,..."));
118
119 static cl::opt<bool>
120 NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, "
121                                            "do not print the instruction bytes."));
122
123 static cl::opt<bool>
124 UnwindInfo("unwind-info", cl::desc("Display unwind information"));
125
126 static cl::alias
127 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
128                 cl::aliasopt(UnwindInfo));
129
130 static cl::opt<bool>
131 PrivateHeaders("private-headers",
132                cl::desc("Display format specific file headers"));
133
134 static cl::alias
135 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
136                     cl::aliasopt(PrivateHeaders));
137
138 static StringRef ToolName;
139
140 bool llvm::error(std::error_code EC) {
141   if (!EC)
142     return false;
143
144   outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
145   outs().flush();
146   return true;
147 }
148
149 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
150   // Figure out the target triple.
151   llvm::Triple TheTriple("unknown-unknown-unknown");
152   if (TripleName.empty()) {
153     if (Obj) {
154       TheTriple.setArch(Triple::ArchType(Obj->getArch()));
155       // TheTriple defaults to ELF, and COFF doesn't have an environment:
156       // the best we can do here is indicate that it is mach-o.
157       if (Obj->isMachO())
158         TheTriple.setObjectFormat(Triple::MachO);
159
160       if (Obj->isCOFF()) {
161         const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
162         if (COFFObj->getArch() == Triple::thumb)
163           TheTriple.setTriple("thumbv7-windows");
164       }
165     }
166   } else
167     TheTriple.setTriple(Triple::normalize(TripleName));
168
169   // Get the target specific parser.
170   std::string Error;
171   const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
172                                                          Error);
173   if (!TheTarget) {
174     errs() << ToolName << ": " << Error;
175     return nullptr;
176   }
177
178   // Update the triple name and return the found target.
179   TripleName = TheTriple.getTriple();
180   return TheTarget;
181 }
182
183 void llvm::DumpBytes(StringRef bytes) {
184   static const char hex_rep[] = "0123456789abcdef";
185   // FIXME: The real way to do this is to figure out the longest instruction
186   //        and align to that size before printing. I'll fix this when I get
187   //        around to outputting relocations.
188   // 15 is the longest x86 instruction
189   // 3 is for the hex rep of a byte + a space.
190   // 1 is for the null terminator.
191   enum { OutputSize = (15 * 3) + 1 };
192   char output[OutputSize];
193
194   assert(bytes.size() <= 15
195     && "DumpBytes only supports instructions of up to 15 bytes");
196   memset(output, ' ', sizeof(output));
197   unsigned index = 0;
198   for (StringRef::iterator i = bytes.begin(),
199                            e = bytes.end(); i != e; ++i) {
200     output[index] = hex_rep[(*i & 0xF0) >> 4];
201     output[index + 1] = hex_rep[*i & 0xF];
202     index += 3;
203   }
204
205   output[sizeof(output) - 1] = 0;
206   outs() << output;
207 }
208
209 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
210   uint64_t a_addr, b_addr;
211   if (error(a.getOffset(a_addr))) return false;
212   if (error(b.getOffset(b_addr))) return false;
213   return a_addr < b_addr;
214 }
215
216 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
217   const Target *TheTarget = getTarget(Obj);
218   // getTarget() will have already issued a diagnostic if necessary, so
219   // just bail here if it failed.
220   if (!TheTarget)
221     return;
222
223   // Package up features to be passed to target/subtarget
224   std::string FeaturesStr;
225   if (MAttrs.size()) {
226     SubtargetFeatures Features;
227     for (unsigned i = 0; i != MAttrs.size(); ++i)
228       Features.AddFeature(MAttrs[i]);
229     FeaturesStr = Features.getString();
230   }
231
232   std::unique_ptr<const MCRegisterInfo> MRI(
233       TheTarget->createMCRegInfo(TripleName));
234   if (!MRI) {
235     errs() << "error: no register info for target " << TripleName << "\n";
236     return;
237   }
238
239   // Set up disassembler.
240   std::unique_ptr<const MCAsmInfo> AsmInfo(
241       TheTarget->createMCAsmInfo(*MRI, TripleName));
242   if (!AsmInfo) {
243     errs() << "error: no assembly info for target " << TripleName << "\n";
244     return;
245   }
246
247   std::unique_ptr<const MCSubtargetInfo> STI(
248       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
249   if (!STI) {
250     errs() << "error: no subtarget info for target " << TripleName << "\n";
251     return;
252   }
253
254   std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
255   if (!MII) {
256     errs() << "error: no instruction info for target " << TripleName << "\n";
257     return;
258   }
259
260   std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
261   MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
262
263   std::unique_ptr<MCDisassembler> DisAsm(
264     TheTarget->createMCDisassembler(*STI, Ctx));
265
266   if (!DisAsm) {
267     errs() << "error: no disassembler for target " << TripleName << "\n";
268     return;
269   }
270
271   std::unique_ptr<const MCInstrAnalysis> MIA(
272       TheTarget->createMCInstrAnalysis(MII.get()));
273
274   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
275   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
276       AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
277   if (!IP) {
278     errs() << "error: no instruction printer for target " << TripleName
279       << '\n';
280     return;
281   }
282
283   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ":  " :
284                                                  "\t\t\t%08" PRIx64 ":  ";
285
286   // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
287   // in RelocSecs contain the relocations for section S.
288   std::error_code EC;
289   std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
290   for (const SectionRef &Section : Obj->sections()) {
291     section_iterator Sec2 = Section.getRelocatedSection();
292     if (Sec2 != Obj->section_end())
293       SectionRelocMap[*Sec2].push_back(Section);
294   }
295
296   for (const SectionRef &Section : Obj->sections()) {
297     bool Text;
298     if (error(Section.isText(Text)))
299       break;
300     if (!Text)
301       continue;
302
303     uint64_t SectionAddr;
304     if (error(Section.getAddress(SectionAddr)))
305       break;
306
307     uint64_t SectSize;
308     if (error(Section.getSize(SectSize)))
309       break;
310
311     // Make a list of all the symbols in this section.
312     std::vector<std::pair<uint64_t, StringRef>> Symbols;
313     for (const SymbolRef &Symbol : Obj->symbols()) {
314       bool contains;
315       if (!error(Section.containsSymbol(Symbol, contains)) && contains) {
316         uint64_t Address;
317         if (error(Symbol.getAddress(Address)))
318           break;
319         if (Address == UnknownAddressOrSize)
320           continue;
321         Address -= SectionAddr;
322         if (Address >= SectSize)
323           continue;
324
325         StringRef Name;
326         if (error(Symbol.getName(Name)))
327           break;
328         Symbols.push_back(std::make_pair(Address, Name));
329       }
330     }
331
332     // Sort the symbols by address, just in case they didn't come in that way.
333     array_pod_sort(Symbols.begin(), Symbols.end());
334
335     // Make a list of all the relocations for this section.
336     std::vector<RelocationRef> Rels;
337     if (InlineRelocs) {
338       for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
339         for (const RelocationRef &Reloc : RelocSec.relocations()) {
340           Rels.push_back(Reloc);
341         }
342       }
343     }
344
345     // Sort relocations by address.
346     std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
347
348     StringRef SegmentName = "";
349     if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
350       DataRefImpl DR = Section.getRawDataRefImpl();
351       SegmentName = MachO->getSectionFinalSegmentName(DR);
352     }
353     StringRef name;
354     if (error(Section.getName(name)))
355       break;
356     outs() << "Disassembly of section ";
357     if (!SegmentName.empty())
358       outs() << SegmentName << ",";
359     outs() << name << ':';
360
361     // If the section has no symbols just insert a dummy one and disassemble
362     // the whole section.
363     if (Symbols.empty())
364       Symbols.push_back(std::make_pair(0, name));
365
366
367     SmallString<40> Comments;
368     raw_svector_ostream CommentStream(Comments);
369
370     StringRef Bytes;
371     if (error(Section.getContents(Bytes)))
372       break;
373     StringRefMemoryObject memoryObject(Bytes, SectionAddr);
374     uint64_t Size;
375     uint64_t Index;
376
377     std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
378     std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
379     // Disassemble symbol by symbol.
380     for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
381
382       uint64_t Start = Symbols[si].first;
383       // The end is either the section end or the beginning of the next symbol.
384       uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
385       // If this symbol has the same address as the next symbol, then skip it.
386       if (Start == End)
387         continue;
388
389       outs() << '\n' << Symbols[si].second << ":\n";
390
391 #ifndef NDEBUG
392       raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
393 #else
394       raw_ostream &DebugOut = nulls();
395 #endif
396
397       for (Index = Start; Index < End; Index += Size) {
398         MCInst Inst;
399
400         if (DisAsm->getInstruction(Inst, Size, memoryObject,
401                                    SectionAddr + Index,
402                                    DebugOut, CommentStream)) {
403           outs() << format("%8" PRIx64 ":", SectionAddr + Index);
404           if (!NoShowRawInsn) {
405             outs() << "\t";
406             DumpBytes(StringRef(Bytes.data() + Index, Size));
407           }
408           IP->printInst(&Inst, outs(), "");
409           outs() << CommentStream.str();
410           Comments.clear();
411           outs() << "\n";
412         } else {
413           errs() << ToolName << ": warning: invalid instruction encoding\n";
414           if (Size == 0)
415             Size = 1; // skip illegible bytes
416         }
417
418         // Print relocation for instruction.
419         while (rel_cur != rel_end) {
420           bool hidden = false;
421           uint64_t addr;
422           SmallString<16> name;
423           SmallString<32> val;
424
425           // If this relocation is hidden, skip it.
426           if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
427           if (hidden) goto skip_print_rel;
428
429           if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
430           // Stop when rel_cur's address is past the current instruction.
431           if (addr >= Index + Size) break;
432           if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
433           if (error(rel_cur->getValueString(val))) goto skip_print_rel;
434
435           outs() << format(Fmt.data(), SectionAddr + addr) << name
436                  << "\t" << val << "\n";
437
438         skip_print_rel:
439           ++rel_cur;
440         }
441       }
442     }
443   }
444 }
445
446 static void PrintRelocations(const ObjectFile *Obj) {
447   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
448                                                  "%08" PRIx64;
449   // Regular objdump doesn't print relocations in non-relocatable object
450   // files.
451   if (!Obj->isRelocatableObject())
452     return;
453
454   for (const SectionRef &Section : Obj->sections()) {
455     if (Section.relocation_begin() == Section.relocation_end())
456       continue;
457     StringRef secname;
458     if (error(Section.getName(secname)))
459       continue;
460     outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
461     for (const RelocationRef &Reloc : Section.relocations()) {
462       bool hidden;
463       uint64_t address;
464       SmallString<32> relocname;
465       SmallString<32> valuestr;
466       if (error(Reloc.getHidden(hidden)))
467         continue;
468       if (hidden)
469         continue;
470       if (error(Reloc.getTypeName(relocname)))
471         continue;
472       if (error(Reloc.getOffset(address)))
473         continue;
474       if (error(Reloc.getValueString(valuestr)))
475         continue;
476       outs() << format(Fmt.data(), address) << " " << relocname << " "
477              << valuestr << "\n";
478     }
479     outs() << "\n";
480   }
481 }
482
483 static void PrintSectionHeaders(const ObjectFile *Obj) {
484   outs() << "Sections:\n"
485             "Idx Name          Size      Address          Type\n";
486   unsigned i = 0;
487   for (const SectionRef &Section : Obj->sections()) {
488     StringRef Name;
489     if (error(Section.getName(Name)))
490       return;
491     uint64_t Address;
492     if (error(Section.getAddress(Address)))
493       return;
494     uint64_t Size;
495     if (error(Section.getSize(Size)))
496       return;
497     bool Text, Data, BSS;
498     if (error(Section.isText(Text)))
499       return;
500     if (error(Section.isData(Data)))
501       return;
502     if (error(Section.isBSS(BSS)))
503       return;
504     std::string Type = (std::string(Text ? "TEXT " : "") +
505                         (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
506     outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
507                      Name.str().c_str(), Size, Address, Type.c_str());
508     ++i;
509   }
510 }
511
512 static void PrintSectionContents(const ObjectFile *Obj) {
513   std::error_code EC;
514   for (const SectionRef &Section : Obj->sections()) {
515     StringRef Name;
516     StringRef Contents;
517     uint64_t BaseAddr;
518     bool BSS;
519     if (error(Section.getName(Name)))
520       continue;
521     if (error(Section.getAddress(BaseAddr)))
522       continue;
523     if (error(Section.isBSS(BSS)))
524       continue;
525
526     outs() << "Contents of section " << Name << ":\n";
527     if (BSS) {
528       uint64_t Size;
529       if (error(Section.getSize(Size)))
530         continue;
531       outs() << format("<skipping contents of bss section at [%04" PRIx64
532                        ", %04" PRIx64 ")>\n",
533                        BaseAddr, BaseAddr + Size);
534       continue;
535     }
536
537     if (error(Section.getContents(Contents)))
538       continue;
539
540     // Dump out the content as hex and printable ascii characters.
541     for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
542       outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
543       // Dump line of hex.
544       for (std::size_t i = 0; i < 16; ++i) {
545         if (i != 0 && i % 4 == 0)
546           outs() << ' ';
547         if (addr + i < end)
548           outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
549                  << hexdigit(Contents[addr + i] & 0xF, true);
550         else
551           outs() << "  ";
552       }
553       // Print ascii.
554       outs() << "  ";
555       for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
556         if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
557           outs() << Contents[addr + i];
558         else
559           outs() << ".";
560       }
561       outs() << "\n";
562     }
563   }
564 }
565
566 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
567   for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
568     ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
569     StringRef Name;
570     if (error(Symbol.getError()))
571       return;
572
573     if (error(coff->getSymbolName(*Symbol, Name)))
574       return;
575
576     outs() << "[" << format("%2d", SI) << "]"
577            << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
578            << "(fl 0x00)" // Flag bits, which COFF doesn't have.
579            << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
580            << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
581            << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
582            << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
583            << Name << "\n";
584
585     for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
586       if (Symbol->isSectionDefinition()) {
587         const coff_aux_section_definition *asd;
588         if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
589           return;
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(asd->Number)
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 printPrivateFileHeader(const ObjectFile *o) {
724   if (o->isELF()) {
725     printELFFileHeader(o);
726   } else if (o->isCOFF()) {
727     printCOFFFileHeader(o);
728   } else if (o->isMachO()) {
729     printMachOFileHeader(o);
730   }
731 }
732
733 static void DumpObject(const ObjectFile *o) {
734   outs() << '\n';
735   outs() << o->getFileName()
736          << ":\tfile format " << o->getFileFormatName() << "\n\n";
737
738   if (Disassemble)
739     DisassembleObject(o, Relocations);
740   if (Relocations && !Disassemble)
741     PrintRelocations(o);
742   if (SectionHeaders)
743     PrintSectionHeaders(o);
744   if (SectionContents)
745     PrintSectionContents(o);
746   if (SymbolTable)
747     PrintSymbolTable(o);
748   if (UnwindInfo)
749     PrintUnwindInfo(o);
750   if (PrivateHeaders)
751     printPrivateFileHeader(o);
752   if (ExportsTrie)
753     printExportsTrie(o);
754 }
755
756 /// @brief Dump each object file in \a a;
757 static void DumpArchive(const Archive *a) {
758   for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
759        ++i) {
760     ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
761     if (std::error_code EC = ChildOrErr.getError()) {
762       // Ignore non-object files.
763       if (EC != object_error::invalid_file_type)
764         errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
765                << ".\n";
766       continue;
767     }
768     if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
769       DumpObject(o);
770     else
771       errs() << ToolName << ": '" << a->getFileName() << "': "
772               << "Unrecognized file type.\n";
773   }
774 }
775
776 /// @brief Open file and figure out how to dump it.
777 static void DumpInput(StringRef file) {
778   // If file isn't stdin, check that it exists.
779   if (file != "-" && !sys::fs::exists(file)) {
780     errs() << ToolName << ": '" << file << "': " << "No such file\n";
781     return;
782   }
783
784   if (MachOOpt && Disassemble) {
785     DisassembleInputMachO(file);
786     return;
787   }
788
789   // Attempt to open the binary.
790   ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
791   if (std::error_code EC = BinaryOrErr.getError()) {
792     errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
793     return;
794   }
795   Binary &Binary = *BinaryOrErr.get().getBinary();
796
797   if (Archive *a = dyn_cast<Archive>(&Binary))
798     DumpArchive(a);
799   else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
800     DumpObject(o);
801   else
802     errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
803 }
804
805 int main(int argc, char **argv) {
806   // Print a stack trace if we signal out.
807   sys::PrintStackTraceOnErrorSignal();
808   PrettyStackTraceProgram X(argc, argv);
809   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
810
811   // Initialize targets and assembly printers/parsers.
812   llvm::InitializeAllTargetInfos();
813   llvm::InitializeAllTargetMCs();
814   llvm::InitializeAllAsmParsers();
815   llvm::InitializeAllDisassemblers();
816
817   // Register the target printer for --version.
818   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
819
820   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
821   TripleName = Triple::normalize(TripleName);
822
823   ToolName = argv[0];
824
825   // Defaults to a.out if no filenames specified.
826   if (InputFilenames.size() == 0)
827     InputFilenames.push_back("a.out");
828
829   if (!Disassemble
830       && !Relocations
831       && !SectionHeaders
832       && !SectionContents
833       && !SymbolTable
834       && !UnwindInfo
835       && !PrivateHeaders
836       && !ExportsTrie) {
837     cl::PrintHelpMessage();
838     return 2;
839   }
840
841   std::for_each(InputFilenames.begin(), InputFilenames.end(),
842                 DumpInput);
843
844   return 0;
845 }