1 //===-- llvm-nm.cpp - Symbol table dumping utility for llvm ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This program is a utility that works like traditional Unix "nm", that is, it
11 // prints out the names of symbols in a bitcode or object file, along with some
12 // information about each symbol.
14 // This "nm" supports many of the features of GNU "nm", including its different
17 //===----------------------------------------------------------------------===//
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Object/Archive.h"
23 #include "llvm/Object/MachOUniversal.h"
24 #include "llvm/Object/ObjectFile.h"
25 #include "llvm/PassManager.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/Format.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/PrettyStackTrace.h"
32 #include "llvm/Support/Program.h"
33 #include "llvm/Support/Signals.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Support/system_error.h"
42 using namespace object;
45 enum OutputFormatTy { bsd, sysv, posix };
46 cl::opt<OutputFormatTy>
47 OutputFormat("format",
48 cl::desc("Specify output format"),
49 cl::values(clEnumVal(bsd, "BSD format"),
50 clEnumVal(sysv, "System V format"),
51 clEnumVal(posix, "POSIX.2 format"),
52 clEnumValEnd), cl::init(bsd));
53 cl::alias OutputFormat2("f", cl::desc("Alias for --format"),
54 cl::aliasopt(OutputFormat));
57 InputFilenames(cl::Positional, cl::desc("<input bitcode files>"),
60 cl::opt<bool> UndefinedOnly("undefined-only",
61 cl::desc("Show only undefined symbols"));
62 cl::alias UndefinedOnly2("u", cl::desc("Alias for --undefined-only"),
63 cl::aliasopt(UndefinedOnly));
65 cl::opt<bool> DynamicSyms("dynamic",
66 cl::desc("Display the dynamic symbols instead "
67 "of normal symbols."));
68 cl::alias DynamicSyms2("D", cl::desc("Alias for --dynamic"),
69 cl::aliasopt(DynamicSyms));
71 cl::opt<bool> DefinedOnly("defined-only",
72 cl::desc("Show only defined symbols"));
74 cl::opt<bool> ExternalOnly("extern-only",
75 cl::desc("Show only external symbols"));
76 cl::alias ExternalOnly2("g", cl::desc("Alias for --extern-only"),
77 cl::aliasopt(ExternalOnly));
79 cl::opt<bool> BSDFormat("B", cl::desc("Alias for --format=bsd"));
80 cl::opt<bool> POSIXFormat("P", cl::desc("Alias for --format=posix"));
82 cl::opt<bool> PrintFileName("print-file-name",
83 cl::desc("Precede each symbol with the object file it came from"));
85 cl::alias PrintFileNameA("A", cl::desc("Alias for --print-file-name"),
86 cl::aliasopt(PrintFileName));
87 cl::alias PrintFileNameo("o", cl::desc("Alias for --print-file-name"),
88 cl::aliasopt(PrintFileName));
90 cl::opt<bool> DebugSyms("debug-syms",
91 cl::desc("Show all symbols, even debugger only"));
92 cl::alias DebugSymsa("a", cl::desc("Alias for --debug-syms"),
93 cl::aliasopt(DebugSyms));
95 cl::opt<bool> NumericSort("numeric-sort",
96 cl::desc("Sort symbols by address"));
97 cl::alias NumericSortn("n", cl::desc("Alias for --numeric-sort"),
98 cl::aliasopt(NumericSort));
99 cl::alias NumericSortv("v", cl::desc("Alias for --numeric-sort"),
100 cl::aliasopt(NumericSort));
102 cl::opt<bool> NoSort("no-sort",
103 cl::desc("Show symbols in order encountered"));
104 cl::alias NoSortp("p", cl::desc("Alias for --no-sort"),
105 cl::aliasopt(NoSort));
107 cl::opt<bool> PrintSize("print-size",
108 cl::desc("Show symbol size instead of address"));
109 cl::alias PrintSizeS("S", cl::desc("Alias for --print-size"),
110 cl::aliasopt(PrintSize));
112 cl::opt<bool> SizeSort("size-sort", cl::desc("Sort symbols by size"));
114 cl::opt<bool> WithoutAliases("without-aliases", cl::Hidden,
115 cl::desc("Exclude aliases from output"));
117 cl::opt<bool> ArchiveMap("print-armap",
118 cl::desc("Print the archive map"));
119 cl::alias ArchiveMaps("s", cl::desc("Alias for --print-armap"),
120 cl::aliasopt(ArchiveMap));
121 bool PrintAddress = true;
123 bool MultipleFiles = false;
125 bool HadError = false;
127 std::string ToolName;
131 static void error(Twine message, Twine path = Twine()) {
132 errs() << ToolName << ": " << path << ": " << message << ".\n";
135 static bool error(error_code ec, Twine path = Twine()) {
137 error(ec.message(), path);
152 static bool CompareSymbolAddress(const NMSymbol &a, const NMSymbol &b) {
153 if (a.Address < b.Address)
155 else if (a.Address == b.Address && a.Name < b.Name)
157 else if (a.Address == b.Address && a.Name == b.Name && a.Size < b.Size)
164 static bool CompareSymbolSize(const NMSymbol &a, const NMSymbol &b) {
167 else if (a.Size == b.Size && a.Name < b.Name)
169 else if (a.Size == b.Size && a.Name == b.Name && a.Address < b.Address)
175 static bool CompareSymbolName(const NMSymbol &a, const NMSymbol &b) {
178 else if (a.Name == b.Name && a.Size < b.Size)
180 else if (a.Name == b.Name && a.Size == b.Size && a.Address < b.Address)
186 StringRef CurrentFilename;
187 typedef std::vector<NMSymbol> SymbolListT;
188 SymbolListT SymbolList;
191 static void SortAndPrintSymbolList() {
194 std::sort(SymbolList.begin(), SymbolList.end(), CompareSymbolAddress);
196 std::sort(SymbolList.begin(), SymbolList.end(), CompareSymbolSize);
198 std::sort(SymbolList.begin(), SymbolList.end(), CompareSymbolName);
201 if (OutputFormat == posix && MultipleFiles) {
202 outs() << '\n' << CurrentFilename << ":\n";
203 } else if (OutputFormat == bsd && MultipleFiles) {
204 outs() << "\n" << CurrentFilename << ":\n";
205 } else if (OutputFormat == sysv) {
206 outs() << "\n\nSymbols from " << CurrentFilename << ":\n\n"
207 << "Name Value Class Type"
208 << " Size Line Section\n";
211 for (SymbolListT::iterator i = SymbolList.begin(),
212 e = SymbolList.end(); i != e; ++i) {
213 if ((i->TypeChar != 'U') && UndefinedOnly)
215 if ((i->TypeChar == 'U') && DefinedOnly)
217 if (SizeSort && !PrintAddress && i->Size == UnknownAddressOrSize)
220 char SymbolAddrStr[10] = "";
221 char SymbolSizeStr[10] = "";
223 if (OutputFormat == sysv || i->Address == object::UnknownAddressOrSize)
224 strcpy(SymbolAddrStr, " ");
225 if (OutputFormat == sysv)
226 strcpy(SymbolSizeStr, " ");
228 if (i->Address != object::UnknownAddressOrSize)
229 format("%08" PRIx64, i->Address).print(SymbolAddrStr,
230 sizeof(SymbolAddrStr));
231 if (i->Size != object::UnknownAddressOrSize)
232 format("%08" PRIx64, i->Size).print(SymbolSizeStr, sizeof(SymbolSizeStr));
234 if (OutputFormat == posix) {
235 outs() << i->Name << " " << i->TypeChar << " "
236 << SymbolAddrStr << SymbolSizeStr << "\n";
237 } else if (OutputFormat == bsd) {
239 outs() << SymbolAddrStr << ' ';
241 outs() << SymbolSizeStr;
242 if (i->Size != object::UnknownAddressOrSize)
245 outs() << i->TypeChar << " " << i->Name << "\n";
246 } else if (OutputFormat == sysv) {
247 std::string PaddedName (i->Name);
248 while (PaddedName.length () < 20)
250 outs() << PaddedName << "|" << SymbolAddrStr << "| "
252 << " | |" << SymbolSizeStr << "| |\n";
259 static char TypeCharForSymbol(GlobalValue &GV) {
260 if (GV.isDeclaration()) return 'U';
261 if (GV.hasLinkOnceLinkage()) return 'C';
262 if (GV.hasCommonLinkage()) return 'C';
263 if (GV.hasWeakLinkage()) return 'W';
264 if (isa<Function>(GV) && GV.hasInternalLinkage()) return 't';
265 if (isa<Function>(GV)) return 'T';
266 if (isa<GlobalVariable>(GV) && GV.hasInternalLinkage()) return 'd';
267 if (isa<GlobalVariable>(GV)) return 'D';
268 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(&GV)) {
269 const GlobalValue *AliasedGV = GA->getAliasedGlobal();
270 if (isa<Function>(AliasedGV)) return 'T';
271 if (isa<GlobalVariable>(AliasedGV)) return 'D';
276 static void DumpSymbolNameForGlobalValue(GlobalValue &GV) {
277 // Private linkage and available_externally linkage don't exist in symtab.
278 if (GV.hasPrivateLinkage() ||
279 GV.hasLinkerPrivateLinkage() ||
280 GV.hasLinkerPrivateWeakLinkage() ||
281 GV.hasAvailableExternallyLinkage())
283 char TypeChar = TypeCharForSymbol(GV);
284 if (GV.hasLocalLinkage () && ExternalOnly)
288 s.Address = object::UnknownAddressOrSize;
289 s.Size = object::UnknownAddressOrSize;
290 s.TypeChar = TypeChar;
291 s.Name = GV.getName();
292 SymbolList.push_back(s);
295 static void DumpSymbolNamesFromModule(Module *M) {
296 CurrentFilename = M->getModuleIdentifier();
297 std::for_each (M->begin(), M->end(), DumpSymbolNameForGlobalValue);
298 std::for_each (M->global_begin(), M->global_end(),
299 DumpSymbolNameForGlobalValue);
301 std::for_each (M->alias_begin(), M->alias_end(),
302 DumpSymbolNameForGlobalValue);
304 SortAndPrintSymbolList();
307 static void DumpSymbolNamesFromObject(ObjectFile *obj) {
309 symbol_iterator ibegin = obj->begin_symbols();
310 symbol_iterator iend = obj->end_symbols();
312 ibegin = obj->begin_dynamic_symbols();
313 iend = obj->end_dynamic_symbols();
315 for (symbol_iterator i = ibegin; i != iend; i.increment(ec)) {
316 if (error(ec)) break;
318 if (error(i->getFlags(symflags))) break;
319 if (!DebugSyms && (symflags & SymbolRef::SF_FormatSpecific))
322 s.Size = object::UnknownAddressOrSize;
323 s.Address = object::UnknownAddressOrSize;
324 if (PrintSize || SizeSort) {
325 if (error(i->getSize(s.Size))) break;
328 if (error(i->getAddress(s.Address))) break;
329 if (error(i->getNMTypeChar(s.TypeChar))) break;
330 if (error(i->getName(s.Name))) break;
331 SymbolList.push_back(s);
334 CurrentFilename = obj->getFileName();
335 SortAndPrintSymbolList();
338 static void DumpSymbolNamesFromFile(std::string &Filename) {
339 if (Filename != "-" && !sys::fs::exists(Filename)) {
340 errs() << ToolName << ": '" << Filename << "': " << "No such file\n";
344 OwningPtr<MemoryBuffer> Buffer;
345 if (error(MemoryBuffer::getFileOrSTDIN(Filename, Buffer), Filename))
348 sys::fs::file_magic magic = sys::fs::identify_magic(Buffer->getBuffer());
350 LLVMContext &Context = getGlobalContext();
351 std::string ErrorMessage;
352 if (magic == sys::fs::file_magic::bitcode) {
354 Result = ParseBitcodeFile(Buffer.get(), Context, &ErrorMessage);
356 DumpSymbolNamesFromModule(Result);
359 error(ErrorMessage, Filename);
362 } else if (magic == sys::fs::file_magic::archive) {
363 OwningPtr<Binary> arch;
364 if (error(object::createBinary(Buffer.take(), arch), Filename))
367 if (object::Archive *a = dyn_cast<object::Archive>(arch.get())) {
369 object::Archive::symbol_iterator I = a->begin_symbols();
370 object::Archive::symbol_iterator E = a->end_symbols();
372 outs() << "Archive map" << "\n";
373 for (; I != E; ++I) {
374 object::Archive::child_iterator c;
377 if (error(I->getMember(c)))
379 if (error(I->getName(symname)))
381 if (error(c->getName(filename)))
383 outs() << symname << " in " << filename << "\n";
389 for (object::Archive::child_iterator i = a->begin_children(),
390 e = a->end_children(); i != e; ++i) {
391 OwningPtr<Binary> child;
392 if (i->getAsBinary(child)) {
393 // Try opening it as a bitcode file.
394 OwningPtr<MemoryBuffer> buff;
395 if (error(i->getMemoryBuffer(buff)))
399 Result = ParseBitcodeFile(buff.get(), Context, &ErrorMessage);
402 DumpSymbolNamesFromModule(Result);
407 if (object::ObjectFile *o = dyn_cast<ObjectFile>(child.get())) {
408 outs() << o->getFileName() << ":\n";
409 DumpSymbolNamesFromObject(o);
413 } else if (magic == sys::fs::file_magic::macho_universal_binary) {
414 OwningPtr<Binary> Bin;
415 if (error(object::createBinary(Buffer.take(), Bin), Filename))
418 object::MachOUniversalBinary *UB =
419 cast<object::MachOUniversalBinary>(Bin.get());
420 for (object::MachOUniversalBinary::object_iterator
421 I = UB->begin_objects(),
422 E = UB->end_objects();
424 OwningPtr<ObjectFile> Obj;
425 if (!I->getAsObjectFile(Obj)) {
426 outs() << Obj->getFileName() << ":\n";
427 DumpSymbolNamesFromObject(Obj.get());
430 } else if (magic.is_object()) {
431 OwningPtr<Binary> obj;
432 if (error(object::createBinary(Buffer.take(), obj), Filename))
434 if (object::ObjectFile *o = dyn_cast<ObjectFile>(obj.get()))
435 DumpSymbolNamesFromObject(o);
437 errs() << ToolName << ": " << Filename << ": "
438 << "unrecognizable file type\n";
444 int main(int argc, char **argv) {
445 // Print a stack trace if we signal out.
446 sys::PrintStackTraceOnErrorSignal();
447 PrettyStackTraceProgram X(argc, argv);
449 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
451 // Initialize PassManager for -time-passes support.
452 initializePassManager();
454 cl::ParseCommandLineOptions(argc, argv, "llvm symbol table dumper\n");
456 // llvm-nm only reads binary files.
457 if (error(sys::ChangeStdinToBinary()))
461 if (BSDFormat) OutputFormat = bsd;
462 if (POSIXFormat) OutputFormat = posix;
464 // The relative order of these is important. If you pass --size-sort it should
465 // only print out the size. However, if you pass -S --size-sort, it should
466 // print out both the size and address.
467 if (SizeSort && !PrintSize) PrintAddress = false;
468 if (OutputFormat == sysv || SizeSort) PrintSize = true;
470 switch (InputFilenames.size()) {
471 case 0: InputFilenames.push_back("-");
473 default: MultipleFiles = true;
476 std::for_each(InputFilenames.begin(), InputFilenames.end(),
477 DumpSymbolNamesFromFile);