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