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