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/Function.h"
20 #include "llvm/IR/GlobalAlias.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/Object/Archive.h"
24 #include "llvm/Object/COFF.h"
25 #include "llvm/Object/ELFObjectFile.h"
26 #include "llvm/Object/IRObjectFile.h"
27 #include "llvm/Object/MachO.h"
28 #include "llvm/Object/MachOUniversal.h"
29 #include "llvm/Object/ObjectFile.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/FileSystem.h"
32 #include "llvm/Support/Format.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/PrettyStackTrace.h"
36 #include "llvm/Support/Program.h"
37 #include "llvm/Support/Signals.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Support/system_error.h"
46 using namespace object;
49 enum OutputFormatTy { bsd, sysv, posix };
50 cl::opt<OutputFormatTy> OutputFormat(
51 "format", cl::desc("Specify output format"),
52 cl::values(clEnumVal(bsd, "BSD format"), clEnumVal(sysv, "System V format"),
53 clEnumVal(posix, "POSIX.2 format"), clEnumValEnd),
55 cl::alias OutputFormat2("f", cl::desc("Alias for --format"),
56 cl::aliasopt(OutputFormat));
58 cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<input files>"),
61 cl::opt<bool> UndefinedOnly("undefined-only",
62 cl::desc("Show only undefined symbols"));
63 cl::alias UndefinedOnly2("u", cl::desc("Alias for --undefined-only"),
64 cl::aliasopt(UndefinedOnly));
66 cl::opt<bool> DynamicSyms("dynamic",
67 cl::desc("Display the dynamic symbols instead "
68 "of normal symbols."));
69 cl::alias DynamicSyms2("D", cl::desc("Alias for --dynamic"),
70 cl::aliasopt(DynamicSyms));
72 cl::opt<bool> DefinedOnly("defined-only",
73 cl::desc("Show only defined symbols"));
75 cl::opt<bool> ExternalOnly("extern-only",
76 cl::desc("Show only external symbols"));
77 cl::alias ExternalOnly2("g", cl::desc("Alias for --extern-only"),
78 cl::aliasopt(ExternalOnly));
80 cl::opt<bool> BSDFormat("B", cl::desc("Alias for --format=bsd"));
81 cl::opt<bool> POSIXFormat("P", cl::desc("Alias for --format=posix"));
83 cl::opt<bool> PrintFileName(
85 cl::desc("Precede each symbol with the object file it came from"));
87 cl::alias PrintFileNameA("A", cl::desc("Alias for --print-file-name"),
88 cl::aliasopt(PrintFileName));
89 cl::alias PrintFileNameo("o", cl::desc("Alias for --print-file-name"),
90 cl::aliasopt(PrintFileName));
92 cl::opt<bool> DebugSyms("debug-syms",
93 cl::desc("Show all symbols, even debugger only"));
94 cl::alias DebugSymsa("a", cl::desc("Alias for --debug-syms"),
95 cl::aliasopt(DebugSyms));
97 cl::opt<bool> NumericSort("numeric-sort", cl::desc("Sort symbols by address"));
98 cl::alias NumericSortn("n", cl::desc("Alias for --numeric-sort"),
99 cl::aliasopt(NumericSort));
100 cl::alias NumericSortv("v", cl::desc("Alias for --numeric-sort"),
101 cl::aliasopt(NumericSort));
103 cl::opt<bool> NoSort("no-sort", cl::desc("Show symbols in order encountered"));
104 cl::alias NoSortp("p", cl::desc("Alias for --no-sort"), cl::aliasopt(NoSort));
106 cl::opt<bool> PrintSize("print-size",
107 cl::desc("Show symbol size instead of address"));
108 cl::alias PrintSizeS("S", cl::desc("Alias for --print-size"),
109 cl::aliasopt(PrintSize));
111 cl::opt<bool> SizeSort("size-sort", cl::desc("Sort symbols by size"));
113 cl::opt<bool> WithoutAliases("without-aliases", cl::Hidden,
114 cl::desc("Exclude aliases from output"));
116 cl::opt<bool> ArchiveMap("print-armap", cl::desc("Print the archive map"));
117 cl::alias ArchiveMaps("s", cl::desc("Alias for --print-armap"),
118 cl::aliasopt(ArchiveMap));
119 bool PrintAddress = true;
121 bool MultipleFiles = false;
123 bool HadError = false;
125 std::string ToolName;
128 static void error(Twine Message, Twine Path = Twine()) {
130 errs() << ToolName << ": " << Path << ": " << Message << ".\n";
133 static bool error(error_code EC, Twine Path = Twine()) {
135 error(EC.message(), Path);
150 static bool compareSymbolAddress(const NMSymbol &A, const NMSymbol &B) {
151 if (A.Address < B.Address)
153 else if (A.Address == B.Address && A.Name < B.Name)
155 else if (A.Address == B.Address && A.Name == B.Name && A.Size < B.Size)
161 static bool compareSymbolSize(const NMSymbol &A, const NMSymbol &B) {
164 else if (A.Size == B.Size && A.Name < B.Name)
166 else if (A.Size == B.Size && A.Name == B.Name && A.Address < B.Address)
172 static bool compareSymbolName(const NMSymbol &A, const NMSymbol &B) {
175 else if (A.Name == B.Name && A.Size < B.Size)
177 else if (A.Name == B.Name && A.Size == B.Size && A.Address < B.Address)
183 static StringRef CurrentFilename;
184 typedef std::vector<NMSymbol> SymbolListT;
185 static SymbolListT SymbolList;
187 static void sortAndPrintSymbolList() {
190 std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolAddress);
192 std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolSize);
194 std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolName);
197 if (OutputFormat == posix && MultipleFiles) {
198 outs() << '\n' << CurrentFilename << ":\n";
199 } else if (OutputFormat == bsd && MultipleFiles) {
200 outs() << "\n" << CurrentFilename << ":\n";
201 } else if (OutputFormat == sysv) {
202 outs() << "\n\nSymbols from " << CurrentFilename << ":\n\n"
203 << "Name Value Class Type"
204 << " Size Line Section\n";
207 for (SymbolListT::iterator I = SymbolList.begin(), E = SymbolList.end();
209 if ((I->TypeChar != 'U') && UndefinedOnly)
211 if ((I->TypeChar == 'U') && DefinedOnly)
213 if (SizeSort && !PrintAddress && I->Size == UnknownAddressOrSize)
216 char SymbolAddrStr[10] = "";
217 char SymbolSizeStr[10] = "";
219 if (OutputFormat == sysv || I->Address == UnknownAddressOrSize)
220 strcpy(SymbolAddrStr, " ");
221 if (OutputFormat == sysv)
222 strcpy(SymbolSizeStr, " ");
224 if (I->Address != UnknownAddressOrSize)
225 format("%08" PRIx64, I->Address)
226 .print(SymbolAddrStr, sizeof(SymbolAddrStr));
227 if (I->Size != UnknownAddressOrSize)
228 format("%08" PRIx64, I->Size).print(SymbolSizeStr, sizeof(SymbolSizeStr));
230 if (OutputFormat == posix) {
231 outs() << I->Name << " " << I->TypeChar << " " << SymbolAddrStr
232 << SymbolSizeStr << "\n";
233 } else if (OutputFormat == bsd) {
235 outs() << SymbolAddrStr << ' ';
237 outs() << SymbolSizeStr;
238 if (I->Size != UnknownAddressOrSize)
241 outs() << I->TypeChar << " " << I->Name << "\n";
242 } else if (OutputFormat == sysv) {
243 std::string PaddedName(I->Name);
244 while (PaddedName.length() < 20)
246 outs() << PaddedName << "|" << SymbolAddrStr << "| " << I->TypeChar
247 << " | |" << SymbolSizeStr << "| |\n";
254 template <class ELFT>
255 static char getSymbolNMTypeChar(ELFObjectFile<ELFT> &Obj,
256 basic_symbol_iterator I) {
257 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
258 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
261 symbol_iterator SymI(I);
263 DataRefImpl Symb = I->getRawDataRefImpl();
264 const Elf_Sym *ESym = Obj.getSymbol(Symb);
265 const ELFFile<ELFT> &EF = *Obj.getELFFile();
266 const Elf_Shdr *ESec = EF.getSection(ESym);
269 switch (ESec->sh_type) {
270 case ELF::SHT_PROGBITS:
271 case ELF::SHT_DYNAMIC:
272 switch (ESec->sh_flags) {
273 case(ELF::SHF_ALLOC | ELF::SHF_EXECINSTR) :
275 case(ELF::SHF_TLS | ELF::SHF_ALLOC | ELF::SHF_WRITE) :
276 case(ELF::SHF_ALLOC | ELF::SHF_WRITE) :
279 case(ELF::SHF_ALLOC | ELF::SHF_MERGE) :
280 case(ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS) :
284 case ELF::SHT_NOBITS:
289 if (ESym->getType() == ELF::STT_SECTION) {
291 if (error(SymI->getName(Name)))
293 return StringSwitch<char>(Name)
294 .StartsWith(".debug", 'N')
295 .StartsWith(".note", 'n')
302 static char getSymbolNMTypeChar(COFFObjectFile &Obj, symbol_iterator I) {
303 const coff_symbol *Symb = Obj.getCOFFSymbol(I);
305 symbol_iterator SymI(I);
308 if (error(SymI->getName(Name)))
311 char Ret = StringSwitch<char>(Name)
312 .StartsWith(".debug", 'N')
313 .StartsWith(".sxdata", 'N')
319 uint32_t Characteristics = 0;
320 if (Symb->SectionNumber > 0) {
321 section_iterator SecI = Obj.section_end();
322 if (error(SymI->getSection(SecI)))
324 const coff_section *Section = Obj.getCOFFSection(SecI);
325 Characteristics = Section->Characteristics;
328 switch (Symb->SectionNumber) {
329 case COFF::IMAGE_SYM_DEBUG:
332 // Check section type.
333 if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
335 else if (Characteristics & COFF::IMAGE_SCN_MEM_READ &&
336 ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only.
338 else if (Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
340 else if (Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
342 else if (Characteristics & COFF::IMAGE_SCN_LNK_INFO)
345 // Check for section symbol.
346 else if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC &&
354 static uint8_t getNType(MachOObjectFile &Obj, DataRefImpl Symb) {
356 MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb);
359 MachO::nlist STE = Obj.getSymbolTableEntry(Symb);
363 static char getSymbolNMTypeChar(MachOObjectFile &Obj, basic_symbol_iterator I) {
364 DataRefImpl Symb = I->getRawDataRefImpl();
365 uint8_t NType = getNType(Obj, Symb);
367 switch (NType & MachO::N_TYPE) {
370 case MachO::N_SECT: {
371 section_iterator Sec = Obj.section_end();
372 Obj.getSymbolSection(Symb, Sec);
373 DataRefImpl Ref = Sec->getRawDataRefImpl();
374 StringRef SectionName;
375 Obj.getSectionName(Ref, SectionName);
376 StringRef SegmentName = Obj.getSectionFinalSegmentName(Ref);
377 if (SegmentName == "__TEXT" && SectionName == "__text")
387 static char getSymbolNMTypeChar(const GlobalValue &GV) {
388 if (isa<Function>(GV))
390 // FIXME: should we print 'b'? At the IR level we cannot be sure if this
391 // will be in bss or not, but we could approximate.
392 if (isa<GlobalVariable>(GV))
394 const GlobalAlias *GA = cast<GlobalAlias>(&GV);
395 const GlobalValue *AliasedGV = GA->getAliasedGlobal();
396 return getSymbolNMTypeChar(*AliasedGV);
399 static char getSymbolNMTypeChar(IRObjectFile &Obj, basic_symbol_iterator I) {
400 const GlobalValue &GV = Obj.getSymbolGV(I->getRawDataRefImpl());
401 return getSymbolNMTypeChar(GV);
404 template <class ELFT>
405 static bool isObject(ELFObjectFile<ELFT> &Obj, symbol_iterator I) {
406 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
408 DataRefImpl Symb = I->getRawDataRefImpl();
409 const Elf_Sym *ESym = Obj.getSymbol(Symb);
411 return ESym->getType() == ELF::STT_OBJECT;
414 static bool isObject(SymbolicFile *Obj, basic_symbol_iterator I) {
415 if (ELF32LEObjectFile *ELF = dyn_cast<ELF32LEObjectFile>(Obj))
416 return isObject(*ELF, I);
417 if (ELF64LEObjectFile *ELF = dyn_cast<ELF64LEObjectFile>(Obj))
418 return isObject(*ELF, I);
419 if (ELF32BEObjectFile *ELF = dyn_cast<ELF32BEObjectFile>(Obj))
420 return isObject(*ELF, I);
421 if (ELF64BEObjectFile *ELF = dyn_cast<ELF64BEObjectFile>(Obj))
422 return isObject(*ELF, I);
426 static char getNMTypeChar(SymbolicFile *Obj, basic_symbol_iterator I) {
427 uint32_t Symflags = I->getFlags();
428 if ((Symflags & object::SymbolRef::SF_Weak) && !isa<MachOObjectFile>(Obj)) {
429 char Ret = isObject(Obj, I) ? 'v' : 'w';
430 if (!(Symflags & object::SymbolRef::SF_Undefined))
435 if (Symflags & object::SymbolRef::SF_Undefined)
438 if (Symflags & object::SymbolRef::SF_Common)
442 if (Symflags & object::SymbolRef::SF_Absolute)
444 else if (IRObjectFile *IR = dyn_cast<IRObjectFile>(Obj))
445 Ret = getSymbolNMTypeChar(*IR, I);
446 else if (COFFObjectFile *COFF = dyn_cast<COFFObjectFile>(Obj))
447 Ret = getSymbolNMTypeChar(*COFF, I);
448 else if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Obj))
449 Ret = getSymbolNMTypeChar(*MachO, I);
450 else if (ELF32LEObjectFile *ELF = dyn_cast<ELF32LEObjectFile>(Obj))
451 Ret = getSymbolNMTypeChar(*ELF, I);
452 else if (ELF64LEObjectFile *ELF = dyn_cast<ELF64LEObjectFile>(Obj))
453 Ret = getSymbolNMTypeChar(*ELF, I);
454 else if (ELF32BEObjectFile *ELF = dyn_cast<ELF32BEObjectFile>(Obj))
455 Ret = getSymbolNMTypeChar(*ELF, I);
457 Ret = getSymbolNMTypeChar(*cast<ELF64BEObjectFile>(Obj), I);
459 if (Symflags & object::SymbolRef::SF_Global)
465 static void dumpSymbolNamesFromObject(SymbolicFile *Obj) {
466 basic_symbol_iterator IBegin = Obj->symbol_begin();
467 basic_symbol_iterator IEnd = Obj->symbol_end();
470 error("File format has no dynamic symbol table", Obj->getFileName());
473 std::pair<symbol_iterator, symbol_iterator> IDyn =
474 getELFDynamicSymbolIterators(Obj);
478 std::string NameBuffer;
479 raw_string_ostream OS(NameBuffer);
480 for (basic_symbol_iterator I = IBegin; I != IEnd; ++I) {
481 uint32_t SymFlags = I->getFlags();
482 if (!DebugSyms && (SymFlags & SymbolRef::SF_FormatSpecific))
484 if (WithoutAliases) {
485 if (IRObjectFile *IR = dyn_cast<IRObjectFile>(Obj)) {
486 const GlobalValue &GV = IR->getSymbolGV(I->getRawDataRefImpl());
487 if(isa<GlobalAlias>(GV))
492 S.Size = UnknownAddressOrSize;
493 S.Address = UnknownAddressOrSize;
494 if ((PrintSize || SizeSort) && isa<ObjectFile>(Obj)) {
495 symbol_iterator SymI = I;
496 if (error(SymI->getSize(S.Size)))
499 if (PrintAddress && isa<ObjectFile>(Obj))
500 if (error(symbol_iterator(I)->getAddress(S.Address)))
502 S.TypeChar = getNMTypeChar(Obj, I);
503 if (error(I->printName(OS)))
506 SymbolList.push_back(S);
510 const char *P = NameBuffer.c_str();
511 for (unsigned I = 0; I < SymbolList.size(); ++I) {
512 SymbolList[I].Name = P;
516 CurrentFilename = Obj->getFileName();
517 sortAndPrintSymbolList();
520 static void dumpSymbolNamesFromFile(std::string &Filename) {
521 std::unique_ptr<MemoryBuffer> Buffer;
522 if (error(MemoryBuffer::getFileOrSTDIN(Filename, Buffer), Filename))
525 LLVMContext &Context = getGlobalContext();
526 ErrorOr<Binary *> BinaryOrErr = createBinary(Buffer.release(), &Context);
527 if (error(BinaryOrErr.getError(), Filename))
529 std::unique_ptr<Binary> Bin(BinaryOrErr.get());
531 if (Archive *A = dyn_cast<Archive>(Bin.get())) {
533 Archive::symbol_iterator I = A->symbol_begin();
534 Archive::symbol_iterator E = A->symbol_end();
536 outs() << "Archive map\n";
537 for (; I != E; ++I) {
538 Archive::child_iterator C;
541 if (error(I->getMember(C)))
543 if (error(I->getName(SymName)))
545 if (error(C->getName(FileName)))
547 outs() << SymName << " in " << FileName << "\n";
553 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
555 std::unique_ptr<Binary> Child;
556 if (I->getAsBinary(Child, &Context))
558 if (SymbolicFile *O = dyn_cast<SymbolicFile>(Child.get())) {
559 outs() << O->getFileName() << ":\n";
560 dumpSymbolNamesFromObject(O);
565 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin.get())) {
566 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
567 E = UB->end_objects();
569 std::unique_ptr<ObjectFile> Obj;
570 if (!I->getAsObjectFile(Obj)) {
571 outs() << Obj->getFileName() << ":\n";
572 dumpSymbolNamesFromObject(Obj.get());
577 if (SymbolicFile *O = dyn_cast<SymbolicFile>(Bin.get())) {
578 dumpSymbolNamesFromObject(O);
581 error("unrecognizable file type", Filename);
585 int main(int argc, char **argv) {
586 // Print a stack trace if we signal out.
587 sys::PrintStackTraceOnErrorSignal();
588 PrettyStackTraceProgram X(argc, argv);
590 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
591 cl::ParseCommandLineOptions(argc, argv, "llvm symbol table dumper\n");
593 // llvm-nm only reads binary files.
594 if (error(sys::ChangeStdinToBinary()))
601 OutputFormat = posix;
603 // The relative order of these is important. If you pass --size-sort it should
604 // only print out the size. However, if you pass -S --size-sort, it should
605 // print out both the size and address.
606 if (SizeSort && !PrintSize)
607 PrintAddress = false;
608 if (OutputFormat == sysv || SizeSort)
611 switch (InputFilenames.size()) {
613 InputFilenames.push_back("-");
617 MultipleFiles = true;
620 std::for_each(InputFilenames.begin(), InputFilenames.end(),
621 dumpSymbolNamesFromFile);