add bitcode reading support to llvm-nm
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 bytecode 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/Bytecode/Reader.h"
22 #include "llvm/Bytecode/Archive.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/MemoryBuffer.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 cl::opt<bool> Bitcode("bitcode");
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 bytecode 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.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                                                             return '?';
82 }
83
84 static void DumpSymbolNameForGlobalValue(GlobalValue &GV) {
85   const std::string SymbolAddrStr = "        "; // Not used yet...
86   char TypeChar = TypeCharForSymbol (GV);
87   if ((TypeChar != 'U') && UndefinedOnly)
88     return;
89   if ((TypeChar == 'U') && DefinedOnly)
90     return;
91   if (GV.hasInternalLinkage () && ExternalOnly)
92     return;
93   if (OutputFormat == posix) {
94     std::cout << GV.getName () << " " << TypeCharForSymbol (GV) << " "
95               << SymbolAddrStr << "\n";
96   } else if (OutputFormat == bsd) {
97     std::cout << SymbolAddrStr << " " << TypeCharForSymbol (GV) << " "
98               << GV.getName () << "\n";
99   } else if (OutputFormat == sysv) {
100     std::string PaddedName (GV.getName ());
101     while (PaddedName.length () < 20)
102       PaddedName += " ";
103     std::cout << PaddedName << "|" << SymbolAddrStr << "|   "
104               << TypeCharForSymbol (GV)
105               << "  |                  |      |     |\n";
106   }
107 }
108
109 static void DumpSymbolNamesFromModule(Module *M) {
110   const std::string &Filename = M->getModuleIdentifier ();
111   if (OutputFormat == posix && MultipleFiles) {
112     std::cout << Filename << ":\n";
113   } else if (OutputFormat == bsd && MultipleFiles) {
114     std::cout << "\n" << Filename << ":\n";
115   } else if (OutputFormat == sysv) {
116     std::cout << "\n\nSymbols from " << Filename << ":\n\n"
117               << "Name                  Value   Class        Type"
118               << "         Size   Line  Section\n";
119   }
120   std::for_each (M->begin (), M->end (), DumpSymbolNameForGlobalValue);
121   std::for_each (M->global_begin (), M->global_end (), DumpSymbolNameForGlobalValue);
122 }
123
124 static void DumpSymbolNamesFromFile(std::string &Filename) {
125   std::string ErrorMessage;
126   sys::Path aPath(Filename);
127   // Note: Currently we do not support reading an archive from stdin.
128   if (Filename == "-" || aPath.isBytecodeFile()) {
129     Module *Result = ParseBytecodeFile(Filename,
130                                        Compressor::decompressToNewBuffer,
131                                        &ErrorMessage);
132     if (Result) {
133       DumpSymbolNamesFromModule (Result);
134     } else {
135       std::cerr << ToolName << ": " << Filename << ": " << ErrorMessage << "\n";
136       return;
137     }
138   } else if (aPath.isBitcodeFile()) {
139     std::auto_ptr<MemoryBuffer> Buffer(
140                    MemoryBuffer::getFileOrSTDIN(&Filename[0], Filename.size()));
141     Module *Result = 0;
142     if (Buffer.get())
143       Result = ParseBitcodeFile(Buffer.get(), &ErrorMessage);
144     
145     if (Result)
146       DumpSymbolNamesFromModule(Result);
147     else {
148       std::cerr << ToolName << ": " << Filename << ": " << ErrorMessage << "\n";
149       return;
150     }
151     
152   } else if (aPath.isArchive()) {
153     std::string ErrMsg;
154     Archive* archive = Archive::OpenAndLoad(sys::Path(Filename), &ErrorMessage);
155     if (!archive)
156       std::cerr << ToolName << ": " << Filename << ": " << ErrorMessage << "\n";
157     std::vector<Module *> Modules;
158     if (archive->getAllModules(Modules, &ErrorMessage)) {
159       std::cerr << ToolName << ": " << Filename << ": " << ErrorMessage << "\n";
160       return;
161     }
162     MultipleFiles = true;
163     std::for_each (Modules.begin(), Modules.end(), DumpSymbolNamesFromModule);
164   } else {
165     std::cerr << ToolName << ": " << Filename << ": "
166               << "unrecognizable file type\n";
167     return;
168   }
169 }
170
171 int main(int argc, char **argv) {
172   llvm_shutdown_obj X;  // Call llvm_shutdown() on exit.
173   cl::ParseCommandLineOptions(argc, argv, " llvm symbol table dumper\n");
174   sys::PrintStackTraceOnErrorSignal();
175
176   ToolName = argv[0];
177   if (BSDFormat) OutputFormat = bsd;
178   if (POSIXFormat) OutputFormat = posix;
179
180   switch (InputFilenames.size()) {
181   case 0: InputFilenames.push_back("-");
182   case 1: break;
183   default: MultipleFiles = true;
184   }
185
186   std::for_each(InputFilenames.begin(), InputFilenames.end(),
187                 DumpSymbolNamesFromFile);
188   return 0;
189 }