llvm-objdump: Don't print contents of BSS sections: it makes no sense and crashes...
[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 StringRef
195 getSectionFinalSegmentName(const MachOObjectFileBase *MachO, DataRefImpl DR) {
196   if (const MachOObjectFileLE *O = dyn_cast<MachOObjectFileLE>(MachO))
197     return O->getSectionFinalSegmentName(DR);
198   const MachOObjectFileBE *O = dyn_cast<MachOObjectFileBE>(MachO);
199   return O->getSectionFinalSegmentName(DR);
200 }
201
202 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
203   const Target *TheTarget = getTarget(Obj);
204   // getTarget() will have already issued a diagnostic if necessary, so
205   // just bail here if it failed.
206   if (!TheTarget)
207     return;
208
209   // Package up features to be passed to target/subtarget
210   std::string FeaturesStr;
211   if (MAttrs.size()) {
212     SubtargetFeatures Features;
213     for (unsigned i = 0; i != MAttrs.size(); ++i)
214       Features.AddFeature(MAttrs[i]);
215     FeaturesStr = Features.getString();
216   }
217
218   error_code ec;
219   for (section_iterator i = Obj->begin_sections(),
220                         e = Obj->end_sections();
221                         i != e; i.increment(ec)) {
222     if (error(ec)) break;
223     bool text;
224     if (error(i->isText(text))) break;
225     if (!text) continue;
226
227     uint64_t SectionAddr;
228     if (error(i->getAddress(SectionAddr))) break;
229
230     // Make a list of all the symbols in this section.
231     std::vector<std::pair<uint64_t, StringRef> > Symbols;
232     for (symbol_iterator si = Obj->begin_symbols(),
233                          se = Obj->end_symbols();
234                          si != se; si.increment(ec)) {
235       bool contains;
236       if (!error(i->containsSymbol(*si, contains)) && contains) {
237         uint64_t Address;
238         if (error(si->getAddress(Address))) break;
239         if (Address == UnknownAddressOrSize) continue;
240         Address -= SectionAddr;
241
242         StringRef Name;
243         if (error(si->getName(Name))) break;
244         Symbols.push_back(std::make_pair(Address, Name));
245       }
246     }
247
248     // Sort the symbols by address, just in case they didn't come in that way.
249     array_pod_sort(Symbols.begin(), Symbols.end());
250
251     // Make a list of all the relocations for this section.
252     std::vector<RelocationRef> Rels;
253     if (InlineRelocs) {
254       for (relocation_iterator ri = i->begin_relocations(),
255                                re = i->end_relocations();
256                                ri != re; ri.increment(ec)) {
257         if (error(ec)) break;
258         Rels.push_back(*ri);
259       }
260     }
261
262     // Sort relocations by address.
263     std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
264
265     StringRef SegmentName = "";
266     if (const MachOObjectFileBase *MachO =
267         dyn_cast<const MachOObjectFileBase>(Obj)) {
268       DataRefImpl DR = i->getRawDataRefImpl();
269       SegmentName = getSectionFinalSegmentName(MachO, DR);
270     }
271     StringRef name;
272     if (error(i->getName(name))) break;
273     outs() << "Disassembly of section ";
274     if (!SegmentName.empty())
275       outs() << SegmentName << ",";
276     outs() << name << ':';
277
278     // If the section has no symbols just insert a dummy one and disassemble
279     // the whole section.
280     if (Symbols.empty())
281       Symbols.push_back(std::make_pair(0, name));
282
283     // Set up disassembler.
284     OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
285
286     if (!AsmInfo) {
287       errs() << "error: no assembly info for target " << TripleName << "\n";
288       return;
289     }
290
291     OwningPtr<const MCSubtargetInfo> STI(
292       TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
293
294     if (!STI) {
295       errs() << "error: no subtarget info for target " << TripleName << "\n";
296       return;
297     }
298
299     OwningPtr<const MCDisassembler> DisAsm(
300       TheTarget->createMCDisassembler(*STI));
301     if (!DisAsm) {
302       errs() << "error: no disassembler for target " << TripleName << "\n";
303       return;
304     }
305
306     OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
307     if (!MRI) {
308       errs() << "error: no register info for target " << TripleName << "\n";
309       return;
310     }
311
312     OwningPtr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
313     if (!MII) {
314       errs() << "error: no instruction info for target " << TripleName << "\n";
315       return;
316     }
317
318     int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
319     OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
320                                 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
321     if (!IP) {
322       errs() << "error: no instruction printer for target " << TripleName
323              << '\n';
324       return;
325     }
326
327     StringRef Bytes;
328     if (error(i->getContents(Bytes))) break;
329     StringRefMemoryObject memoryObject(Bytes);
330     uint64_t Size;
331     uint64_t Index;
332     uint64_t SectSize;
333     if (error(i->getSize(SectSize))) break;
334
335     std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
336     std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
337     // Disassemble symbol by symbol.
338     for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
339       uint64_t Start = Symbols[si].first;
340       uint64_t End;
341       // The end is either the size of the section or the beginning of the next
342       // symbol.
343       if (si == se - 1)
344         End = SectSize;
345       // Make sure this symbol takes up space.
346       else if (Symbols[si + 1].first != Start)
347         End = Symbols[si + 1].first - 1;
348       else
349         // This symbol has the same address as the next symbol. Skip it.
350         continue;
351
352       outs() << '\n' << Symbols[si].second << ":\n";
353
354 #ifndef NDEBUG
355         raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
356 #else
357         raw_ostream &DebugOut = nulls();
358 #endif
359
360       for (Index = Start; Index < End; Index += Size) {
361         MCInst Inst;
362
363         if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
364                                    DebugOut, nulls())) {
365           outs() << format("%8" PRIx64 ":", SectionAddr + Index);
366           if (!NoShowRawInsn) {
367             outs() << "\t";
368             DumpBytes(StringRef(Bytes.data() + Index, Size));
369           }
370           IP->printInst(&Inst, outs(), "");
371           outs() << "\n";
372         } else {
373           errs() << ToolName << ": warning: invalid instruction encoding\n";
374           if (Size == 0)
375             Size = 1; // skip illegible bytes
376         }
377
378         // Print relocation for instruction.
379         while (rel_cur != rel_end) {
380           bool hidden = false;
381           uint64_t addr;
382           SmallString<16> name;
383           SmallString<32> val;
384
385           // If this relocation is hidden, skip it.
386           if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
387           if (hidden) goto skip_print_rel;
388
389           if (error(rel_cur->getAddress(addr))) goto skip_print_rel;
390           // Stop when rel_cur's address is past the current instruction.
391           if (addr >= Index + Size) break;
392           if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
393           if (error(rel_cur->getValueString(val))) goto skip_print_rel;
394
395           outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
396                  << "\t" << val << "\n";
397
398         skip_print_rel:
399           ++rel_cur;
400         }
401       }
402     }
403   }
404 }
405
406 static void PrintRelocations(const ObjectFile *o) {
407   error_code ec;
408   for (section_iterator si = o->begin_sections(), se = o->end_sections();
409                                                   si != se; si.increment(ec)){
410     if (error(ec)) return;
411     if (si->begin_relocations() == si->end_relocations())
412       continue;
413     StringRef secname;
414     if (error(si->getName(secname))) continue;
415     outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
416     for (relocation_iterator ri = si->begin_relocations(),
417                              re = si->end_relocations();
418                              ri != re; ri.increment(ec)) {
419       if (error(ec)) return;
420
421       bool hidden;
422       uint64_t address;
423       SmallString<32> relocname;
424       SmallString<32> valuestr;
425       if (error(ri->getHidden(hidden))) continue;
426       if (hidden) continue;
427       if (error(ri->getTypeName(relocname))) continue;
428       if (error(ri->getAddress(address))) continue;
429       if (error(ri->getValueString(valuestr))) continue;
430       outs() << address << " " << relocname << " " << valuestr << "\n";
431     }
432     outs() << "\n";
433   }
434 }
435
436 static void PrintSectionHeaders(const ObjectFile *o) {
437   outs() << "Sections:\n"
438             "Idx Name          Size      Address          Type\n";
439   error_code ec;
440   unsigned i = 0;
441   for (section_iterator si = o->begin_sections(), se = o->end_sections();
442                                                   si != se; si.increment(ec)) {
443     if (error(ec)) return;
444     StringRef Name;
445     if (error(si->getName(Name))) return;
446     uint64_t Address;
447     if (error(si->getAddress(Address))) return;
448     uint64_t Size;
449     if (error(si->getSize(Size))) return;
450     bool Text, Data, BSS;
451     if (error(si->isText(Text))) return;
452     if (error(si->isData(Data))) return;
453     if (error(si->isBSS(BSS))) return;
454     std::string Type = (std::string(Text ? "TEXT " : "") +
455                         (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
456     outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
457                      i, Name.str().c_str(), Size, Address, Type.c_str());
458     ++i;
459   }
460 }
461
462 static void PrintSectionContents(const ObjectFile *o) {
463   error_code ec;
464   for (section_iterator si = o->begin_sections(),
465                         se = o->end_sections();
466                         si != se; si.increment(ec)) {
467     if (error(ec)) return;
468     StringRef Name;
469     StringRef Contents;
470     uint64_t BaseAddr;
471     bool BSS;
472     if (error(si->getName(Name))) continue;
473     if (error(si->getContents(Contents))) continue;
474     if (error(si->getAddress(BaseAddr))) continue;
475     if (error(si->isBSS(BSS))) continue;
476
477     outs() << "Contents of section " << Name << ":\n";
478     if (BSS) {
479       outs() << format("<skipping contents of bss section at [%04" PRIx64
480                        ", %04" PRIx64 ")>\n", BaseAddr,
481                        BaseAddr + Contents.size());
482       continue;
483     }
484
485     // Dump out the content as hex and printable ascii characters.
486     for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
487       outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
488       // Dump line of hex.
489       for (std::size_t i = 0; i < 16; ++i) {
490         if (i != 0 && i % 4 == 0)
491           outs() << ' ';
492         if (addr + i < end)
493           outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
494                  << hexdigit(Contents[addr + i] & 0xF, true);
495         else
496           outs() << "  ";
497       }
498       // Print ascii.
499       outs() << "  ";
500       for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
501         if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
502           outs() << Contents[addr + i];
503         else
504           outs() << ".";
505       }
506       outs() << "\n";
507     }
508   }
509 }
510
511 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
512   const coff_file_header *header;
513   if (error(coff->getHeader(header))) return;
514   int aux_count = 0;
515   const coff_symbol *symbol = 0;
516   for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
517     if (aux_count--) {
518       // Figure out which type of aux this is.
519       if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
520           && symbol->Value == 0) { // Section definition.
521         const coff_aux_section_definition *asd;
522         if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
523           return;
524         outs() << "AUX "
525                << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
526                          , unsigned(asd->Length)
527                          , unsigned(asd->NumberOfRelocations)
528                          , unsigned(asd->NumberOfLinenumbers)
529                          , unsigned(asd->CheckSum))
530                << format("assoc %d comdat %d\n"
531                          , unsigned(asd->Number)
532                          , unsigned(asd->Selection));
533       } else
534         outs() << "AUX Unknown\n";
535     } else {
536       StringRef name;
537       if (error(coff->getSymbol(i, symbol))) return;
538       if (error(coff->getSymbolName(symbol, name))) return;
539       outs() << "[" << format("%2d", i) << "]"
540              << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
541              << "(fl 0x00)" // Flag bits, which COFF doesn't have.
542              << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
543              << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
544              << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
545              << "0x" << format("%08x", unsigned(symbol->Value)) << " "
546              << name << "\n";
547       aux_count = symbol->NumberOfAuxSymbols;
548     }
549   }
550 }
551
552 static void PrintSymbolTable(const ObjectFile *o) {
553   outs() << "SYMBOL TABLE:\n";
554
555   if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
556     PrintCOFFSymbolTable(coff);
557   else {
558     error_code ec;
559     for (symbol_iterator si = o->begin_symbols(),
560                          se = o->end_symbols(); si != se; si.increment(ec)) {
561       if (error(ec)) return;
562       StringRef Name;
563       uint64_t Address;
564       SymbolRef::Type Type;
565       uint64_t Size;
566       uint32_t Flags;
567       section_iterator Section = o->end_sections();
568       if (error(si->getName(Name))) continue;
569       if (error(si->getAddress(Address))) continue;
570       if (error(si->getFlags(Flags))) continue;
571       if (error(si->getType(Type))) continue;
572       if (error(si->getSize(Size))) continue;
573       if (error(si->getSection(Section))) continue;
574
575       bool Global = Flags & SymbolRef::SF_Global;
576       bool Weak = Flags & SymbolRef::SF_Weak;
577       bool Absolute = Flags & SymbolRef::SF_Absolute;
578
579       if (Address == UnknownAddressOrSize)
580         Address = 0;
581       if (Size == UnknownAddressOrSize)
582         Size = 0;
583       char GlobLoc = ' ';
584       if (Type != SymbolRef::ST_Unknown)
585         GlobLoc = Global ? 'g' : 'l';
586       char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
587                    ? 'd' : ' ';
588       char FileFunc = ' ';
589       if (Type == SymbolRef::ST_File)
590         FileFunc = 'f';
591       else if (Type == SymbolRef::ST_Function)
592         FileFunc = 'F';
593
594       const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
595                                                      "%08" PRIx64;
596
597       outs() << format(Fmt, Address) << " "
598              << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
599              << (Weak ? 'w' : ' ') // Weak?
600              << ' ' // Constructor. Not supported yet.
601              << ' ' // Warning. Not supported yet.
602              << ' ' // Indirect reference to another symbol.
603              << Debug // Debugging (d) or dynamic (D) symbol.
604              << FileFunc // Name of function (F), file (f) or object (O).
605              << ' ';
606       if (Absolute)
607         outs() << "*ABS*";
608       else if (Section == o->end_sections())
609         outs() << "*UND*";
610       else {
611         if (const MachOObjectFileBase *MachO =
612             dyn_cast<const MachOObjectFileBase>(o)) {
613           DataRefImpl DR = Section->getRawDataRefImpl();
614           StringRef SegmentName = getSectionFinalSegmentName(MachO, DR);
615           outs() << SegmentName << ",";
616         }
617         StringRef SectionName;
618         if (error(Section->getName(SectionName)))
619           SectionName = "";
620         outs() << SectionName;
621       }
622       outs() << '\t'
623              << format("%08" PRIx64 " ", Size)
624              << Name
625              << '\n';
626     }
627   }
628 }
629
630 static void PrintUnwindInfo(const ObjectFile *o) {
631   outs() << "Unwind info:\n\n";
632
633   if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
634     printCOFFUnwindInfo(coff);
635   } else {
636     // TODO: Extract DWARF dump tool to objdump.
637     errs() << "This operation is only currently supported "
638               "for COFF object files.\n";
639     return;
640   }
641 }
642
643 static void DumpObject(const ObjectFile *o) {
644   outs() << '\n';
645   outs() << o->getFileName()
646          << ":\tfile format " << o->getFileFormatName() << "\n\n";
647
648   if (Disassemble)
649     DisassembleObject(o, Relocations);
650   if (Relocations && !Disassemble)
651     PrintRelocations(o);
652   if (SectionHeaders)
653     PrintSectionHeaders(o);
654   if (SectionContents)
655     PrintSectionContents(o);
656   if (SymbolTable)
657     PrintSymbolTable(o);
658   if (UnwindInfo)
659     PrintUnwindInfo(o);
660   if (PrivateHeaders && o->isELF())
661     printELFFileHeader(o);
662 }
663
664 /// @brief Dump each object file in \a a;
665 static void DumpArchive(const Archive *a) {
666   for (Archive::child_iterator i = a->begin_children(),
667                                e = a->end_children(); i != e; ++i) {
668     OwningPtr<Binary> child;
669     if (error_code ec = i->getAsBinary(child)) {
670       // Ignore non-object files.
671       if (ec != object_error::invalid_file_type)
672         errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
673                << ".\n";
674       continue;
675     }
676     if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
677       DumpObject(o);
678     else
679       errs() << ToolName << ": '" << a->getFileName() << "': "
680               << "Unrecognized file type.\n";
681   }
682 }
683
684 /// @brief Open file and figure out how to dump it.
685 static void DumpInput(StringRef file) {
686   // If file isn't stdin, check that it exists.
687   if (file != "-" && !sys::fs::exists(file)) {
688     errs() << ToolName << ": '" << file << "': " << "No such file\n";
689     return;
690   }
691
692   if (MachOOpt && Disassemble) {
693     DisassembleInputMachO(file);
694     return;
695   }
696
697   // Attempt to open the binary.
698   OwningPtr<Binary> binary;
699   if (error_code ec = createBinary(file, binary)) {
700     errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
701     return;
702   }
703
704   if (Archive *a = dyn_cast<Archive>(binary.get()))
705     DumpArchive(a);
706   else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
707     DumpObject(o);
708   else
709     errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
710 }
711
712 int main(int argc, char **argv) {
713   // Print a stack trace if we signal out.
714   sys::PrintStackTraceOnErrorSignal();
715   PrettyStackTraceProgram X(argc, argv);
716   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
717
718   // Initialize targets and assembly printers/parsers.
719   llvm::InitializeAllTargetInfos();
720   llvm::InitializeAllTargetMCs();
721   llvm::InitializeAllAsmParsers();
722   llvm::InitializeAllDisassemblers();
723
724   // Register the target printer for --version.
725   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
726
727   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
728   TripleName = Triple::normalize(TripleName);
729
730   ToolName = argv[0];
731
732   // Defaults to a.out if no filenames specified.
733   if (InputFilenames.size() == 0)
734     InputFilenames.push_back("a.out");
735
736   if (!Disassemble
737       && !Relocations
738       && !SectionHeaders
739       && !SectionContents
740       && !SymbolTable
741       && !UnwindInfo
742       && !PrivateHeaders) {
743     cl::PrintHelpMessage();
744     return 2;
745   }
746
747   std::for_each(InputFilenames.begin(), InputFilenames.end(),
748                 DumpInput);
749
750   return 0;
751 }