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