Don't fetch pointers from a InMemoryStruct.
[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 "MCFunction.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCDisassembler.h"
27 #include "llvm/MC/MCInst.h"
28 #include "llvm/MC/MCInstPrinter.h"
29 #include "llvm/MC/MCInstrInfo.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSubtargetInfo.h"
32 #include "llvm/Object/Archive.h"
33 #include "llvm/Object/COFF.h"
34 #include "llvm/Object/MachO.h"
35 #include "llvm/Object/ObjectFile.h"
36 #include "llvm/Support/Casting.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/FileSystem.h"
40 #include "llvm/Support/Format.h"
41 #include "llvm/Support/GraphWriter.h"
42 #include "llvm/Support/Host.h"
43 #include "llvm/Support/ManagedStatic.h"
44 #include "llvm/Support/MemoryBuffer.h"
45 #include "llvm/Support/MemoryObject.h"
46 #include "llvm/Support/PrettyStackTrace.h"
47 #include "llvm/Support/Signals.h"
48 #include "llvm/Support/SourceMgr.h"
49 #include "llvm/Support/TargetRegistry.h"
50 #include "llvm/Support/TargetSelect.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/Support/system_error.h"
53 #include <algorithm>
54 #include <cctype>
55 #include <cstring>
56 using namespace llvm;
57 using namespace object;
58
59 static cl::list<std::string>
60 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
61
62 static cl::opt<bool>
63 Disassemble("disassemble",
64   cl::desc("Display assembler mnemonics for the machine instructions"));
65 static cl::alias
66 Disassembled("d", cl::desc("Alias for --disassemble"),
67              cl::aliasopt(Disassemble));
68
69 static cl::opt<bool>
70 Relocations("r", cl::desc("Display the relocation entries in the file"));
71
72 static cl::opt<bool>
73 SectionContents("s", cl::desc("Display the content of each section"));
74
75 static cl::opt<bool>
76 SymbolTable("t", cl::desc("Display the symbol table"));
77
78 static cl::opt<bool>
79 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
80 static cl::alias
81 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
82
83 cl::opt<std::string>
84 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
85                                     "see -version for available targets"));
86
87 cl::opt<std::string>
88 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
89                                 "see -version for available targets"));
90
91 static cl::opt<bool>
92 SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
93                                            "for each section."));
94 static cl::alias
95 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
96                     cl::aliasopt(SectionHeaders));
97 static cl::alias
98 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
99                       cl::aliasopt(SectionHeaders));
100
101 static cl::list<std::string>
102 MAttrs("mattr",
103   cl::CommaSeparated,
104   cl::desc("Target specific attributes"),
105   cl::value_desc("a1,+a2,-a3,..."));
106
107 static cl::opt<bool>
108 NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, "
109                                            "do not print the instruction bytes."));
110
111 static cl::opt<bool>
112 UnwindInfo("unwind-info", cl::desc("Display unwind information"));
113
114 static cl::alias
115 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
116                 cl::aliasopt(UnwindInfo));
117
118 static cl::opt<bool>
119 PrivateHeaders("private-headers",
120                cl::desc("Display format specific file headers"));
121
122 static cl::alias
123 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
124                     cl::aliasopt(PrivateHeaders));
125
126 static StringRef ToolName;
127
128 bool llvm::error(error_code ec) {
129   if (!ec) return false;
130
131   outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
132   outs().flush();
133   return true;
134 }
135
136 static const Target *getTarget(const ObjectFile *Obj = NULL) {
137   // Figure out the target triple.
138   llvm::Triple TheTriple("unknown-unknown-unknown");
139   if (TripleName.empty()) {
140     if (Obj)
141       TheTriple.setArch(Triple::ArchType(Obj->getArch()));
142   } else
143     TheTriple.setTriple(Triple::normalize(TripleName));
144
145   // Get the target specific parser.
146   std::string Error;
147   const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
148                                                          Error);
149   if (!TheTarget) {
150     errs() << ToolName << ": " << Error;
151     return 0;
152   }
153
154   // Update the triple name and return the found target.
155   TripleName = TheTriple.getTriple();
156   return TheTarget;
157 }
158
159 void llvm::StringRefMemoryObject::anchor() { }
160
161 void llvm::DumpBytes(StringRef bytes) {
162   static const char hex_rep[] = "0123456789abcdef";
163   // FIXME: The real way to do this is to figure out the longest instruction
164   //        and align to that size before printing. I'll fix this when I get
165   //        around to outputting relocations.
166   // 15 is the longest x86 instruction
167   // 3 is for the hex rep of a byte + a space.
168   // 1 is for the null terminator.
169   enum { OutputSize = (15 * 3) + 1 };
170   char output[OutputSize];
171
172   assert(bytes.size() <= 15
173     && "DumpBytes only supports instructions of up to 15 bytes");
174   memset(output, ' ', sizeof(output));
175   unsigned index = 0;
176   for (StringRef::iterator i = bytes.begin(),
177                            e = bytes.end(); i != e; ++i) {
178     output[index] = hex_rep[(*i & 0xF0) >> 4];
179     output[index + 1] = hex_rep[*i & 0xF];
180     index += 3;
181   }
182
183   output[sizeof(output) - 1] = 0;
184   outs() << output;
185 }
186
187 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
188   uint64_t a_addr, b_addr;
189   if (error(a.getAddress(a_addr))) return false;
190   if (error(b.getAddress(b_addr))) return false;
191   return a_addr < b_addr;
192 }
193
194 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
195   const Target *TheTarget = getTarget(Obj);
196   // getTarget() will have already issued a diagnostic if necessary, so
197   // just bail here if it failed.
198   if (!TheTarget)
199     return;
200
201   // Package up features to be passed to target/subtarget
202   std::string FeaturesStr;
203   if (MAttrs.size()) {
204     SubtargetFeatures Features;
205     for (unsigned i = 0; i != MAttrs.size(); ++i)
206       Features.AddFeature(MAttrs[i]);
207     FeaturesStr = Features.getString();
208   }
209
210   error_code ec;
211   for (section_iterator i = Obj->begin_sections(),
212                         e = Obj->end_sections();
213                         i != e; i.increment(ec)) {
214     if (error(ec)) break;
215     bool text;
216     if (error(i->isText(text))) break;
217     if (!text) continue;
218
219     uint64_t SectionAddr;
220     if (error(i->getAddress(SectionAddr))) break;
221
222     // Make a list of all the symbols in this section.
223     std::vector<std::pair<uint64_t, StringRef> > Symbols;
224     for (symbol_iterator si = Obj->begin_symbols(),
225                          se = Obj->end_symbols();
226                          si != se; si.increment(ec)) {
227       bool contains;
228       if (!error(i->containsSymbol(*si, contains)) && contains) {
229         uint64_t Address;
230         if (error(si->getAddress(Address))) break;
231         if (Address == UnknownAddressOrSize) continue;
232         Address -= SectionAddr;
233
234         StringRef Name;
235         if (error(si->getName(Name))) break;
236         Symbols.push_back(std::make_pair(Address, Name));
237       }
238     }
239
240     // Sort the symbols by address, just in case they didn't come in that way.
241     array_pod_sort(Symbols.begin(), Symbols.end());
242
243     // Make a list of all the relocations for this section.
244     std::vector<RelocationRef> Rels;
245     if (InlineRelocs) {
246       for (relocation_iterator ri = i->begin_relocations(),
247                                re = i->end_relocations();
248                                ri != re; ri.increment(ec)) {
249         if (error(ec)) break;
250         Rels.push_back(*ri);
251       }
252     }
253
254     // Sort relocations by address.
255     std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
256
257     StringRef SegmentName = "";
258     if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
259       DataRefImpl DR = i->getRawDataRefImpl();
260       SegmentName = MachO->getSectionFinalSegmentName(DR);
261     }
262     StringRef name;
263     if (error(i->getName(name))) break;
264     outs() << "Disassembly of section ";
265     if (!SegmentName.empty())
266       outs() << SegmentName << ",";
267     outs() << name << ':';
268
269     // If the section has no symbols just insert a dummy one and disassemble
270     // the whole section.
271     if (Symbols.empty())
272       Symbols.push_back(std::make_pair(0, name));
273
274     // Set up disassembler.
275     OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
276
277     if (!AsmInfo) {
278       errs() << "error: no assembly info for target " << TripleName << "\n";
279       return;
280     }
281
282     OwningPtr<const MCSubtargetInfo> STI(
283       TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
284
285     if (!STI) {
286       errs() << "error: no subtarget info for target " << TripleName << "\n";
287       return;
288     }
289
290     OwningPtr<const MCDisassembler> DisAsm(
291       TheTarget->createMCDisassembler(*STI));
292     if (!DisAsm) {
293       errs() << "error: no disassembler for target " << TripleName << "\n";
294       return;
295     }
296
297     OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
298     if (!MRI) {
299       errs() << "error: no register info for target " << TripleName << "\n";
300       return;
301     }
302
303     OwningPtr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
304     if (!MII) {
305       errs() << "error: no instruction info for target " << TripleName << "\n";
306       return;
307     }
308
309     int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
310     OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
311                                 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
312     if (!IP) {
313       errs() << "error: no instruction printer for target " << TripleName
314              << '\n';
315       return;
316     }
317
318     StringRef Bytes;
319     if (error(i->getContents(Bytes))) break;
320     StringRefMemoryObject memoryObject(Bytes);
321     uint64_t Size;
322     uint64_t Index;
323     uint64_t SectSize;
324     if (error(i->getSize(SectSize))) break;
325
326     std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
327     std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
328     // Disassemble symbol by symbol.
329     for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
330       uint64_t Start = Symbols[si].first;
331       uint64_t End;
332       // The end is either the size of the section or the beginning of the next
333       // symbol.
334       if (si == se - 1)
335         End = SectSize;
336       // Make sure this symbol takes up space.
337       else if (Symbols[si + 1].first != Start)
338         End = Symbols[si + 1].first - 1;
339       else
340         // This symbol has the same address as the next symbol. Skip it.
341         continue;
342
343       outs() << '\n' << Symbols[si].second << ":\n";
344
345 #ifndef NDEBUG
346         raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
347 #else
348         raw_ostream &DebugOut = nulls();
349 #endif
350
351       for (Index = Start; Index < End; Index += Size) {
352         MCInst Inst;
353
354         if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
355                                    DebugOut, nulls())) {
356           outs() << format("%8" PRIx64 ":", SectionAddr + Index);
357           if (!NoShowRawInsn) {
358             outs() << "\t";
359             DumpBytes(StringRef(Bytes.data() + Index, Size));
360           }
361           IP->printInst(&Inst, outs(), "");
362           outs() << "\n";
363         } else {
364           errs() << ToolName << ": warning: invalid instruction encoding\n";
365           if (Size == 0)
366             Size = 1; // skip illegible bytes
367         }
368
369         // Print relocation for instruction.
370         while (rel_cur != rel_end) {
371           bool hidden = false;
372           uint64_t addr;
373           SmallString<16> name;
374           SmallString<32> val;
375
376           // If this relocation is hidden, skip it.
377           if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
378           if (hidden) goto skip_print_rel;
379
380           if (error(rel_cur->getAddress(addr))) goto skip_print_rel;
381           // Stop when rel_cur's address is past the current instruction.
382           if (addr >= Index + Size) break;
383           if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
384           if (error(rel_cur->getValueString(val))) goto skip_print_rel;
385
386           outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
387                  << "\t" << val << "\n";
388
389         skip_print_rel:
390           ++rel_cur;
391         }
392       }
393     }
394   }
395 }
396
397 static void PrintRelocations(const ObjectFile *o) {
398   error_code ec;
399   for (section_iterator si = o->begin_sections(), se = o->end_sections();
400                                                   si != se; si.increment(ec)){
401     if (error(ec)) return;
402     if (si->begin_relocations() == si->end_relocations())
403       continue;
404     StringRef secname;
405     if (error(si->getName(secname))) continue;
406     outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
407     for (relocation_iterator ri = si->begin_relocations(),
408                              re = si->end_relocations();
409                              ri != re; ri.increment(ec)) {
410       if (error(ec)) return;
411
412       bool hidden;
413       uint64_t address;
414       SmallString<32> relocname;
415       SmallString<32> valuestr;
416       if (error(ri->getHidden(hidden))) continue;
417       if (hidden) continue;
418       if (error(ri->getTypeName(relocname))) continue;
419       if (error(ri->getAddress(address))) continue;
420       if (error(ri->getValueString(valuestr))) continue;
421       outs() << address << " " << relocname << " " << valuestr << "\n";
422     }
423     outs() << "\n";
424   }
425 }
426
427 static void PrintSectionHeaders(const ObjectFile *o) {
428   outs() << "Sections:\n"
429             "Idx Name          Size      Address          Type\n";
430   error_code ec;
431   unsigned i = 0;
432   for (section_iterator si = o->begin_sections(), se = o->end_sections();
433                                                   si != se; si.increment(ec)) {
434     if (error(ec)) return;
435     StringRef Name;
436     if (error(si->getName(Name))) return;
437     uint64_t Address;
438     if (error(si->getAddress(Address))) return;
439     uint64_t Size;
440     if (error(si->getSize(Size))) return;
441     bool Text, Data, BSS;
442     if (error(si->isText(Text))) return;
443     if (error(si->isData(Data))) return;
444     if (error(si->isBSS(BSS))) return;
445     std::string Type = (std::string(Text ? "TEXT " : "") +
446                         (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
447     outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
448                      i, Name.str().c_str(), Size, Address, Type.c_str());
449     ++i;
450   }
451 }
452
453 static void PrintSectionContents(const ObjectFile *o) {
454   error_code ec;
455   for (section_iterator si = o->begin_sections(),
456                         se = o->end_sections();
457                         si != se; si.increment(ec)) {
458     if (error(ec)) return;
459     StringRef Name;
460     StringRef Contents;
461     uint64_t BaseAddr;
462     if (error(si->getName(Name))) continue;
463     if (error(si->getContents(Contents))) continue;
464     if (error(si->getAddress(BaseAddr))) continue;
465
466     outs() << "Contents of section " << Name << ":\n";
467
468     // Dump out the content as hex and printable ascii characters.
469     for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
470       outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
471       // Dump line of hex.
472       for (std::size_t i = 0; i < 16; ++i) {
473         if (i != 0 && i % 4 == 0)
474           outs() << ' ';
475         if (addr + i < end)
476           outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
477                  << hexdigit(Contents[addr + i] & 0xF, true);
478         else
479           outs() << "  ";
480       }
481       // Print ascii.
482       outs() << "  ";
483       for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
484         if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
485           outs() << Contents[addr + i];
486         else
487           outs() << ".";
488       }
489       outs() << "\n";
490     }
491   }
492 }
493
494 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
495   const coff_file_header *header;
496   if (error(coff->getHeader(header))) return;
497   int aux_count = 0;
498   const coff_symbol *symbol = 0;
499   for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
500     if (aux_count--) {
501       // Figure out which type of aux this is.
502       if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
503           && symbol->Value == 0) { // Section definition.
504         const coff_aux_section_definition *asd;
505         if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
506           return;
507         outs() << "AUX "
508                << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
509                          , unsigned(asd->Length)
510                          , unsigned(asd->NumberOfRelocations)
511                          , unsigned(asd->NumberOfLinenumbers)
512                          , unsigned(asd->CheckSum))
513                << format("assoc %d comdat %d\n"
514                          , unsigned(asd->Number)
515                          , unsigned(asd->Selection));
516       } else
517         outs() << "AUX Unknown\n";
518     } else {
519       StringRef name;
520       if (error(coff->getSymbol(i, symbol))) return;
521       if (error(coff->getSymbolName(symbol, name))) return;
522       outs() << "[" << format("%2d", i) << "]"
523              << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
524              << "(fl 0x00)" // Flag bits, which COFF doesn't have.
525              << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
526              << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
527              << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
528              << "0x" << format("%08x", unsigned(symbol->Value)) << " "
529              << name << "\n";
530       aux_count = symbol->NumberOfAuxSymbols;
531     }
532   }
533 }
534
535 static void PrintSymbolTable(const ObjectFile *o) {
536   outs() << "SYMBOL TABLE:\n";
537
538   if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
539     PrintCOFFSymbolTable(coff);
540   else {
541     error_code ec;
542     for (symbol_iterator si = o->begin_symbols(),
543                          se = o->end_symbols(); si != se; si.increment(ec)) {
544       if (error(ec)) return;
545       StringRef Name;
546       uint64_t Address;
547       SymbolRef::Type Type;
548       uint64_t Size;
549       uint32_t Flags;
550       section_iterator Section = o->end_sections();
551       if (error(si->getName(Name))) continue;
552       if (error(si->getAddress(Address))) continue;
553       if (error(si->getFlags(Flags))) continue;
554       if (error(si->getType(Type))) continue;
555       if (error(si->getSize(Size))) continue;
556       if (error(si->getSection(Section))) continue;
557
558       bool Global = Flags & SymbolRef::SF_Global;
559       bool Weak = Flags & SymbolRef::SF_Weak;
560       bool Absolute = Flags & SymbolRef::SF_Absolute;
561
562       if (Address == UnknownAddressOrSize)
563         Address = 0;
564       if (Size == UnknownAddressOrSize)
565         Size = 0;
566       char GlobLoc = ' ';
567       if (Type != SymbolRef::ST_Unknown)
568         GlobLoc = Global ? 'g' : 'l';
569       char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
570                    ? 'd' : ' ';
571       char FileFunc = ' ';
572       if (Type == SymbolRef::ST_File)
573         FileFunc = 'f';
574       else if (Type == SymbolRef::ST_Function)
575         FileFunc = 'F';
576
577       const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
578                                                      "%08" PRIx64;
579
580       outs() << format(Fmt, Address) << " "
581              << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
582              << (Weak ? 'w' : ' ') // Weak?
583              << ' ' // Constructor. Not supported yet.
584              << ' ' // Warning. Not supported yet.
585              << ' ' // Indirect reference to another symbol.
586              << Debug // Debugging (d) or dynamic (D) symbol.
587              << FileFunc // Name of function (F), file (f) or object (O).
588              << ' ';
589       if (Absolute)
590         outs() << "*ABS*";
591       else if (Section == o->end_sections())
592         outs() << "*UND*";
593       else {
594         if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(o)) {
595           DataRefImpl DR = Section->getRawDataRefImpl();
596           StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
597           outs() << SegmentName << ",";
598         }
599         StringRef SectionName;
600         if (error(Section->getName(SectionName)))
601           SectionName = "";
602         outs() << SectionName;
603       }
604       outs() << '\t'
605              << format("%08" PRIx64 " ", Size)
606              << Name
607              << '\n';
608     }
609   }
610 }
611
612 static void PrintUnwindInfo(const ObjectFile *o) {
613   outs() << "Unwind info:\n\n";
614
615   if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
616     printCOFFUnwindInfo(coff);
617   } else {
618     // TODO: Extract DWARF dump tool to objdump.
619     errs() << "This operation is only currently supported "
620               "for COFF object files.\n";
621     return;
622   }
623 }
624
625 static void DumpObject(const ObjectFile *o) {
626   outs() << '\n';
627   outs() << o->getFileName()
628          << ":\tfile format " << o->getFileFormatName() << "\n\n";
629
630   if (Disassemble)
631     DisassembleObject(o, Relocations);
632   if (Relocations && !Disassemble)
633     PrintRelocations(o);
634   if (SectionHeaders)
635     PrintSectionHeaders(o);
636   if (SectionContents)
637     PrintSectionContents(o);
638   if (SymbolTable)
639     PrintSymbolTable(o);
640   if (UnwindInfo)
641     PrintUnwindInfo(o);
642   if (PrivateHeaders && o->isELF())
643     printELFFileHeader(o);
644 }
645
646 /// @brief Dump each object file in \a a;
647 static void DumpArchive(const Archive *a) {
648   for (Archive::child_iterator i = a->begin_children(),
649                                e = a->end_children(); i != e; ++i) {
650     OwningPtr<Binary> child;
651     if (error_code ec = i->getAsBinary(child)) {
652       // Ignore non-object files.
653       if (ec != object_error::invalid_file_type)
654         errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
655                << ".\n";
656       continue;
657     }
658     if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
659       DumpObject(o);
660     else
661       errs() << ToolName << ": '" << a->getFileName() << "': "
662               << "Unrecognized file type.\n";
663   }
664 }
665
666 /// @brief Open file and figure out how to dump it.
667 static void DumpInput(StringRef file) {
668   // If file isn't stdin, check that it exists.
669   if (file != "-" && !sys::fs::exists(file)) {
670     errs() << ToolName << ": '" << file << "': " << "No such file\n";
671     return;
672   }
673
674   if (MachOOpt && Disassemble) {
675     DisassembleInputMachO(file);
676     return;
677   }
678
679   // Attempt to open the binary.
680   OwningPtr<Binary> binary;
681   if (error_code ec = createBinary(file, binary)) {
682     errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
683     return;
684   }
685
686   if (Archive *a = dyn_cast<Archive>(binary.get()))
687     DumpArchive(a);
688   else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
689     DumpObject(o);
690   else
691     errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
692 }
693
694 int main(int argc, char **argv) {
695   // Print a stack trace if we signal out.
696   sys::PrintStackTraceOnErrorSignal();
697   PrettyStackTraceProgram X(argc, argv);
698   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
699
700   // Initialize targets and assembly printers/parsers.
701   llvm::InitializeAllTargetInfos();
702   llvm::InitializeAllTargetMCs();
703   llvm::InitializeAllAsmParsers();
704   llvm::InitializeAllDisassemblers();
705
706   // Register the target printer for --version.
707   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
708
709   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
710   TripleName = Triple::normalize(TripleName);
711
712   ToolName = argv[0];
713
714   // Defaults to a.out if no filenames specified.
715   if (InputFilenames.size() == 0)
716     InputFilenames.push_back("a.out");
717
718   if (!Disassemble
719       && !Relocations
720       && !SectionHeaders
721       && !SectionContents
722       && !SymbolTable
723       && !UnwindInfo
724       && !PrivateHeaders) {
725     cl::PrintHelpMessage();
726     return 2;
727   }
728
729   std::for_each(InputFilenames.begin(), InputFilenames.end(),
730                 DumpInput);
731
732   return 0;
733 }