Move error handling down to getSymbolNMTypeChar.
[oota-llvm.git] / tools / llvm-nm / llvm-nm.cpp
1 //===-- llvm-nm.cpp - Symbol table 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 traditional Unix "nm", that is, it
11 // prints out the names of symbols in a bitcode or object file, along with some
12 // information about each symbol.
13 //
14 // This "nm" supports many of the features of GNU "nm", including its different
15 // output formats.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Object/Archive.h"
23 #include "llvm/Object/COFF.h"
24 #include "llvm/Object/ELFObjectFile.h"
25 #include "llvm/Object/MachO.h"
26 #include "llvm/Object/MachOUniversal.h"
27 #include "llvm/Object/ObjectFile.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/FileSystem.h"
30 #include "llvm/Support/Format.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/PrettyStackTrace.h"
34 #include "llvm/Support/Program.h"
35 #include "llvm/Support/Signals.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Support/system_error.h"
38 #include <algorithm>
39 #include <cctype>
40 #include <cerrno>
41 #include <cstring>
42 #include <vector>
43 using namespace llvm;
44 using namespace object;
45
46 namespace {
47 enum OutputFormatTy { bsd, sysv, posix };
48 cl::opt<OutputFormatTy> OutputFormat(
49     "format", cl::desc("Specify output format"),
50     cl::values(clEnumVal(bsd, "BSD format"), clEnumVal(sysv, "System V format"),
51                clEnumVal(posix, "POSIX.2 format"), clEnumValEnd),
52     cl::init(bsd));
53 cl::alias OutputFormat2("f", cl::desc("Alias for --format"),
54                         cl::aliasopt(OutputFormat));
55
56 cl::list<std::string> InputFilenames(cl::Positional,
57                                      cl::desc("<input bitcode files>"),
58                                      cl::ZeroOrMore);
59
60 cl::opt<bool> UndefinedOnly("undefined-only",
61                             cl::desc("Show only undefined symbols"));
62 cl::alias UndefinedOnly2("u", cl::desc("Alias for --undefined-only"),
63                          cl::aliasopt(UndefinedOnly));
64
65 cl::opt<bool> DynamicSyms("dynamic",
66                           cl::desc("Display the dynamic symbols instead "
67                                    "of normal symbols."));
68 cl::alias DynamicSyms2("D", cl::desc("Alias for --dynamic"),
69                        cl::aliasopt(DynamicSyms));
70
71 cl::opt<bool> DefinedOnly("defined-only",
72                           cl::desc("Show only defined symbols"));
73
74 cl::opt<bool> ExternalOnly("extern-only",
75                            cl::desc("Show only external symbols"));
76 cl::alias ExternalOnly2("g", cl::desc("Alias for --extern-only"),
77                         cl::aliasopt(ExternalOnly));
78
79 cl::opt<bool> BSDFormat("B", cl::desc("Alias for --format=bsd"));
80 cl::opt<bool> POSIXFormat("P", cl::desc("Alias for --format=posix"));
81
82 cl::opt<bool> PrintFileName(
83     "print-file-name",
84     cl::desc("Precede each symbol with the object file it came from"));
85
86 cl::alias PrintFileNameA("A", cl::desc("Alias for --print-file-name"),
87                          cl::aliasopt(PrintFileName));
88 cl::alias PrintFileNameo("o", cl::desc("Alias for --print-file-name"),
89                          cl::aliasopt(PrintFileName));
90
91 cl::opt<bool> DebugSyms("debug-syms",
92                         cl::desc("Show all symbols, even debugger only"));
93 cl::alias DebugSymsa("a", cl::desc("Alias for --debug-syms"),
94                      cl::aliasopt(DebugSyms));
95
96 cl::opt<bool> NumericSort("numeric-sort", cl::desc("Sort symbols by address"));
97 cl::alias NumericSortn("n", cl::desc("Alias for --numeric-sort"),
98                        cl::aliasopt(NumericSort));
99 cl::alias NumericSortv("v", cl::desc("Alias for --numeric-sort"),
100                        cl::aliasopt(NumericSort));
101
102 cl::opt<bool> NoSort("no-sort", cl::desc("Show symbols in order encountered"));
103 cl::alias NoSortp("p", cl::desc("Alias for --no-sort"), cl::aliasopt(NoSort));
104
105 cl::opt<bool> PrintSize("print-size",
106                         cl::desc("Show symbol size instead of address"));
107 cl::alias PrintSizeS("S", cl::desc("Alias for --print-size"),
108                      cl::aliasopt(PrintSize));
109
110 cl::opt<bool> SizeSort("size-sort", cl::desc("Sort symbols by size"));
111
112 cl::opt<bool> WithoutAliases("without-aliases", cl::Hidden,
113                              cl::desc("Exclude aliases from output"));
114
115 cl::opt<bool> ArchiveMap("print-armap", cl::desc("Print the archive map"));
116 cl::alias ArchiveMaps("s", cl::desc("Alias for --print-armap"),
117                       cl::aliasopt(ArchiveMap));
118 bool PrintAddress = true;
119
120 bool MultipleFiles = false;
121
122 bool HadError = false;
123
124 std::string ToolName;
125 }
126
127 static void error(Twine Message, Twine Path = Twine()) {
128   HadError = true;
129   errs() << ToolName << ": " << Path << ": " << Message << ".\n";
130 }
131
132 static bool error(error_code EC, Twine Path = Twine()) {
133   if (EC) {
134     error(EC.message(), Path);
135     return true;
136   }
137   return false;
138 }
139
140 namespace {
141 struct NMSymbol {
142   uint64_t Address;
143   uint64_t Size;
144   char TypeChar;
145   StringRef Name;
146 };
147 }
148
149 static bool compareSymbolAddress(const NMSymbol &A, const NMSymbol &B) {
150   if (A.Address < B.Address)
151     return true;
152   else if (A.Address == B.Address && A.Name < B.Name)
153     return true;
154   else if (A.Address == B.Address && A.Name == B.Name && A.Size < B.Size)
155     return true;
156   else
157     return false;
158 }
159
160 static bool compareSymbolSize(const NMSymbol &A, const NMSymbol &B) {
161   if (A.Size < B.Size)
162     return true;
163   else if (A.Size == B.Size && A.Name < B.Name)
164     return true;
165   else if (A.Size == B.Size && A.Name == B.Name && A.Address < B.Address)
166     return true;
167   else
168     return false;
169 }
170
171 static bool compareSymbolName(const NMSymbol &A, const NMSymbol &B) {
172   if (A.Name < B.Name)
173     return true;
174   else if (A.Name == B.Name && A.Size < B.Size)
175     return true;
176   else if (A.Name == B.Name && A.Size == B.Size && A.Address < B.Address)
177     return true;
178   else
179     return false;
180 }
181
182 static StringRef CurrentFilename;
183 typedef std::vector<NMSymbol> SymbolListT;
184 static SymbolListT SymbolList;
185
186 static void sortAndPrintSymbolList() {
187   if (!NoSort) {
188     if (NumericSort)
189       std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolAddress);
190     else if (SizeSort)
191       std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolSize);
192     else
193       std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolName);
194   }
195
196   if (OutputFormat == posix && MultipleFiles) {
197     outs() << '\n' << CurrentFilename << ":\n";
198   } else if (OutputFormat == bsd && MultipleFiles) {
199     outs() << "\n" << CurrentFilename << ":\n";
200   } else if (OutputFormat == sysv) {
201     outs() << "\n\nSymbols from " << CurrentFilename << ":\n\n"
202            << "Name                  Value   Class        Type"
203            << "         Size   Line  Section\n";
204   }
205
206   for (SymbolListT::iterator I = SymbolList.begin(), E = SymbolList.end();
207        I != E; ++I) {
208     if ((I->TypeChar != 'U') && UndefinedOnly)
209       continue;
210     if ((I->TypeChar == 'U') && DefinedOnly)
211       continue;
212     if (SizeSort && !PrintAddress && I->Size == UnknownAddressOrSize)
213       continue;
214
215     char SymbolAddrStr[10] = "";
216     char SymbolSizeStr[10] = "";
217
218     if (OutputFormat == sysv || I->Address == UnknownAddressOrSize)
219       strcpy(SymbolAddrStr, "        ");
220     if (OutputFormat == sysv)
221       strcpy(SymbolSizeStr, "        ");
222
223     if (I->Address != UnknownAddressOrSize)
224       format("%08" PRIx64, I->Address)
225           .print(SymbolAddrStr, sizeof(SymbolAddrStr));
226     if (I->Size != UnknownAddressOrSize)
227       format("%08" PRIx64, I->Size).print(SymbolSizeStr, sizeof(SymbolSizeStr));
228
229     if (OutputFormat == posix) {
230       outs() << I->Name << " " << I->TypeChar << " " << SymbolAddrStr
231              << SymbolSizeStr << "\n";
232     } else if (OutputFormat == bsd) {
233       if (PrintAddress)
234         outs() << SymbolAddrStr << ' ';
235       if (PrintSize) {
236         outs() << SymbolSizeStr;
237         if (I->Size != UnknownAddressOrSize)
238           outs() << ' ';
239       }
240       outs() << I->TypeChar << " " << I->Name << "\n";
241     } else if (OutputFormat == sysv) {
242       std::string PaddedName(I->Name);
243       while (PaddedName.length() < 20)
244         PaddedName += " ";
245       outs() << PaddedName << "|" << SymbolAddrStr << "|   " << I->TypeChar
246              << "  |                  |" << SymbolSizeStr << "|     |\n";
247     }
248   }
249
250   SymbolList.clear();
251 }
252
253 static char typeCharForSymbol(GlobalValue &GV) {
254   if (GV.isDeclaration())
255     return 'U';
256   if (GV.hasLinkOnceLinkage())
257     return 'C';
258   if (GV.hasCommonLinkage())
259     return 'C';
260   if (GV.hasWeakLinkage())
261     return 'W';
262   if (isa<Function>(GV) && GV.hasInternalLinkage())
263     return 't';
264   if (isa<Function>(GV))
265     return 'T';
266   if (isa<GlobalVariable>(GV) && GV.hasInternalLinkage())
267     return 'd';
268   if (isa<GlobalVariable>(GV))
269     return 'D';
270   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(&GV)) {
271     const GlobalValue *AliasedGV = GA->getAliasedGlobal();
272     if (isa<Function>(AliasedGV))
273       return 'T';
274     if (isa<GlobalVariable>(AliasedGV))
275       return 'D';
276   }
277   return '?';
278 }
279
280 static void dumpSymbolNameForGlobalValue(GlobalValue &GV) {
281   // Private linkage and available_externally linkage don't exist in symtab.
282   if (GV.hasPrivateLinkage() || GV.hasLinkerPrivateLinkage() ||
283       GV.hasLinkerPrivateWeakLinkage() || GV.hasAvailableExternallyLinkage())
284     return;
285   char TypeChar = typeCharForSymbol(GV);
286   if (GV.hasLocalLinkage() && ExternalOnly)
287     return;
288
289   NMSymbol S;
290   S.Address = UnknownAddressOrSize;
291   S.Size = UnknownAddressOrSize;
292   S.TypeChar = TypeChar;
293   S.Name = GV.getName();
294   SymbolList.push_back(S);
295 }
296
297 static void dumpSymbolNamesFromModule(Module *M) {
298   CurrentFilename = M->getModuleIdentifier();
299   std::for_each(M->begin(), M->end(), dumpSymbolNameForGlobalValue);
300   std::for_each(M->global_begin(), M->global_end(),
301                 dumpSymbolNameForGlobalValue);
302   if (!WithoutAliases)
303     std::for_each(M->alias_begin(), M->alias_end(),
304                   dumpSymbolNameForGlobalValue);
305
306   sortAndPrintSymbolList();
307 }
308
309 template <class ELFT>
310 static char getSymbolNMTypeChar(ELFObjectFile<ELFT> &Obj, symbol_iterator I) {
311   typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
312   typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
313
314   DataRefImpl Symb = I->getRawDataRefImpl();
315   const Elf_Sym *ESym = Obj.getSymbol(Symb);
316   const ELFFile<ELFT> &EF = *Obj.getELFFile();
317   const Elf_Shdr *ESec = EF.getSection(ESym);
318
319   char Ret = '?';
320
321   if (ESec) {
322     switch (ESec->sh_type) {
323     case ELF::SHT_PROGBITS:
324     case ELF::SHT_DYNAMIC:
325       switch (ESec->sh_flags) {
326       case(ELF::SHF_ALLOC | ELF::SHF_EXECINSTR) :
327         Ret = 't';
328         break;
329       case(ELF::SHF_TLS | ELF::SHF_ALLOC | ELF::SHF_WRITE) :
330       case(ELF::SHF_ALLOC | ELF::SHF_WRITE) :
331         Ret = 'd';
332         break;
333       case ELF::SHF_ALLOC:
334       case(ELF::SHF_ALLOC | ELF::SHF_MERGE) :
335       case(ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS) :
336         Ret = 'r';
337         break;
338       }
339       break;
340     case ELF::SHT_NOBITS:
341       Ret = 'b';
342     }
343   }
344
345   switch (EF.getSymbolTableIndex(ESym)) {
346   case ELF::SHN_UNDEF:
347     if (Ret == '?')
348       Ret = 'U';
349     break;
350   case ELF::SHN_ABS:
351     Ret = 'a';
352     break;
353   case ELF::SHN_COMMON:
354     Ret = 'c';
355     break;
356   }
357
358   switch (ESym->getBinding()) {
359   case ELF::STB_GLOBAL:
360     Ret = ::toupper(Ret);
361     break;
362   case ELF::STB_WEAK:
363     if (EF.getSymbolTableIndex(ESym) == ELF::SHN_UNDEF)
364       Ret = 'w';
365     else if (ESym->getType() == ELF::STT_OBJECT)
366       Ret = 'V';
367     else
368       Ret = 'W';
369   }
370
371   if (Ret == '?' && ESym->getType() == ELF::STT_SECTION) {
372     StringRef Name;
373     if (error(I->getName(Name)))
374       return '?';
375     return StringSwitch<char>(Name)
376         .StartsWith(".debug", 'N')
377         .StartsWith(".note", 'n')
378         .Default('?');
379   }
380
381   return Ret;
382 }
383
384 static char getSymbolNMTypeChar(COFFObjectFile &Obj, symbol_iterator I) {
385   const coff_symbol *Symb = Obj.getCOFFSymbol(I);
386   StringRef Name;
387   if (error(I->getName(Name)))
388     return '?';
389   char Ret = StringSwitch<char>(Name)
390                  .StartsWith(".debug", 'N')
391                  .StartsWith(".sxdata", 'N')
392                  .Default('?');
393
394   if (Ret != '?')
395     return Ret;
396
397   uint32_t Characteristics = 0;
398   if (Symb->SectionNumber > 0) {
399     section_iterator SecI = Obj.end_sections();
400     if (error(I->getSection(SecI)))
401       return '?';
402     const coff_section *Section = Obj.getCOFFSection(SecI);
403     Characteristics = Section->Characteristics;
404   }
405
406   switch (Symb->SectionNumber) {
407   case COFF::IMAGE_SYM_UNDEFINED:
408     // Check storage classes.
409     if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL) {
410       return 'w';                   // Don't do ::toupper.
411     } else if (Symb->Value != 0)    // Check for common symbols.
412       Ret = 'c';
413     else
414       Ret = 'u';
415     break;
416   case COFF::IMAGE_SYM_ABSOLUTE:
417     Ret = 'a';
418     break;
419   case COFF::IMAGE_SYM_DEBUG:
420     Ret = 'n';
421     break;
422   default:
423     // Check section type.
424     if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
425       Ret = 't';
426     else if (Characteristics & COFF::IMAGE_SCN_MEM_READ &&
427              ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only.
428       Ret = 'r';
429     else if (Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
430       Ret = 'd';
431     else if (Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
432       Ret = 'b';
433     else if (Characteristics & COFF::IMAGE_SCN_LNK_INFO)
434       Ret = 'i';
435
436     // Check for section symbol.
437     else if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC &&
438              Symb->Value == 0)
439       Ret = 's';
440   }
441
442   if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL)
443     Ret = ::toupper(static_cast<unsigned char>(Ret));
444
445   return Ret;
446 }
447
448 static uint8_t getNType(MachOObjectFile &Obj, DataRefImpl Symb) {
449   if (Obj.is64Bit()) {
450     MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb);
451     return STE.n_type;
452   }
453   MachO::nlist STE = Obj.getSymbolTableEntry(Symb);
454   return STE.n_type;
455 }
456
457 static char getSymbolNMTypeChar(MachOObjectFile &Obj, symbol_iterator I) {
458   DataRefImpl Symb = I->getRawDataRefImpl();
459   uint8_t NType = getNType(Obj, Symb);
460
461   char Char;
462   switch (NType & MachO::N_TYPE) {
463   case MachO::N_UNDF:
464     Char = 'u';
465     break;
466   case MachO::N_ABS:
467     Char = 's';
468     break;
469   case MachO::N_SECT: {
470     section_iterator Sec = Obj.end_sections();
471     Obj.getSymbolSection(Symb, Sec);
472     DataRefImpl Ref = Sec->getRawDataRefImpl();
473     StringRef SectionName;
474     Obj.getSectionName(Ref, SectionName);
475     StringRef SegmentName = Obj.getSectionFinalSegmentName(Ref);
476     if (SegmentName == "__TEXT" && SectionName == "__text")
477       Char = 't';
478     else
479       Char = 's';
480   } break;
481   default:
482     Char = '?';
483     break;
484   }
485
486   if (NType & (MachO::N_EXT | MachO::N_PEXT))
487     Char = toupper(static_cast<unsigned char>(Char));
488   return Char;
489 }
490
491 static char getNMTypeChar(ObjectFile *Obj, symbol_iterator I) {
492   if (COFFObjectFile *COFF = dyn_cast<COFFObjectFile>(Obj))
493     return getSymbolNMTypeChar(*COFF, I);
494   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Obj))
495     return getSymbolNMTypeChar(*MachO, I);
496   if (ELF32LEObjectFile *ELF = dyn_cast<ELF32LEObjectFile>(Obj))
497     return getSymbolNMTypeChar(*ELF, I);
498   if (ELF64LEObjectFile *ELF = dyn_cast<ELF64LEObjectFile>(Obj))
499     return getSymbolNMTypeChar(*ELF, I);
500   if (ELF32BEObjectFile *ELF = dyn_cast<ELF32BEObjectFile>(Obj))
501     return getSymbolNMTypeChar(*ELF, I);
502   ELF64BEObjectFile *ELF = cast<ELF64BEObjectFile>(Obj);
503   return getSymbolNMTypeChar(*ELF, I);
504 }
505
506 static void getDynamicSymbolIterators(ObjectFile *Obj, symbol_iterator &Begin,
507                                       symbol_iterator &End) {
508   if (ELF32LEObjectFile *ELF = dyn_cast<ELF32LEObjectFile>(Obj)) {
509     Begin = ELF->begin_dynamic_symbols();
510     End = ELF->end_dynamic_symbols();
511     return;
512   }
513   if (ELF64LEObjectFile *ELF = dyn_cast<ELF64LEObjectFile>(Obj)) {
514     Begin = ELF->begin_dynamic_symbols();
515     End = ELF->end_dynamic_symbols();
516     return;
517   }
518   if (ELF32BEObjectFile *ELF = dyn_cast<ELF32BEObjectFile>(Obj)) {
519     Begin = ELF->begin_dynamic_symbols();
520     End = ELF->end_dynamic_symbols();
521     return;
522   }
523   ELF64BEObjectFile *ELF = cast<ELF64BEObjectFile>(Obj);
524   Begin = ELF->begin_dynamic_symbols();
525   End = ELF->end_dynamic_symbols();
526   return;
527 }
528
529 static void dumpSymbolNamesFromObject(ObjectFile *Obj) {
530   symbol_iterator IBegin = Obj->begin_symbols();
531   symbol_iterator IEnd = Obj->end_symbols();
532   if (DynamicSyms) {
533     if (!Obj->isELF()) {
534       error("File format has no dynamic symbol table", Obj->getFileName());
535       return;
536     }
537     getDynamicSymbolIterators(Obj, IBegin, IEnd);
538   }
539   for (symbol_iterator I = IBegin; I != IEnd; ++I) {
540     uint32_t SymFlags = I->getFlags();
541     if (!DebugSyms && (SymFlags & SymbolRef::SF_FormatSpecific))
542       continue;
543     NMSymbol S;
544     S.Size = UnknownAddressOrSize;
545     S.Address = UnknownAddressOrSize;
546     if (PrintSize || SizeSort) {
547       if (error(I->getSize(S.Size)))
548         break;
549     }
550     if (PrintAddress)
551       if (error(I->getAddress(S.Address)))
552         break;
553     S.TypeChar = getNMTypeChar(Obj, I);
554     if (error(I->getName(S.Name)))
555       break;
556     SymbolList.push_back(S);
557   }
558
559   CurrentFilename = Obj->getFileName();
560   sortAndPrintSymbolList();
561 }
562
563 static void dumpSymbolNamesFromFile(std::string &Filename) {
564   OwningPtr<MemoryBuffer> Buffer;
565   if (error(MemoryBuffer::getFileOrSTDIN(Filename, Buffer), Filename))
566     return;
567
568   sys::fs::file_magic Magic = sys::fs::identify_magic(Buffer->getBuffer());
569
570   LLVMContext &Context = getGlobalContext();
571   if (Magic == sys::fs::file_magic::bitcode) {
572     ErrorOr<Module *> ModuleOrErr = parseBitcodeFile(Buffer.get(), Context);
573     if (error(ModuleOrErr.getError(), Filename)) {
574       return;
575     } else {
576       Module *Result = ModuleOrErr.get();
577       dumpSymbolNamesFromModule(Result);
578       delete Result;
579     }
580     return;
581   }
582
583   ErrorOr<Binary *> BinaryOrErr = createBinary(Buffer.take(), Magic);
584   if (error(BinaryOrErr.getError(), Filename))
585     return;
586   OwningPtr<Binary> Bin(BinaryOrErr.get());
587
588   if (Archive *A = dyn_cast<Archive>(Bin.get())) {
589     if (ArchiveMap) {
590       Archive::symbol_iterator I = A->symbol_begin();
591       Archive::symbol_iterator E = A->symbol_end();
592       if (I != E) {
593         outs() << "Archive map\n";
594         for (; I != E; ++I) {
595           Archive::child_iterator C;
596           StringRef SymName;
597           StringRef FileName;
598           if (error(I->getMember(C)))
599             return;
600           if (error(I->getName(SymName)))
601             return;
602           if (error(C->getName(FileName)))
603             return;
604           outs() << SymName << " in " << FileName << "\n";
605         }
606         outs() << "\n";
607       }
608     }
609
610     for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
611          I != E; ++I) {
612       OwningPtr<Binary> Child;
613       if (I->getAsBinary(Child)) {
614         // Try opening it as a bitcode file.
615         OwningPtr<MemoryBuffer> Buff;
616         if (error(I->getMemoryBuffer(Buff)))
617           return;
618
619         ErrorOr<Module *> ModuleOrErr = parseBitcodeFile(Buff.get(), Context);
620         if (ModuleOrErr) {
621           Module *Result = ModuleOrErr.get();
622           dumpSymbolNamesFromModule(Result);
623           delete Result;
624         }
625         continue;
626       }
627       if (ObjectFile *O = dyn_cast<ObjectFile>(Child.get())) {
628         outs() << O->getFileName() << ":\n";
629         dumpSymbolNamesFromObject(O);
630       }
631     }
632     return;
633   }
634   if (MachOUniversalBinary *UB =
635           dyn_cast<object::MachOUniversalBinary>(Bin.get())) {
636     for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
637                                                E = UB->end_objects();
638          I != E; ++I) {
639       OwningPtr<ObjectFile> Obj;
640       if (!I->getAsObjectFile(Obj)) {
641         outs() << Obj->getFileName() << ":\n";
642         dumpSymbolNamesFromObject(Obj.get());
643       }
644     }
645     return;
646   }
647   if (ObjectFile *O = dyn_cast<ObjectFile>(Bin.get())) {
648     dumpSymbolNamesFromObject(O);
649     return;
650   }
651   error("unrecognizable file type", Filename);
652   return;
653 }
654
655 int main(int argc, char **argv) {
656   // Print a stack trace if we signal out.
657   sys::PrintStackTraceOnErrorSignal();
658   PrettyStackTraceProgram X(argc, argv);
659
660   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
661   cl::ParseCommandLineOptions(argc, argv, "llvm symbol table dumper\n");
662
663   // llvm-nm only reads binary files.
664   if (error(sys::ChangeStdinToBinary()))
665     return 1;
666
667   ToolName = argv[0];
668   if (BSDFormat)
669     OutputFormat = bsd;
670   if (POSIXFormat)
671     OutputFormat = posix;
672
673   // The relative order of these is important. If you pass --size-sort it should
674   // only print out the size. However, if you pass -S --size-sort, it should
675   // print out both the size and address.
676   if (SizeSort && !PrintSize)
677     PrintAddress = false;
678   if (OutputFormat == sysv || SizeSort)
679     PrintSize = true;
680
681   switch (InputFilenames.size()) {
682   case 0:
683     InputFilenames.push_back("-");
684   case 1:
685     break;
686   default:
687     MultipleFiles = true;
688   }
689
690   std::for_each(InputFilenames.begin(), InputFilenames.end(),
691                 dumpSymbolNamesFromFile);
692
693   if (HadError)
694     return 1;
695
696   return 0;
697 }