8d1fa729bd7dc94ab0291dc3ed5119b8046dbd4a
[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       if (ESym->getType() == ELF::STT_OBJECT)
365         Ret = 'v';
366       else
367         Ret = 'w';
368     }
369     else if (ESym->getType() == ELF::STT_OBJECT)
370       Ret = 'V';
371     else
372       Ret = 'W';
373   }
374
375   if (Ret == '?' && ESym->getType() == ELF::STT_SECTION) {
376     StringRef Name;
377     if (error(I->getName(Name)))
378       return '?';
379     return StringSwitch<char>(Name)
380         .StartsWith(".debug", 'N')
381         .StartsWith(".note", 'n')
382         .Default('?');
383   }
384
385   return Ret;
386 }
387
388 static char getSymbolNMTypeChar(COFFObjectFile &Obj, symbol_iterator I) {
389   const coff_symbol *Symb = Obj.getCOFFSymbol(I);
390   StringRef Name;
391   if (error(I->getName(Name)))
392     return '?';
393   char Ret = StringSwitch<char>(Name)
394                  .StartsWith(".debug", 'N')
395                  .StartsWith(".sxdata", 'N')
396                  .Default('?');
397
398   if (Ret != '?')
399     return Ret;
400
401   uint32_t Characteristics = 0;
402   if (Symb->SectionNumber > 0) {
403     section_iterator SecI = Obj.end_sections();
404     if (error(I->getSection(SecI)))
405       return '?';
406     const coff_section *Section = Obj.getCOFFSection(SecI);
407     Characteristics = Section->Characteristics;
408   }
409
410   switch (Symb->SectionNumber) {
411   case COFF::IMAGE_SYM_UNDEFINED:
412     // Check storage classes.
413     if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL) {
414       return 'w';                   // Don't do ::toupper.
415     } else if (Symb->Value != 0)    // Check for common symbols.
416       Ret = 'c';
417     else
418       Ret = 'u';
419     break;
420   case COFF::IMAGE_SYM_ABSOLUTE:
421     Ret = 'a';
422     break;
423   case COFF::IMAGE_SYM_DEBUG:
424     Ret = 'n';
425     break;
426   default:
427     // Check section type.
428     if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
429       Ret = 't';
430     else if (Characteristics & COFF::IMAGE_SCN_MEM_READ &&
431              ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only.
432       Ret = 'r';
433     else if (Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
434       Ret = 'd';
435     else if (Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
436       Ret = 'b';
437     else if (Characteristics & COFF::IMAGE_SCN_LNK_INFO)
438       Ret = 'i';
439
440     // Check for section symbol.
441     else if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC &&
442              Symb->Value == 0)
443       Ret = 's';
444   }
445
446   if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL)
447     Ret = ::toupper(static_cast<unsigned char>(Ret));
448
449   return Ret;
450 }
451
452 static uint8_t getNType(MachOObjectFile &Obj, DataRefImpl Symb) {
453   if (Obj.is64Bit()) {
454     MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb);
455     return STE.n_type;
456   }
457   MachO::nlist STE = Obj.getSymbolTableEntry(Symb);
458   return STE.n_type;
459 }
460
461 static char getSymbolNMTypeChar(MachOObjectFile &Obj, symbol_iterator I) {
462   DataRefImpl Symb = I->getRawDataRefImpl();
463   uint8_t NType = getNType(Obj, Symb);
464
465   char Char;
466   switch (NType & MachO::N_TYPE) {
467   case MachO::N_UNDF:
468     Char = 'u';
469     break;
470   case MachO::N_ABS:
471     Char = 's';
472     break;
473   case MachO::N_SECT: {
474     section_iterator Sec = Obj.end_sections();
475     Obj.getSymbolSection(Symb, Sec);
476     DataRefImpl Ref = Sec->getRawDataRefImpl();
477     StringRef SectionName;
478     Obj.getSectionName(Ref, SectionName);
479     StringRef SegmentName = Obj.getSectionFinalSegmentName(Ref);
480     if (SegmentName == "__TEXT" && SectionName == "__text")
481       Char = 't';
482     else
483       Char = 's';
484   } break;
485   default:
486     Char = '?';
487     break;
488   }
489
490   if (NType & (MachO::N_EXT | MachO::N_PEXT))
491     Char = toupper(static_cast<unsigned char>(Char));
492   return Char;
493 }
494
495 static char getNMTypeChar(ObjectFile *Obj, symbol_iterator I) {
496   if (COFFObjectFile *COFF = dyn_cast<COFFObjectFile>(Obj))
497     return getSymbolNMTypeChar(*COFF, I);
498   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Obj))
499     return getSymbolNMTypeChar(*MachO, I);
500   if (ELF32LEObjectFile *ELF = dyn_cast<ELF32LEObjectFile>(Obj))
501     return getSymbolNMTypeChar(*ELF, I);
502   if (ELF64LEObjectFile *ELF = dyn_cast<ELF64LEObjectFile>(Obj))
503     return getSymbolNMTypeChar(*ELF, I);
504   if (ELF32BEObjectFile *ELF = dyn_cast<ELF32BEObjectFile>(Obj))
505     return getSymbolNMTypeChar(*ELF, I);
506   ELF64BEObjectFile *ELF = cast<ELF64BEObjectFile>(Obj);
507   return getSymbolNMTypeChar(*ELF, I);
508 }
509
510 static void getDynamicSymbolIterators(ObjectFile *Obj, symbol_iterator &Begin,
511                                       symbol_iterator &End) {
512   if (ELF32LEObjectFile *ELF = dyn_cast<ELF32LEObjectFile>(Obj)) {
513     Begin = ELF->begin_dynamic_symbols();
514     End = ELF->end_dynamic_symbols();
515     return;
516   }
517   if (ELF64LEObjectFile *ELF = dyn_cast<ELF64LEObjectFile>(Obj)) {
518     Begin = ELF->begin_dynamic_symbols();
519     End = ELF->end_dynamic_symbols();
520     return;
521   }
522   if (ELF32BEObjectFile *ELF = dyn_cast<ELF32BEObjectFile>(Obj)) {
523     Begin = ELF->begin_dynamic_symbols();
524     End = ELF->end_dynamic_symbols();
525     return;
526   }
527   ELF64BEObjectFile *ELF = cast<ELF64BEObjectFile>(Obj);
528   Begin = ELF->begin_dynamic_symbols();
529   End = ELF->end_dynamic_symbols();
530   return;
531 }
532
533 static void dumpSymbolNamesFromObject(ObjectFile *Obj) {
534   symbol_iterator IBegin = Obj->begin_symbols();
535   symbol_iterator IEnd = Obj->end_symbols();
536   if (DynamicSyms) {
537     if (!Obj->isELF()) {
538       error("File format has no dynamic symbol table", Obj->getFileName());
539       return;
540     }
541     getDynamicSymbolIterators(Obj, IBegin, IEnd);
542   }
543   for (symbol_iterator I = IBegin; I != IEnd; ++I) {
544     uint32_t SymFlags = I->getFlags();
545     if (!DebugSyms && (SymFlags & SymbolRef::SF_FormatSpecific))
546       continue;
547     NMSymbol S;
548     S.Size = UnknownAddressOrSize;
549     S.Address = UnknownAddressOrSize;
550     if (PrintSize || SizeSort) {
551       if (error(I->getSize(S.Size)))
552         break;
553     }
554     if (PrintAddress)
555       if (error(I->getAddress(S.Address)))
556         break;
557     S.TypeChar = getNMTypeChar(Obj, I);
558     if (error(I->getName(S.Name)))
559       break;
560     SymbolList.push_back(S);
561   }
562
563   CurrentFilename = Obj->getFileName();
564   sortAndPrintSymbolList();
565 }
566
567 static void dumpSymbolNamesFromFile(std::string &Filename) {
568   OwningPtr<MemoryBuffer> Buffer;
569   if (error(MemoryBuffer::getFileOrSTDIN(Filename, Buffer), Filename))
570     return;
571
572   sys::fs::file_magic Magic = sys::fs::identify_magic(Buffer->getBuffer());
573
574   LLVMContext &Context = getGlobalContext();
575   if (Magic == sys::fs::file_magic::bitcode) {
576     ErrorOr<Module *> ModuleOrErr = parseBitcodeFile(Buffer.get(), Context);
577     if (error(ModuleOrErr.getError(), Filename)) {
578       return;
579     } else {
580       Module *Result = ModuleOrErr.get();
581       dumpSymbolNamesFromModule(Result);
582       delete Result;
583     }
584     return;
585   }
586
587   ErrorOr<Binary *> BinaryOrErr = createBinary(Buffer.take(), Magic);
588   if (error(BinaryOrErr.getError(), Filename))
589     return;
590   OwningPtr<Binary> Bin(BinaryOrErr.get());
591
592   if (Archive *A = dyn_cast<Archive>(Bin.get())) {
593     if (ArchiveMap) {
594       Archive::symbol_iterator I = A->symbol_begin();
595       Archive::symbol_iterator E = A->symbol_end();
596       if (I != E) {
597         outs() << "Archive map\n";
598         for (; I != E; ++I) {
599           Archive::child_iterator C;
600           StringRef SymName;
601           StringRef FileName;
602           if (error(I->getMember(C)))
603             return;
604           if (error(I->getName(SymName)))
605             return;
606           if (error(C->getName(FileName)))
607             return;
608           outs() << SymName << " in " << FileName << "\n";
609         }
610         outs() << "\n";
611       }
612     }
613
614     for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
615          I != E; ++I) {
616       OwningPtr<Binary> Child;
617       if (I->getAsBinary(Child)) {
618         // Try opening it as a bitcode file.
619         OwningPtr<MemoryBuffer> Buff;
620         if (error(I->getMemoryBuffer(Buff)))
621           return;
622
623         ErrorOr<Module *> ModuleOrErr = parseBitcodeFile(Buff.get(), Context);
624         if (ModuleOrErr) {
625           Module *Result = ModuleOrErr.get();
626           dumpSymbolNamesFromModule(Result);
627           delete Result;
628         }
629         continue;
630       }
631       if (ObjectFile *O = dyn_cast<ObjectFile>(Child.get())) {
632         outs() << O->getFileName() << ":\n";
633         dumpSymbolNamesFromObject(O);
634       }
635     }
636     return;
637   }
638   if (MachOUniversalBinary *UB =
639           dyn_cast<object::MachOUniversalBinary>(Bin.get())) {
640     for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
641                                                E = UB->end_objects();
642          I != E; ++I) {
643       OwningPtr<ObjectFile> Obj;
644       if (!I->getAsObjectFile(Obj)) {
645         outs() << Obj->getFileName() << ":\n";
646         dumpSymbolNamesFromObject(Obj.get());
647       }
648     }
649     return;
650   }
651   if (ObjectFile *O = dyn_cast<ObjectFile>(Bin.get())) {
652     dumpSymbolNamesFromObject(O);
653     return;
654   }
655   error("unrecognizable file type", Filename);
656   return;
657 }
658
659 int main(int argc, char **argv) {
660   // Print a stack trace if we signal out.
661   sys::PrintStackTraceOnErrorSignal();
662   PrettyStackTraceProgram X(argc, argv);
663
664   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
665   cl::ParseCommandLineOptions(argc, argv, "llvm symbol table dumper\n");
666
667   // llvm-nm only reads binary files.
668   if (error(sys::ChangeStdinToBinary()))
669     return 1;
670
671   ToolName = argv[0];
672   if (BSDFormat)
673     OutputFormat = bsd;
674   if (POSIXFormat)
675     OutputFormat = posix;
676
677   // The relative order of these is important. If you pass --size-sort it should
678   // only print out the size. However, if you pass -S --size-sort, it should
679   // print out both the size and address.
680   if (SizeSort && !PrintSize)
681     PrintAddress = false;
682   if (OutputFormat == sysv || SizeSort)
683     PrintSize = true;
684
685   switch (InputFilenames.size()) {
686   case 0:
687     InputFilenames.push_back("-");
688   case 1:
689     break;
690   default:
691     MultipleFiles = true;
692   }
693
694   std::for_each(InputFilenames.begin(), InputFilenames.end(),
695                 dumpSymbolNamesFromFile);
696
697   if (HadError)
698     return 1;
699
700   return 0;
701 }