Don't use 'using std::error_code' in include/llvm.
[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 using std::error_code;
49
50 namespace {
51 enum OutputFormatTy { bsd, sysv, posix, darwin };
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"),
56                clEnumVal(darwin, "Darwin -m format"), clEnumValEnd),
57     cl::init(bsd));
58 cl::alias OutputFormat2("f", cl::desc("Alias for --format"),
59                         cl::aliasopt(OutputFormat));
60
61 cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<input 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   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
582       return 's';
583   }
584   }
585
586   return '?';
587 }
588
589 static char getSymbolNMTypeChar(const GlobalValue &GV) {
590   if (GV.getType()->getElementType()->isFunctionTy())
591     return 't';
592   // FIXME: should we print 'b'? At the IR level we cannot be sure if this
593   // will be in bss or not, but we could approximate.
594   return 'd';
595 }
596
597 static char getSymbolNMTypeChar(IRObjectFile &Obj, basic_symbol_iterator I) {
598   const GlobalValue &GV = Obj.getSymbolGV(I->getRawDataRefImpl());
599   return getSymbolNMTypeChar(GV);
600 }
601
602 template <class ELFT>
603 static bool isObject(ELFObjectFile<ELFT> &Obj, symbol_iterator I) {
604   typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
605
606   DataRefImpl Symb = I->getRawDataRefImpl();
607   const Elf_Sym *ESym = Obj.getSymbol(Symb);
608
609   return ESym->getType() == ELF::STT_OBJECT;
610 }
611
612 static bool isObject(SymbolicFile *Obj, basic_symbol_iterator I) {
613   if (ELF32LEObjectFile *ELF = dyn_cast<ELF32LEObjectFile>(Obj))
614     return isObject(*ELF, I);
615   if (ELF64LEObjectFile *ELF = dyn_cast<ELF64LEObjectFile>(Obj))
616     return isObject(*ELF, I);
617   if (ELF32BEObjectFile *ELF = dyn_cast<ELF32BEObjectFile>(Obj))
618     return isObject(*ELF, I);
619   if (ELF64BEObjectFile *ELF = dyn_cast<ELF64BEObjectFile>(Obj))
620     return isObject(*ELF, I);
621   return false;
622 }
623
624 static char getNMTypeChar(SymbolicFile *Obj, basic_symbol_iterator I) {
625   uint32_t Symflags = I->getFlags();
626   if ((Symflags & object::SymbolRef::SF_Weak) && !isa<MachOObjectFile>(Obj)) {
627     char Ret = isObject(Obj, I) ? 'v' : 'w';
628     if (!(Symflags & object::SymbolRef::SF_Undefined))
629       Ret = toupper(Ret);
630     return Ret;
631   }
632
633   if (Symflags & object::SymbolRef::SF_Undefined)
634     return 'U';
635
636   if (Symflags & object::SymbolRef::SF_Common)
637     return 'C';
638
639   char Ret = '?';
640   if (Symflags & object::SymbolRef::SF_Absolute)
641     Ret = 'a';
642   else if (IRObjectFile *IR = dyn_cast<IRObjectFile>(Obj))
643     Ret = getSymbolNMTypeChar(*IR, I);
644   else if (COFFObjectFile *COFF = dyn_cast<COFFObjectFile>(Obj))
645     Ret = getSymbolNMTypeChar(*COFF, I);
646   else if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Obj))
647     Ret = getSymbolNMTypeChar(*MachO, I);
648   else if (ELF32LEObjectFile *ELF = dyn_cast<ELF32LEObjectFile>(Obj))
649     Ret = getSymbolNMTypeChar(*ELF, I);
650   else if (ELF64LEObjectFile *ELF = dyn_cast<ELF64LEObjectFile>(Obj))
651     Ret = getSymbolNMTypeChar(*ELF, I);
652   else if (ELF32BEObjectFile *ELF = dyn_cast<ELF32BEObjectFile>(Obj))
653     Ret = getSymbolNMTypeChar(*ELF, I);
654   else
655     Ret = getSymbolNMTypeChar(*cast<ELF64BEObjectFile>(Obj), I);
656
657   if (Symflags & object::SymbolRef::SF_Global)
658     Ret = toupper(Ret);
659
660   return Ret;
661 }
662
663 static void dumpSymbolNamesFromObject(SymbolicFile *Obj) {
664   basic_symbol_iterator IBegin = Obj->symbol_begin();
665   basic_symbol_iterator IEnd = Obj->symbol_end();
666   if (DynamicSyms) {
667     if (!Obj->isELF()) {
668       error("File format has no dynamic symbol table", Obj->getFileName());
669       return;
670     }
671     std::pair<symbol_iterator, symbol_iterator> IDyn =
672         getELFDynamicSymbolIterators(Obj);
673     IBegin = IDyn.first;
674     IEnd = IDyn.second;
675   }
676   std::string NameBuffer;
677   raw_string_ostream OS(NameBuffer);
678   for (basic_symbol_iterator I = IBegin; I != IEnd; ++I) {
679     uint32_t SymFlags = I->getFlags();
680     if (!DebugSyms && (SymFlags & SymbolRef::SF_FormatSpecific))
681       continue;
682     if (WithoutAliases) {
683       if (IRObjectFile *IR = dyn_cast<IRObjectFile>(Obj)) {
684         const GlobalValue &GV = IR->getSymbolGV(I->getRawDataRefImpl());
685         if(isa<GlobalAlias>(GV))
686           continue;
687       }
688     }
689     NMSymbol S;
690     S.Size = UnknownAddressOrSize;
691     S.Address = UnknownAddressOrSize;
692     if ((PrintSize || SizeSort) && isa<ObjectFile>(Obj)) {
693       symbol_iterator SymI = I;
694       if (error(SymI->getSize(S.Size)))
695         break;
696     }
697     if (PrintAddress && isa<ObjectFile>(Obj))
698       if (error(symbol_iterator(I)->getAddress(S.Address)))
699         break;
700     S.TypeChar = getNMTypeChar(Obj, I);
701     if (error(I->printName(OS)))
702       break;
703     OS << '\0';
704     S.Symb = I->getRawDataRefImpl();
705     SymbolList.push_back(S);
706   }
707
708   OS.flush();
709   const char *P = NameBuffer.c_str();
710   for (unsigned I = 0; I < SymbolList.size(); ++I) {
711     SymbolList[I].Name = P;
712     P += strlen(P) + 1;
713   }
714
715   CurrentFilename = Obj->getFileName();
716   sortAndPrintSymbolList(Obj);
717 }
718
719 static void dumpSymbolNamesFromFile(std::string &Filename) {
720   std::unique_ptr<MemoryBuffer> Buffer;
721   if (error(MemoryBuffer::getFileOrSTDIN(Filename, Buffer), Filename))
722     return;
723
724   LLVMContext &Context = getGlobalContext();
725   ErrorOr<Binary *> BinaryOrErr = createBinary(Buffer.release(), &Context);
726   if (error(BinaryOrErr.getError(), Filename))
727     return;
728   std::unique_ptr<Binary> Bin(BinaryOrErr.get());
729
730   if (Archive *A = dyn_cast<Archive>(Bin.get())) {
731     if (ArchiveMap) {
732       Archive::symbol_iterator I = A->symbol_begin();
733       Archive::symbol_iterator E = A->symbol_end();
734       if (I != E) {
735         outs() << "Archive map\n";
736         for (; I != E; ++I) {
737           Archive::child_iterator C;
738           StringRef SymName;
739           StringRef FileName;
740           if (error(I->getMember(C)))
741             return;
742           if (error(I->getName(SymName)))
743             return;
744           if (error(C->getName(FileName)))
745             return;
746           outs() << SymName << " in " << FileName << "\n";
747         }
748         outs() << "\n";
749       }
750     }
751
752     for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
753          I != E; ++I) {
754       std::unique_ptr<Binary> Child;
755       if (I->getAsBinary(Child, &Context))
756         continue;
757       if (SymbolicFile *O = dyn_cast<SymbolicFile>(Child.get())) {
758         outs() << O->getFileName() << ":\n";
759         dumpSymbolNamesFromObject(O);
760       }
761     }
762     return;
763   }
764   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin.get())) {
765     for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
766                                                E = UB->end_objects();
767          I != E; ++I) {
768       std::unique_ptr<ObjectFile> Obj;
769       std::unique_ptr<Archive> A;
770       if (!I->getAsObjectFile(Obj)) {
771         outs() << Obj->getFileName() << ":\n";
772         dumpSymbolNamesFromObject(Obj.get());
773       }
774       else if (!I->getAsArchive(A)) {
775         for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
776              AI != AE; ++AI) {
777           std::unique_ptr<Binary> Child;
778           if (AI->getAsBinary(Child, &Context))
779             continue;
780           if (SymbolicFile *O = dyn_cast<SymbolicFile>(Child.get())) {
781             outs() << A->getFileName() << ":";
782             outs() << O->getFileName() << ":\n";
783             dumpSymbolNamesFromObject(O);
784           }
785         }
786       }
787     }
788     return;
789   }
790   if (SymbolicFile *O = dyn_cast<SymbolicFile>(Bin.get())) {
791     dumpSymbolNamesFromObject(O);
792     return;
793   }
794   error("unrecognizable file type", Filename);
795   return;
796 }
797
798 int main(int argc, char **argv) {
799   // Print a stack trace if we signal out.
800   sys::PrintStackTraceOnErrorSignal();
801   PrettyStackTraceProgram X(argc, argv);
802
803   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
804   cl::ParseCommandLineOptions(argc, argv, "llvm symbol table dumper\n");
805
806   // llvm-nm only reads binary files.
807   if (error(sys::ChangeStdinToBinary()))
808     return 1;
809
810   ToolName = argv[0];
811   if (BSDFormat)
812     OutputFormat = bsd;
813   if (POSIXFormat)
814     OutputFormat = posix;
815
816   // The relative order of these is important. If you pass --size-sort it should
817   // only print out the size. However, if you pass -S --size-sort, it should
818   // print out both the size and address.
819   if (SizeSort && !PrintSize)
820     PrintAddress = false;
821   if (OutputFormat == sysv || SizeSort)
822     PrintSize = true;
823
824   switch (InputFilenames.size()) {
825   case 0:
826     InputFilenames.push_back("-");
827   case 1:
828     break;
829   default:
830     MultipleFiles = true;
831   }
832
833   std::for_each(InputFilenames.begin(), InputFilenames.end(),
834                 dumpSymbolNamesFromFile);
835
836   if (HadError)
837     return 1;
838
839   return 0;
840 }