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