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