Added the -m option as an alias for -format=darwin to llvm-nm and llvm-size
[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/Function.h"
20 #include "llvm/IR/GlobalAlias.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/Object/Archive.h"
24 #include "llvm/Object/COFF.h"
25 #include "llvm/Object/ELFObjectFile.h"
26 #include "llvm/Object/IRObjectFile.h"
27 #include "llvm/Object/MachO.h"
28 #include "llvm/Object/MachOUniversal.h"
29 #include "llvm/Object/ObjectFile.h"
30 #include "llvm/Support/COFF.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/Format.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/Program.h"
38 #include "llvm/Support/Signals.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <algorithm>
41 #include <cctype>
42 #include <cerrno>
43 #include <cstring>
44 #include <system_error>
45 #include <vector>
46 using namespace llvm;
47 using namespace object;
48
49 namespace {
50 enum OutputFormatTy { bsd, sysv, posix, darwin };
51 cl::opt<OutputFormatTy> OutputFormat(
52     "format", cl::desc("Specify output format"),
53     cl::values(clEnumVal(bsd, "BSD format"), clEnumVal(sysv, "System V format"),
54                clEnumVal(posix, "POSIX.2 format"),
55                clEnumVal(darwin, "Darwin -m 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, cl::desc("<input files>"),
61                                      cl::ZeroOrMore);
62
63 cl::opt<bool> UndefinedOnly("undefined-only",
64                             cl::desc("Show only undefined symbols"));
65 cl::alias UndefinedOnly2("u", cl::desc("Alias for --undefined-only"),
66                          cl::aliasopt(UndefinedOnly));
67
68 cl::opt<bool> DynamicSyms("dynamic",
69                           cl::desc("Display the dynamic symbols instead "
70                                    "of normal symbols."));
71 cl::alias DynamicSyms2("D", cl::desc("Alias for --dynamic"),
72                        cl::aliasopt(DynamicSyms));
73
74 cl::opt<bool> DefinedOnly("defined-only",
75                           cl::desc("Show only defined symbols"));
76
77 cl::opt<bool> ExternalOnly("extern-only",
78                            cl::desc("Show only external symbols"));
79 cl::alias ExternalOnly2("g", cl::desc("Alias for --extern-only"),
80                         cl::aliasopt(ExternalOnly));
81
82 cl::opt<bool> BSDFormat("B", cl::desc("Alias for --format=bsd"));
83 cl::opt<bool> POSIXFormat("P", cl::desc("Alias for --format=posix"));
84 cl::opt<bool> DarwinFormat("m", cl::desc("Alias for --format=darwin"));
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(std::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   DataRefImpl Symb;
151 };
152 }
153
154 static bool compareSymbolAddress(const NMSymbol &A, const NMSymbol &B) {
155   if (A.Address < B.Address)
156     return true;
157   else if (A.Address == B.Address && A.Name < B.Name)
158     return true;
159   else if (A.Address == B.Address && A.Name == B.Name && A.Size < B.Size)
160     return true;
161   else
162     return false;
163 }
164
165 static bool compareSymbolSize(const NMSymbol &A, const NMSymbol &B) {
166   if (A.Size < B.Size)
167     return true;
168   else if (A.Size == B.Size && A.Name < B.Name)
169     return true;
170   else if (A.Size == B.Size && A.Name == B.Name && A.Address < B.Address)
171     return true;
172   else
173     return false;
174 }
175
176 static bool compareSymbolName(const NMSymbol &A, const NMSymbol &B) {
177   if (A.Name < B.Name)
178     return true;
179   else if (A.Name == B.Name && A.Size < B.Size)
180     return true;
181   else if (A.Name == B.Name && A.Size == B.Size && A.Address < B.Address)
182     return true;
183   else
184     return false;
185 }
186
187 static char isSymbolList64Bit(SymbolicFile *Obj) {
188   if (isa<IRObjectFile>(Obj))
189     return false;
190   else if (isa<COFFObjectFile>(Obj))
191     return false;
192   else if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Obj))
193     return MachO->is64Bit();
194   else if (isa<ELF32LEObjectFile>(Obj))
195     return false;
196   else if (isa<ELF64LEObjectFile>(Obj))
197     return true;
198   else if (isa<ELF32BEObjectFile>(Obj))
199     return false;
200   else if(isa<ELF64BEObjectFile>(Obj))
201     return true;
202   else
203     return false;
204 }
205
206 static StringRef CurrentFilename;
207 typedef std::vector<NMSymbol> SymbolListT;
208 static SymbolListT SymbolList;
209
210 // darwinPrintSymbol() is used to print a symbol from a Mach-O file when the
211 // the OutputFormat is darwin.  It produces the same output as darwin's nm(1) -m
212 // output.
213 static void darwinPrintSymbol(MachOObjectFile *MachO, SymbolListT::iterator I,
214                               char *SymbolAddrStr, const char *printBlanks) {
215   MachO::mach_header H;
216   MachO::mach_header_64 H_64;
217   uint32_t Filetype, Flags;
218   MachO::nlist_64 STE_64;
219   MachO::nlist STE;
220   uint8_t NType;
221   uint16_t NDesc;
222   uint64_t NValue;
223   if (MachO->is64Bit()) {
224     H_64 = MachO->MachOObjectFile::getHeader64();
225     Filetype = H_64.filetype;
226     Flags = H_64.flags;
227     STE_64 = MachO->getSymbol64TableEntry(I->Symb);
228     NType = STE_64.n_type;
229     NDesc = STE_64.n_desc;
230     NValue = STE_64.n_value;
231   } else {
232     H = MachO->MachOObjectFile::getHeader();
233     Filetype = H.filetype;
234     Flags = H.flags;
235     STE = MachO->getSymbolTableEntry(I->Symb);
236     NType = STE.n_type;
237     NDesc = STE.n_desc;
238     NValue = STE.n_value;
239   }
240
241   if (PrintAddress) {
242     if ((NType & MachO::N_TYPE) == MachO::N_INDR)
243       strcpy(SymbolAddrStr, printBlanks);
244     outs() << SymbolAddrStr << ' ';
245   }
246
247   switch (NType & MachO::N_TYPE) {
248   case MachO::N_UNDF:
249     if (NValue != 0) {
250       outs() << "(common) ";
251       if (MachO::GET_COMM_ALIGN(NDesc) != 0)
252         outs() << "(alignment 2^" <<
253                    (int)MachO::GET_COMM_ALIGN(NDesc) << ") ";
254     } else {
255       if ((NType & MachO::N_TYPE) == MachO::N_PBUD)
256         outs() << "(prebound ";
257       else
258         outs() << "(";
259       if ((NDesc & MachO::REFERENCE_TYPE) ==
260           MachO::REFERENCE_FLAG_UNDEFINED_LAZY)
261         outs() << "undefined [lazy bound]) ";
262       else if ((NDesc & MachO::REFERENCE_TYPE) ==
263                MachO::REFERENCE_FLAG_UNDEFINED_LAZY)
264         outs() << "undefined [private lazy bound]) ";
265       else if ((NDesc & MachO::REFERENCE_TYPE) ==
266                MachO::REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY)
267         outs() << "undefined [private]) ";
268       else
269         outs() << "undefined) ";
270     }
271     break;
272   case MachO::N_ABS:
273     outs() << "(absolute) ";
274     break;
275   case MachO::N_INDR:
276     outs() << "(indirect) ";
277     break;
278   case MachO::N_SECT: {
279     section_iterator Sec = MachO->section_end();
280     MachO->getSymbolSection(I->Symb, Sec);
281     DataRefImpl Ref = Sec->getRawDataRefImpl();
282     StringRef SectionName;
283     MachO->getSectionName(Ref, SectionName);
284     StringRef SegmentName = MachO->getSectionFinalSegmentName(Ref);
285     outs() << "(" << SegmentName << "," << SectionName << ") ";
286     break;
287   }
288   default:
289     outs() << "(?) ";
290     break;
291   }
292
293   if (NType & MachO::N_EXT) {
294     if (NDesc & MachO::REFERENCED_DYNAMICALLY)
295       outs() << "[referenced dynamically] ";
296     if (NType & MachO::N_PEXT) {
297       if ((NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF)
298         outs() <<  "weak private external ";
299       else
300         outs() <<  "private external ";
301     } else {
302       if ((NDesc & MachO::N_WEAK_REF) == MachO::N_WEAK_REF ||
303           (NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF){
304         if ((NDesc & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF)) ==
305             (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
306           outs() << "weak external automatically hidden ";
307         else
308           outs() << "weak external ";
309       }
310       else
311         outs() << "external ";
312     }
313   } else {
314     if (NType & MachO::N_PEXT)
315       outs() << "non-external (was a private external) ";
316     else
317       outs() << "non-external ";
318   }
319
320   if (Filetype == MachO::MH_OBJECT &&
321       (NDesc & MachO::N_NO_DEAD_STRIP) == MachO::N_NO_DEAD_STRIP)
322     outs() << "[no dead strip] ";
323
324   if (Filetype == MachO::MH_OBJECT &&
325       ((NType & MachO::N_TYPE) != MachO::N_UNDF) &&
326       (NDesc & MachO::N_SYMBOL_RESOLVER) == MachO::N_SYMBOL_RESOLVER)
327     outs() << "[symbol resolver] ";
328
329   if (Filetype == MachO::MH_OBJECT &&
330       ((NType & MachO::N_TYPE) != MachO::N_UNDF) &&
331       (NDesc & MachO::N_ALT_ENTRY) == MachO::N_ALT_ENTRY)
332     outs() << "[alt entry] ";
333
334   if ((NDesc & MachO::N_ARM_THUMB_DEF) == MachO::N_ARM_THUMB_DEF)
335     outs() << "[Thumb] ";
336
337   if ((NType & MachO::N_TYPE) == MachO::N_INDR) {
338     outs() << I->Name << " (for ";
339     StringRef IndirectName;
340     if (MachO->getIndirectName(I->Symb, IndirectName))
341       outs() << "?)";
342     else
343       outs() << IndirectName << ")";
344   }
345   else
346     outs() << I->Name;
347
348   if ((Flags & MachO::MH_TWOLEVEL) == MachO::MH_TWOLEVEL &&
349       (((NType & MachO::N_TYPE) == MachO::N_UNDF &&
350         NValue == 0) ||
351        (NType & MachO::N_TYPE) == MachO::N_PBUD)) {
352     uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(NDesc);
353     if (LibraryOrdinal != 0) {
354       if (LibraryOrdinal == MachO::EXECUTABLE_ORDINAL)
355         outs() << " (from executable)";
356       else if (LibraryOrdinal == MachO::DYNAMIC_LOOKUP_ORDINAL)
357         outs() << " (dynamically looked up)";
358       else {
359         StringRef LibraryName;
360         if (MachO->getLibraryShortNameByIndex(LibraryOrdinal - 1,
361                                               LibraryName))
362           outs() << " (from bad library ordinal " <<
363                  LibraryOrdinal << ")";
364         else
365           outs() << " (from " << LibraryName << ")";
366       }
367     }
368   }
369
370   outs() << "\n";
371 }
372
373 static void sortAndPrintSymbolList(SymbolicFile *Obj) {
374   if (!NoSort) {
375     if (NumericSort)
376       std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolAddress);
377     else if (SizeSort)
378       std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolSize);
379     else
380       std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolName);
381   }
382
383   if (OutputFormat == posix && MultipleFiles) {
384     outs() << '\n' << CurrentFilename << ":\n";
385   } else if (OutputFormat == bsd && MultipleFiles) {
386     outs() << "\n" << CurrentFilename << ":\n";
387   } else if (OutputFormat == sysv) {
388     outs() << "\n\nSymbols from " << CurrentFilename << ":\n\n"
389            << "Name                  Value   Class        Type"
390            << "         Size   Line  Section\n";
391   }
392
393   const char *printBlanks, *printFormat;
394   if (isSymbolList64Bit(Obj)) {
395     printBlanks = "                ";
396     printFormat = "%016" PRIx64;
397   } else {
398     printBlanks = "        ";
399     printFormat = "%08" PRIx64;
400   }
401
402   for (SymbolListT::iterator I = SymbolList.begin(), E = SymbolList.end();
403        I != E; ++I) {
404     if ((I->TypeChar != 'U') && UndefinedOnly)
405       continue;
406     if ((I->TypeChar == 'U') && DefinedOnly)
407       continue;
408     if (SizeSort && !PrintAddress && I->Size == UnknownAddressOrSize)
409       continue;
410
411     char SymbolAddrStr[18] = "";
412     char SymbolSizeStr[18] = "";
413
414     if (OutputFormat == sysv || I->Address == UnknownAddressOrSize)
415       strcpy(SymbolAddrStr, printBlanks);
416     if (OutputFormat == sysv)
417       strcpy(SymbolSizeStr, printBlanks);
418
419     if (I->Address != UnknownAddressOrSize)
420       format(printFormat, I->Address)
421           .print(SymbolAddrStr, sizeof(SymbolAddrStr));
422     if (I->Size != UnknownAddressOrSize)
423       format(printFormat, I->Size).print(SymbolSizeStr, sizeof(SymbolSizeStr));
424
425     // If OutputFormat is darwin and we have a MachOObjectFile print as darwin's
426     // nm(1) -m output, else if OutputFormat is darwin and not a Mach-O object
427     // fall back to OutputFormat bsd (see below).
428     MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Obj);
429     if (OutputFormat == darwin && MachO) {
430       darwinPrintSymbol(MachO, I, SymbolAddrStr, printBlanks);
431     } else if (OutputFormat == posix) {
432       outs() << I->Name << " " << I->TypeChar << " " << SymbolAddrStr
433              << SymbolSizeStr << "\n";
434     } else if (OutputFormat == bsd || (OutputFormat == darwin && !MachO)) {
435       if (PrintAddress)
436         outs() << SymbolAddrStr << ' ';
437       if (PrintSize) {
438         outs() << SymbolSizeStr;
439         if (I->Size != UnknownAddressOrSize)
440           outs() << ' ';
441       }
442       outs() << I->TypeChar << " " << I->Name << "\n";
443     } else if (OutputFormat == sysv) {
444       std::string PaddedName(I->Name);
445       while (PaddedName.length() < 20)
446         PaddedName += " ";
447       outs() << PaddedName << "|" << SymbolAddrStr << "|   " << I->TypeChar
448              << "  |                  |" << SymbolSizeStr << "|     |\n";
449     }
450   }
451
452   SymbolList.clear();
453 }
454
455 template <class ELFT>
456 static char getSymbolNMTypeChar(ELFObjectFile<ELFT> &Obj,
457                                 basic_symbol_iterator I) {
458   typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
459   typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
460
461   // OK, this is ELF
462   symbol_iterator SymI(I);
463
464   DataRefImpl Symb = I->getRawDataRefImpl();
465   const Elf_Sym *ESym = Obj.getSymbol(Symb);
466   const ELFFile<ELFT> &EF = *Obj.getELFFile();
467   const Elf_Shdr *ESec = EF.getSection(ESym);
468
469   if (ESec) {
470     switch (ESec->sh_type) {
471     case ELF::SHT_PROGBITS:
472     case ELF::SHT_DYNAMIC:
473       switch (ESec->sh_flags) {
474       case(ELF::SHF_ALLOC | ELF::SHF_EXECINSTR) :
475         return 't';
476       case(ELF::SHF_TLS | ELF::SHF_ALLOC | ELF::SHF_WRITE) :
477       case(ELF::SHF_ALLOC | ELF::SHF_WRITE) :
478         return 'd';
479       case ELF::SHF_ALLOC:
480       case(ELF::SHF_ALLOC | ELF::SHF_MERGE) :
481       case(ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS) :
482         return 'r';
483       }
484       break;
485     case ELF::SHT_NOBITS:
486       return 'b';
487     }
488   }
489
490   if (ESym->getType() == ELF::STT_SECTION) {
491     StringRef Name;
492     if (error(SymI->getName(Name)))
493       return '?';
494     return StringSwitch<char>(Name)
495         .StartsWith(".debug", 'N')
496         .StartsWith(".note", 'n')
497         .Default('?');
498   }
499
500   return '?';
501 }
502
503 static char getSymbolNMTypeChar(COFFObjectFile &Obj, symbol_iterator I) {
504   const coff_symbol *Symb = Obj.getCOFFSymbol(*I);
505   // OK, this is COFF.
506   symbol_iterator SymI(I);
507
508   StringRef Name;
509   if (error(SymI->getName(Name)))
510     return '?';
511
512   char Ret = StringSwitch<char>(Name)
513                  .StartsWith(".debug", 'N')
514                  .StartsWith(".sxdata", 'N')
515                  .Default('?');
516
517   if (Ret != '?')
518     return Ret;
519
520   uint32_t Characteristics = 0;
521   if (!COFF::isReservedSectionNumber(Symb->SectionNumber)) {
522     section_iterator SecI = Obj.section_end();
523     if (error(SymI->getSection(SecI)))
524       return '?';
525     const coff_section *Section = Obj.getCOFFSection(*SecI);
526     Characteristics = Section->Characteristics;
527   }
528
529   switch (Symb->SectionNumber) {
530   case COFF::IMAGE_SYM_DEBUG:
531     return 'n';
532   default:
533     // Check section type.
534     if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
535       return 't';
536     else if (Characteristics & COFF::IMAGE_SCN_MEM_READ &&
537              ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only.
538       return 'r';
539     else if (Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
540       return 'd';
541     else if (Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
542       return 'b';
543     else if (Characteristics & COFF::IMAGE_SCN_LNK_INFO)
544       return 'i';
545
546     // Check for section symbol.
547     else if (Symb->isSectionDefinition())
548       return 's';
549   }
550
551   return '?';
552 }
553
554 static uint8_t getNType(MachOObjectFile &Obj, DataRefImpl Symb) {
555   if (Obj.is64Bit()) {
556     MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb);
557     return STE.n_type;
558   }
559   MachO::nlist STE = Obj.getSymbolTableEntry(Symb);
560   return STE.n_type;
561 }
562
563 static char getSymbolNMTypeChar(MachOObjectFile &Obj, basic_symbol_iterator I) {
564   DataRefImpl Symb = I->getRawDataRefImpl();
565   uint8_t NType = getNType(Obj, Symb);
566
567   switch (NType & MachO::N_TYPE) {
568   case MachO::N_ABS:
569     return 's';
570   case MachO::N_INDR:
571     return 'i';
572   case MachO::N_SECT: {
573     section_iterator Sec = Obj.section_end();
574     Obj.getSymbolSection(Symb, Sec);
575     DataRefImpl Ref = Sec->getRawDataRefImpl();
576     StringRef SectionName;
577     Obj.getSectionName(Ref, SectionName);
578     StringRef SegmentName = Obj.getSectionFinalSegmentName(Ref);
579     if (SegmentName == "__TEXT" && SectionName == "__text")
580       return 't';
581     else if (SegmentName == "__DATA" && SectionName == "__data")
582       return 'd';
583     else if (SegmentName == "__DATA" && SectionName == "__bss")
584       return 'b';
585     else
586       return 's';
587   }
588   }
589
590   return '?';
591 }
592
593 static char getSymbolNMTypeChar(const GlobalValue &GV) {
594   if (GV.getType()->getElementType()->isFunctionTy())
595     return 't';
596   // FIXME: should we print 'b'? At the IR level we cannot be sure if this
597   // will be in bss or not, but we could approximate.
598   return 'd';
599 }
600
601 static char getSymbolNMTypeChar(IRObjectFile &Obj, basic_symbol_iterator I) {
602   const GlobalValue &GV = Obj.getSymbolGV(I->getRawDataRefImpl());
603   return getSymbolNMTypeChar(GV);
604 }
605
606 template <class ELFT>
607 static bool isObject(ELFObjectFile<ELFT> &Obj, symbol_iterator I) {
608   typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
609
610   DataRefImpl Symb = I->getRawDataRefImpl();
611   const Elf_Sym *ESym = Obj.getSymbol(Symb);
612
613   return ESym->getType() == ELF::STT_OBJECT;
614 }
615
616 static bool isObject(SymbolicFile *Obj, basic_symbol_iterator I) {
617   if (ELF32LEObjectFile *ELF = dyn_cast<ELF32LEObjectFile>(Obj))
618     return isObject(*ELF, I);
619   if (ELF64LEObjectFile *ELF = dyn_cast<ELF64LEObjectFile>(Obj))
620     return isObject(*ELF, I);
621   if (ELF32BEObjectFile *ELF = dyn_cast<ELF32BEObjectFile>(Obj))
622     return isObject(*ELF, I);
623   if (ELF64BEObjectFile *ELF = dyn_cast<ELF64BEObjectFile>(Obj))
624     return isObject(*ELF, I);
625   return false;
626 }
627
628 static char getNMTypeChar(SymbolicFile *Obj, basic_symbol_iterator I) {
629   uint32_t Symflags = I->getFlags();
630   if ((Symflags & object::SymbolRef::SF_Weak) && !isa<MachOObjectFile>(Obj)) {
631     char Ret = isObject(Obj, I) ? 'v' : 'w';
632     if (!(Symflags & object::SymbolRef::SF_Undefined))
633       Ret = toupper(Ret);
634     return Ret;
635   }
636
637   if (Symflags & object::SymbolRef::SF_Undefined)
638     return 'U';
639
640   if (Symflags & object::SymbolRef::SF_Common)
641     return 'C';
642
643   char Ret = '?';
644   if (Symflags & object::SymbolRef::SF_Absolute)
645     Ret = 'a';
646   else if (IRObjectFile *IR = dyn_cast<IRObjectFile>(Obj))
647     Ret = getSymbolNMTypeChar(*IR, I);
648   else if (COFFObjectFile *COFF = dyn_cast<COFFObjectFile>(Obj))
649     Ret = getSymbolNMTypeChar(*COFF, I);
650   else if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Obj))
651     Ret = getSymbolNMTypeChar(*MachO, I);
652   else if (ELF32LEObjectFile *ELF = dyn_cast<ELF32LEObjectFile>(Obj))
653     Ret = getSymbolNMTypeChar(*ELF, I);
654   else if (ELF64LEObjectFile *ELF = dyn_cast<ELF64LEObjectFile>(Obj))
655     Ret = getSymbolNMTypeChar(*ELF, I);
656   else if (ELF32BEObjectFile *ELF = dyn_cast<ELF32BEObjectFile>(Obj))
657     Ret = getSymbolNMTypeChar(*ELF, I);
658   else
659     Ret = getSymbolNMTypeChar(*cast<ELF64BEObjectFile>(Obj), I);
660
661   if (Symflags & object::SymbolRef::SF_Global)
662     Ret = toupper(Ret);
663
664   return Ret;
665 }
666
667 static void dumpSymbolNamesFromObject(SymbolicFile *Obj) {
668   basic_symbol_iterator IBegin = Obj->symbol_begin();
669   basic_symbol_iterator IEnd = Obj->symbol_end();
670   if (DynamicSyms) {
671     if (!Obj->isELF()) {
672       error("File format has no dynamic symbol table", Obj->getFileName());
673       return;
674     }
675     std::pair<symbol_iterator, symbol_iterator> IDyn =
676         getELFDynamicSymbolIterators(Obj);
677     IBegin = IDyn.first;
678     IEnd = IDyn.second;
679   }
680   std::string NameBuffer;
681   raw_string_ostream OS(NameBuffer);
682   for (basic_symbol_iterator I = IBegin; I != IEnd; ++I) {
683     uint32_t SymFlags = I->getFlags();
684     if (!DebugSyms && (SymFlags & SymbolRef::SF_FormatSpecific))
685       continue;
686     if (WithoutAliases) {
687       if (IRObjectFile *IR = dyn_cast<IRObjectFile>(Obj)) {
688         const GlobalValue &GV = IR->getSymbolGV(I->getRawDataRefImpl());
689         if(isa<GlobalAlias>(GV))
690           continue;
691       }
692     }
693     NMSymbol S;
694     S.Size = UnknownAddressOrSize;
695     S.Address = UnknownAddressOrSize;
696     if ((PrintSize || SizeSort) && isa<ObjectFile>(Obj)) {
697       symbol_iterator SymI = I;
698       if (error(SymI->getSize(S.Size)))
699         break;
700     }
701     if (PrintAddress && isa<ObjectFile>(Obj))
702       if (error(symbol_iterator(I)->getAddress(S.Address)))
703         break;
704     S.TypeChar = getNMTypeChar(Obj, I);
705     if (error(I->printName(OS)))
706       break;
707     OS << '\0';
708     S.Symb = I->getRawDataRefImpl();
709     SymbolList.push_back(S);
710   }
711
712   OS.flush();
713   const char *P = NameBuffer.c_str();
714   for (unsigned I = 0; I < SymbolList.size(); ++I) {
715     SymbolList[I].Name = P;
716     P += strlen(P) + 1;
717   }
718
719   CurrentFilename = Obj->getFileName();
720   sortAndPrintSymbolList(Obj);
721 }
722
723 static void dumpSymbolNamesFromFile(std::string &Filename) {
724   std::unique_ptr<MemoryBuffer> Buffer;
725   if (error(MemoryBuffer::getFileOrSTDIN(Filename, Buffer), Filename))
726     return;
727
728   LLVMContext &Context = getGlobalContext();
729   ErrorOr<Binary *> BinaryOrErr = createBinary(Buffer.release(), &Context);
730   if (error(BinaryOrErr.getError(), Filename))
731     return;
732   std::unique_ptr<Binary> Bin(BinaryOrErr.get());
733
734   if (Archive *A = dyn_cast<Archive>(Bin.get())) {
735     if (ArchiveMap) {
736       Archive::symbol_iterator I = A->symbol_begin();
737       Archive::symbol_iterator E = A->symbol_end();
738       if (I != E) {
739         outs() << "Archive map\n";
740         for (; I != E; ++I) {
741           ErrorOr<Archive::child_iterator> C = I->getMember();
742           if (error(C.getError()))
743             return;
744           ErrorOr<StringRef> FileNameOrErr = C.get()->getName();
745           if (error(FileNameOrErr.getError()))
746             return;
747           StringRef SymName = I->getName();
748           outs() << SymName << " in " << FileNameOrErr.get() << "\n";
749         }
750         outs() << "\n";
751       }
752     }
753
754     for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
755          I != E; ++I) {
756       ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary(&Context);
757       if (ChildOrErr.getError())
758         continue;
759       if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
760         if (isa<MachOObjectFile>(O)) {
761           outs() << Filename << "(" << O->getFileName() << ")";
762         } else
763           outs() << O->getFileName();
764         outs() << ":\n";
765         dumpSymbolNamesFromObject(O);
766       }
767     }
768     return;
769   }
770   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin.get())) {
771     bool moreThanOneArch = UB->getNumberOfObjects() > 1;
772     for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
773                                                E = UB->end_objects();
774          I != E; ++I) {
775       std::unique_ptr<ObjectFile> Obj;
776       std::unique_ptr<Archive> A;
777       if (!I->getAsObjectFile(Obj)) {
778         outs() << Obj->getFileName();
779         if (isa<MachOObjectFile>(Obj.get()) && moreThanOneArch)
780           outs() << " (for architecture " << I->getArchTypeName() << ")";
781         outs() << ":\n";
782         dumpSymbolNamesFromObject(Obj.get());
783       }
784       else if (!I->getAsArchive(A)) {
785         for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
786              AI != AE; ++AI) {
787           ErrorOr<std::unique_ptr<Binary>> ChildOrErr =
788               AI->getAsBinary(&Context);
789           if (ChildOrErr.getError())
790             continue;
791           if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
792             outs() << A->getFileName();
793             if (isa<MachOObjectFile>(O)) {
794               outs() << "(" << O->getFileName() << ")";
795               if (moreThanOneArch)
796                 outs() << " (for architecture " << I->getArchTypeName() << ")";
797             } else
798               outs() << ":" << O->getFileName();
799             outs() << ":\n";
800             dumpSymbolNamesFromObject(O);
801           }
802         }
803       }
804     }
805     return;
806   }
807   if (SymbolicFile *O = dyn_cast<SymbolicFile>(Bin.get())) {
808     dumpSymbolNamesFromObject(O);
809     return;
810   }
811   error("unrecognizable file type", Filename);
812   return;
813 }
814
815 int main(int argc, char **argv) {
816   // Print a stack trace if we signal out.
817   sys::PrintStackTraceOnErrorSignal();
818   PrettyStackTraceProgram X(argc, argv);
819
820   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
821   cl::ParseCommandLineOptions(argc, argv, "llvm symbol table dumper\n");
822
823   // llvm-nm only reads binary files.
824   if (error(sys::ChangeStdinToBinary()))
825     return 1;
826
827   ToolName = argv[0];
828   if (BSDFormat)
829     OutputFormat = bsd;
830   if (POSIXFormat)
831     OutputFormat = posix;
832   if (DarwinFormat)
833     OutputFormat = darwin;
834
835   // The relative order of these is important. If you pass --size-sort it should
836   // only print out the size. However, if you pass -S --size-sort, it should
837   // print out both the size and address.
838   if (SizeSort && !PrintSize)
839     PrintAddress = false;
840   if (OutputFormat == sysv || SizeSort)
841     PrintSize = true;
842
843   switch (InputFilenames.size()) {
844   case 0:
845     InputFilenames.push_back("-");
846   case 1:
847     break;
848   default:
849     MultipleFiles = true;
850   }
851
852   std::for_each(InputFilenames.begin(), InputFilenames.end(),
853                 dumpSymbolNamesFromFile);
854
855   if (HadError)
856     return 1;
857
858   return 0;
859 }