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