[Object] Add {begin,end}_dynamic_symbols stubs and implementation for ELF.
[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",
11 // that is, it prints out the names of symbols in a bitcode file,
12 // along with some information about each symbol.
13 //
14 // This "nm" does not print symbols' addresses. It supports many of
15 // the features of GNU "nm", including its different output formats.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/LLVMContext.h"
20 #include "llvm/Module.h"
21 #include "llvm/Bitcode/ReaderWriter.h"
22 #include "llvm/Bitcode/Archive.h"
23 #include "llvm/Object/Archive.h"
24 #include "llvm/Object/ObjectFile.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/PrettyStackTrace.h"
30 #include "llvm/Support/Program.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Support/Signals.h"
33 #include "llvm/Support/Format.h"
34 #include "llvm/Support/system_error.h"
35 #include <algorithm>
36 #include <cctype>
37 #include <cerrno>
38 #include <cstring>
39 #include <vector>
40 using namespace llvm;
41 using namespace object;
42
43 namespace {
44   enum OutputFormatTy { bsd, sysv, posix };
45   cl::opt<OutputFormatTy>
46   OutputFormat("format",
47        cl::desc("Specify output format"),
48          cl::values(clEnumVal(bsd,   "BSD format"),
49                     clEnumVal(sysv,  "System V format"),
50                     clEnumVal(posix, "POSIX.2 format"),
51                     clEnumValEnd), cl::init(bsd));
52   cl::alias OutputFormat2("f", cl::desc("Alias for --format"),
53                           cl::aliasopt(OutputFormat));
54
55   cl::list<std::string>
56   InputFilenames(cl::Positional, cl::desc("<input bitcode files>"),
57                  cl::ZeroOrMore);
58
59   cl::opt<bool> UndefinedOnly("undefined-only",
60                               cl::desc("Show only undefined symbols"));
61   cl::alias UndefinedOnly2("u", cl::desc("Alias for --undefined-only"),
62                            cl::aliasopt(UndefinedOnly));
63
64   cl::opt<bool> DynamicSyms("dynamic",
65                              cl::desc("Display the dynamic symbols instead "
66                                       "of normal symbols."));
67   cl::alias DynamicSyms2("D", cl::desc("Alias for --dynamic"),
68                          cl::aliasopt(DynamicSyms));
69
70   cl::opt<bool> DefinedOnly("defined-only",
71                             cl::desc("Show only defined symbols"));
72
73   cl::opt<bool> ExternalOnly("extern-only",
74                              cl::desc("Show only external symbols"));
75   cl::alias ExternalOnly2("g", cl::desc("Alias for --extern-only"),
76                           cl::aliasopt(ExternalOnly));
77
78   cl::opt<bool> BSDFormat("B", cl::desc("Alias for --format=bsd"));
79   cl::opt<bool> POSIXFormat("P", cl::desc("Alias for --format=posix"));
80
81   cl::opt<bool> PrintFileName("print-file-name",
82     cl::desc("Precede each symbol with the object file it came from"));
83
84   cl::alias PrintFileNameA("A", cl::desc("Alias for --print-file-name"),
85                                 cl::aliasopt(PrintFileName));
86   cl::alias PrintFileNameo("o", cl::desc("Alias for --print-file-name"),
87                                 cl::aliasopt(PrintFileName));
88
89   cl::opt<bool> DebugSyms("debug-syms",
90     cl::desc("Show all symbols, even debugger only"));
91   cl::alias DebugSymsa("a", cl::desc("Alias for --debug-syms"),
92                             cl::aliasopt(DebugSyms));
93
94   cl::opt<bool> NumericSort("numeric-sort",
95     cl::desc("Sort symbols by address"));
96   cl::alias NumericSortn("n", cl::desc("Alias for --numeric-sort"),
97                               cl::aliasopt(NumericSort));
98   cl::alias NumericSortv("v", cl::desc("Alias for --numeric-sort"),
99                               cl::aliasopt(NumericSort));
100
101   cl::opt<bool> NoSort("no-sort",
102     cl::desc("Show symbols in order encountered"));
103   cl::alias NoSortp("p", cl::desc("Alias for --no-sort"),
104                          cl::aliasopt(NoSort));
105
106   cl::opt<bool> PrintSize("print-size",
107     cl::desc("Show symbol size instead of address"));
108   cl::alias PrintSizeS("S", cl::desc("Alias for --print-size"),
109                             cl::aliasopt(PrintSize));
110
111   cl::opt<bool> SizeSort("size-sort", cl::desc("Sort symbols by size"));
112
113   bool PrintAddress = true;
114
115   bool MultipleFiles = false;
116
117   std::string ToolName;
118 }
119
120
121 static void error(Twine message, Twine path = Twine()) {
122   errs() << ToolName << ": " << path << ": " << message << ".\n";
123 }
124
125 static bool error(error_code ec, Twine path = Twine()) {
126   if (ec) {
127     error(ec.message(), path);
128     return true;
129   }
130   return false;
131 }
132
133 namespace {
134   struct NMSymbol {
135     uint64_t  Address;
136     uint64_t  Size;
137     char      TypeChar;
138     StringRef Name;
139   };
140
141   static bool CompareSymbolAddress(const NMSymbol &a, const NMSymbol &b) {
142     if (a.Address < b.Address)
143       return true;
144     else if (a.Address == b.Address && a.Name < b.Name)
145       return true;
146     else
147       return false;
148
149   }
150
151   static bool CompareSymbolSize(const NMSymbol &a, const NMSymbol &b) {
152     if (a.Size < b.Size)
153       return true;
154     else if (a.Size == b.Size && a.Name < b.Name)
155       return true;
156     else
157       return false;
158   }
159
160   static bool CompareSymbolName(const NMSymbol &a, const NMSymbol &b) {
161     return a.Name < b.Name;
162   }
163
164   StringRef CurrentFilename;
165   typedef std::vector<NMSymbol> SymbolListT;
166   SymbolListT SymbolList;
167 }
168
169 static void SortAndPrintSymbolList() {
170   if (!NoSort) {
171     if (NumericSort)
172       std::sort(SymbolList.begin(), SymbolList.end(), CompareSymbolAddress);
173     else if (SizeSort)
174       std::sort(SymbolList.begin(), SymbolList.end(), CompareSymbolSize);
175     else
176       std::sort(SymbolList.begin(), SymbolList.end(), CompareSymbolName);
177   }
178
179   if (OutputFormat == posix && MultipleFiles) {
180     outs() << '\n' << CurrentFilename << ":\n";
181   } else if (OutputFormat == bsd && MultipleFiles) {
182     outs() << "\n" << CurrentFilename << ":\n";
183   } else if (OutputFormat == sysv) {
184     outs() << "\n\nSymbols from " << CurrentFilename << ":\n\n"
185            << "Name                  Value   Class        Type"
186            << "         Size   Line  Section\n";
187   }
188
189   for (SymbolListT::iterator i = SymbolList.begin(),
190                              e = SymbolList.end(); i != e; ++i) {
191     if ((i->TypeChar != 'U') && UndefinedOnly)
192       continue;
193     if ((i->TypeChar == 'U') && DefinedOnly)
194       continue;
195     if (SizeSort && !PrintAddress && i->Size == UnknownAddressOrSize)
196       continue;
197
198     char SymbolAddrStr[10] = "";
199     char SymbolSizeStr[10] = "";
200
201     if (OutputFormat == sysv || i->Address == object::UnknownAddressOrSize)
202       strcpy(SymbolAddrStr, "        ");
203     if (OutputFormat == sysv)
204       strcpy(SymbolSizeStr, "        ");
205
206     if (i->Address != object::UnknownAddressOrSize)
207       format("%08"PRIx64, i->Address).print(SymbolAddrStr, sizeof(SymbolAddrStr));
208     if (i->Size != object::UnknownAddressOrSize)
209       format("%08"PRIx64, i->Size).print(SymbolSizeStr, sizeof(SymbolSizeStr));
210
211     if (OutputFormat == posix) {
212       outs() << i->Name << " " << i->TypeChar << " "
213              << SymbolAddrStr << SymbolSizeStr << "\n";
214     } else if (OutputFormat == bsd) {
215       if (PrintAddress)
216         outs() << SymbolAddrStr << ' ';
217       if (PrintSize) {
218         outs() << SymbolSizeStr;
219         if (i->Size != object::UnknownAddressOrSize)
220           outs() << ' ';
221       }
222       outs() << i->TypeChar << " " << i->Name  << "\n";
223     } else if (OutputFormat == sysv) {
224       std::string PaddedName (i->Name);
225       while (PaddedName.length () < 20)
226         PaddedName += " ";
227       outs() << PaddedName << "|" << SymbolAddrStr << "|   "
228              << i->TypeChar
229              << "  |                  |" << SymbolSizeStr << "|     |\n";
230     }
231   }
232
233   SymbolList.clear();
234 }
235
236 static char TypeCharForSymbol(GlobalValue &GV) {
237   if (GV.isDeclaration())                                  return 'U';
238   if (GV.hasLinkOnceLinkage())                             return 'C';
239   if (GV.hasCommonLinkage())                               return 'C';
240   if (GV.hasWeakLinkage())                                 return 'W';
241   if (isa<Function>(GV) && GV.hasInternalLinkage())        return 't';
242   if (isa<Function>(GV))                                   return 'T';
243   if (isa<GlobalVariable>(GV) && GV.hasInternalLinkage())  return 'd';
244   if (isa<GlobalVariable>(GV))                             return 'D';
245   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(&GV)) {
246     const GlobalValue *AliasedGV = GA->getAliasedGlobal();
247     if (isa<Function>(AliasedGV))                          return 'T';
248     if (isa<GlobalVariable>(AliasedGV))                    return 'D';
249   }
250                                                            return '?';
251 }
252
253 static void DumpSymbolNameForGlobalValue(GlobalValue &GV) {
254   // Private linkage and available_externally linkage don't exist in symtab.
255   if (GV.hasPrivateLinkage() ||
256       GV.hasLinkerPrivateLinkage() ||
257       GV.hasLinkerPrivateWeakLinkage() ||
258       GV.hasLinkerPrivateWeakDefAutoLinkage() ||
259       GV.hasAvailableExternallyLinkage())
260     return;
261   char TypeChar = TypeCharForSymbol(GV);
262   if (GV.hasLocalLinkage () && ExternalOnly)
263     return;
264
265   NMSymbol s;
266   s.Address = object::UnknownAddressOrSize;
267   s.Size = object::UnknownAddressOrSize;
268   s.TypeChar = TypeChar;
269   s.Name     = GV.getName();
270   SymbolList.push_back(s);
271 }
272
273 static void DumpSymbolNamesFromModule(Module *M) {
274   CurrentFilename = M->getModuleIdentifier();
275   std::for_each (M->begin(), M->end(), DumpSymbolNameForGlobalValue);
276   std::for_each (M->global_begin(), M->global_end(),
277                  DumpSymbolNameForGlobalValue);
278   std::for_each (M->alias_begin(), M->alias_end(),
279                  DumpSymbolNameForGlobalValue);
280
281   SortAndPrintSymbolList();
282 }
283
284 static void DumpSymbolNamesFromObject(ObjectFile *obj) {
285   error_code ec;
286   symbol_iterator ibegin = obj->begin_symbols();
287   symbol_iterator iend = obj->end_symbols();
288   if (DynamicSyms) {
289     ibegin = obj->begin_dynamic_symbols();
290     iend = obj->end_dynamic_symbols();
291   }
292   for (symbol_iterator i = ibegin; i != iend; i.increment(ec)) {
293     if (error(ec)) break;
294     bool internal;
295     if (error(i->isInternal(internal))) break;
296     if (!DebugSyms && internal)
297       continue;
298     NMSymbol s;
299     s.Size = object::UnknownAddressOrSize;
300     s.Address = object::UnknownAddressOrSize;
301     if (PrintSize || SizeSort) {
302       if (error(i->getSize(s.Size))) break;
303     }
304     if (PrintAddress)
305       if (error(i->getAddress(s.Address))) break;
306     if (error(i->getNMTypeChar(s.TypeChar))) break;
307     if (error(i->getName(s.Name))) break;
308     SymbolList.push_back(s);
309   }
310
311   CurrentFilename = obj->getFileName();
312   SortAndPrintSymbolList();
313 }
314
315 static void DumpSymbolNamesFromFile(std::string &Filename) {
316   if (Filename != "-" && !sys::fs::exists(Filename)) {
317     errs() << ToolName << ": '" << Filename << "': " << "No such file\n";
318     return;
319   }
320
321   OwningPtr<MemoryBuffer> Buffer;
322   if (error(MemoryBuffer::getFileOrSTDIN(Filename, Buffer), Filename))
323     return;
324
325   sys::fs::file_magic magic = sys::fs::identify_magic(Buffer->getBuffer());
326
327   LLVMContext &Context = getGlobalContext();
328   std::string ErrorMessage;
329   if (magic == sys::fs::file_magic::bitcode) {
330     Module *Result = 0;
331     Result = ParseBitcodeFile(Buffer.get(), Context, &ErrorMessage);
332     if (Result) {
333       DumpSymbolNamesFromModule(Result);
334       delete Result;
335     } else {
336       error(ErrorMessage, Filename);
337       return;
338     }
339   } else if (magic == sys::fs::file_magic::archive) {
340     OwningPtr<Binary> arch;
341     if (error(object::createBinary(Buffer.take(), arch), Filename))
342       return;
343
344     if (object::Archive *a = dyn_cast<object::Archive>(arch.get())) {
345       for (object::Archive::child_iterator i = a->begin_children(),
346                                            e = a->end_children(); i != e; ++i) {
347         OwningPtr<Binary> child;
348         if (i->getAsBinary(child)) {
349           // Try opening it as a bitcode file.
350           OwningPtr<MemoryBuffer> buff(i->getBuffer());
351           Module *Result = 0;
352           if (buff)
353             Result = ParseBitcodeFile(buff.get(), Context, &ErrorMessage);
354
355           if (Result) {
356             DumpSymbolNamesFromModule(Result);
357             delete Result;
358           }
359           continue;
360         }
361         if (object::ObjectFile *o = dyn_cast<ObjectFile>(child.get())) {
362           outs() << o->getFileName() << ":\n";
363           DumpSymbolNamesFromObject(o);
364         }
365       }
366     }
367   } else if (magic.is_object()) {
368     OwningPtr<Binary> obj;
369     if (error(object::createBinary(Buffer.take(), obj), Filename))
370       return;
371     if (object::ObjectFile *o = dyn_cast<ObjectFile>(obj.get()))
372       DumpSymbolNamesFromObject(o);
373   } else {
374     errs() << ToolName << ": " << Filename << ": "
375            << "unrecognizable file type\n";
376     return;
377   }
378 }
379
380 int main(int argc, char **argv) {
381   // Print a stack trace if we signal out.
382   sys::PrintStackTraceOnErrorSignal();
383   PrettyStackTraceProgram X(argc, argv);
384
385   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
386   cl::ParseCommandLineOptions(argc, argv, "llvm symbol table dumper\n");
387
388   // llvm-nm only reads binary files.
389   if (error(sys::Program::ChangeStdinToBinary()))
390     return 1;
391
392   ToolName = argv[0];
393   if (BSDFormat) OutputFormat = bsd;
394   if (POSIXFormat) OutputFormat = posix;
395
396   // The relative order of these is important. If you pass --size-sort it should
397   // only print out the size. However, if you pass -S --size-sort, it should
398   // print out both the size and address.
399   if (SizeSort && !PrintSize) PrintAddress = false;
400   if (OutputFormat == sysv || SizeSort) PrintSize = true;
401
402   switch (InputFilenames.size()) {
403   case 0: InputFilenames.push_back("-");
404   case 1: break;
405   default: MultipleFiles = true;
406   }
407
408   std::for_each(InputFilenames.begin(), InputFilenames.end(),
409                 DumpSymbolNamesFromFile);
410   return 0;
411 }