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