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