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/TargetSelect.h"
45 #include <system_error>
48 using namespace object;
51 enum OutputFormatTy { bsd, sysv, posix, darwin };
52 cl::opt<OutputFormatTy> OutputFormat(
53 "format", cl::desc("Specify output format"),
54 cl::values(clEnumVal(bsd, "BSD format"), clEnumVal(sysv, "System V format"),
55 clEnumVal(posix, "POSIX.2 format"),
56 clEnumVal(darwin, "Darwin -m format"), clEnumValEnd),
58 cl::alias OutputFormat2("f", cl::desc("Alias for --format"),
59 cl::aliasopt(OutputFormat));
61 cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<input files>"),
64 cl::opt<bool> UndefinedOnly("undefined-only",
65 cl::desc("Show only undefined symbols"));
66 cl::alias UndefinedOnly2("u", cl::desc("Alias for --undefined-only"),
67 cl::aliasopt(UndefinedOnly));
69 cl::opt<bool> DynamicSyms("dynamic",
70 cl::desc("Display the dynamic symbols instead "
71 "of normal symbols."));
72 cl::alias DynamicSyms2("D", cl::desc("Alias for --dynamic"),
73 cl::aliasopt(DynamicSyms));
75 cl::opt<bool> DefinedOnly("defined-only",
76 cl::desc("Show only defined symbols"));
77 cl::alias DefinedOnly2("U", cl::desc("Alias for --defined-only"),
78 cl::aliasopt(DefinedOnly));
80 cl::opt<bool> ExternalOnly("extern-only",
81 cl::desc("Show only external symbols"));
82 cl::alias ExternalOnly2("g", cl::desc("Alias for --extern-only"),
83 cl::aliasopt(ExternalOnly));
85 cl::opt<bool> BSDFormat("B", cl::desc("Alias for --format=bsd"));
86 cl::opt<bool> POSIXFormat("P", cl::desc("Alias for --format=posix"));
87 cl::opt<bool> DarwinFormat("m", cl::desc("Alias for --format=darwin"));
89 static cl::list<std::string>
90 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
94 cl::opt<bool> PrintFileName(
96 cl::desc("Precede each symbol with the object file it came from"));
98 cl::alias PrintFileNameA("A", cl::desc("Alias for --print-file-name"),
99 cl::aliasopt(PrintFileName));
100 cl::alias PrintFileNameo("o", cl::desc("Alias for --print-file-name"),
101 cl::aliasopt(PrintFileName));
103 cl::opt<bool> DebugSyms("debug-syms",
104 cl::desc("Show all symbols, even debugger only"));
105 cl::alias DebugSymsa("a", cl::desc("Alias for --debug-syms"),
106 cl::aliasopt(DebugSyms));
108 cl::opt<bool> NumericSort("numeric-sort", cl::desc("Sort symbols by address"));
109 cl::alias NumericSortn("n", cl::desc("Alias for --numeric-sort"),
110 cl::aliasopt(NumericSort));
111 cl::alias NumericSortv("v", cl::desc("Alias for --numeric-sort"),
112 cl::aliasopt(NumericSort));
114 cl::opt<bool> NoSort("no-sort", cl::desc("Show symbols in order encountered"));
115 cl::alias NoSortp("p", cl::desc("Alias for --no-sort"), cl::aliasopt(NoSort));
117 cl::opt<bool> ReverseSort("reverse-sort", cl::desc("Sort in reverse order"));
118 cl::alias ReverseSortr("r", cl::desc("Alias for --reverse-sort"),
119 cl::aliasopt(ReverseSort));
121 cl::opt<bool> PrintSize("print-size",
122 cl::desc("Show symbol size instead of address"));
123 cl::alias PrintSizeS("S", cl::desc("Alias for --print-size"),
124 cl::aliasopt(PrintSize));
126 cl::opt<bool> SizeSort("size-sort", cl::desc("Sort symbols by size"));
128 cl::opt<bool> WithoutAliases("without-aliases", cl::Hidden,
129 cl::desc("Exclude aliases from output"));
131 cl::opt<bool> ArchiveMap("print-armap", cl::desc("Print the archive map"));
132 cl::alias ArchiveMaps("M", cl::desc("Alias for --print-armap"),
133 cl::aliasopt(ArchiveMap));
135 cl::opt<bool> JustSymbolName("just-symbol-name",
136 cl::desc("Print just the symbol's name"));
137 cl::alias JustSymbolNames("j", cl::desc("Alias for --just-symbol-name"),
138 cl::aliasopt(JustSymbolName));
140 // FIXME: This option takes exactly two strings and should be allowed anywhere
141 // on the command line. Such that "llvm-nm -s __TEXT __text foo.o" would work.
142 // But that does not as the CommandLine Library does not have a way to make
143 // this work. For now the "-s __TEXT __text" has to be last on the command
145 cl::list<std::string> SegSect("s", cl::Positional, cl::ZeroOrMore,
146 cl::desc("Dump only symbols from this segment "
147 "and section name, Mach-O only"));
149 cl::opt<bool> FormatMachOasHex("x", cl::desc("Print symbol entry in hex, "
152 bool PrintAddress = true;
154 bool MultipleFiles = false;
156 bool HadError = false;
158 std::string ToolName;
161 static void error(Twine Message, Twine Path = Twine()) {
163 errs() << ToolName << ": " << Path << ": " << Message << ".\n";
166 static bool error(std::error_code EC, Twine Path = Twine()) {
168 error(EC.message(), Path);
184 static bool compareSymbolAddress(const NMSymbol &A, const NMSymbol &B) {
186 if (A.Address < B.Address)
188 else if (A.Address == B.Address && A.Name < B.Name)
190 else if (A.Address == B.Address && A.Name == B.Name && A.Size < B.Size)
195 if (A.Address > B.Address)
197 else if (A.Address == B.Address && A.Name > B.Name)
199 else if (A.Address == B.Address && A.Name == B.Name && A.Size > B.Size)
206 static bool compareSymbolSize(const NMSymbol &A, const NMSymbol &B) {
210 else if (A.Size == B.Size && A.Name < B.Name)
212 else if (A.Size == B.Size && A.Name == B.Name && A.Address < B.Address)
219 else if (A.Size == B.Size && A.Name > B.Name)
221 else if (A.Size == B.Size && A.Name == B.Name && A.Address > B.Address)
228 static bool compareSymbolName(const NMSymbol &A, const NMSymbol &B) {
232 else if (A.Name == B.Name && A.Size < B.Size)
234 else if (A.Name == B.Name && A.Size == B.Size && A.Address < B.Address)
241 else if (A.Name == B.Name && A.Size > B.Size)
243 else if (A.Name == B.Name && A.Size == B.Size && A.Address > B.Address)
250 static char isSymbolList64Bit(SymbolicFile *Obj) {
251 if (isa<IRObjectFile>(Obj))
253 else if (isa<COFFObjectFile>(Obj))
255 else if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Obj))
256 return MachO->is64Bit();
257 else if (isa<ELF32LEObjectFile>(Obj))
259 else if (isa<ELF64LEObjectFile>(Obj))
261 else if (isa<ELF32BEObjectFile>(Obj))
263 else if (isa<ELF64BEObjectFile>(Obj))
269 static StringRef CurrentFilename;
270 typedef std::vector<NMSymbol> SymbolListT;
271 static SymbolListT SymbolList;
273 // darwinPrintSymbol() is used to print a symbol from a Mach-O file when the
274 // the OutputFormat is darwin or we are printing Mach-O symbols in hex. For
275 // the darwin format it produces the same output as darwin's nm(1) -m output
276 // and when printing Mach-O symbols in hex it produces the same output as
277 // darwin's nm(1) -x format.
278 static void darwinPrintSymbol(MachOObjectFile *MachO, SymbolListT::iterator I,
279 char *SymbolAddrStr, const char *printBlanks) {
280 MachO::mach_header H;
281 MachO::mach_header_64 H_64;
282 uint32_t Filetype, Flags;
283 MachO::nlist_64 STE_64;
290 if (MachO->is64Bit()) {
291 H_64 = MachO->MachOObjectFile::getHeader64();
292 Filetype = H_64.filetype;
294 STE_64 = MachO->getSymbol64TableEntry(I->Symb);
295 NType = STE_64.n_type;
296 NSect = STE_64.n_sect;
297 NDesc = STE_64.n_desc;
298 NStrx = STE_64.n_strx;
299 NValue = STE_64.n_value;
301 H = MachO->MachOObjectFile::getHeader();
302 Filetype = H.filetype;
304 STE = MachO->getSymbolTableEntry(I->Symb);
309 NValue = STE.n_value;
312 // If we are printing Mach-O symbols in hex do that and return.
313 if (FormatMachOasHex) {
315 const char *printFormat;
316 if (MachO->is64Bit())
317 printFormat = "%016" PRIx64;
319 printFormat = "%08" PRIx64;
320 format(printFormat, NValue).print(Str, sizeof(Str));
321 outs() << Str << ' ';
322 format("%02x", NType).print(Str, sizeof(Str));
323 outs() << Str << ' ';
324 format("%02x", NSect).print(Str, sizeof(Str));
325 outs() << Str << ' ';
326 format("%04x", NDesc).print(Str, sizeof(Str));
327 outs() << Str << ' ';
328 format("%08x", NStrx).print(Str, sizeof(Str));
329 outs() << Str << ' ';
330 outs() << I->Name << "\n";
335 if ((NType & MachO::N_TYPE) == MachO::N_INDR)
336 strcpy(SymbolAddrStr, printBlanks);
337 outs() << SymbolAddrStr << ' ';
340 switch (NType & MachO::N_TYPE) {
343 outs() << "(common) ";
344 if (MachO::GET_COMM_ALIGN(NDesc) != 0)
345 outs() << "(alignment 2^" << (int)MachO::GET_COMM_ALIGN(NDesc) << ") ";
347 if ((NType & MachO::N_TYPE) == MachO::N_PBUD)
348 outs() << "(prebound ";
351 if ((NDesc & MachO::REFERENCE_TYPE) ==
352 MachO::REFERENCE_FLAG_UNDEFINED_LAZY)
353 outs() << "undefined [lazy bound]) ";
354 else if ((NDesc & MachO::REFERENCE_TYPE) ==
355 MachO::REFERENCE_FLAG_UNDEFINED_LAZY)
356 outs() << "undefined [private lazy bound]) ";
357 else if ((NDesc & MachO::REFERENCE_TYPE) ==
358 MachO::REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY)
359 outs() << "undefined [private]) ";
361 outs() << "undefined) ";
365 outs() << "(absolute) ";
368 outs() << "(indirect) ";
370 case MachO::N_SECT: {
371 section_iterator Sec = MachO->section_end();
372 MachO->getSymbolSection(I->Symb, Sec);
373 DataRefImpl Ref = Sec->getRawDataRefImpl();
374 StringRef SectionName;
375 MachO->getSectionName(Ref, SectionName);
376 StringRef SegmentName = MachO->getSectionFinalSegmentName(Ref);
377 outs() << "(" << SegmentName << "," << SectionName << ") ";
385 if (NType & MachO::N_EXT) {
386 if (NDesc & MachO::REFERENCED_DYNAMICALLY)
387 outs() << "[referenced dynamically] ";
388 if (NType & MachO::N_PEXT) {
389 if ((NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF)
390 outs() << "weak private external ";
392 outs() << "private external ";
394 if ((NDesc & MachO::N_WEAK_REF) == MachO::N_WEAK_REF ||
395 (NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF) {
396 if ((NDesc & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF)) ==
397 (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
398 outs() << "weak external automatically hidden ";
400 outs() << "weak external ";
402 outs() << "external ";
405 if (NType & MachO::N_PEXT)
406 outs() << "non-external (was a private external) ";
408 outs() << "non-external ";
411 if (Filetype == MachO::MH_OBJECT &&
412 (NDesc & MachO::N_NO_DEAD_STRIP) == MachO::N_NO_DEAD_STRIP)
413 outs() << "[no dead strip] ";
415 if (Filetype == MachO::MH_OBJECT &&
416 ((NType & MachO::N_TYPE) != MachO::N_UNDF) &&
417 (NDesc & MachO::N_SYMBOL_RESOLVER) == MachO::N_SYMBOL_RESOLVER)
418 outs() << "[symbol resolver] ";
420 if (Filetype == MachO::MH_OBJECT &&
421 ((NType & MachO::N_TYPE) != MachO::N_UNDF) &&
422 (NDesc & MachO::N_ALT_ENTRY) == MachO::N_ALT_ENTRY)
423 outs() << "[alt entry] ";
425 if ((NDesc & MachO::N_ARM_THUMB_DEF) == MachO::N_ARM_THUMB_DEF)
426 outs() << "[Thumb] ";
428 if ((NType & MachO::N_TYPE) == MachO::N_INDR) {
429 outs() << I->Name << " (for ";
430 StringRef IndirectName;
431 if (MachO->getIndirectName(I->Symb, IndirectName))
434 outs() << IndirectName << ")";
438 if ((Flags & MachO::MH_TWOLEVEL) == MachO::MH_TWOLEVEL &&
439 (((NType & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0) ||
440 (NType & MachO::N_TYPE) == MachO::N_PBUD)) {
441 uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(NDesc);
442 if (LibraryOrdinal != 0) {
443 if (LibraryOrdinal == MachO::EXECUTABLE_ORDINAL)
444 outs() << " (from executable)";
445 else if (LibraryOrdinal == MachO::DYNAMIC_LOOKUP_ORDINAL)
446 outs() << " (dynamically looked up)";
448 StringRef LibraryName;
449 if (MachO->getLibraryShortNameByIndex(LibraryOrdinal - 1, LibraryName))
450 outs() << " (from bad library ordinal " << LibraryOrdinal << ")";
452 outs() << " (from " << LibraryName << ")";
460 // Table that maps Darwin's Mach-O stab constants to strings to allow printing.
461 struct DarwinStabName {
465 static const struct DarwinStabName DarwinStabNames[] = {
466 {MachO::N_GSYM, "GSYM"},
467 {MachO::N_FNAME, "FNAME"},
468 {MachO::N_FUN, "FUN"},
469 {MachO::N_STSYM, "STSYM"},
470 {MachO::N_LCSYM, "LCSYM"},
471 {MachO::N_BNSYM, "BNSYM"},
473 {MachO::N_AST, "AST"},
474 {MachO::N_OPT, "OPT"},
475 {MachO::N_RSYM, "RSYM"},
476 {MachO::N_SLINE, "SLINE"},
477 {MachO::N_ENSYM, "ENSYM"},
478 {MachO::N_SSYM, "SSYM"},
480 {MachO::N_OSO, "OSO"},
481 {MachO::N_LSYM, "LSYM"},
482 {MachO::N_BINCL, "BINCL"},
483 {MachO::N_SOL, "SOL"},
484 {MachO::N_PARAMS, "PARAM"},
485 {MachO::N_VERSION, "VERS"},
486 {MachO::N_OLEVEL, "OLEV"},
487 {MachO::N_PSYM, "PSYM"},
488 {MachO::N_EINCL, "EINCL"},
489 {MachO::N_ENTRY, "ENTRY"},
490 {MachO::N_LBRAC, "LBRAC"},
491 {MachO::N_EXCL, "EXCL"},
492 {MachO::N_RBRAC, "RBRAC"},
493 {MachO::N_BCOMM, "BCOMM"},
494 {MachO::N_ECOMM, "ECOMM"},
495 {MachO::N_ECOML, "ECOML"},
496 {MachO::N_LENG, "LENG"},
498 static const char *getDarwinStabString(uint8_t NType) {
499 for (unsigned i = 0; DarwinStabNames[i].Name; i++) {
500 if (DarwinStabNames[i].NType == NType)
501 return DarwinStabNames[i].Name;
506 // darwinPrintStab() prints the n_sect, n_desc along with a symbolic name of
507 // a stab n_type value in a Mach-O file.
508 static void darwinPrintStab(MachOObjectFile *MachO, SymbolListT::iterator I) {
509 MachO::nlist_64 STE_64;
514 if (MachO->is64Bit()) {
515 STE_64 = MachO->getSymbol64TableEntry(I->Symb);
516 NType = STE_64.n_type;
517 NSect = STE_64.n_sect;
518 NDesc = STE_64.n_desc;
520 STE = MachO->getSymbolTableEntry(I->Symb);
527 format("%02x", NSect).print(Str, sizeof(Str));
528 outs() << ' ' << Str << ' ';
529 format("%04x", NDesc).print(Str, sizeof(Str));
530 outs() << Str << ' ';
531 if (const char *stabString = getDarwinStabString(NType))
532 format("%5.5s", stabString).print(Str, sizeof(Str));
534 format(" %02x", NType).print(Str, sizeof(Str));
538 static void sortAndPrintSymbolList(SymbolicFile *Obj, bool printName) {
541 std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolAddress);
543 std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolSize);
545 std::sort(SymbolList.begin(), SymbolList.end(), compareSymbolName);
548 if (OutputFormat == posix && MultipleFiles && printName) {
549 outs() << '\n' << CurrentFilename << ":\n";
550 } else if (OutputFormat == bsd && MultipleFiles && printName) {
551 outs() << "\n" << CurrentFilename << ":\n";
552 } else if (OutputFormat == sysv) {
553 outs() << "\n\nSymbols from " << CurrentFilename << ":\n\n"
554 << "Name Value Class Type"
555 << " Size Line Section\n";
558 const char *printBlanks, *printFormat;
559 if (isSymbolList64Bit(Obj)) {
561 printFormat = "%016" PRIx64;
564 printFormat = "%08" PRIx64;
567 for (SymbolListT::iterator I = SymbolList.begin(), E = SymbolList.end();
569 if ((I->TypeChar != 'U') && UndefinedOnly)
571 if ((I->TypeChar == 'U') && DefinedOnly)
573 if (SizeSort && !PrintAddress && I->Size == UnknownAddressOrSize)
575 if (JustSymbolName) {
576 outs() << I->Name << "\n";
580 char SymbolAddrStr[18] = "";
581 char SymbolSizeStr[18] = "";
583 if (OutputFormat == sysv || I->Address == UnknownAddressOrSize)
584 strcpy(SymbolAddrStr, printBlanks);
585 if (OutputFormat == sysv)
586 strcpy(SymbolSizeStr, printBlanks);
588 if (I->Address != UnknownAddressOrSize)
589 format(printFormat, I->Address)
590 .print(SymbolAddrStr, sizeof(SymbolAddrStr));
591 if (I->Size != UnknownAddressOrSize)
592 format(printFormat, I->Size).print(SymbolSizeStr, sizeof(SymbolSizeStr));
594 // If OutputFormat is darwin or we are printing Mach-O symbols in hex and
595 // we have a MachOObjectFile, call darwinPrintSymbol to print as darwin's
596 // nm(1) -m output or hex, else if OutputFormat is darwin or we are
597 // printing Mach-O symbols in hex and not a Mach-O object fall back to
598 // OutputFormat bsd (see below).
599 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Obj);
600 if ((OutputFormat == darwin || FormatMachOasHex) && MachO) {
601 darwinPrintSymbol(MachO, I, SymbolAddrStr, printBlanks);
602 } else if (OutputFormat == posix) {
603 outs() << I->Name << " " << I->TypeChar << " " << SymbolAddrStr
604 << SymbolSizeStr << "\n";
605 } else if (OutputFormat == bsd || (OutputFormat == darwin && !MachO)) {
607 outs() << SymbolAddrStr << ' ';
609 outs() << SymbolSizeStr;
610 if (I->Size != UnknownAddressOrSize)
613 outs() << I->TypeChar;
614 if (I->TypeChar == '-' && MachO)
615 darwinPrintStab(MachO, I);
616 outs() << " " << I->Name << "\n";
617 } else if (OutputFormat == sysv) {
618 std::string PaddedName(I->Name);
619 while (PaddedName.length() < 20)
621 outs() << PaddedName << "|" << SymbolAddrStr << "| " << I->TypeChar
622 << " | |" << SymbolSizeStr << "| |\n";
629 template <class ELFT>
630 static char getSymbolNMTypeChar(ELFObjectFile<ELFT> &Obj,
631 basic_symbol_iterator I) {
632 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
633 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
636 symbol_iterator SymI(I);
638 DataRefImpl Symb = I->getRawDataRefImpl();
639 const Elf_Sym *ESym = Obj.getSymbol(Symb);
640 const ELFFile<ELFT> &EF = *Obj.getELFFile();
641 const Elf_Shdr *ESec = EF.getSection(ESym);
644 switch (ESec->sh_type) {
645 case ELF::SHT_PROGBITS:
646 case ELF::SHT_DYNAMIC:
647 switch (ESec->sh_flags) {
648 case (ELF::SHF_ALLOC | ELF::SHF_EXECINSTR):
650 case (ELF::SHF_TLS | ELF::SHF_ALLOC | ELF::SHF_WRITE):
651 case (ELF::SHF_ALLOC | ELF::SHF_WRITE):
654 case (ELF::SHF_ALLOC | ELF::SHF_MERGE):
655 case (ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS):
659 case ELF::SHT_NOBITS:
664 if (ESym->getType() == ELF::STT_SECTION) {
666 if (error(SymI->getName(Name)))
668 return StringSwitch<char>(Name)
669 .StartsWith(".debug", 'N')
670 .StartsWith(".note", 'n')
677 static char getSymbolNMTypeChar(COFFObjectFile &Obj, symbol_iterator I) {
678 const coff_symbol *Symb = Obj.getCOFFSymbol(*I);
680 symbol_iterator SymI(I);
683 if (error(SymI->getName(Name)))
686 char Ret = StringSwitch<char>(Name)
687 .StartsWith(".debug", 'N')
688 .StartsWith(".sxdata", 'N')
694 uint32_t Characteristics = 0;
695 if (!COFF::isReservedSectionNumber(Symb->SectionNumber)) {
696 section_iterator SecI = Obj.section_end();
697 if (error(SymI->getSection(SecI)))
699 const coff_section *Section = Obj.getCOFFSection(*SecI);
700 Characteristics = Section->Characteristics;
703 switch (Symb->SectionNumber) {
704 case COFF::IMAGE_SYM_DEBUG:
707 // Check section type.
708 if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
710 else if (Characteristics & COFF::IMAGE_SCN_MEM_READ &&
711 ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only.
713 else if (Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
715 else if (Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
717 else if (Characteristics & COFF::IMAGE_SCN_LNK_INFO)
720 // Check for section symbol.
721 else if (Symb->isSectionDefinition())
728 static uint8_t getNType(MachOObjectFile &Obj, DataRefImpl Symb) {
730 MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb);
733 MachO::nlist STE = Obj.getSymbolTableEntry(Symb);
737 static char getSymbolNMTypeChar(MachOObjectFile &Obj, basic_symbol_iterator I) {
738 DataRefImpl Symb = I->getRawDataRefImpl();
739 uint8_t NType = getNType(Obj, Symb);
741 if (NType & MachO::N_STAB)
744 switch (NType & MachO::N_TYPE) {
749 case MachO::N_SECT: {
750 section_iterator Sec = Obj.section_end();
751 Obj.getSymbolSection(Symb, Sec);
752 DataRefImpl Ref = Sec->getRawDataRefImpl();
753 StringRef SectionName;
754 Obj.getSectionName(Ref, SectionName);
755 StringRef SegmentName = Obj.getSectionFinalSegmentName(Ref);
756 if (SegmentName == "__TEXT" && SectionName == "__text")
758 else if (SegmentName == "__DATA" && SectionName == "__data")
760 else if (SegmentName == "__DATA" && SectionName == "__bss")
770 static char getSymbolNMTypeChar(const GlobalValue &GV) {
771 if (GV.getType()->getElementType()->isFunctionTy())
773 // FIXME: should we print 'b'? At the IR level we cannot be sure if this
774 // will be in bss or not, but we could approximate.
778 static char getSymbolNMTypeChar(IRObjectFile &Obj, basic_symbol_iterator I) {
779 const GlobalValue *GV = Obj.getSymbolGV(I->getRawDataRefImpl());
782 return getSymbolNMTypeChar(*GV);
785 template <class ELFT>
786 static bool isObject(ELFObjectFile<ELFT> &Obj, symbol_iterator I) {
787 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
789 DataRefImpl Symb = I->getRawDataRefImpl();
790 const Elf_Sym *ESym = Obj.getSymbol(Symb);
792 return ESym->getType() == ELF::STT_OBJECT;
795 static bool isObject(SymbolicFile *Obj, basic_symbol_iterator I) {
796 if (ELF32LEObjectFile *ELF = dyn_cast<ELF32LEObjectFile>(Obj))
797 return isObject(*ELF, I);
798 if (ELF64LEObjectFile *ELF = dyn_cast<ELF64LEObjectFile>(Obj))
799 return isObject(*ELF, I);
800 if (ELF32BEObjectFile *ELF = dyn_cast<ELF32BEObjectFile>(Obj))
801 return isObject(*ELF, I);
802 if (ELF64BEObjectFile *ELF = dyn_cast<ELF64BEObjectFile>(Obj))
803 return isObject(*ELF, I);
807 static char getNMTypeChar(SymbolicFile *Obj, basic_symbol_iterator I) {
808 uint32_t Symflags = I->getFlags();
809 if ((Symflags & object::SymbolRef::SF_Weak) && !isa<MachOObjectFile>(Obj)) {
810 char Ret = isObject(Obj, I) ? 'v' : 'w';
811 if (!(Symflags & object::SymbolRef::SF_Undefined))
816 if (Symflags & object::SymbolRef::SF_Undefined)
819 if (Symflags & object::SymbolRef::SF_Common)
823 if (Symflags & object::SymbolRef::SF_Absolute)
825 else if (IRObjectFile *IR = dyn_cast<IRObjectFile>(Obj))
826 Ret = getSymbolNMTypeChar(*IR, I);
827 else if (COFFObjectFile *COFF = dyn_cast<COFFObjectFile>(Obj))
828 Ret = getSymbolNMTypeChar(*COFF, I);
829 else if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Obj))
830 Ret = getSymbolNMTypeChar(*MachO, I);
831 else if (ELF32LEObjectFile *ELF = dyn_cast<ELF32LEObjectFile>(Obj))
832 Ret = getSymbolNMTypeChar(*ELF, I);
833 else if (ELF64LEObjectFile *ELF = dyn_cast<ELF64LEObjectFile>(Obj))
834 Ret = getSymbolNMTypeChar(*ELF, I);
835 else if (ELF32BEObjectFile *ELF = dyn_cast<ELF32BEObjectFile>(Obj))
836 Ret = getSymbolNMTypeChar(*ELF, I);
838 Ret = getSymbolNMTypeChar(*cast<ELF64BEObjectFile>(Obj), I);
840 if (Symflags & object::SymbolRef::SF_Global)
846 // getNsectForSegSect() is used to implement the Mach-O "-s segname sectname"
847 // option to dump only those symbols from that section in a Mach-O file.
848 // It is called once for each Mach-O file from dumpSymbolNamesFromObject()
849 // to get the section number for that named section from the command line
850 // arguments. It returns the section number for that section in the Mach-O
851 // file or zero it is not present.
852 static unsigned getNsectForSegSect(MachOObjectFile *Obj) {
854 for (section_iterator I = Obj->section_begin(), E = Obj->section_end();
856 DataRefImpl Ref = I->getRawDataRefImpl();
857 StringRef SectionName;
858 Obj->getSectionName(Ref, SectionName);
859 StringRef SegmentName = Obj->getSectionFinalSegmentName(Ref);
860 if (SegmentName == SegSect[0] && SectionName == SegSect[1])
867 // getNsectInMachO() is used to implement the Mach-O "-s segname sectname"
868 // option to dump only those symbols from that section in a Mach-O file.
869 // It is called once for each symbol in a Mach-O file from
870 // dumpSymbolNamesFromObject() and returns the section number for that symbol
871 // if it is in a section, else it returns 0.
872 static unsigned getNsectInMachO(MachOObjectFile &Obj, basic_symbol_iterator I) {
873 DataRefImpl Symb = I->getRawDataRefImpl();
875 MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb);
876 if ((STE.n_type & MachO::N_TYPE) == MachO::N_SECT)
880 MachO::nlist STE = Obj.getSymbolTableEntry(Symb);
881 if ((STE.n_type & MachO::N_TYPE) == MachO::N_SECT)
886 static void dumpSymbolNamesFromObject(SymbolicFile *Obj, bool printName) {
887 basic_symbol_iterator IBegin = Obj->symbol_begin();
888 basic_symbol_iterator IEnd = Obj->symbol_end();
891 error("File format has no dynamic symbol table", Obj->getFileName());
894 std::pair<symbol_iterator, symbol_iterator> IDyn =
895 getELFDynamicSymbolIterators(Obj);
899 std::string NameBuffer;
900 raw_string_ostream OS(NameBuffer);
901 // If a "-s segname sectname" option was specified and this is a Mach-O
902 // file get the section number for that section in this object file.
903 unsigned int Nsect = 0;
904 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Obj);
905 if (SegSect.size() != 0 && MachO) {
906 Nsect = getNsectForSegSect(MachO);
907 // If this section is not in the object file no symbols are printed.
911 for (basic_symbol_iterator I = IBegin; I != IEnd; ++I) {
912 uint32_t SymFlags = I->getFlags();
913 if (!DebugSyms && (SymFlags & SymbolRef::SF_FormatSpecific))
915 if (WithoutAliases) {
916 if (IRObjectFile *IR = dyn_cast<IRObjectFile>(Obj)) {
917 const GlobalValue *GV = IR->getSymbolGV(I->getRawDataRefImpl());
918 if (GV && isa<GlobalAlias>(GV))
922 // If a "-s segname sectname" option was specified and this is a Mach-O
923 // file and this section appears in this file, Nsect will be non-zero then
924 // see if this symbol is a symbol from that section and if not skip it.
925 if (Nsect && Nsect != getNsectInMachO(*MachO, I))
928 S.Size = UnknownAddressOrSize;
929 S.Address = UnknownAddressOrSize;
930 if ((PrintSize || SizeSort) && isa<ObjectFile>(Obj)) {
931 symbol_iterator SymI = I;
932 if (error(SymI->getSize(S.Size)))
935 if (PrintAddress && isa<ObjectFile>(Obj))
936 if (error(symbol_iterator(I)->getAddress(S.Address)))
938 S.TypeChar = getNMTypeChar(Obj, I);
939 if (error(I->printName(OS)))
942 S.Symb = I->getRawDataRefImpl();
943 SymbolList.push_back(S);
947 const char *P = NameBuffer.c_str();
948 for (unsigned I = 0; I < SymbolList.size(); ++I) {
949 SymbolList[I].Name = P;
953 CurrentFilename = Obj->getFileName();
954 sortAndPrintSymbolList(Obj, printName);
957 // checkMachOAndArchFlags() checks to see if the SymbolicFile is a Mach-O file
958 // and if it is and there is a list of architecture flags is specified then
959 // check to make sure this Mach-O file is one of those architectures or all
960 // architectures was specificed. If not then an error is generated and this
961 // routine returns false. Else it returns true.
962 static bool checkMachOAndArchFlags(SymbolicFile *O, std::string &Filename) {
963 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
964 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
965 bool ArchFound = false;
966 MachO::mach_header H;
967 MachO::mach_header_64 H_64;
969 if (MachO->is64Bit()) {
970 H_64 = MachO->MachOObjectFile::getHeader64();
971 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
973 H = MachO->MachOObjectFile::getHeader();
974 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
977 for (i = 0; i < ArchFlags.size(); ++i) {
978 if (ArchFlags[i] == T.getArchName())
984 "file: " + Filename + " does not contain architecture");
991 static void dumpSymbolNamesFromFile(std::string &Filename) {
992 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
993 MemoryBuffer::getFileOrSTDIN(Filename);
994 if (error(BufferOrErr.getError(), Filename))
996 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get());
998 LLVMContext &Context = getGlobalContext();
999 ErrorOr<Binary *> BinaryOrErr = createBinary(Buffer, &Context);
1000 if (error(BinaryOrErr.getError(), Filename))
1003 std::unique_ptr<Binary> Bin(BinaryOrErr.get());
1005 if (Archive *A = dyn_cast<Archive>(Bin.get())) {
1007 Archive::symbol_iterator I = A->symbol_begin();
1008 Archive::symbol_iterator E = A->symbol_end();
1010 outs() << "Archive map\n";
1011 for (; I != E; ++I) {
1012 ErrorOr<Archive::child_iterator> C = I->getMember();
1013 if (error(C.getError()))
1015 ErrorOr<StringRef> FileNameOrErr = C.get()->getName();
1016 if (error(FileNameOrErr.getError()))
1018 StringRef SymName = I->getName();
1019 outs() << SymName << " in " << FileNameOrErr.get() << "\n";
1025 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1027 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary(&Context);
1028 if (ChildOrErr.getError())
1030 if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1031 if (!checkMachOAndArchFlags(O, Filename))
1034 if (isa<MachOObjectFile>(O)) {
1035 outs() << Filename << "(" << O->getFileName() << ")";
1037 outs() << O->getFileName();
1039 dumpSymbolNamesFromObject(O, false);
1044 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin.get())) {
1045 // If we have a list of architecture flags specified dump only those.
1046 if (!ArchAll && ArchFlags.size() != 0) {
1047 // Look for a slice in the universal binary that matches each ArchFlag.
1049 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1051 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1052 E = UB->end_objects();
1054 if (ArchFlags[i] == I->getArchTypeName()) {
1056 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1057 I->getAsObjectFile();
1058 std::unique_ptr<Archive> A;
1060 std::unique_ptr<ObjectFile> Obj = std::move(ObjOrErr.get());
1061 if (ArchFlags.size() > 1) {
1062 outs() << "\n" << Obj->getFileName() << " (for architecture "
1063 << I->getArchTypeName() << ")"
1066 dumpSymbolNamesFromObject(Obj.get(), false);
1067 } else if (!I->getAsArchive(A)) {
1068 for (Archive::child_iterator AI = A->child_begin(),
1069 AE = A->child_end();
1071 ErrorOr<std::unique_ptr<Binary>> ChildOrErr =
1072 AI->getAsBinary(&Context);
1073 if (ChildOrErr.getError())
1075 if (SymbolicFile *O =
1076 dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1077 outs() << "\n" << A->getFileName();
1078 outs() << "(" << O->getFileName() << ")";
1079 if (ArchFlags.size() > 1) {
1080 outs() << " (for architecture " << I->getArchTypeName()
1084 dumpSymbolNamesFromObject(O, false);
1092 "file: " + Filename + " does not contain architecture");
1098 // No architecture flags were specified so if this contains a slice that
1099 // matches the host architecture dump only that.
1101 StringRef HostArchName = MachOObjectFile::getHostArch().getArchName();
1102 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1103 E = UB->end_objects();
1105 if (HostArchName == I->getArchTypeName()) {
1106 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1107 std::unique_ptr<Archive> A;
1109 std::unique_ptr<ObjectFile> Obj = std::move(ObjOrErr.get());
1110 dumpSymbolNamesFromObject(Obj.get(), false);
1111 } else if (!I->getAsArchive(A)) {
1112 for (Archive::child_iterator AI = A->child_begin(),
1113 AE = A->child_end();
1115 ErrorOr<std::unique_ptr<Binary>> ChildOrErr =
1116 AI->getAsBinary(&Context);
1117 if (ChildOrErr.getError())
1119 if (SymbolicFile *O =
1120 dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1121 outs() << "\n" << A->getFileName() << "(" << O->getFileName()
1124 dumpSymbolNamesFromObject(O, false);
1132 // Either all architectures have been specified or none have been specified
1133 // and this does not contain the host architecture so dump all the slices.
1134 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1135 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1136 E = UB->end_objects();
1138 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1139 std::unique_ptr<Archive> A;
1141 std::unique_ptr<ObjectFile> Obj = std::move(ObjOrErr.get());
1142 if (moreThanOneArch)
1144 outs() << Obj->getFileName();
1145 if (isa<MachOObjectFile>(Obj.get()) && moreThanOneArch)
1146 outs() << " (for architecture " << I->getArchTypeName() << ")";
1148 dumpSymbolNamesFromObject(Obj.get(), false);
1149 } else if (!I->getAsArchive(A)) {
1150 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1152 ErrorOr<std::unique_ptr<Binary>> ChildOrErr =
1153 AI->getAsBinary(&Context);
1154 if (ChildOrErr.getError())
1156 if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1157 outs() << "\n" << A->getFileName();
1158 if (isa<MachOObjectFile>(O)) {
1159 outs() << "(" << O->getFileName() << ")";
1160 if (moreThanOneArch)
1161 outs() << " (for architecture " << I->getArchTypeName() << ")";
1163 outs() << ":" << O->getFileName();
1165 dumpSymbolNamesFromObject(O, false);
1172 if (SymbolicFile *O = dyn_cast<SymbolicFile>(Bin.get())) {
1173 if (!checkMachOAndArchFlags(O, Filename))
1175 dumpSymbolNamesFromObject(O, true);
1178 error("unrecognizable file type", Filename);
1182 int main(int argc, char **argv) {
1183 // Print a stack trace if we signal out.
1184 sys::PrintStackTraceOnErrorSignal();
1185 PrettyStackTraceProgram X(argc, argv);
1187 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1188 cl::ParseCommandLineOptions(argc, argv, "llvm symbol table dumper\n");
1190 // llvm-nm only reads binary files.
1191 if (error(sys::ChangeStdinToBinary()))
1194 llvm::InitializeAllTargetInfos();
1195 llvm::InitializeAllTargetMCs();
1196 llvm::InitializeAllAsmParsers();
1202 OutputFormat = posix;
1204 OutputFormat = darwin;
1206 // The relative order of these is important. If you pass --size-sort it should
1207 // only print out the size. However, if you pass -S --size-sort, it should
1208 // print out both the size and address.
1209 if (SizeSort && !PrintSize)
1210 PrintAddress = false;
1211 if (OutputFormat == sysv || SizeSort)
1214 switch (InputFilenames.size()) {
1216 InputFilenames.push_back("a.out");
1220 MultipleFiles = true;
1223 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1224 if (ArchFlags[i] == "all") {
1227 Triple T = MachOObjectFile::getArch(ArchFlags[i]);
1228 if (T.getArch() == Triple::UnknownArch)
1229 error("Unknown architecture named '" + ArchFlags[i] + "'",
1230 "for the -arch option");
1234 if (SegSect.size() != 0 && SegSect.size() != 2)
1235 error("bad number of arguments (must be two arguments)",
1236 "for the -s option");
1238 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1239 dumpSymbolNamesFromFile);