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/TargetSelect.h"
40 #include "llvm/Support/raw_ostream.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 cl::opt<bool> NoLLVMBitcode("no-llvm-bc",
153 cl::desc("Disable LLVM bitcode reader"));
155 bool PrintAddress = true;
157 bool MultipleFiles = false;
159 bool HadError = false;
161 std::string ToolName;
164 static void error(Twine Message, Twine Path = Twine()) {
166 errs() << ToolName << ": " << Path << ": " << Message << ".\n";
169 static bool error(std::error_code EC, Twine Path = Twine()) {
171 error(EC.message(), Path);
187 static bool compareSymbolAddress(const NMSymbol &A, const NMSymbol &B) {
188 if (A.TypeChar == 'U' && B.TypeChar != 'U')
190 if (A.TypeChar != 'U' && B.TypeChar == 'U')
192 if (A.Address < B.Address)
194 if (A.Address == B.Address && A.Name < B.Name)
196 if (A.Address == B.Address && A.Name == B.Name && A.Size < B.Size)
201 static bool compareSymbolSize(const NMSymbol &A, const NMSymbol &B) {
204 if (A.Size == B.Size && A.Name < B.Name)
206 if (A.Size == B.Size && A.Name == B.Name && A.Address < B.Address)
211 static bool compareSymbolName(const NMSymbol &A, const NMSymbol &B) {
214 if (A.Name == B.Name && A.Size < B.Size)
216 if (A.Name == B.Name && A.Size == B.Size && A.Address < B.Address)
221 static char isSymbolList64Bit(SymbolicFile &Obj) {
222 if (isa<IRObjectFile>(Obj))
224 if (isa<COFFObjectFile>(Obj))
226 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj))
227 return MachO->is64Bit();
228 return cast<ELFObjectFileBase>(Obj).getBytesInAddress() == 8;
231 static StringRef CurrentFilename;
232 typedef std::vector<NMSymbol> SymbolListT;
233 static SymbolListT SymbolList;
235 // darwinPrintSymbol() is used to print a symbol from a Mach-O file when the
236 // the OutputFormat is darwin or we are printing Mach-O symbols in hex. For
237 // the darwin format it produces the same output as darwin's nm(1) -m output
238 // and when printing Mach-O symbols in hex it produces the same output as
239 // darwin's nm(1) -x format.
240 static void darwinPrintSymbol(MachOObjectFile *MachO, SymbolListT::iterator I,
241 char *SymbolAddrStr, const char *printBlanks) {
242 MachO::mach_header H;
243 MachO::mach_header_64 H_64;
244 uint32_t Filetype, Flags;
245 MachO::nlist_64 STE_64;
252 if (MachO->is64Bit()) {
253 H_64 = MachO->MachOObjectFile::getHeader64();
254 Filetype = H_64.filetype;
256 STE_64 = MachO->getSymbol64TableEntry(I->Symb);
257 NType = STE_64.n_type;
258 NSect = STE_64.n_sect;
259 NDesc = STE_64.n_desc;
260 NStrx = STE_64.n_strx;
261 NValue = STE_64.n_value;
263 H = MachO->MachOObjectFile::getHeader();
264 Filetype = H.filetype;
266 STE = MachO->getSymbolTableEntry(I->Symb);
271 NValue = STE.n_value;
274 // If we are printing Mach-O symbols in hex do that and return.
275 if (FormatMachOasHex) {
277 const char *printFormat;
278 if (MachO->is64Bit())
279 printFormat = "%016" PRIx64;
281 printFormat = "%08" PRIx64;
282 format(printFormat, NValue).print(Str, sizeof(Str));
283 outs() << Str << ' ';
284 format("%02x", NType).print(Str, sizeof(Str));
285 outs() << Str << ' ';
286 format("%02x", NSect).print(Str, sizeof(Str));
287 outs() << Str << ' ';
288 format("%04x", NDesc).print(Str, sizeof(Str));
289 outs() << Str << ' ';
290 format("%08x", NStrx).print(Str, sizeof(Str));
291 outs() << Str << ' ';
292 outs() << I->Name << "\n";
297 if ((NType & MachO::N_TYPE) == MachO::N_INDR)
298 strcpy(SymbolAddrStr, printBlanks);
299 outs() << SymbolAddrStr << ' ';
302 switch (NType & MachO::N_TYPE) {
305 outs() << "(common) ";
306 if (MachO::GET_COMM_ALIGN(NDesc) != 0)
307 outs() << "(alignment 2^" << (int)MachO::GET_COMM_ALIGN(NDesc) << ") ";
309 if ((NType & MachO::N_TYPE) == MachO::N_PBUD)
310 outs() << "(prebound ";
313 if ((NDesc & MachO::REFERENCE_TYPE) ==
314 MachO::REFERENCE_FLAG_UNDEFINED_LAZY)
315 outs() << "undefined [lazy bound]) ";
316 else if ((NDesc & MachO::REFERENCE_TYPE) ==
317 MachO::REFERENCE_FLAG_UNDEFINED_LAZY)
318 outs() << "undefined [private lazy bound]) ";
319 else if ((NDesc & MachO::REFERENCE_TYPE) ==
320 MachO::REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY)
321 outs() << "undefined [private]) ";
323 outs() << "undefined) ";
327 outs() << "(absolute) ";
330 outs() << "(indirect) ";
332 case MachO::N_SECT: {
333 section_iterator Sec = MachO->section_end();
334 MachO->getSymbolSection(I->Symb, Sec);
335 DataRefImpl Ref = Sec->getRawDataRefImpl();
336 StringRef SectionName;
337 MachO->getSectionName(Ref, SectionName);
338 StringRef SegmentName = MachO->getSectionFinalSegmentName(Ref);
339 outs() << "(" << SegmentName << "," << SectionName << ") ";
347 if (NType & MachO::N_EXT) {
348 if (NDesc & MachO::REFERENCED_DYNAMICALLY)
349 outs() << "[referenced dynamically] ";
350 if (NType & MachO::N_PEXT) {
351 if ((NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF)
352 outs() << "weak private external ";
354 outs() << "private external ";
356 if ((NDesc & MachO::N_WEAK_REF) == MachO::N_WEAK_REF ||
357 (NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF) {
358 if ((NDesc & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF)) ==
359 (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
360 outs() << "weak external automatically hidden ";
362 outs() << "weak external ";
364 outs() << "external ";
367 if (NType & MachO::N_PEXT)
368 outs() << "non-external (was a private external) ";
370 outs() << "non-external ";
373 if (Filetype == MachO::MH_OBJECT &&
374 (NDesc & MachO::N_NO_DEAD_STRIP) == MachO::N_NO_DEAD_STRIP)
375 outs() << "[no dead strip] ";
377 if (Filetype == MachO::MH_OBJECT &&
378 ((NType & MachO::N_TYPE) != MachO::N_UNDF) &&
379 (NDesc & MachO::N_SYMBOL_RESOLVER) == MachO::N_SYMBOL_RESOLVER)
380 outs() << "[symbol resolver] ";
382 if (Filetype == MachO::MH_OBJECT &&
383 ((NType & MachO::N_TYPE) != MachO::N_UNDF) &&
384 (NDesc & MachO::N_ALT_ENTRY) == MachO::N_ALT_ENTRY)
385 outs() << "[alt entry] ";
387 if ((NDesc & MachO::N_ARM_THUMB_DEF) == MachO::N_ARM_THUMB_DEF)
388 outs() << "[Thumb] ";
390 if ((NType & MachO::N_TYPE) == MachO::N_INDR) {
391 outs() << I->Name << " (for ";
392 StringRef IndirectName;
393 if (MachO->getIndirectName(I->Symb, IndirectName))
396 outs() << IndirectName << ")";
400 if ((Flags & MachO::MH_TWOLEVEL) == MachO::MH_TWOLEVEL &&
401 (((NType & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0) ||
402 (NType & MachO::N_TYPE) == MachO::N_PBUD)) {
403 uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(NDesc);
404 if (LibraryOrdinal != 0) {
405 if (LibraryOrdinal == MachO::EXECUTABLE_ORDINAL)
406 outs() << " (from executable)";
407 else if (LibraryOrdinal == MachO::DYNAMIC_LOOKUP_ORDINAL)
408 outs() << " (dynamically looked up)";
410 StringRef LibraryName;
411 if (MachO->getLibraryShortNameByIndex(LibraryOrdinal - 1, LibraryName))
412 outs() << " (from bad library ordinal " << LibraryOrdinal << ")";
414 outs() << " (from " << LibraryName << ")";
422 // Table that maps Darwin's Mach-O stab constants to strings to allow printing.
423 struct DarwinStabName {
427 static const struct DarwinStabName DarwinStabNames[] = {
428 {MachO::N_GSYM, "GSYM"},
429 {MachO::N_FNAME, "FNAME"},
430 {MachO::N_FUN, "FUN"},
431 {MachO::N_STSYM, "STSYM"},
432 {MachO::N_LCSYM, "LCSYM"},
433 {MachO::N_BNSYM, "BNSYM"},
435 {MachO::N_AST, "AST"},
436 {MachO::N_OPT, "OPT"},
437 {MachO::N_RSYM, "RSYM"},
438 {MachO::N_SLINE, "SLINE"},
439 {MachO::N_ENSYM, "ENSYM"},
440 {MachO::N_SSYM, "SSYM"},
442 {MachO::N_OSO, "OSO"},
443 {MachO::N_LSYM, "LSYM"},
444 {MachO::N_BINCL, "BINCL"},
445 {MachO::N_SOL, "SOL"},
446 {MachO::N_PARAMS, "PARAM"},
447 {MachO::N_VERSION, "VERS"},
448 {MachO::N_OLEVEL, "OLEV"},
449 {MachO::N_PSYM, "PSYM"},
450 {MachO::N_EINCL, "EINCL"},
451 {MachO::N_ENTRY, "ENTRY"},
452 {MachO::N_LBRAC, "LBRAC"},
453 {MachO::N_EXCL, "EXCL"},
454 {MachO::N_RBRAC, "RBRAC"},
455 {MachO::N_BCOMM, "BCOMM"},
456 {MachO::N_ECOMM, "ECOMM"},
457 {MachO::N_ECOML, "ECOML"},
458 {MachO::N_LENG, "LENG"},
460 static const char *getDarwinStabString(uint8_t NType) {
461 for (unsigned i = 0; DarwinStabNames[i].Name; i++) {
462 if (DarwinStabNames[i].NType == NType)
463 return DarwinStabNames[i].Name;
468 // darwinPrintStab() prints the n_sect, n_desc along with a symbolic name of
469 // a stab n_type value in a Mach-O file.
470 static void darwinPrintStab(MachOObjectFile *MachO, SymbolListT::iterator I) {
471 MachO::nlist_64 STE_64;
476 if (MachO->is64Bit()) {
477 STE_64 = MachO->getSymbol64TableEntry(I->Symb);
478 NType = STE_64.n_type;
479 NSect = STE_64.n_sect;
480 NDesc = STE_64.n_desc;
482 STE = MachO->getSymbolTableEntry(I->Symb);
489 format("%02x", NSect).print(Str, sizeof(Str));
490 outs() << ' ' << Str << ' ';
491 format("%04x", NDesc).print(Str, sizeof(Str));
492 outs() << Str << ' ';
493 if (const char *stabString = getDarwinStabString(NType))
494 format("%5.5s", stabString).print(Str, sizeof(Str));
496 format(" %02x", NType).print(Str, sizeof(Str));
500 static void sortAndPrintSymbolList(SymbolicFile &Obj, bool printName,
501 std::string ArchiveName,
502 std::string ArchitectureName) {
504 std::function<bool(const NMSymbol &, const NMSymbol &)> Cmp;
506 Cmp = compareSymbolAddress;
508 Cmp = compareSymbolSize;
510 Cmp = compareSymbolName;
513 Cmp = [=](const NMSymbol &A, const NMSymbol &B) { return !Cmp(A, B); };
514 std::sort(SymbolList.begin(), SymbolList.end(), Cmp);
517 if (!PrintFileName) {
518 if (OutputFormat == posix && MultipleFiles && printName) {
519 outs() << '\n' << CurrentFilename << ":\n";
520 } else if (OutputFormat == bsd && MultipleFiles && printName) {
521 outs() << "\n" << CurrentFilename << ":\n";
522 } else if (OutputFormat == sysv) {
523 outs() << "\n\nSymbols from " << CurrentFilename << ":\n\n"
524 << "Name Value Class Type"
525 << " Size Line Section\n";
529 const char *printBlanks, *printFormat;
530 if (isSymbolList64Bit(Obj)) {
532 printFormat = "%016" PRIx64;
535 printFormat = "%08" PRIx64;
538 for (SymbolListT::iterator I = SymbolList.begin(), E = SymbolList.end();
540 if ((I->TypeChar != 'U') && UndefinedOnly)
542 if ((I->TypeChar == 'U') && DefinedOnly)
544 if (SizeSort && !PrintAddress)
547 if (!ArchitectureName.empty())
548 outs() << "(for architecture " << ArchitectureName << "):";
549 if (!ArchiveName.empty())
550 outs() << ArchiveName << ":";
551 outs() << CurrentFilename << ": ";
553 if (JustSymbolName || (UndefinedOnly && isa<MachOObjectFile>(Obj))) {
554 outs() << I->Name << "\n";
558 char SymbolAddrStr[18] = "";
559 char SymbolSizeStr[18] = "";
561 if (OutputFormat == sysv || I->Address == UnknownAddress)
562 strcpy(SymbolAddrStr, printBlanks);
563 if (OutputFormat == sysv)
564 strcpy(SymbolSizeStr, printBlanks);
566 if (I->Address != UnknownAddress)
567 format(printFormat, I->Address)
568 .print(SymbolAddrStr, sizeof(SymbolAddrStr));
569 format(printFormat, I->Size).print(SymbolSizeStr, sizeof(SymbolSizeStr));
571 // If OutputFormat is darwin or we are printing Mach-O symbols in hex and
572 // we have a MachOObjectFile, call darwinPrintSymbol to print as darwin's
573 // nm(1) -m output or hex, else if OutputFormat is darwin or we are
574 // printing Mach-O symbols in hex and not a Mach-O object fall back to
575 // OutputFormat bsd (see below).
576 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj);
577 if ((OutputFormat == darwin || FormatMachOasHex) && MachO) {
578 darwinPrintSymbol(MachO, I, SymbolAddrStr, printBlanks);
579 } else if (OutputFormat == posix) {
580 outs() << I->Name << " " << I->TypeChar << " " << SymbolAddrStr
581 << SymbolSizeStr << "\n";
582 } else if (OutputFormat == bsd || (OutputFormat == darwin && !MachO)) {
584 outs() << SymbolAddrStr << ' ';
586 outs() << SymbolSizeStr;
589 outs() << I->TypeChar;
590 if (I->TypeChar == '-' && MachO)
591 darwinPrintStab(MachO, I);
592 outs() << " " << I->Name << "\n";
593 } else if (OutputFormat == sysv) {
594 std::string PaddedName(I->Name);
595 while (PaddedName.length() < 20)
597 outs() << PaddedName << "|" << SymbolAddrStr << "| " << I->TypeChar
598 << " | |" << SymbolSizeStr << "| |\n";
605 static char getSymbolNMTypeChar(ELFObjectFileBase &Obj,
606 basic_symbol_iterator I) {
608 elf_symbol_iterator SymI(I);
610 elf_section_iterator SecI = Obj.section_end();
611 if (error(SymI->getSection(SecI)))
614 if (SecI != Obj.section_end()) {
615 switch (SecI->getType()) {
616 case ELF::SHT_PROGBITS:
617 case ELF::SHT_DYNAMIC:
618 switch (SecI->getFlags()) {
619 case (ELF::SHF_ALLOC | ELF::SHF_EXECINSTR):
621 case (ELF::SHF_TLS | ELF::SHF_ALLOC | ELF::SHF_WRITE):
622 case (ELF::SHF_ALLOC | ELF::SHF_WRITE):
625 case (ELF::SHF_ALLOC | ELF::SHF_MERGE):
626 case (ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS):
630 case ELF::SHT_NOBITS:
635 if (SymI->getELFType() == ELF::STT_SECTION) {
636 ErrorOr<StringRef> Name = SymI->getName();
637 if (error(Name.getError()))
639 return StringSwitch<char>(*Name)
640 .StartsWith(".debug", 'N')
641 .StartsWith(".note", 'n')
648 static char getSymbolNMTypeChar(COFFObjectFile &Obj, symbol_iterator I) {
649 COFFSymbolRef Symb = Obj.getCOFFSymbol(*I);
651 symbol_iterator SymI(I);
653 ErrorOr<StringRef> Name = SymI->getName();
654 if (error(Name.getError()))
657 char Ret = StringSwitch<char>(*Name)
658 .StartsWith(".debug", 'N')
659 .StartsWith(".sxdata", 'N')
665 uint32_t Characteristics = 0;
666 if (!COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
667 section_iterator SecI = Obj.section_end();
668 if (error(SymI->getSection(SecI)))
670 const coff_section *Section = Obj.getCOFFSection(*SecI);
671 Characteristics = Section->Characteristics;
674 switch (Symb.getSectionNumber()) {
675 case COFF::IMAGE_SYM_DEBUG:
678 // Check section type.
679 if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
681 if (Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
682 return Characteristics & COFF::IMAGE_SCN_MEM_WRITE ? 'd' : 'r';
683 if (Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
685 if (Characteristics & COFF::IMAGE_SCN_LNK_INFO)
687 // Check for section symbol.
688 if (Symb.isSectionDefinition())
695 static uint8_t getNType(MachOObjectFile &Obj, DataRefImpl Symb) {
697 MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb);
700 MachO::nlist STE = Obj.getSymbolTableEntry(Symb);
704 static char getSymbolNMTypeChar(MachOObjectFile &Obj, basic_symbol_iterator I) {
705 DataRefImpl Symb = I->getRawDataRefImpl();
706 uint8_t NType = getNType(Obj, Symb);
708 if (NType & MachO::N_STAB)
711 switch (NType & MachO::N_TYPE) {
716 case MachO::N_SECT: {
717 section_iterator Sec = Obj.section_end();
718 Obj.getSymbolSection(Symb, Sec);
719 DataRefImpl Ref = Sec->getRawDataRefImpl();
720 StringRef SectionName;
721 Obj.getSectionName(Ref, SectionName);
722 StringRef SegmentName = Obj.getSectionFinalSegmentName(Ref);
723 if (SegmentName == "__TEXT" && SectionName == "__text")
725 else if (SegmentName == "__DATA" && SectionName == "__data")
727 else if (SegmentName == "__DATA" && SectionName == "__bss")
737 static char getSymbolNMTypeChar(const GlobalValue &GV) {
738 if (GV.getType()->getElementType()->isFunctionTy())
740 // FIXME: should we print 'b'? At the IR level we cannot be sure if this
741 // will be in bss or not, but we could approximate.
745 static char getSymbolNMTypeChar(IRObjectFile &Obj, basic_symbol_iterator I) {
746 const GlobalValue *GV = Obj.getSymbolGV(I->getRawDataRefImpl());
749 return getSymbolNMTypeChar(*GV);
752 static bool isObject(SymbolicFile &Obj, basic_symbol_iterator I) {
753 auto *ELF = dyn_cast<ELFObjectFileBase>(&Obj);
757 return elf_symbol_iterator(I)->getELFType() == ELF::STT_OBJECT;
760 static char getNMTypeChar(SymbolicFile &Obj, basic_symbol_iterator I) {
761 uint32_t Symflags = I->getFlags();
762 if ((Symflags & object::SymbolRef::SF_Weak) && !isa<MachOObjectFile>(Obj)) {
763 char Ret = isObject(Obj, I) ? 'v' : 'w';
764 if (!(Symflags & object::SymbolRef::SF_Undefined))
769 if (Symflags & object::SymbolRef::SF_Undefined)
772 if (Symflags & object::SymbolRef::SF_Common)
776 if (Symflags & object::SymbolRef::SF_Absolute)
778 else if (IRObjectFile *IR = dyn_cast<IRObjectFile>(&Obj))
779 Ret = getSymbolNMTypeChar(*IR, I);
780 else if (COFFObjectFile *COFF = dyn_cast<COFFObjectFile>(&Obj))
781 Ret = getSymbolNMTypeChar(*COFF, I);
782 else if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj))
783 Ret = getSymbolNMTypeChar(*MachO, I);
785 Ret = getSymbolNMTypeChar(cast<ELFObjectFileBase>(Obj), I);
787 if (Symflags & object::SymbolRef::SF_Global)
793 // getNsectForSegSect() is used to implement the Mach-O "-s segname sectname"
794 // option to dump only those symbols from that section in a Mach-O file.
795 // It is called once for each Mach-O file from dumpSymbolNamesFromObject()
796 // to get the section number for that named section from the command line
797 // arguments. It returns the section number for that section in the Mach-O
798 // file or zero it is not present.
799 static unsigned getNsectForSegSect(MachOObjectFile *Obj) {
801 for (section_iterator I = Obj->section_begin(), E = Obj->section_end();
803 DataRefImpl Ref = I->getRawDataRefImpl();
804 StringRef SectionName;
805 Obj->getSectionName(Ref, SectionName);
806 StringRef SegmentName = Obj->getSectionFinalSegmentName(Ref);
807 if (SegmentName == SegSect[0] && SectionName == SegSect[1])
814 // getNsectInMachO() is used to implement the Mach-O "-s segname sectname"
815 // option to dump only those symbols from that section in a Mach-O file.
816 // It is called once for each symbol in a Mach-O file from
817 // dumpSymbolNamesFromObject() and returns the section number for that symbol
818 // if it is in a section, else it returns 0.
819 static unsigned getNsectInMachO(MachOObjectFile &Obj, BasicSymbolRef Sym) {
820 DataRefImpl Symb = Sym.getRawDataRefImpl();
822 MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb);
823 if ((STE.n_type & MachO::N_TYPE) == MachO::N_SECT)
827 MachO::nlist STE = Obj.getSymbolTableEntry(Symb);
828 if ((STE.n_type & MachO::N_TYPE) == MachO::N_SECT)
833 static void dumpSymbolNamesFromObject(SymbolicFile &Obj, bool printName,
834 std::string ArchiveName = std::string(),
835 std::string ArchitectureName =
837 auto Symbols = Obj.symbols();
839 const auto *E = dyn_cast<ELFObjectFileBase>(&Obj);
841 error("File format has no dynamic symbol table", Obj.getFileName());
844 auto DynSymbols = E->getDynamicSymbolIterators();
846 make_range<basic_symbol_iterator>(DynSymbols.begin(), DynSymbols.end());
848 std::string NameBuffer;
849 raw_string_ostream OS(NameBuffer);
850 // If a "-s segname sectname" option was specified and this is a Mach-O
851 // file get the section number for that section in this object file.
852 unsigned int Nsect = 0;
853 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj);
854 if (SegSect.size() != 0 && MachO) {
855 Nsect = getNsectForSegSect(MachO);
856 // If this section is not in the object file no symbols are printed.
860 for (BasicSymbolRef Sym : Symbols) {
861 uint32_t SymFlags = Sym.getFlags();
862 if (!DebugSyms && (SymFlags & SymbolRef::SF_FormatSpecific))
864 if (WithoutAliases) {
865 if (IRObjectFile *IR = dyn_cast<IRObjectFile>(&Obj)) {
866 const GlobalValue *GV = IR->getSymbolGV(Sym.getRawDataRefImpl());
867 if (GV && isa<GlobalAlias>(GV))
871 // If a "-s segname sectname" option was specified and this is a Mach-O
872 // file and this section appears in this file, Nsect will be non-zero then
873 // see if this symbol is a symbol from that section and if not skip it.
874 if (Nsect && Nsect != getNsectInMachO(*MachO, Sym))
878 S.Address = UnknownAddress;
880 if (isa<ELFObjectFileBase>(&Obj))
881 S.Size = ELFSymbolRef(Sym).getSize();
883 if (PrintAddress && isa<ObjectFile>(Obj)) {
884 SymbolRef SymRef(Sym);
885 if (SymFlags & SymbolRef::SF_Common) {
886 S.Address = SymRef.getCommonSize();
888 ErrorOr<uint64_t> AddressOrErr = SymRef.getAddress();
889 if (error(AddressOrErr.getError()))
891 S.Address = *AddressOrErr;
894 S.TypeChar = getNMTypeChar(Obj, Sym);
895 if (error(Sym.printName(OS)))
898 S.Symb = Sym.getRawDataRefImpl();
899 SymbolList.push_back(S);
903 const char *P = NameBuffer.c_str();
904 for (unsigned I = 0; I < SymbolList.size(); ++I) {
905 SymbolList[I].Name = P;
909 CurrentFilename = Obj.getFileName();
910 sortAndPrintSymbolList(Obj, printName, ArchiveName, ArchitectureName);
913 // checkMachOAndArchFlags() checks to see if the SymbolicFile is a Mach-O file
914 // and if it is and there is a list of architecture flags is specified then
915 // check to make sure this Mach-O file is one of those architectures or all
916 // architectures was specificed. If not then an error is generated and this
917 // routine returns false. Else it returns true.
918 static bool checkMachOAndArchFlags(SymbolicFile *O, std::string &Filename) {
919 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
921 if (!MachO || ArchAll || ArchFlags.size() == 0)
924 MachO::mach_header H;
925 MachO::mach_header_64 H_64;
927 if (MachO->is64Bit()) {
928 H_64 = MachO->MachOObjectFile::getHeader64();
929 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
931 H = MachO->MachOObjectFile::getHeader();
932 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
935 ArchFlags.begin(), ArchFlags.end(),
936 [&](const std::string &Name) { return Name == T.getArchName(); })) {
937 error("No architecture specified", Filename);
943 static void dumpSymbolNamesFromFile(std::string &Filename) {
944 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
945 MemoryBuffer::getFileOrSTDIN(Filename);
946 if (error(BufferOrErr.getError(), Filename))
949 LLVMContext &Context = getGlobalContext();
950 ErrorOr<std::unique_ptr<Binary>> BinaryOrErr = createBinary(
951 BufferOrErr.get()->getMemBufferRef(), NoLLVMBitcode ? nullptr : &Context);
952 if (error(BinaryOrErr.getError(), Filename))
954 Binary &Bin = *BinaryOrErr.get();
956 if (Archive *A = dyn_cast<Archive>(&Bin)) {
958 Archive::symbol_iterator I = A->symbol_begin();
959 Archive::symbol_iterator E = A->symbol_end();
961 outs() << "Archive map\n";
962 for (; I != E; ++I) {
963 ErrorOr<Archive::child_iterator> C = I->getMember();
964 if (error(C.getError()))
966 ErrorOr<StringRef> FileNameOrErr = C.get()->getName();
967 if (error(FileNameOrErr.getError()))
969 StringRef SymName = I->getName();
970 outs() << SymName << " in " << FileNameOrErr.get() << "\n";
976 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
978 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary(&Context);
979 if (ChildOrErr.getError())
981 if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
982 if (!checkMachOAndArchFlags(O, Filename))
984 if (!PrintFileName) {
986 if (isa<MachOObjectFile>(O)) {
987 outs() << Filename << "(" << O->getFileName() << ")";
989 outs() << O->getFileName();
992 dumpSymbolNamesFromObject(*O, false, Filename);
997 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
998 // If we have a list of architecture flags specified dump only those.
999 if (!ArchAll && ArchFlags.size() != 0) {
1000 // Look for a slice in the universal binary that matches each ArchFlag.
1002 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1004 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1005 E = UB->end_objects();
1007 if (ArchFlags[i] == I->getArchTypeName()) {
1009 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1010 I->getAsObjectFile();
1011 std::string ArchiveName;
1012 std::string ArchitectureName;
1013 ArchiveName.clear();
1014 ArchitectureName.clear();
1016 ObjectFile &Obj = *ObjOrErr.get();
1017 if (ArchFlags.size() > 1) {
1019 ArchitectureName = I->getArchTypeName();
1021 outs() << "\n" << Obj.getFileName() << " (for architecture "
1022 << I->getArchTypeName() << ")"
1025 dumpSymbolNamesFromObject(Obj, false, ArchiveName,
1027 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1028 I->getAsArchive()) {
1029 std::unique_ptr<Archive> &A = *AOrErr;
1030 for (Archive::child_iterator AI = A->child_begin(),
1031 AE = A->child_end();
1033 ErrorOr<std::unique_ptr<Binary>> ChildOrErr =
1034 AI->getAsBinary(&Context);
1035 if (ChildOrErr.getError())
1037 if (SymbolicFile *O =
1038 dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1039 if (PrintFileName) {
1040 ArchiveName = A->getFileName();
1041 if (ArchFlags.size() > 1)
1042 ArchitectureName = I->getArchTypeName();
1044 outs() << "\n" << A->getFileName();
1045 outs() << "(" << O->getFileName() << ")";
1046 if (ArchFlags.size() > 1) {
1047 outs() << " (for architecture " << I->getArchTypeName()
1052 dumpSymbolNamesFromObject(*O, false, ArchiveName,
1061 "file: " + Filename + " does not contain architecture");
1067 // No architecture flags were specified so if this contains a slice that
1068 // matches the host architecture dump only that.
1070 StringRef HostArchName = MachOObjectFile::getHostArch().getArchName();
1071 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1072 E = UB->end_objects();
1074 if (HostArchName == I->getArchTypeName()) {
1075 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1076 std::string ArchiveName;
1077 ArchiveName.clear();
1079 ObjectFile &Obj = *ObjOrErr.get();
1080 dumpSymbolNamesFromObject(Obj, false);
1081 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1082 I->getAsArchive()) {
1083 std::unique_ptr<Archive> &A = *AOrErr;
1084 for (Archive::child_iterator AI = A->child_begin(),
1085 AE = A->child_end();
1087 ErrorOr<std::unique_ptr<Binary>> ChildOrErr =
1088 AI->getAsBinary(&Context);
1089 if (ChildOrErr.getError())
1091 if (SymbolicFile *O =
1092 dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1094 ArchiveName = A->getFileName();
1096 outs() << "\n" << A->getFileName() << "(" << O->getFileName()
1099 dumpSymbolNamesFromObject(*O, false, ArchiveName);
1107 // Either all architectures have been specified or none have been specified
1108 // and this does not contain the host architecture so dump all the slices.
1109 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1110 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1111 E = UB->end_objects();
1113 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1114 std::string ArchiveName;
1115 std::string ArchitectureName;
1116 ArchiveName.clear();
1117 ArchitectureName.clear();
1119 ObjectFile &Obj = *ObjOrErr.get();
1120 if (PrintFileName) {
1121 if (isa<MachOObjectFile>(Obj) && moreThanOneArch)
1122 ArchitectureName = I->getArchTypeName();
1124 if (moreThanOneArch)
1126 outs() << Obj.getFileName();
1127 if (isa<MachOObjectFile>(Obj) && moreThanOneArch)
1128 outs() << " (for architecture " << I->getArchTypeName() << ")";
1131 dumpSymbolNamesFromObject(Obj, false, ArchiveName, ArchitectureName);
1132 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1133 std::unique_ptr<Archive> &A = *AOrErr;
1134 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1136 ErrorOr<std::unique_ptr<Binary>> ChildOrErr =
1137 AI->getAsBinary(&Context);
1138 if (ChildOrErr.getError())
1140 if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1141 if (PrintFileName) {
1142 ArchiveName = A->getFileName();
1143 if (isa<MachOObjectFile>(O) && moreThanOneArch)
1144 ArchitectureName = I->getArchTypeName();
1146 outs() << "\n" << A->getFileName();
1147 if (isa<MachOObjectFile>(O)) {
1148 outs() << "(" << O->getFileName() << ")";
1149 if (moreThanOneArch)
1150 outs() << " (for architecture " << I->getArchTypeName()
1153 outs() << ":" << O->getFileName();
1156 dumpSymbolNamesFromObject(*O, false, ArchiveName, ArchitectureName);
1163 if (SymbolicFile *O = dyn_cast<SymbolicFile>(&Bin)) {
1164 if (!checkMachOAndArchFlags(O, Filename))
1166 dumpSymbolNamesFromObject(*O, true);
1169 error("unrecognizable file type", Filename);
1173 int main(int argc, char **argv) {
1174 // Print a stack trace if we signal out.
1175 sys::PrintStackTraceOnErrorSignal();
1176 PrettyStackTraceProgram X(argc, argv);
1178 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1179 cl::ParseCommandLineOptions(argc, argv, "llvm symbol table dumper\n");
1181 // llvm-nm only reads binary files.
1182 if (error(sys::ChangeStdinToBinary()))
1185 llvm::InitializeAllTargetInfos();
1186 llvm::InitializeAllTargetMCs();
1187 llvm::InitializeAllAsmParsers();
1193 OutputFormat = posix;
1195 OutputFormat = darwin;
1197 // The relative order of these is important. If you pass --size-sort it should
1198 // only print out the size. However, if you pass -S --size-sort, it should
1199 // print out both the size and address.
1200 if (SizeSort && !PrintSize)
1201 PrintAddress = false;
1202 if (OutputFormat == sysv || SizeSort)
1205 switch (InputFilenames.size()) {
1207 InputFilenames.push_back("a.out");
1211 MultipleFiles = true;
1214 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1215 if (ArchFlags[i] == "all") {
1218 if (!MachOObjectFile::isValidArch(ArchFlags[i]))
1219 error("Unknown architecture named '" + ArchFlags[i] + "'",
1220 "for the -arch option");
1224 if (SegSect.size() != 0 && SegSect.size() != 2)
1225 error("bad number of arguments (must be two arguments)",
1226 "for the -s option");
1228 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1229 dumpSymbolNamesFromFile);