Encapsulate PassManager debug flags to avoid static init and cxa_exit.
[oota-llvm.git] / tools / llvm-nm / llvm-nm.cpp
1 //===-- llvm-nm.cpp - Symbol table dumping utility for llvm ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This program is a utility that works like traditional Unix "nm", that is, it
11 // prints out the names of symbols in a bitcode or object file, along with some
12 // information about each symbol.
13 //
14 // This "nm" supports many of the features of GNU "nm", including its different
15 // output formats.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Object/Archive.h"
23 #include "llvm/Object/MachOUniversal.h"
24 #include "llvm/Object/ObjectFile.h"
25 #include "llvm/PassManager.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/Format.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/PrettyStackTrace.h"
32 #include "llvm/Support/Program.h"
33 #include "llvm/Support/Signals.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Support/system_error.h"
36 #include <algorithm>
37 #include <cctype>
38 #include <cerrno>
39 #include <cstring>
40 #include <vector>
41 using namespace llvm;
42 using namespace object;
43
44 namespace {
45   enum OutputFormatTy { bsd, sysv, posix };
46   cl::opt<OutputFormatTy>
47   OutputFormat("format",
48        cl::desc("Specify output format"),
49          cl::values(clEnumVal(bsd,   "BSD format"),
50                     clEnumVal(sysv,  "System V format"),
51                     clEnumVal(posix, "POSIX.2 format"),
52                     clEnumValEnd), cl::init(bsd));
53   cl::alias OutputFormat2("f", cl::desc("Alias for --format"),
54                           cl::aliasopt(OutputFormat));
55
56   cl::list<std::string>
57   InputFilenames(cl::Positional, cl::desc("<input bitcode files>"),
58                  cl::ZeroOrMore);
59
60   cl::opt<bool> UndefinedOnly("undefined-only",
61                               cl::desc("Show only undefined symbols"));
62   cl::alias UndefinedOnly2("u", cl::desc("Alias for --undefined-only"),
63                            cl::aliasopt(UndefinedOnly));
64
65   cl::opt<bool> DynamicSyms("dynamic",
66                              cl::desc("Display the dynamic symbols instead "
67                                       "of normal symbols."));
68   cl::alias DynamicSyms2("D", cl::desc("Alias for --dynamic"),
69                          cl::aliasopt(DynamicSyms));
70
71   cl::opt<bool> DefinedOnly("defined-only",
72                             cl::desc("Show only defined symbols"));
73
74   cl::opt<bool> ExternalOnly("extern-only",
75                              cl::desc("Show only external symbols"));
76   cl::alias ExternalOnly2("g", cl::desc("Alias for --extern-only"),
77                           cl::aliasopt(ExternalOnly));
78
79   cl::opt<bool> BSDFormat("B", cl::desc("Alias for --format=bsd"));
80   cl::opt<bool> POSIXFormat("P", cl::desc("Alias for --format=posix"));
81
82   cl::opt<bool> PrintFileName("print-file-name",
83     cl::desc("Precede each symbol with the object file it came from"));
84
85   cl::alias PrintFileNameA("A", cl::desc("Alias for --print-file-name"),
86                                 cl::aliasopt(PrintFileName));
87   cl::alias PrintFileNameo("o", cl::desc("Alias for --print-file-name"),
88                                 cl::aliasopt(PrintFileName));
89
90   cl::opt<bool> DebugSyms("debug-syms",
91     cl::desc("Show all symbols, even debugger only"));
92   cl::alias DebugSymsa("a", cl::desc("Alias for --debug-syms"),
93                             cl::aliasopt(DebugSyms));
94
95   cl::opt<bool> NumericSort("numeric-sort",
96     cl::desc("Sort symbols by address"));
97   cl::alias NumericSortn("n", cl::desc("Alias for --numeric-sort"),
98                               cl::aliasopt(NumericSort));
99   cl::alias NumericSortv("v", cl::desc("Alias for --numeric-sort"),
100                               cl::aliasopt(NumericSort));
101
102   cl::opt<bool> NoSort("no-sort",
103     cl::desc("Show symbols in order encountered"));
104   cl::alias NoSortp("p", cl::desc("Alias for --no-sort"),
105                          cl::aliasopt(NoSort));
106
107   cl::opt<bool> PrintSize("print-size",
108     cl::desc("Show symbol size instead of address"));
109   cl::alias PrintSizeS("S", cl::desc("Alias for --print-size"),
110                             cl::aliasopt(PrintSize));
111
112   cl::opt<bool> SizeSort("size-sort", cl::desc("Sort symbols by size"));
113
114   cl::opt<bool> WithoutAliases("without-aliases", cl::Hidden,
115                                cl::desc("Exclude aliases from output"));
116
117   cl::opt<bool> ArchiveMap("print-armap",
118     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
131 static void error(Twine message, Twine path = Twine()) {
132   errs() << ToolName << ": " << path << ": " << message << ".\n";
133 }
134
135 static bool error(error_code ec, Twine path = Twine()) {
136   if (ec) {
137     error(ec.message(), path);
138     HadError = true;
139     return true;
140   }
141   return false;
142 }
143
144 namespace {
145   struct NMSymbol {
146     uint64_t  Address;
147     uint64_t  Size;
148     char      TypeChar;
149     StringRef Name;
150   };
151
152   static bool CompareSymbolAddress(const NMSymbol &a, const NMSymbol &b) {
153     if (a.Address < b.Address)
154       return true;
155     else if (a.Address == b.Address && a.Name < b.Name)
156       return true;
157     else if (a.Address == b.Address && a.Name == b.Name && a.Size < b.Size)
158       return true;
159     else
160       return false;
161
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   StringRef CurrentFilename;
187   typedef std::vector<NMSymbol> SymbolListT;
188   SymbolListT SymbolList;
189 }
190
191 static void SortAndPrintSymbolList() {
192   if (!NoSort) {
193     if (NumericSort)
194       std::sort(SymbolList.begin(), SymbolList.end(), CompareSymbolAddress);
195     else if (SizeSort)
196       std::sort(SymbolList.begin(), SymbolList.end(), CompareSymbolSize);
197     else
198       std::sort(SymbolList.begin(), SymbolList.end(), CompareSymbolName);
199   }
200
201   if (OutputFormat == posix && MultipleFiles) {
202     outs() << '\n' << CurrentFilename << ":\n";
203   } else if (OutputFormat == bsd && MultipleFiles) {
204     outs() << "\n" << CurrentFilename << ":\n";
205   } else if (OutputFormat == sysv) {
206     outs() << "\n\nSymbols from " << CurrentFilename << ":\n\n"
207            << "Name                  Value   Class        Type"
208            << "         Size   Line  Section\n";
209   }
210
211   for (SymbolListT::iterator i = SymbolList.begin(),
212                              e = SymbolList.end(); i != e; ++i) {
213     if ((i->TypeChar != 'U') && UndefinedOnly)
214       continue;
215     if ((i->TypeChar == 'U') && DefinedOnly)
216       continue;
217     if (SizeSort && !PrintAddress && i->Size == UnknownAddressOrSize)
218       continue;
219
220     char SymbolAddrStr[10] = "";
221     char SymbolSizeStr[10] = "";
222
223     if (OutputFormat == sysv || i->Address == object::UnknownAddressOrSize)
224       strcpy(SymbolAddrStr, "        ");
225     if (OutputFormat == sysv)
226       strcpy(SymbolSizeStr, "        ");
227
228     if (i->Address != object::UnknownAddressOrSize)
229       format("%08" PRIx64, i->Address).print(SymbolAddrStr,
230                                              sizeof(SymbolAddrStr));
231     if (i->Size != object::UnknownAddressOrSize)
232       format("%08" PRIx64, i->Size).print(SymbolSizeStr, sizeof(SymbolSizeStr));
233
234     if (OutputFormat == posix) {
235       outs() << i->Name << " " << i->TypeChar << " "
236              << SymbolAddrStr << SymbolSizeStr << "\n";
237     } else if (OutputFormat == bsd) {
238       if (PrintAddress)
239         outs() << SymbolAddrStr << ' ';
240       if (PrintSize) {
241         outs() << SymbolSizeStr;
242         if (i->Size != object::UnknownAddressOrSize)
243           outs() << ' ';
244       }
245       outs() << i->TypeChar << " " << i->Name  << "\n";
246     } else if (OutputFormat == sysv) {
247       std::string PaddedName (i->Name);
248       while (PaddedName.length () < 20)
249         PaddedName += " ";
250       outs() << PaddedName << "|" << SymbolAddrStr << "|   "
251              << i->TypeChar
252              << "  |                  |" << SymbolSizeStr << "|     |\n";
253     }
254   }
255
256   SymbolList.clear();
257 }
258
259 static char TypeCharForSymbol(GlobalValue &GV) {
260   if (GV.isDeclaration())                                  return 'U';
261   if (GV.hasLinkOnceLinkage())                             return 'C';
262   if (GV.hasCommonLinkage())                               return 'C';
263   if (GV.hasWeakLinkage())                                 return 'W';
264   if (isa<Function>(GV) && GV.hasInternalLinkage())        return 't';
265   if (isa<Function>(GV))                                   return 'T';
266   if (isa<GlobalVariable>(GV) && GV.hasInternalLinkage())  return 'd';
267   if (isa<GlobalVariable>(GV))                             return 'D';
268   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(&GV)) {
269     const GlobalValue *AliasedGV = GA->getAliasedGlobal();
270     if (isa<Function>(AliasedGV))                          return 'T';
271     if (isa<GlobalVariable>(AliasedGV))                    return 'D';
272   }
273                                                            return '?';
274 }
275
276 static void DumpSymbolNameForGlobalValue(GlobalValue &GV) {
277   // Private linkage and available_externally linkage don't exist in symtab.
278   if (GV.hasPrivateLinkage() ||
279       GV.hasLinkerPrivateLinkage() ||
280       GV.hasLinkerPrivateWeakLinkage() ||
281       GV.hasAvailableExternallyLinkage())
282     return;
283   char TypeChar = TypeCharForSymbol(GV);
284   if (GV.hasLocalLinkage () && ExternalOnly)
285     return;
286
287   NMSymbol s;
288   s.Address = object::UnknownAddressOrSize;
289   s.Size = object::UnknownAddressOrSize;
290   s.TypeChar = TypeChar;
291   s.Name     = GV.getName();
292   SymbolList.push_back(s);
293 }
294
295 static void DumpSymbolNamesFromModule(Module *M) {
296   CurrentFilename = M->getModuleIdentifier();
297   std::for_each (M->begin(), M->end(), DumpSymbolNameForGlobalValue);
298   std::for_each (M->global_begin(), M->global_end(),
299                  DumpSymbolNameForGlobalValue);
300   if (!WithoutAliases)
301     std::for_each (M->alias_begin(), M->alias_end(),
302                    DumpSymbolNameForGlobalValue);
303
304   SortAndPrintSymbolList();
305 }
306
307 static void DumpSymbolNamesFromObject(ObjectFile *obj) {
308   error_code ec;
309   symbol_iterator ibegin = obj->begin_symbols();
310   symbol_iterator iend = obj->end_symbols();
311   if (DynamicSyms) {
312     ibegin = obj->begin_dynamic_symbols();
313     iend = obj->end_dynamic_symbols();
314   }
315   for (symbol_iterator i = ibegin; i != iend; i.increment(ec)) {
316     if (error(ec)) break;
317     uint32_t symflags;
318     if (error(i->getFlags(symflags))) break;
319     if (!DebugSyms && (symflags & SymbolRef::SF_FormatSpecific))
320       continue;
321     NMSymbol s;
322     s.Size = object::UnknownAddressOrSize;
323     s.Address = object::UnknownAddressOrSize;
324     if (PrintSize || SizeSort) {
325       if (error(i->getSize(s.Size))) break;
326     }
327     if (PrintAddress)
328       if (error(i->getAddress(s.Address))) break;
329     if (error(i->getNMTypeChar(s.TypeChar))) break;
330     if (error(i->getName(s.Name))) break;
331     SymbolList.push_back(s);
332   }
333
334   CurrentFilename = obj->getFileName();
335   SortAndPrintSymbolList();
336 }
337
338 static void DumpSymbolNamesFromFile(std::string &Filename) {
339   if (Filename != "-" && !sys::fs::exists(Filename)) {
340     errs() << ToolName << ": '" << Filename << "': " << "No such file\n";
341     return;
342   }
343
344   OwningPtr<MemoryBuffer> Buffer;
345   if (error(MemoryBuffer::getFileOrSTDIN(Filename, Buffer), Filename))
346     return;
347
348   sys::fs::file_magic magic = sys::fs::identify_magic(Buffer->getBuffer());
349
350   LLVMContext &Context = getGlobalContext();
351   std::string ErrorMessage;
352   if (magic == sys::fs::file_magic::bitcode) {
353     Module *Result = 0;
354     Result = ParseBitcodeFile(Buffer.get(), Context, &ErrorMessage);
355     if (Result) {
356       DumpSymbolNamesFromModule(Result);
357       delete Result;
358     } else {
359       error(ErrorMessage, Filename);
360       return;
361     }
362   } else if (magic == sys::fs::file_magic::archive) {
363     OwningPtr<Binary> arch;
364     if (error(object::createBinary(Buffer.take(), arch), Filename))
365       return;
366
367     if (object::Archive *a = dyn_cast<object::Archive>(arch.get())) {
368       if (ArchiveMap) {
369         object::Archive::symbol_iterator I = a->begin_symbols();
370         object::Archive::symbol_iterator E = a->end_symbols();
371         if (I !=E) {
372           outs() << "Archive map" << "\n";
373           for (; I != E; ++I) {
374             object::Archive::child_iterator c;
375             StringRef symname;
376             StringRef filename;
377             if (error(I->getMember(c)))
378               return;
379             if (error(I->getName(symname)))
380               return;
381             if (error(c->getName(filename)))
382               return;
383             outs() << symname << " in " << filename << "\n";
384           }
385           outs() << "\n";
386         }
387       }
388
389       for (object::Archive::child_iterator i = a->begin_children(),
390                                            e = a->end_children(); i != e; ++i) {
391         OwningPtr<Binary> child;
392         if (i->getAsBinary(child)) {
393           // Try opening it as a bitcode file.
394           OwningPtr<MemoryBuffer> buff;
395           if (error(i->getMemoryBuffer(buff)))
396             return;
397           Module *Result = 0;
398           if (buff)
399             Result = ParseBitcodeFile(buff.get(), Context, &ErrorMessage);
400
401           if (Result) {
402             DumpSymbolNamesFromModule(Result);
403             delete Result;
404           }
405           continue;
406         }
407         if (object::ObjectFile *o = dyn_cast<ObjectFile>(child.get())) {
408           outs() << o->getFileName() << ":\n";
409           DumpSymbolNamesFromObject(o);
410         }
411       }
412     }
413   } else if (magic == sys::fs::file_magic::macho_universal_binary) {
414     OwningPtr<Binary> Bin;
415     if (error(object::createBinary(Buffer.take(), Bin), Filename))
416       return;
417
418     object::MachOUniversalBinary *UB =
419         cast<object::MachOUniversalBinary>(Bin.get());
420     for (object::MachOUniversalBinary::object_iterator
421              I = UB->begin_objects(),
422              E = UB->end_objects();
423          I != E; ++I) {
424       OwningPtr<ObjectFile> Obj;
425       if (!I->getAsObjectFile(Obj)) {
426         outs() << Obj->getFileName() << ":\n";
427         DumpSymbolNamesFromObject(Obj.get());
428       }
429     }
430   } else if (magic.is_object()) {
431     OwningPtr<Binary> obj;
432     if (error(object::createBinary(Buffer.take(), obj), Filename))
433       return;
434     if (object::ObjectFile *o = dyn_cast<ObjectFile>(obj.get()))
435       DumpSymbolNamesFromObject(o);
436   } else {
437     errs() << ToolName << ": " << Filename << ": "
438            << "unrecognizable file type\n";
439     HadError = true;
440     return;
441   }
442 }
443
444 int main(int argc, char **argv) {
445   // Print a stack trace if we signal out.
446   sys::PrintStackTraceOnErrorSignal();
447   PrettyStackTraceProgram X(argc, argv);
448
449   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
450
451   // Initialize PassManager for -time-passes support.
452   initializePassManager();
453
454   cl::ParseCommandLineOptions(argc, argv, "llvm symbol table dumper\n");
455
456   // llvm-nm only reads binary files.
457   if (error(sys::ChangeStdinToBinary()))
458     return 1;
459
460   ToolName = argv[0];
461   if (BSDFormat) OutputFormat = bsd;
462   if (POSIXFormat) OutputFormat = posix;
463
464   // The relative order of these is important. If you pass --size-sort it should
465   // only print out the size. However, if you pass -S --size-sort, it should
466   // print out both the size and address.
467   if (SizeSort && !PrintSize) PrintAddress = false;
468   if (OutputFormat == sysv || SizeSort) PrintSize = true;
469
470   switch (InputFilenames.size()) {
471   case 0: InputFilenames.push_back("-");
472   case 1: break;
473   default: MultipleFiles = true;
474   }
475
476   std::for_each(InputFilenames.begin(), InputFilenames.end(),
477                 DumpSymbolNamesFromFile);
478
479   if (HadError)
480     return 1;
481
482   return 0;
483 }