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/COFF.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/Format.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/Program.h"
38 #include "llvm/Support/Signals.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Support/system_error.h"
47 using namespace object;
50 enum OutputFormatTy { bsd, sysv, posix };
51 cl::opt<OutputFormatTy> OutputFormat(
52 "format", cl::desc("Specify output format"),
53 cl::values(clEnumVal(bsd, "BSD format"), clEnumVal(sysv, "System V format"),
54 clEnumVal(posix, "POSIX.2 format"), clEnumValEnd),
56 cl::alias OutputFormat2("f", cl::desc("Alias for --format"),
57 cl::aliasopt(OutputFormat));
59 cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<input files>"),
62 cl::opt<bool> UndefinedOnly("undefined-only",
63 cl::desc("Show only undefined symbols"));
64 cl::alias UndefinedOnly2("u", cl::desc("Alias for --undefined-only"),
65 cl::aliasopt(UndefinedOnly));
67 cl::opt<bool> DynamicSyms("dynamic",
68 cl::desc("Display the dynamic symbols instead "
69 "of normal symbols."));
70 cl::alias DynamicSyms2("D", cl::desc("Alias for --dynamic"),
71 cl::aliasopt(DynamicSyms));
73 cl::opt<bool> DefinedOnly("defined-only",
74 cl::desc("Show only defined symbols"));
76 cl::opt<bool> ExternalOnly("extern-only",
77 cl::desc("Show only external symbols"));
78 cl::alias ExternalOnly2("g", cl::desc("Alias for --extern-only"),
79 cl::aliasopt(ExternalOnly));
81 cl::opt<bool> BSDFormat("B", cl::desc("Alias for --format=bsd"));
82 cl::opt<bool> POSIXFormat("P", cl::desc("Alias for --format=posix"));
84 cl::opt<bool> PrintFileName(
86 cl::desc("Precede each symbol with the object file it came from"));
88 cl::alias PrintFileNameA("A", cl::desc("Alias for --print-file-name"),
89 cl::aliasopt(PrintFileName));
90 cl::alias PrintFileNameo("o", cl::desc("Alias for --print-file-name"),
91 cl::aliasopt(PrintFileName));
93 cl::opt<bool> DebugSyms("debug-syms",
94 cl::desc("Show all symbols, even debugger only"));
95 cl::alias DebugSymsa("a", cl::desc("Alias for --debug-syms"),
96 cl::aliasopt(DebugSyms));
98 cl::opt<bool> NumericSort("numeric-sort", cl::desc("Sort symbols by address"));
99 cl::alias NumericSortn("n", cl::desc("Alias for --numeric-sort"),
100 cl::aliasopt(NumericSort));
101 cl::alias NumericSortv("v", cl::desc("Alias for --numeric-sort"),
102 cl::aliasopt(NumericSort));
104 cl::opt<bool> NoSort("no-sort", cl::desc("Show symbols in order encountered"));
105 cl::alias NoSortp("p", cl::desc("Alias for --no-sort"), 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", cl::desc("Print the archive map"));
118 cl::alias ArchiveMaps("s", cl::desc("Alias for --print-armap"),
119 cl::aliasopt(ArchiveMap));
120 bool PrintAddress = true;
122 bool MultipleFiles = false;
124 bool HadError = false;
126 std::string ToolName;
129 static void error(Twine Message, Twine Path = Twine()) {
131 errs() << ToolName << ": " << Path << ": " << Message << ".\n";
134 static bool error(error_code EC, Twine Path = Twine()) {
136 error(EC.message(), Path);
151 static bool compareSymbolAddress(const NMSymbol &A, const NMSymbol &B) {
152 if (A.Address < B.Address)
154 else if (A.Address == B.Address && A.Name < B.Name)
156 else if (A.Address == B.Address && A.Name == B.Name && A.Size < B.Size)
162 static bool compareSymbolSize(const NMSymbol &A, const NMSymbol &B) {
165 else if (A.Size == B.Size && A.Name < B.Name)
167 else if (A.Size == B.Size && A.Name == B.Name && A.Address < B.Address)
173 static bool compareSymbolName(const NMSymbol &A, const NMSymbol &B) {
176 else if (A.Name == B.Name && A.Size < B.Size)
178 else if (A.Name == B.Name && A.Size == B.Size && A.Address < B.Address)
184 static StringRef CurrentFilename;
185 typedef std::vector<NMSymbol> SymbolListT;
186 static SymbolListT SymbolList;
188 static void sortAndPrintSymbolList() {
191 std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolAddress);
193 std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolSize);
195 std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolName);
198 if (OutputFormat == posix && MultipleFiles) {
199 outs() << '\n' << CurrentFilename << ":\n";
200 } else if (OutputFormat == bsd && MultipleFiles) {
201 outs() << "\n" << CurrentFilename << ":\n";
202 } else if (OutputFormat == sysv) {
203 outs() << "\n\nSymbols from " << CurrentFilename << ":\n\n"
204 << "Name Value Class Type"
205 << " Size Line Section\n";
208 for (SymbolListT::iterator I = SymbolList.begin(), E = SymbolList.end();
210 if ((I->TypeChar != 'U') && UndefinedOnly)
212 if ((I->TypeChar == 'U') && DefinedOnly)
214 if (SizeSort && !PrintAddress && I->Size == UnknownAddressOrSize)
217 char SymbolAddrStr[10] = "";
218 char SymbolSizeStr[10] = "";
220 if (OutputFormat == sysv || I->Address == UnknownAddressOrSize)
221 strcpy(SymbolAddrStr, " ");
222 if (OutputFormat == sysv)
223 strcpy(SymbolSizeStr, " ");
225 if (I->Address != UnknownAddressOrSize)
226 format("%08" PRIx64, I->Address)
227 .print(SymbolAddrStr, sizeof(SymbolAddrStr));
228 if (I->Size != UnknownAddressOrSize)
229 format("%08" PRIx64, I->Size).print(SymbolSizeStr, sizeof(SymbolSizeStr));
231 if (OutputFormat == posix) {
232 outs() << I->Name << " " << I->TypeChar << " " << SymbolAddrStr
233 << SymbolSizeStr << "\n";
234 } else if (OutputFormat == bsd) {
236 outs() << SymbolAddrStr << ' ';
238 outs() << SymbolSizeStr;
239 if (I->Size != UnknownAddressOrSize)
242 outs() << I->TypeChar << " " << I->Name << "\n";
243 } else if (OutputFormat == sysv) {
244 std::string PaddedName(I->Name);
245 while (PaddedName.length() < 20)
247 outs() << PaddedName << "|" << SymbolAddrStr << "| " << I->TypeChar
248 << " | |" << SymbolSizeStr << "| |\n";
255 template <class ELFT>
256 static char getSymbolNMTypeChar(ELFObjectFile<ELFT> &Obj,
257 basic_symbol_iterator I) {
258 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
259 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
262 symbol_iterator SymI(I);
264 DataRefImpl Symb = I->getRawDataRefImpl();
265 const Elf_Sym *ESym = Obj.getSymbol(Symb);
266 const ELFFile<ELFT> &EF = *Obj.getELFFile();
267 const Elf_Shdr *ESec = EF.getSection(ESym);
270 switch (ESec->sh_type) {
271 case ELF::SHT_PROGBITS:
272 case ELF::SHT_DYNAMIC:
273 switch (ESec->sh_flags) {
274 case(ELF::SHF_ALLOC | ELF::SHF_EXECINSTR) :
276 case(ELF::SHF_TLS | ELF::SHF_ALLOC | ELF::SHF_WRITE) :
277 case(ELF::SHF_ALLOC | ELF::SHF_WRITE) :
280 case(ELF::SHF_ALLOC | ELF::SHF_MERGE) :
281 case(ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS) :
285 case ELF::SHT_NOBITS:
290 if (ESym->getType() == ELF::STT_SECTION) {
292 if (error(SymI->getName(Name)))
294 return StringSwitch<char>(Name)
295 .StartsWith(".debug", 'N')
296 .StartsWith(".note", 'n')
303 static char getSymbolNMTypeChar(COFFObjectFile &Obj, symbol_iterator I) {
304 const coff_symbol *Symb = Obj.getCOFFSymbol(*I);
306 symbol_iterator SymI(I);
309 if (error(SymI->getName(Name)))
312 char Ret = StringSwitch<char>(Name)
313 .StartsWith(".debug", 'N')
314 .StartsWith(".sxdata", 'N')
320 uint32_t Characteristics = 0;
321 if (!COFF::isReservedSectionNumber(Symb->SectionNumber)) {
322 section_iterator SecI = Obj.section_end();
323 if (error(SymI->getSection(SecI)))
325 const coff_section *Section = Obj.getCOFFSection(*SecI);
326 Characteristics = Section->Characteristics;
329 switch (Symb->SectionNumber) {
330 case COFF::IMAGE_SYM_DEBUG:
333 // Check section type.
334 if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
336 else if (Characteristics & COFF::IMAGE_SCN_MEM_READ &&
337 ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only.
339 else if (Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
341 else if (Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
343 else if (Characteristics & COFF::IMAGE_SCN_LNK_INFO)
346 // Check for section symbol.
347 else if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC &&
355 static uint8_t getNType(MachOObjectFile &Obj, DataRefImpl Symb) {
357 MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb);
360 MachO::nlist STE = Obj.getSymbolTableEntry(Symb);
364 static char getSymbolNMTypeChar(MachOObjectFile &Obj, basic_symbol_iterator I) {
365 DataRefImpl Symb = I->getRawDataRefImpl();
366 uint8_t NType = getNType(Obj, Symb);
368 switch (NType & MachO::N_TYPE) {
371 case MachO::N_SECT: {
372 section_iterator Sec = Obj.section_end();
373 Obj.getSymbolSection(Symb, Sec);
374 DataRefImpl Ref = Sec->getRawDataRefImpl();
375 StringRef SectionName;
376 Obj.getSectionName(Ref, SectionName);
377 StringRef SegmentName = Obj.getSectionFinalSegmentName(Ref);
378 if (SegmentName == "__TEXT" && SectionName == "__text")
388 static char getSymbolNMTypeChar(const GlobalValue &GV) {
389 if (isa<Function>(GV))
391 // FIXME: should we print 'b'? At the IR level we cannot be sure if this
392 // will be in bss or not, but we could approximate.
393 if (isa<GlobalVariable>(GV))
395 const GlobalAlias *GA = cast<GlobalAlias>(&GV);
396 const GlobalValue *AliasedGV = GA->getAliasedGlobal();
397 return getSymbolNMTypeChar(*AliasedGV);
400 static char getSymbolNMTypeChar(IRObjectFile &Obj, basic_symbol_iterator I) {
401 const GlobalValue &GV = Obj.getSymbolGV(I->getRawDataRefImpl());
402 return getSymbolNMTypeChar(GV);
405 template <class ELFT>
406 static bool isObject(ELFObjectFile<ELFT> &Obj, symbol_iterator I) {
407 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
409 DataRefImpl Symb = I->getRawDataRefImpl();
410 const Elf_Sym *ESym = Obj.getSymbol(Symb);
412 return ESym->getType() == ELF::STT_OBJECT;
415 static bool isObject(SymbolicFile *Obj, basic_symbol_iterator I) {
416 if (ELF32LEObjectFile *ELF = dyn_cast<ELF32LEObjectFile>(Obj))
417 return isObject(*ELF, I);
418 if (ELF64LEObjectFile *ELF = dyn_cast<ELF64LEObjectFile>(Obj))
419 return isObject(*ELF, I);
420 if (ELF32BEObjectFile *ELF = dyn_cast<ELF32BEObjectFile>(Obj))
421 return isObject(*ELF, I);
422 if (ELF64BEObjectFile *ELF = dyn_cast<ELF64BEObjectFile>(Obj))
423 return isObject(*ELF, I);
427 static char getNMTypeChar(SymbolicFile *Obj, basic_symbol_iterator I) {
428 uint32_t Symflags = I->getFlags();
429 if ((Symflags & object::SymbolRef::SF_Weak) && !isa<MachOObjectFile>(Obj)) {
430 char Ret = isObject(Obj, I) ? 'v' : 'w';
431 if (!(Symflags & object::SymbolRef::SF_Undefined))
436 if (Symflags & object::SymbolRef::SF_Undefined)
439 if (Symflags & object::SymbolRef::SF_Common)
443 if (Symflags & object::SymbolRef::SF_Absolute)
445 else if (IRObjectFile *IR = dyn_cast<IRObjectFile>(Obj))
446 Ret = getSymbolNMTypeChar(*IR, I);
447 else if (COFFObjectFile *COFF = dyn_cast<COFFObjectFile>(Obj))
448 Ret = getSymbolNMTypeChar(*COFF, I);
449 else if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Obj))
450 Ret = getSymbolNMTypeChar(*MachO, I);
451 else if (ELF32LEObjectFile *ELF = dyn_cast<ELF32LEObjectFile>(Obj))
452 Ret = getSymbolNMTypeChar(*ELF, I);
453 else if (ELF64LEObjectFile *ELF = dyn_cast<ELF64LEObjectFile>(Obj))
454 Ret = getSymbolNMTypeChar(*ELF, I);
455 else if (ELF32BEObjectFile *ELF = dyn_cast<ELF32BEObjectFile>(Obj))
456 Ret = getSymbolNMTypeChar(*ELF, I);
458 Ret = getSymbolNMTypeChar(*cast<ELF64BEObjectFile>(Obj), I);
460 if (Symflags & object::SymbolRef::SF_Global)
466 static void dumpSymbolNamesFromObject(SymbolicFile *Obj) {
467 basic_symbol_iterator IBegin = Obj->symbol_begin();
468 basic_symbol_iterator IEnd = Obj->symbol_end();
471 error("File format has no dynamic symbol table", Obj->getFileName());
474 std::pair<symbol_iterator, symbol_iterator> IDyn =
475 getELFDynamicSymbolIterators(Obj);
479 std::string NameBuffer;
480 raw_string_ostream OS(NameBuffer);
481 for (basic_symbol_iterator I = IBegin; I != IEnd; ++I) {
482 uint32_t SymFlags = I->getFlags();
483 if (!DebugSyms && (SymFlags & SymbolRef::SF_FormatSpecific))
485 if (WithoutAliases) {
486 if (IRObjectFile *IR = dyn_cast<IRObjectFile>(Obj)) {
487 const GlobalValue &GV = IR->getSymbolGV(I->getRawDataRefImpl());
488 if(isa<GlobalAlias>(GV))
493 S.Size = UnknownAddressOrSize;
494 S.Address = UnknownAddressOrSize;
495 if ((PrintSize || SizeSort) && isa<ObjectFile>(Obj)) {
496 symbol_iterator SymI = I;
497 if (error(SymI->getSize(S.Size)))
500 if (PrintAddress && isa<ObjectFile>(Obj))
501 if (error(symbol_iterator(I)->getAddress(S.Address)))
503 S.TypeChar = getNMTypeChar(Obj, I);
504 if (error(I->printName(OS)))
507 SymbolList.push_back(S);
511 const char *P = NameBuffer.c_str();
512 for (unsigned I = 0; I < SymbolList.size(); ++I) {
513 SymbolList[I].Name = P;
517 CurrentFilename = Obj->getFileName();
518 sortAndPrintSymbolList();
521 static void dumpSymbolNamesFromFile(std::string &Filename) {
522 std::unique_ptr<MemoryBuffer> Buffer;
523 if (error(MemoryBuffer::getFileOrSTDIN(Filename, Buffer), Filename))
526 LLVMContext &Context = getGlobalContext();
527 ErrorOr<Binary *> BinaryOrErr = createBinary(Buffer.release(), &Context);
528 if (error(BinaryOrErr.getError(), Filename))
530 std::unique_ptr<Binary> Bin(BinaryOrErr.get());
532 if (Archive *A = dyn_cast<Archive>(Bin.get())) {
534 Archive::symbol_iterator I = A->symbol_begin();
535 Archive::symbol_iterator E = A->symbol_end();
537 outs() << "Archive map\n";
538 for (; I != E; ++I) {
539 Archive::child_iterator C;
542 if (error(I->getMember(C)))
544 if (error(I->getName(SymName)))
546 if (error(C->getName(FileName)))
548 outs() << SymName << " in " << FileName << "\n";
554 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
556 std::unique_ptr<Binary> Child;
557 if (I->getAsBinary(Child, &Context))
559 if (SymbolicFile *O = dyn_cast<SymbolicFile>(Child.get())) {
560 outs() << O->getFileName() << ":\n";
561 dumpSymbolNamesFromObject(O);
566 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin.get())) {
567 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
568 E = UB->end_objects();
570 std::unique_ptr<ObjectFile> Obj;
571 if (!I->getAsObjectFile(Obj)) {
572 outs() << Obj->getFileName() << ":\n";
573 dumpSymbolNamesFromObject(Obj.get());
578 if (SymbolicFile *O = dyn_cast<SymbolicFile>(Bin.get())) {
579 dumpSymbolNamesFromObject(O);
582 error("unrecognizable file type", Filename);
586 int main(int argc, char **argv) {
587 // Print a stack trace if we signal out.
588 sys::PrintStackTraceOnErrorSignal();
589 PrettyStackTraceProgram X(argc, argv);
591 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
592 cl::ParseCommandLineOptions(argc, argv, "llvm symbol table dumper\n");
594 // llvm-nm only reads binary files.
595 if (error(sys::ChangeStdinToBinary()))
602 OutputFormat = posix;
604 // The relative order of these is important. If you pass --size-sort it should
605 // only print out the size. However, if you pass -S --size-sort, it should
606 // print out both the size and address.
607 if (SizeSort && !PrintSize)
608 PrintAddress = false;
609 if (OutputFormat == sysv || SizeSort)
612 switch (InputFilenames.size()) {
614 InputFilenames.push_back("-");
618 MultipleFiles = true;
621 std::for_each(InputFilenames.begin(), InputFilenames.end(),
622 dumpSymbolNamesFromFile);