give each Record a location.
[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/Module.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/Bitcode/Archive.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/PrettyStackTrace.h"
26 #include "llvm/System/Signals.h"
27 #include <algorithm>
28 #include <cctype>
29 #include <cerrno>
30 #include <cstring>
31 #include <iostream>
32 using namespace llvm;
33
34 namespace {
35   enum OutputFormatTy { bsd, sysv, posix };
36   cl::opt<OutputFormatTy>
37   OutputFormat("format",
38        cl::desc("Specify output format"),
39          cl::values(clEnumVal(bsd,   "BSD format"),
40                     clEnumVal(sysv,  "System V format"),
41                     clEnumVal(posix, "POSIX.2 format"),
42                     clEnumValEnd), cl::init(bsd));
43   cl::alias OutputFormat2("f", cl::desc("Alias for --format"),
44                           cl::aliasopt(OutputFormat));
45
46   cl::list<std::string>
47   InputFilenames(cl::Positional, cl::desc("<input bitcode files>"),
48                  cl::ZeroOrMore);
49
50   cl::opt<bool> UndefinedOnly("undefined-only",
51                               cl::desc("Show only undefined symbols"));
52   cl::alias UndefinedOnly2("u", cl::desc("Alias for --undefined-only"),
53                            cl::aliasopt(UndefinedOnly));
54
55   cl::opt<bool> DefinedOnly("defined-only",
56                             cl::desc("Show only defined symbols"));
57
58   cl::opt<bool> ExternalOnly("extern-only",
59                              cl::desc("Show only external symbols"));
60   cl::alias ExternalOnly2("g", cl::desc("Alias for --extern-only"),
61                           cl::aliasopt(ExternalOnly));
62
63   cl::opt<bool> BSDFormat("B", cl::desc("Alias for --format=bsd"));
64   cl::opt<bool> POSIXFormat("P", cl::desc("Alias for --format=posix"));
65
66   bool MultipleFiles = false;
67
68   std::string ToolName;
69 }
70
71 static char TypeCharForSymbol(GlobalValue &GV) {
72   /* FIXME: what to do with private linkage? */
73   if (GV.isDeclaration())                                  return 'U';
74   if (GV.hasLinkOnceLinkage())                             return 'C';
75   if (GV.hasCommonLinkage())                               return 'C';
76   if (GV.hasWeakLinkage())                                 return 'W';
77   if (isa<Function>(GV) && GV.hasInternalLinkage())        return 't';
78   if (isa<Function>(GV))                                   return 'T';
79   if (isa<GlobalVariable>(GV) && GV.hasInternalLinkage())  return 'd';
80   if (isa<GlobalVariable>(GV))                             return 'D';
81   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(&GV)) {
82     const GlobalValue *AliasedGV = GA->getAliasedGlobal();
83     if (isa<Function>(AliasedGV))                          return 'T';
84     if (isa<GlobalVariable>(AliasedGV))                    return 'D';
85   }
86                                                            return '?';
87 }
88
89 static void DumpSymbolNameForGlobalValue(GlobalValue &GV) {
90   const std::string SymbolAddrStr = "        "; // Not used yet...
91   char TypeChar = TypeCharForSymbol (GV);
92   if ((TypeChar != 'U') && UndefinedOnly)
93     return;
94   if ((TypeChar == 'U') && DefinedOnly)
95     return;
96   if (GV.hasLocalLinkage () && ExternalOnly)
97     return;
98   if (OutputFormat == posix) {
99     std::cout << GV.getName () << " " << TypeCharForSymbol (GV) << " "
100               << SymbolAddrStr << "\n";
101   } else if (OutputFormat == bsd) {
102     std::cout << SymbolAddrStr << " " << TypeCharForSymbol (GV) << " "
103               << GV.getName () << "\n";
104   } else if (OutputFormat == sysv) {
105     std::string PaddedName (GV.getName ());
106     while (PaddedName.length () < 20)
107       PaddedName += " ";
108     std::cout << PaddedName << "|" << SymbolAddrStr << "|   "
109               << TypeCharForSymbol (GV)
110               << "  |                  |      |     |\n";
111   }
112 }
113
114 static void DumpSymbolNamesFromModule(Module *M) {
115   const std::string &Filename = M->getModuleIdentifier ();
116   if (OutputFormat == posix && MultipleFiles) {
117     std::cout << Filename << ":\n";
118   } else if (OutputFormat == bsd && MultipleFiles) {
119     std::cout << "\n" << Filename << ":\n";
120   } else if (OutputFormat == sysv) {
121     std::cout << "\n\nSymbols from " << Filename << ":\n\n"
122               << "Name                  Value   Class        Type"
123               << "         Size   Line  Section\n";
124   }
125   std::for_each (M->begin (), M->end (), DumpSymbolNameForGlobalValue);
126   std::for_each (M->global_begin (), M->global_end (),
127                  DumpSymbolNameForGlobalValue);
128   std::for_each (M->alias_begin (), M->alias_end (),
129                  DumpSymbolNameForGlobalValue);
130 }
131
132 static void DumpSymbolNamesFromFile(std::string &Filename) {
133   std::string ErrorMessage;
134   sys::Path aPath(Filename);
135   // Note: Currently we do not support reading an archive from stdin.
136   if (Filename == "-" || aPath.isBitcodeFile()) {
137     std::auto_ptr<MemoryBuffer> Buffer(
138                    MemoryBuffer::getFileOrSTDIN(Filename, &ErrorMessage));
139     Module *Result = 0;
140     if (Buffer.get())
141       Result = ParseBitcodeFile(Buffer.get(), &ErrorMessage);
142     
143     if (Result)
144       DumpSymbolNamesFromModule(Result);
145     else {
146       std::cerr << ToolName << ": " << Filename << ": " << ErrorMessage << "\n";
147       return;
148     }
149     
150   } else if (aPath.isArchive()) {
151     std::string ErrMsg;
152     Archive* archive = Archive::OpenAndLoad(sys::Path(Filename), &ErrorMessage);
153     if (!archive)
154       std::cerr << ToolName << ": " << Filename << ": " << ErrorMessage << "\n";
155     std::vector<Module *> Modules;
156     if (archive->getAllModules(Modules, &ErrorMessage)) {
157       std::cerr << ToolName << ": " << Filename << ": " << ErrorMessage << "\n";
158       return;
159     }
160     MultipleFiles = true;
161     std::for_each (Modules.begin(), Modules.end(), DumpSymbolNamesFromModule);
162   } else {
163     std::cerr << ToolName << ": " << Filename << ": "
164               << "unrecognizable file type\n";
165     return;
166   }
167 }
168
169 int main(int argc, char **argv) {
170   // Print a stack trace if we signal out.
171   sys::PrintStackTraceOnErrorSignal();
172   PrettyStackTraceProgram X(argc, argv);
173   
174   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
175   cl::ParseCommandLineOptions(argc, argv, "llvm symbol table dumper\n");
176
177   ToolName = argv[0];
178   if (BSDFormat) OutputFormat = bsd;
179   if (POSIXFormat) OutputFormat = posix;
180
181   switch (InputFilenames.size()) {
182   case 0: InputFilenames.push_back("-");
183   case 1: break;
184   default: MultipleFiles = true;
185   }
186
187   std::for_each(InputFilenames.begin(), InputFilenames.end(),
188                 DumpSymbolNamesFromFile);
189   return 0;
190 }