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.Address < B.Address)
190 if (A.Address == B.Address && A.Name < B.Name)
192 if (A.Address == B.Address && A.Name == B.Name && A.Size < B.Size)
197 static bool compareSymbolSize(const NMSymbol &A, const NMSymbol &B) {
200 if (A.Size == B.Size && A.Name < B.Name)
202 if (A.Size == B.Size && A.Name == B.Name && A.Address < B.Address)
207 static bool compareSymbolName(const NMSymbol &A, const NMSymbol &B) {
210 if (A.Name == B.Name && A.Size < B.Size)
212 if (A.Name == B.Name && A.Size == B.Size && A.Address < B.Address)
217 static char isSymbolList64Bit(SymbolicFile &Obj) {
218 if (isa<IRObjectFile>(Obj))
220 if (isa<COFFObjectFile>(Obj))
222 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj))
223 return MachO->is64Bit();
224 return cast<ELFObjectFileBase>(Obj).getBytesInAddress() == 8;
227 static StringRef CurrentFilename;
228 typedef std::vector<NMSymbol> SymbolListT;
229 static SymbolListT SymbolList;
231 // darwinPrintSymbol() is used to print a symbol from a Mach-O file when the
232 // the OutputFormat is darwin or we are printing Mach-O symbols in hex. For
233 // the darwin format it produces the same output as darwin's nm(1) -m output
234 // and when printing Mach-O symbols in hex it produces the same output as
235 // darwin's nm(1) -x format.
236 static void darwinPrintSymbol(MachOObjectFile *MachO, SymbolListT::iterator I,
237 char *SymbolAddrStr, const char *printBlanks) {
238 MachO::mach_header H;
239 MachO::mach_header_64 H_64;
240 uint32_t Filetype, Flags;
241 MachO::nlist_64 STE_64;
248 if (MachO->is64Bit()) {
249 H_64 = MachO->MachOObjectFile::getHeader64();
250 Filetype = H_64.filetype;
252 STE_64 = MachO->getSymbol64TableEntry(I->Symb);
253 NType = STE_64.n_type;
254 NSect = STE_64.n_sect;
255 NDesc = STE_64.n_desc;
256 NStrx = STE_64.n_strx;
257 NValue = STE_64.n_value;
259 H = MachO->MachOObjectFile::getHeader();
260 Filetype = H.filetype;
262 STE = MachO->getSymbolTableEntry(I->Symb);
267 NValue = STE.n_value;
270 // If we are printing Mach-O symbols in hex do that and return.
271 if (FormatMachOasHex) {
273 const char *printFormat;
274 if (MachO->is64Bit())
275 printFormat = "%016" PRIx64;
277 printFormat = "%08" PRIx64;
278 format(printFormat, NValue).print(Str, sizeof(Str));
279 outs() << Str << ' ';
280 format("%02x", NType).print(Str, sizeof(Str));
281 outs() << Str << ' ';
282 format("%02x", NSect).print(Str, sizeof(Str));
283 outs() << Str << ' ';
284 format("%04x", NDesc).print(Str, sizeof(Str));
285 outs() << Str << ' ';
286 format("%08x", NStrx).print(Str, sizeof(Str));
287 outs() << Str << ' ';
288 outs() << I->Name << "\n";
293 if ((NType & MachO::N_TYPE) == MachO::N_INDR)
294 strcpy(SymbolAddrStr, printBlanks);
295 outs() << SymbolAddrStr << ' ';
298 switch (NType & MachO::N_TYPE) {
301 outs() << "(common) ";
302 if (MachO::GET_COMM_ALIGN(NDesc) != 0)
303 outs() << "(alignment 2^" << (int)MachO::GET_COMM_ALIGN(NDesc) << ") ";
305 if ((NType & MachO::N_TYPE) == MachO::N_PBUD)
306 outs() << "(prebound ";
309 if ((NDesc & MachO::REFERENCE_TYPE) ==
310 MachO::REFERENCE_FLAG_UNDEFINED_LAZY)
311 outs() << "undefined [lazy bound]) ";
312 else if ((NDesc & MachO::REFERENCE_TYPE) ==
313 MachO::REFERENCE_FLAG_UNDEFINED_LAZY)
314 outs() << "undefined [private lazy bound]) ";
315 else if ((NDesc & MachO::REFERENCE_TYPE) ==
316 MachO::REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY)
317 outs() << "undefined [private]) ";
319 outs() << "undefined) ";
323 outs() << "(absolute) ";
326 outs() << "(indirect) ";
328 case MachO::N_SECT: {
329 section_iterator Sec = MachO->section_end();
330 MachO->getSymbolSection(I->Symb, Sec);
331 DataRefImpl Ref = Sec->getRawDataRefImpl();
332 StringRef SectionName;
333 MachO->getSectionName(Ref, SectionName);
334 StringRef SegmentName = MachO->getSectionFinalSegmentName(Ref);
335 outs() << "(" << SegmentName << "," << SectionName << ") ";
343 if (NType & MachO::N_EXT) {
344 if (NDesc & MachO::REFERENCED_DYNAMICALLY)
345 outs() << "[referenced dynamically] ";
346 if (NType & MachO::N_PEXT) {
347 if ((NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF)
348 outs() << "weak private external ";
350 outs() << "private external ";
352 if ((NDesc & MachO::N_WEAK_REF) == MachO::N_WEAK_REF ||
353 (NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF) {
354 if ((NDesc & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF)) ==
355 (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
356 outs() << "weak external automatically hidden ";
358 outs() << "weak external ";
360 outs() << "external ";
363 if (NType & MachO::N_PEXT)
364 outs() << "non-external (was a private external) ";
366 outs() << "non-external ";
369 if (Filetype == MachO::MH_OBJECT &&
370 (NDesc & MachO::N_NO_DEAD_STRIP) == MachO::N_NO_DEAD_STRIP)
371 outs() << "[no dead strip] ";
373 if (Filetype == MachO::MH_OBJECT &&
374 ((NType & MachO::N_TYPE) != MachO::N_UNDF) &&
375 (NDesc & MachO::N_SYMBOL_RESOLVER) == MachO::N_SYMBOL_RESOLVER)
376 outs() << "[symbol resolver] ";
378 if (Filetype == MachO::MH_OBJECT &&
379 ((NType & MachO::N_TYPE) != MachO::N_UNDF) &&
380 (NDesc & MachO::N_ALT_ENTRY) == MachO::N_ALT_ENTRY)
381 outs() << "[alt entry] ";
383 if ((NDesc & MachO::N_ARM_THUMB_DEF) == MachO::N_ARM_THUMB_DEF)
384 outs() << "[Thumb] ";
386 if ((NType & MachO::N_TYPE) == MachO::N_INDR) {
387 outs() << I->Name << " (for ";
388 StringRef IndirectName;
389 if (MachO->getIndirectName(I->Symb, IndirectName))
392 outs() << IndirectName << ")";
396 if ((Flags & MachO::MH_TWOLEVEL) == MachO::MH_TWOLEVEL &&
397 (((NType & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0) ||
398 (NType & MachO::N_TYPE) == MachO::N_PBUD)) {
399 uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(NDesc);
400 if (LibraryOrdinal != 0) {
401 if (LibraryOrdinal == MachO::EXECUTABLE_ORDINAL)
402 outs() << " (from executable)";
403 else if (LibraryOrdinal == MachO::DYNAMIC_LOOKUP_ORDINAL)
404 outs() << " (dynamically looked up)";
406 StringRef LibraryName;
407 if (MachO->getLibraryShortNameByIndex(LibraryOrdinal - 1, LibraryName))
408 outs() << " (from bad library ordinal " << LibraryOrdinal << ")";
410 outs() << " (from " << LibraryName << ")";
418 // Table that maps Darwin's Mach-O stab constants to strings to allow printing.
419 struct DarwinStabName {
423 static const struct DarwinStabName DarwinStabNames[] = {
424 {MachO::N_GSYM, "GSYM"},
425 {MachO::N_FNAME, "FNAME"},
426 {MachO::N_FUN, "FUN"},
427 {MachO::N_STSYM, "STSYM"},
428 {MachO::N_LCSYM, "LCSYM"},
429 {MachO::N_BNSYM, "BNSYM"},
431 {MachO::N_AST, "AST"},
432 {MachO::N_OPT, "OPT"},
433 {MachO::N_RSYM, "RSYM"},
434 {MachO::N_SLINE, "SLINE"},
435 {MachO::N_ENSYM, "ENSYM"},
436 {MachO::N_SSYM, "SSYM"},
438 {MachO::N_OSO, "OSO"},
439 {MachO::N_LSYM, "LSYM"},
440 {MachO::N_BINCL, "BINCL"},
441 {MachO::N_SOL, "SOL"},
442 {MachO::N_PARAMS, "PARAM"},
443 {MachO::N_VERSION, "VERS"},
444 {MachO::N_OLEVEL, "OLEV"},
445 {MachO::N_PSYM, "PSYM"},
446 {MachO::N_EINCL, "EINCL"},
447 {MachO::N_ENTRY, "ENTRY"},
448 {MachO::N_LBRAC, "LBRAC"},
449 {MachO::N_EXCL, "EXCL"},
450 {MachO::N_RBRAC, "RBRAC"},
451 {MachO::N_BCOMM, "BCOMM"},
452 {MachO::N_ECOMM, "ECOMM"},
453 {MachO::N_ECOML, "ECOML"},
454 {MachO::N_LENG, "LENG"},
456 static const char *getDarwinStabString(uint8_t NType) {
457 for (unsigned i = 0; DarwinStabNames[i].Name; i++) {
458 if (DarwinStabNames[i].NType == NType)
459 return DarwinStabNames[i].Name;
464 // darwinPrintStab() prints the n_sect, n_desc along with a symbolic name of
465 // a stab n_type value in a Mach-O file.
466 static void darwinPrintStab(MachOObjectFile *MachO, SymbolListT::iterator I) {
467 MachO::nlist_64 STE_64;
472 if (MachO->is64Bit()) {
473 STE_64 = MachO->getSymbol64TableEntry(I->Symb);
474 NType = STE_64.n_type;
475 NSect = STE_64.n_sect;
476 NDesc = STE_64.n_desc;
478 STE = MachO->getSymbolTableEntry(I->Symb);
485 format("%02x", NSect).print(Str, sizeof(Str));
486 outs() << ' ' << Str << ' ';
487 format("%04x", NDesc).print(Str, sizeof(Str));
488 outs() << Str << ' ';
489 if (const char *stabString = getDarwinStabString(NType))
490 format("%5.5s", stabString).print(Str, sizeof(Str));
492 format(" %02x", NType).print(Str, sizeof(Str));
496 static void sortAndPrintSymbolList(SymbolicFile &Obj, bool printName,
497 std::string ArchiveName,
498 std::string ArchitectureName) {
500 std::function<bool(const NMSymbol &, const NMSymbol &)> Cmp;
502 Cmp = compareSymbolAddress;
504 Cmp = compareSymbolSize;
506 Cmp = compareSymbolName;
509 Cmp = [=](const NMSymbol &A, const NMSymbol &B) { return !Cmp(A, B); };
510 std::sort(SymbolList.begin(), SymbolList.end(), Cmp);
513 if (!PrintFileName) {
514 if (OutputFormat == posix && MultipleFiles && printName) {
515 outs() << '\n' << CurrentFilename << ":\n";
516 } else if (OutputFormat == bsd && MultipleFiles && printName) {
517 outs() << "\n" << CurrentFilename << ":\n";
518 } else if (OutputFormat == sysv) {
519 outs() << "\n\nSymbols from " << CurrentFilename << ":\n\n"
520 << "Name Value Class Type"
521 << " Size Line Section\n";
525 const char *printBlanks, *printFormat;
526 if (isSymbolList64Bit(Obj)) {
528 printFormat = "%016" PRIx64;
531 printFormat = "%08" PRIx64;
534 for (SymbolListT::iterator I = SymbolList.begin(), E = SymbolList.end();
536 if ((I->TypeChar != 'U') && UndefinedOnly)
538 if ((I->TypeChar == 'U') && DefinedOnly)
540 if (SizeSort && !PrintAddress)
543 if (!ArchitectureName.empty())
544 outs() << "(for architecture " << ArchitectureName << "):";
545 if (!ArchiveName.empty())
546 outs() << ArchiveName << ":";
547 outs() << CurrentFilename << ": ";
549 if (JustSymbolName || (UndefinedOnly && isa<MachOObjectFile>(Obj))) {
550 outs() << I->Name << "\n";
554 char SymbolAddrStr[18] = "";
555 char SymbolSizeStr[18] = "";
557 if (OutputFormat == sysv || I->Address == UnknownAddress)
558 strcpy(SymbolAddrStr, printBlanks);
559 if (OutputFormat == sysv)
560 strcpy(SymbolSizeStr, printBlanks);
562 if (I->Address != UnknownAddress)
563 format(printFormat, I->Address)
564 .print(SymbolAddrStr, sizeof(SymbolAddrStr));
565 format(printFormat, I->Size).print(SymbolSizeStr, sizeof(SymbolSizeStr));
567 // If OutputFormat is darwin or we are printing Mach-O symbols in hex and
568 // we have a MachOObjectFile, call darwinPrintSymbol to print as darwin's
569 // nm(1) -m output or hex, else if OutputFormat is darwin or we are
570 // printing Mach-O symbols in hex and not a Mach-O object fall back to
571 // OutputFormat bsd (see below).
572 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj);
573 if ((OutputFormat == darwin || FormatMachOasHex) && MachO) {
574 darwinPrintSymbol(MachO, I, SymbolAddrStr, printBlanks);
575 } else if (OutputFormat == posix) {
576 outs() << I->Name << " " << I->TypeChar << " " << SymbolAddrStr
577 << SymbolSizeStr << "\n";
578 } else if (OutputFormat == bsd || (OutputFormat == darwin && !MachO)) {
580 outs() << SymbolAddrStr << ' ';
582 outs() << SymbolSizeStr;
585 outs() << I->TypeChar;
586 if (I->TypeChar == '-' && MachO)
587 darwinPrintStab(MachO, I);
588 outs() << " " << I->Name << "\n";
589 } else if (OutputFormat == sysv) {
590 std::string PaddedName(I->Name);
591 while (PaddedName.length() < 20)
593 outs() << PaddedName << "|" << SymbolAddrStr << "| " << I->TypeChar
594 << " | |" << SymbolSizeStr << "| |\n";
601 static char getSymbolNMTypeChar(ELFObjectFileBase &Obj,
602 basic_symbol_iterator I) {
604 elf_symbol_iterator SymI(I);
606 elf_section_iterator SecI = Obj.section_end();
607 if (error(SymI->getSection(SecI)))
610 if (SecI != Obj.section_end()) {
611 switch (SecI->getType()) {
612 case ELF::SHT_PROGBITS:
613 case ELF::SHT_DYNAMIC:
614 switch (SecI->getFlags()) {
615 case (ELF::SHF_ALLOC | ELF::SHF_EXECINSTR):
617 case (ELF::SHF_TLS | ELF::SHF_ALLOC | ELF::SHF_WRITE):
618 case (ELF::SHF_ALLOC | ELF::SHF_WRITE):
621 case (ELF::SHF_ALLOC | ELF::SHF_MERGE):
622 case (ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS):
626 case ELF::SHT_NOBITS:
631 if (SymI->getELFType() == ELF::STT_SECTION) {
632 ErrorOr<StringRef> Name = SymI->getName();
633 if (error(Name.getError()))
635 return StringSwitch<char>(*Name)
636 .StartsWith(".debug", 'N')
637 .StartsWith(".note", 'n')
644 static char getSymbolNMTypeChar(COFFObjectFile &Obj, symbol_iterator I) {
645 COFFSymbolRef Symb = Obj.getCOFFSymbol(*I);
647 symbol_iterator SymI(I);
649 ErrorOr<StringRef> Name = SymI->getName();
650 if (error(Name.getError()))
653 char Ret = StringSwitch<char>(*Name)
654 .StartsWith(".debug", 'N')
655 .StartsWith(".sxdata", 'N')
661 uint32_t Characteristics = 0;
662 if (!COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
663 section_iterator SecI = Obj.section_end();
664 if (error(SymI->getSection(SecI)))
666 const coff_section *Section = Obj.getCOFFSection(*SecI);
667 Characteristics = Section->Characteristics;
670 switch (Symb.getSectionNumber()) {
671 case COFF::IMAGE_SYM_DEBUG:
674 // Check section type.
675 if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
677 if (Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
678 return Characteristics & COFF::IMAGE_SCN_MEM_WRITE ? 'd' : 'r';
679 if (Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
681 if (Characteristics & COFF::IMAGE_SCN_LNK_INFO)
683 // Check for section symbol.
684 if (Symb.isSectionDefinition())
691 static uint8_t getNType(MachOObjectFile &Obj, DataRefImpl Symb) {
693 MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb);
696 MachO::nlist STE = Obj.getSymbolTableEntry(Symb);
700 static char getSymbolNMTypeChar(MachOObjectFile &Obj, basic_symbol_iterator I) {
701 DataRefImpl Symb = I->getRawDataRefImpl();
702 uint8_t NType = getNType(Obj, Symb);
704 if (NType & MachO::N_STAB)
707 switch (NType & MachO::N_TYPE) {
712 case MachO::N_SECT: {
713 section_iterator Sec = Obj.section_end();
714 Obj.getSymbolSection(Symb, Sec);
715 DataRefImpl Ref = Sec->getRawDataRefImpl();
716 StringRef SectionName;
717 Obj.getSectionName(Ref, SectionName);
718 StringRef SegmentName = Obj.getSectionFinalSegmentName(Ref);
719 if (SegmentName == "__TEXT" && SectionName == "__text")
721 else if (SegmentName == "__DATA" && SectionName == "__data")
723 else if (SegmentName == "__DATA" && SectionName == "__bss")
733 static char getSymbolNMTypeChar(const GlobalValue &GV) {
734 if (GV.getType()->getElementType()->isFunctionTy())
736 // FIXME: should we print 'b'? At the IR level we cannot be sure if this
737 // will be in bss or not, but we could approximate.
741 static char getSymbolNMTypeChar(IRObjectFile &Obj, basic_symbol_iterator I) {
742 const GlobalValue *GV = Obj.getSymbolGV(I->getRawDataRefImpl());
745 return getSymbolNMTypeChar(*GV);
748 static bool isObject(SymbolicFile &Obj, basic_symbol_iterator I) {
749 auto *ELF = dyn_cast<ELFObjectFileBase>(&Obj);
753 return elf_symbol_iterator(I)->getELFType() == ELF::STT_OBJECT;
756 static char getNMTypeChar(SymbolicFile &Obj, basic_symbol_iterator I) {
757 uint32_t Symflags = I->getFlags();
758 if ((Symflags & object::SymbolRef::SF_Weak) && !isa<MachOObjectFile>(Obj)) {
759 char Ret = isObject(Obj, I) ? 'v' : 'w';
760 if (!(Symflags & object::SymbolRef::SF_Undefined))
765 if (Symflags & object::SymbolRef::SF_Undefined)
768 if (Symflags & object::SymbolRef::SF_Common)
772 if (Symflags & object::SymbolRef::SF_Absolute)
774 else if (IRObjectFile *IR = dyn_cast<IRObjectFile>(&Obj))
775 Ret = getSymbolNMTypeChar(*IR, I);
776 else if (COFFObjectFile *COFF = dyn_cast<COFFObjectFile>(&Obj))
777 Ret = getSymbolNMTypeChar(*COFF, I);
778 else if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj))
779 Ret = getSymbolNMTypeChar(*MachO, I);
781 Ret = getSymbolNMTypeChar(cast<ELFObjectFileBase>(Obj), I);
783 if (Symflags & object::SymbolRef::SF_Global)
789 // getNsectForSegSect() is used to implement the Mach-O "-s segname sectname"
790 // option to dump only those symbols from that section in a Mach-O file.
791 // It is called once for each Mach-O file from dumpSymbolNamesFromObject()
792 // to get the section number for that named section from the command line
793 // arguments. It returns the section number for that section in the Mach-O
794 // file or zero it is not present.
795 static unsigned getNsectForSegSect(MachOObjectFile *Obj) {
797 for (section_iterator I = Obj->section_begin(), E = Obj->section_end();
799 DataRefImpl Ref = I->getRawDataRefImpl();
800 StringRef SectionName;
801 Obj->getSectionName(Ref, SectionName);
802 StringRef SegmentName = Obj->getSectionFinalSegmentName(Ref);
803 if (SegmentName == SegSect[0] && SectionName == SegSect[1])
810 // getNsectInMachO() is used to implement the Mach-O "-s segname sectname"
811 // option to dump only those symbols from that section in a Mach-O file.
812 // It is called once for each symbol in a Mach-O file from
813 // dumpSymbolNamesFromObject() and returns the section number for that symbol
814 // if it is in a section, else it returns 0.
815 static unsigned getNsectInMachO(MachOObjectFile &Obj, BasicSymbolRef Sym) {
816 DataRefImpl Symb = Sym.getRawDataRefImpl();
818 MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb);
819 if ((STE.n_type & MachO::N_TYPE) == MachO::N_SECT)
823 MachO::nlist STE = Obj.getSymbolTableEntry(Symb);
824 if ((STE.n_type & MachO::N_TYPE) == MachO::N_SECT)
829 static void dumpSymbolNamesFromObject(SymbolicFile &Obj, bool printName,
830 std::string ArchiveName = std::string(),
831 std::string ArchitectureName =
833 auto Symbols = Obj.symbols();
835 const auto *E = dyn_cast<ELFObjectFileBase>(&Obj);
837 error("File format has no dynamic symbol table", Obj.getFileName());
840 auto DynSymbols = E->getDynamicSymbolIterators();
842 make_range<basic_symbol_iterator>(DynSymbols.begin(), DynSymbols.end());
844 std::string NameBuffer;
845 raw_string_ostream OS(NameBuffer);
846 // If a "-s segname sectname" option was specified and this is a Mach-O
847 // file get the section number for that section in this object file.
848 unsigned int Nsect = 0;
849 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj);
850 if (SegSect.size() != 0 && MachO) {
851 Nsect = getNsectForSegSect(MachO);
852 // If this section is not in the object file no symbols are printed.
856 for (BasicSymbolRef Sym : Symbols) {
857 uint32_t SymFlags = Sym.getFlags();
858 if (!DebugSyms && (SymFlags & SymbolRef::SF_FormatSpecific))
860 if (WithoutAliases) {
861 if (IRObjectFile *IR = dyn_cast<IRObjectFile>(&Obj)) {
862 const GlobalValue *GV = IR->getSymbolGV(Sym.getRawDataRefImpl());
863 if (GV && isa<GlobalAlias>(GV))
867 // If a "-s segname sectname" option was specified and this is a Mach-O
868 // file and this section appears in this file, Nsect will be non-zero then
869 // see if this symbol is a symbol from that section and if not skip it.
870 if (Nsect && Nsect != getNsectInMachO(*MachO, Sym))
874 S.Address = UnknownAddress;
876 if (isa<ELFObjectFileBase>(&Obj))
877 S.Size = ELFSymbolRef(Sym).getSize();
879 if (PrintAddress && isa<ObjectFile>(Obj)) {
880 SymbolRef SymRef(Sym);
881 if (SymFlags & SymbolRef::SF_Common) {
882 S.Address = SymRef.getCommonSize();
884 ErrorOr<uint64_t> AddressOrErr = SymRef.getAddress();
885 if (error(AddressOrErr.getError()))
887 S.Address = *AddressOrErr;
890 S.TypeChar = getNMTypeChar(Obj, Sym);
891 if (error(Sym.printName(OS)))
894 S.Symb = Sym.getRawDataRefImpl();
895 SymbolList.push_back(S);
899 const char *P = NameBuffer.c_str();
900 for (unsigned I = 0; I < SymbolList.size(); ++I) {
901 SymbolList[I].Name = P;
905 CurrentFilename = Obj.getFileName();
906 sortAndPrintSymbolList(Obj, printName, ArchiveName, ArchitectureName);
909 // checkMachOAndArchFlags() checks to see if the SymbolicFile is a Mach-O file
910 // and if it is and there is a list of architecture flags is specified then
911 // check to make sure this Mach-O file is one of those architectures or all
912 // architectures was specificed. If not then an error is generated and this
913 // routine returns false. Else it returns true.
914 static bool checkMachOAndArchFlags(SymbolicFile *O, std::string &Filename) {
915 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
917 if (!MachO || ArchAll || ArchFlags.size() == 0)
920 MachO::mach_header H;
921 MachO::mach_header_64 H_64;
923 if (MachO->is64Bit()) {
924 H_64 = MachO->MachOObjectFile::getHeader64();
925 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
927 H = MachO->MachOObjectFile::getHeader();
928 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
931 ArchFlags.begin(), ArchFlags.end(),
932 [&](const std::string &Name) { return Name == T.getArchName(); })) {
933 error("No architecture specified", Filename);
939 static void dumpSymbolNamesFromFile(std::string &Filename) {
940 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
941 MemoryBuffer::getFileOrSTDIN(Filename);
942 if (error(BufferOrErr.getError(), Filename))
945 LLVMContext &Context = getGlobalContext();
946 ErrorOr<std::unique_ptr<Binary>> BinaryOrErr = createBinary(
947 BufferOrErr.get()->getMemBufferRef(), NoLLVMBitcode ? nullptr : &Context);
948 if (error(BinaryOrErr.getError(), Filename))
950 Binary &Bin = *BinaryOrErr.get();
952 if (Archive *A = dyn_cast<Archive>(&Bin)) {
954 Archive::symbol_iterator I = A->symbol_begin();
955 Archive::symbol_iterator E = A->symbol_end();
957 outs() << "Archive map\n";
958 for (; I != E; ++I) {
959 ErrorOr<Archive::child_iterator> C = I->getMember();
960 if (error(C.getError()))
962 ErrorOr<StringRef> FileNameOrErr = C.get()->getName();
963 if (error(FileNameOrErr.getError()))
965 StringRef SymName = I->getName();
966 outs() << SymName << " in " << FileNameOrErr.get() << "\n";
972 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
974 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary(&Context);
975 if (ChildOrErr.getError())
977 if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
978 if (!checkMachOAndArchFlags(O, Filename))
980 if (!PrintFileName) {
982 if (isa<MachOObjectFile>(O)) {
983 outs() << Filename << "(" << O->getFileName() << ")";
985 outs() << O->getFileName();
988 dumpSymbolNamesFromObject(*O, false, Filename);
993 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
994 // If we have a list of architecture flags specified dump only those.
995 if (!ArchAll && ArchFlags.size() != 0) {
996 // Look for a slice in the universal binary that matches each ArchFlag.
998 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1000 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1001 E = UB->end_objects();
1003 if (ArchFlags[i] == I->getArchTypeName()) {
1005 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1006 I->getAsObjectFile();
1007 std::string ArchiveName;
1008 std::string ArchitectureName;
1009 ArchiveName.clear();
1010 ArchitectureName.clear();
1012 ObjectFile &Obj = *ObjOrErr.get();
1013 if (ArchFlags.size() > 1) {
1015 ArchitectureName = I->getArchTypeName();
1017 outs() << "\n" << Obj.getFileName() << " (for architecture "
1018 << I->getArchTypeName() << ")"
1021 dumpSymbolNamesFromObject(Obj, false, ArchiveName,
1023 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1024 I->getAsArchive()) {
1025 std::unique_ptr<Archive> &A = *AOrErr;
1026 for (Archive::child_iterator AI = A->child_begin(),
1027 AE = A->child_end();
1029 ErrorOr<std::unique_ptr<Binary>> ChildOrErr =
1030 AI->getAsBinary(&Context);
1031 if (ChildOrErr.getError())
1033 if (SymbolicFile *O =
1034 dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1035 if (PrintFileName) {
1036 ArchiveName = A->getFileName();
1037 if (ArchFlags.size() > 1)
1038 ArchitectureName = I->getArchTypeName();
1040 outs() << "\n" << A->getFileName();
1041 outs() << "(" << O->getFileName() << ")";
1042 if (ArchFlags.size() > 1) {
1043 outs() << " (for architecture " << I->getArchTypeName()
1048 dumpSymbolNamesFromObject(*O, false, ArchiveName,
1057 "file: " + Filename + " does not contain architecture");
1063 // No architecture flags were specified so if this contains a slice that
1064 // matches the host architecture dump only that.
1066 StringRef HostArchName = MachOObjectFile::getHostArch().getArchName();
1067 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1068 E = UB->end_objects();
1070 if (HostArchName == I->getArchTypeName()) {
1071 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1072 std::string ArchiveName;
1073 ArchiveName.clear();
1075 ObjectFile &Obj = *ObjOrErr.get();
1076 dumpSymbolNamesFromObject(Obj, false);
1077 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1078 I->getAsArchive()) {
1079 std::unique_ptr<Archive> &A = *AOrErr;
1080 for (Archive::child_iterator AI = A->child_begin(),
1081 AE = A->child_end();
1083 ErrorOr<std::unique_ptr<Binary>> ChildOrErr =
1084 AI->getAsBinary(&Context);
1085 if (ChildOrErr.getError())
1087 if (SymbolicFile *O =
1088 dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1090 ArchiveName = A->getFileName();
1092 outs() << "\n" << A->getFileName() << "(" << O->getFileName()
1095 dumpSymbolNamesFromObject(*O, false, ArchiveName);
1103 // Either all architectures have been specified or none have been specified
1104 // and this does not contain the host architecture so dump all the slices.
1105 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1106 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1107 E = UB->end_objects();
1109 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1110 std::string ArchiveName;
1111 std::string ArchitectureName;
1112 ArchiveName.clear();
1113 ArchitectureName.clear();
1115 ObjectFile &Obj = *ObjOrErr.get();
1116 if (PrintFileName) {
1117 if (isa<MachOObjectFile>(Obj) && moreThanOneArch)
1118 ArchitectureName = I->getArchTypeName();
1120 if (moreThanOneArch)
1122 outs() << Obj.getFileName();
1123 if (isa<MachOObjectFile>(Obj) && moreThanOneArch)
1124 outs() << " (for architecture " << I->getArchTypeName() << ")";
1127 dumpSymbolNamesFromObject(Obj, false, ArchiveName, ArchitectureName);
1128 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1129 std::unique_ptr<Archive> &A = *AOrErr;
1130 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1132 ErrorOr<std::unique_ptr<Binary>> ChildOrErr =
1133 AI->getAsBinary(&Context);
1134 if (ChildOrErr.getError())
1136 if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1137 if (PrintFileName) {
1138 ArchiveName = A->getFileName();
1139 if (isa<MachOObjectFile>(O) && moreThanOneArch)
1140 ArchitectureName = I->getArchTypeName();
1142 outs() << "\n" << A->getFileName();
1143 if (isa<MachOObjectFile>(O)) {
1144 outs() << "(" << O->getFileName() << ")";
1145 if (moreThanOneArch)
1146 outs() << " (for architecture " << I->getArchTypeName()
1149 outs() << ":" << O->getFileName();
1152 dumpSymbolNamesFromObject(*O, false, ArchiveName, ArchitectureName);
1159 if (SymbolicFile *O = dyn_cast<SymbolicFile>(&Bin)) {
1160 if (!checkMachOAndArchFlags(O, Filename))
1162 dumpSymbolNamesFromObject(*O, true);
1165 error("unrecognizable file type", Filename);
1169 int main(int argc, char **argv) {
1170 // Print a stack trace if we signal out.
1171 sys::PrintStackTraceOnErrorSignal();
1172 PrettyStackTraceProgram X(argc, argv);
1174 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1175 cl::ParseCommandLineOptions(argc, argv, "llvm symbol table dumper\n");
1177 // llvm-nm only reads binary files.
1178 if (error(sys::ChangeStdinToBinary()))
1181 llvm::InitializeAllTargetInfos();
1182 llvm::InitializeAllTargetMCs();
1183 llvm::InitializeAllAsmParsers();
1189 OutputFormat = posix;
1191 OutputFormat = darwin;
1193 // The relative order of these is important. If you pass --size-sort it should
1194 // only print out the size. However, if you pass -S --size-sort, it should
1195 // print out both the size and address.
1196 if (SizeSort && !PrintSize)
1197 PrintAddress = false;
1198 if (OutputFormat == sysv || SizeSort)
1201 switch (InputFilenames.size()) {
1203 InputFilenames.push_back("a.out");
1207 MultipleFiles = true;
1210 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1211 if (ArchFlags[i] == "all") {
1214 if (!MachOObjectFile::isValidArch(ArchFlags[i]))
1215 error("Unknown architecture named '" + ArchFlags[i] + "'",
1216 "for the -arch option");
1220 if (SegSect.size() != 0 && SegSect.size() != 2)
1221 error("bad number of arguments (must be two arguments)",
1222 "for the -s option");
1224 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1225 dumpSymbolNamesFromFile);