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