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/COFF.h"
24 #include "llvm/Object/ELFObjectFile.h"
25 #include "llvm/Object/MachO.h"
26 #include "llvm/Object/MachOUniversal.h"
27 #include "llvm/Object/ObjectFile.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/FileSystem.h"
30 #include "llvm/Support/Format.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/PrettyStackTrace.h"
34 #include "llvm/Support/Program.h"
35 #include "llvm/Support/Signals.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Support/system_error.h"
44 using namespace object;
47 enum OutputFormatTy { bsd, sysv, posix };
48 cl::opt<OutputFormatTy> OutputFormat(
49 "format", cl::desc("Specify output format"),
50 cl::values(clEnumVal(bsd, "BSD format"), clEnumVal(sysv, "System V format"),
51 clEnumVal(posix, "POSIX.2 format"), clEnumValEnd),
53 cl::alias OutputFormat2("f", cl::desc("Alias for --format"),
54 cl::aliasopt(OutputFormat));
56 cl::list<std::string> InputFilenames(cl::Positional,
57 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(
84 cl::desc("Precede each symbol with the object file it came from"));
86 cl::alias PrintFileNameA("A", cl::desc("Alias for --print-file-name"),
87 cl::aliasopt(PrintFileName));
88 cl::alias PrintFileNameo("o", cl::desc("Alias for --print-file-name"),
89 cl::aliasopt(PrintFileName));
91 cl::opt<bool> DebugSyms("debug-syms",
92 cl::desc("Show all symbols, even debugger only"));
93 cl::alias DebugSymsa("a", cl::desc("Alias for --debug-syms"),
94 cl::aliasopt(DebugSyms));
96 cl::opt<bool> NumericSort("numeric-sort", 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", cl::desc("Show symbols in order encountered"));
103 cl::alias NoSortp("p", cl::desc("Alias for --no-sort"), cl::aliasopt(NoSort));
105 cl::opt<bool> PrintSize("print-size",
106 cl::desc("Show symbol size instead of address"));
107 cl::alias PrintSizeS("S", cl::desc("Alias for --print-size"),
108 cl::aliasopt(PrintSize));
110 cl::opt<bool> SizeSort("size-sort", cl::desc("Sort symbols by size"));
112 cl::opt<bool> WithoutAliases("without-aliases", cl::Hidden,
113 cl::desc("Exclude aliases from output"));
115 cl::opt<bool> ArchiveMap("print-armap", cl::desc("Print the archive map"));
116 cl::alias ArchiveMaps("s", cl::desc("Alias for --print-armap"),
117 cl::aliasopt(ArchiveMap));
118 bool PrintAddress = true;
120 bool MultipleFiles = false;
122 bool HadError = false;
124 std::string ToolName;
127 static void error(Twine Message, Twine Path = Twine()) {
129 errs() << ToolName << ": " << Path << ": " << Message << ".\n";
132 static bool error(error_code EC, Twine Path = Twine()) {
134 error(EC.message(), Path);
149 static bool compareSymbolAddress(const NMSymbol &A, const NMSymbol &B) {
150 if (A.Address < B.Address)
152 else if (A.Address == B.Address && A.Name < B.Name)
154 else if (A.Address == B.Address && A.Name == B.Name && A.Size < B.Size)
160 static bool compareSymbolSize(const NMSymbol &A, const NMSymbol &B) {
163 else if (A.Size == B.Size && A.Name < B.Name)
165 else if (A.Size == B.Size && A.Name == B.Name && A.Address < B.Address)
171 static bool compareSymbolName(const NMSymbol &A, const NMSymbol &B) {
174 else if (A.Name == B.Name && A.Size < B.Size)
176 else if (A.Name == B.Name && A.Size == B.Size && A.Address < B.Address)
182 static StringRef CurrentFilename;
183 typedef std::vector<NMSymbol> SymbolListT;
184 static SymbolListT SymbolList;
186 static void sortAndPrintSymbolList() {
189 std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolAddress);
191 std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolSize);
193 std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolName);
196 if (OutputFormat == posix && MultipleFiles) {
197 outs() << '\n' << CurrentFilename << ":\n";
198 } else if (OutputFormat == bsd && MultipleFiles) {
199 outs() << "\n" << CurrentFilename << ":\n";
200 } else if (OutputFormat == sysv) {
201 outs() << "\n\nSymbols from " << CurrentFilename << ":\n\n"
202 << "Name Value Class Type"
203 << " Size Line Section\n";
206 for (SymbolListT::iterator I = SymbolList.begin(), E = SymbolList.end();
208 if ((I->TypeChar != 'U') && UndefinedOnly)
210 if ((I->TypeChar == 'U') && DefinedOnly)
212 if (SizeSort && !PrintAddress && I->Size == UnknownAddressOrSize)
215 char SymbolAddrStr[10] = "";
216 char SymbolSizeStr[10] = "";
218 if (OutputFormat == sysv || I->Address == UnknownAddressOrSize)
219 strcpy(SymbolAddrStr, " ");
220 if (OutputFormat == sysv)
221 strcpy(SymbolSizeStr, " ");
223 if (I->Address != UnknownAddressOrSize)
224 format("%08" PRIx64, I->Address)
225 .print(SymbolAddrStr, sizeof(SymbolAddrStr));
226 if (I->Size != UnknownAddressOrSize)
227 format("%08" PRIx64, I->Size).print(SymbolSizeStr, sizeof(SymbolSizeStr));
229 if (OutputFormat == posix) {
230 outs() << I->Name << " " << I->TypeChar << " " << SymbolAddrStr
231 << SymbolSizeStr << "\n";
232 } else if (OutputFormat == bsd) {
234 outs() << SymbolAddrStr << ' ';
236 outs() << SymbolSizeStr;
237 if (I->Size != UnknownAddressOrSize)
240 outs() << I->TypeChar << " " << I->Name << "\n";
241 } else if (OutputFormat == sysv) {
242 std::string PaddedName(I->Name);
243 while (PaddedName.length() < 20)
245 outs() << PaddedName << "|" << SymbolAddrStr << "| " << I->TypeChar
246 << " | |" << SymbolSizeStr << "| |\n";
253 static char typeCharForSymbol(GlobalValue &GV) {
254 if (GV.isDeclaration())
256 if (GV.hasLinkOnceLinkage())
258 if (GV.hasCommonLinkage())
260 if (GV.hasWeakLinkage())
262 if (isa<Function>(GV) && GV.hasInternalLinkage())
264 if (isa<Function>(GV))
266 if (isa<GlobalVariable>(GV) && GV.hasInternalLinkage())
268 if (isa<GlobalVariable>(GV))
270 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(&GV)) {
271 const GlobalValue *AliasedGV = GA->getAliasedGlobal();
272 if (isa<Function>(AliasedGV))
274 if (isa<GlobalVariable>(AliasedGV))
280 static void dumpSymbolNameForGlobalValue(GlobalValue &GV) {
281 // Private linkage and available_externally linkage don't exist in symtab.
282 if (GV.hasPrivateLinkage() || GV.hasLinkerPrivateLinkage() ||
283 GV.hasLinkerPrivateWeakLinkage() || GV.hasAvailableExternallyLinkage())
285 char TypeChar = typeCharForSymbol(GV);
286 if (GV.hasLocalLinkage() && ExternalOnly)
290 S.Address = UnknownAddressOrSize;
291 S.Size = UnknownAddressOrSize;
292 S.TypeChar = TypeChar;
293 S.Name = GV.getName();
294 SymbolList.push_back(S);
297 static void dumpSymbolNamesFromModule(Module *M) {
298 CurrentFilename = M->getModuleIdentifier();
299 std::for_each(M->begin(), M->end(), dumpSymbolNameForGlobalValue);
300 std::for_each(M->global_begin(), M->global_end(),
301 dumpSymbolNameForGlobalValue);
303 std::for_each(M->alias_begin(), M->alias_end(),
304 dumpSymbolNameForGlobalValue);
306 sortAndPrintSymbolList();
309 template <class ELFT>
310 static error_code getSymbolNMTypeChar(ELFObjectFile<ELFT> &Obj,
311 symbol_iterator I, char &Result) {
312 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
313 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
315 DataRefImpl Symb = I->getRawDataRefImpl();
316 const Elf_Sym *ESym = Obj.getSymbol(Symb);
317 const ELFFile<ELFT> &EF = *Obj.getELFFile();
318 const Elf_Shdr *ESec = EF.getSection(ESym);
323 switch (ESec->sh_type) {
324 case ELF::SHT_PROGBITS:
325 case ELF::SHT_DYNAMIC:
326 switch (ESec->sh_flags) {
327 case(ELF::SHF_ALLOC | ELF::SHF_EXECINSTR) :
330 case(ELF::SHF_TLS | ELF::SHF_ALLOC | ELF::SHF_WRITE) :
331 case(ELF::SHF_ALLOC | ELF::SHF_WRITE) :
335 case(ELF::SHF_ALLOC | ELF::SHF_MERGE) :
336 case(ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS) :
341 case ELF::SHT_NOBITS:
346 switch (EF.getSymbolTableIndex(ESym)) {
354 case ELF::SHN_COMMON:
359 switch (ESym->getBinding()) {
360 case ELF::STB_GLOBAL:
361 Ret = ::toupper(Ret);
364 if (EF.getSymbolTableIndex(ESym) == ELF::SHN_UNDEF)
366 else if (ESym->getType() == ELF::STT_OBJECT)
372 if (Ret == '?' && ESym->getType() == ELF::STT_SECTION) {
374 error_code EC = I->getName(Name);
377 Result = StringSwitch<char>(Name)
378 .StartsWith(".debug", 'N')
379 .StartsWith(".note", 'n')
381 return object_error::success;
385 return object_error::success;
388 static error_code getSymbolNMTypeChar(COFFObjectFile &Obj, symbol_iterator I,
390 const coff_symbol *Symb = Obj.getCOFFSymbol(I);
392 if (error_code EC = I->getName(Name))
394 char Ret = StringSwitch<char>(Name)
395 .StartsWith(".debug", 'N')
396 .StartsWith(".sxdata", 'N')
401 return object_error::success;
404 uint32_t Characteristics = 0;
405 if (Symb->SectionNumber > 0) {
406 section_iterator SecI = Obj.end_sections();
407 if (error_code EC = I->getSection(SecI))
409 const coff_section *Section = Obj.getCOFFSection(SecI);
410 Characteristics = Section->Characteristics;
413 switch (Symb->SectionNumber) {
414 case COFF::IMAGE_SYM_UNDEFINED:
415 // Check storage classes.
416 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL) {
418 return object_error::success; // Don't do ::toupper.
419 } else if (Symb->Value != 0) // Check for common symbols.
424 case COFF::IMAGE_SYM_ABSOLUTE:
427 case COFF::IMAGE_SYM_DEBUG:
431 // Check section type.
432 if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
434 else if (Characteristics & COFF::IMAGE_SCN_MEM_READ &&
435 ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only.
437 else if (Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
439 else if (Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
441 else if (Characteristics & COFF::IMAGE_SCN_LNK_INFO)
444 // Check for section symbol.
445 else if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC &&
450 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL)
451 Ret = ::toupper(static_cast<unsigned char>(Ret));
454 return object_error::success;
457 static uint8_t getNType(MachOObjectFile &Obj, DataRefImpl Symb) {
459 MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb);
462 MachO::nlist STE = Obj.getSymbolTableEntry(Symb);
466 static error_code getSymbolNMTypeChar(MachOObjectFile &Obj, symbol_iterator I,
468 DataRefImpl Symb = I->getRawDataRefImpl();
469 uint8_t NType = getNType(Obj, Symb);
472 switch (NType & MachO::N_TYPE) {
479 case MachO::N_SECT: {
480 section_iterator Sec = Obj.end_sections();
481 Obj.getSymbolSection(Symb, Sec);
482 DataRefImpl Ref = Sec->getRawDataRefImpl();
483 StringRef SectionName;
484 Obj.getSectionName(Ref, SectionName);
485 StringRef SegmentName = Obj.getSectionFinalSegmentName(Ref);
486 if (SegmentName == "__TEXT" && SectionName == "__text")
496 if (NType & (MachO::N_EXT | MachO::N_PEXT))
497 Char = toupper(static_cast<unsigned char>(Char));
499 return object_error::success;
502 static char getNMTypeChar(ObjectFile *Obj, symbol_iterator I) {
504 if (COFFObjectFile *COFF = dyn_cast<COFFObjectFile>(Obj)) {
505 error(getSymbolNMTypeChar(*COFF, I, Res));
508 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Obj)) {
509 error(getSymbolNMTypeChar(*MachO, I, Res));
513 if (ELF32LEObjectFile *ELF = dyn_cast<ELF32LEObjectFile>(Obj)) {
514 error(getSymbolNMTypeChar(*ELF, I, Res));
517 if (ELF64LEObjectFile *ELF = dyn_cast<ELF64LEObjectFile>(Obj)) {
518 error(getSymbolNMTypeChar(*ELF, I, Res));
521 if (ELF32BEObjectFile *ELF = dyn_cast<ELF32BEObjectFile>(Obj)) {
522 error(getSymbolNMTypeChar(*ELF, I, Res));
525 ELF64BEObjectFile *ELF = cast<ELF64BEObjectFile>(Obj);
526 error(getSymbolNMTypeChar(*ELF, I, Res));
530 static void getDynamicSymbolIterators(ObjectFile *Obj, symbol_iterator &Begin,
531 symbol_iterator &End) {
532 if (ELF32LEObjectFile *ELF = dyn_cast<ELF32LEObjectFile>(Obj)) {
533 Begin = ELF->begin_dynamic_symbols();
534 End = ELF->end_dynamic_symbols();
537 if (ELF64LEObjectFile *ELF = dyn_cast<ELF64LEObjectFile>(Obj)) {
538 Begin = ELF->begin_dynamic_symbols();
539 End = ELF->end_dynamic_symbols();
542 if (ELF32BEObjectFile *ELF = dyn_cast<ELF32BEObjectFile>(Obj)) {
543 Begin = ELF->begin_dynamic_symbols();
544 End = ELF->end_dynamic_symbols();
547 ELF64BEObjectFile *ELF = cast<ELF64BEObjectFile>(Obj);
548 Begin = ELF->begin_dynamic_symbols();
549 End = ELF->end_dynamic_symbols();
553 static void dumpSymbolNamesFromObject(ObjectFile *Obj) {
554 symbol_iterator IBegin = Obj->begin_symbols();
555 symbol_iterator IEnd = Obj->end_symbols();
558 error("File format has no dynamic symbol table", Obj->getFileName());
561 getDynamicSymbolIterators(Obj, IBegin, IEnd);
563 for (symbol_iterator I = IBegin; I != IEnd; ++I) {
565 if (error(I->getFlags(SymFlags)))
567 if (!DebugSyms && (SymFlags & SymbolRef::SF_FormatSpecific))
570 S.Size = UnknownAddressOrSize;
571 S.Address = UnknownAddressOrSize;
572 if (PrintSize || SizeSort) {
573 if (error(I->getSize(S.Size)))
577 if (error(I->getAddress(S.Address)))
579 S.TypeChar = getNMTypeChar(Obj, I);
580 if (error(I->getName(S.Name)))
582 SymbolList.push_back(S);
585 CurrentFilename = Obj->getFileName();
586 sortAndPrintSymbolList();
589 static void dumpSymbolNamesFromFile(std::string &Filename) {
590 OwningPtr<MemoryBuffer> Buffer;
591 if (error(MemoryBuffer::getFileOrSTDIN(Filename, Buffer), Filename))
594 sys::fs::file_magic Magic = sys::fs::identify_magic(Buffer->getBuffer());
596 LLVMContext &Context = getGlobalContext();
597 if (Magic == sys::fs::file_magic::bitcode) {
598 ErrorOr<Module *> ModuleOrErr = parseBitcodeFile(Buffer.get(), Context);
599 if (error(ModuleOrErr.getError(), Filename)) {
602 Module *Result = ModuleOrErr.get();
603 dumpSymbolNamesFromModule(Result);
609 ErrorOr<Binary *> BinaryOrErr = createBinary(Buffer.take(), Magic);
610 if (error(BinaryOrErr.getError(), Filename))
612 OwningPtr<Binary> Bin(BinaryOrErr.get());
614 if (Archive *A = dyn_cast<Archive>(Bin.get())) {
616 Archive::symbol_iterator I = A->symbol_begin();
617 Archive::symbol_iterator E = A->symbol_end();
619 outs() << "Archive map\n";
620 for (; I != E; ++I) {
621 Archive::child_iterator C;
624 if (error(I->getMember(C)))
626 if (error(I->getName(SymName)))
628 if (error(C->getName(FileName)))
630 outs() << SymName << " in " << FileName << "\n";
636 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
638 OwningPtr<Binary> Child;
639 if (I->getAsBinary(Child)) {
640 // Try opening it as a bitcode file.
641 OwningPtr<MemoryBuffer> Buff;
642 if (error(I->getMemoryBuffer(Buff)))
645 ErrorOr<Module *> ModuleOrErr = parseBitcodeFile(Buff.get(), Context);
647 Module *Result = ModuleOrErr.get();
648 dumpSymbolNamesFromModule(Result);
653 if (ObjectFile *O = dyn_cast<ObjectFile>(Child.get())) {
654 outs() << O->getFileName() << ":\n";
655 dumpSymbolNamesFromObject(O);
660 if (MachOUniversalBinary *UB =
661 dyn_cast<object::MachOUniversalBinary>(Bin.get())) {
662 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
663 E = UB->end_objects();
665 OwningPtr<ObjectFile> Obj;
666 if (!I->getAsObjectFile(Obj)) {
667 outs() << Obj->getFileName() << ":\n";
668 dumpSymbolNamesFromObject(Obj.get());
673 if (ObjectFile *O = dyn_cast<ObjectFile>(Bin.get())) {
674 dumpSymbolNamesFromObject(O);
677 error("unrecognizable file type", Filename);
681 int main(int argc, char **argv) {
682 // Print a stack trace if we signal out.
683 sys::PrintStackTraceOnErrorSignal();
684 PrettyStackTraceProgram X(argc, argv);
686 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
687 cl::ParseCommandLineOptions(argc, argv, "llvm symbol table dumper\n");
689 // llvm-nm only reads binary files.
690 if (error(sys::ChangeStdinToBinary()))
697 OutputFormat = posix;
699 // The relative order of these is important. If you pass --size-sort it should
700 // only print out the size. However, if you pass -S --size-sort, it should
701 // print out both the size and address.
702 if (SizeSort && !PrintSize)
703 PrintAddress = false;
704 if (OutputFormat == sysv || SizeSort)
707 switch (InputFilenames.size()) {
709 InputFilenames.push_back("-");
713 MultipleFiles = true;
716 std::for_each(InputFilenames.begin(), InputFilenames.end(),
717 dumpSymbolNamesFromFile);