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