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 bool ADefined = !(A.Sym.getFlags() & SymbolRef::SF_Undefined);
189 bool BDefined = !(B.Sym.getFlags() & SymbolRef::SF_Undefined);
190 return std::make_tuple(ADefined, A.Address, A.Name, A.Size) <
191 std::make_tuple(BDefined, B.Address, B.Name, B.Size);
194 static bool compareSymbolSize(const NMSymbol &A, const NMSymbol &B) {
195 return std::make_tuple(A.Size, A.Name, A.Address) <
196 std::make_tuple(B.Size, B.Name, B.Address);
199 static bool compareSymbolName(const NMSymbol &A, const NMSymbol &B) {
200 return std::make_tuple(A.Name, A.Size, A.Address) <
201 std::make_tuple(B.Name, B.Size, B.Address);
204 static char isSymbolList64Bit(SymbolicFile &Obj) {
205 if (isa<IRObjectFile>(Obj))
207 if (isa<COFFObjectFile>(Obj))
209 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj))
210 return MachO->is64Bit();
211 return cast<ELFObjectFileBase>(Obj).getBytesInAddress() == 8;
214 static StringRef CurrentFilename;
215 typedef std::vector<NMSymbol> SymbolListT;
216 static SymbolListT SymbolList;
218 // darwinPrintSymbol() is used to print a symbol from a Mach-O file when the
219 // the OutputFormat is darwin or we are printing Mach-O symbols in hex. For
220 // the darwin format it produces the same output as darwin's nm(1) -m output
221 // and when printing Mach-O symbols in hex it produces the same output as
222 // darwin's nm(1) -x format.
223 static void darwinPrintSymbol(MachOObjectFile *MachO, SymbolListT::iterator I,
224 char *SymbolAddrStr, const char *printBlanks) {
225 MachO::mach_header H;
226 MachO::mach_header_64 H_64;
227 uint32_t Filetype, Flags;
228 MachO::nlist_64 STE_64;
235 DataRefImpl SymDRI = I->Sym.getRawDataRefImpl();
236 if (MachO->is64Bit()) {
237 H_64 = MachO->MachOObjectFile::getHeader64();
238 Filetype = H_64.filetype;
240 STE_64 = MachO->getSymbol64TableEntry(SymDRI);
241 NType = STE_64.n_type;
242 NSect = STE_64.n_sect;
243 NDesc = STE_64.n_desc;
244 NStrx = STE_64.n_strx;
245 NValue = STE_64.n_value;
247 H = MachO->MachOObjectFile::getHeader();
248 Filetype = H.filetype;
250 STE = MachO->getSymbolTableEntry(SymDRI);
255 NValue = STE.n_value;
258 // If we are printing Mach-O symbols in hex do that and return.
259 if (FormatMachOasHex) {
261 const char *printFormat;
262 if (MachO->is64Bit())
263 printFormat = "%016" PRIx64;
265 printFormat = "%08" PRIx64;
266 format(printFormat, NValue).print(Str, sizeof(Str));
267 outs() << Str << ' ';
268 format("%02x", NType).print(Str, sizeof(Str));
269 outs() << Str << ' ';
270 format("%02x", NSect).print(Str, sizeof(Str));
271 outs() << Str << ' ';
272 format("%04x", NDesc).print(Str, sizeof(Str));
273 outs() << Str << ' ';
274 format("%08x", NStrx).print(Str, sizeof(Str));
275 outs() << Str << ' ';
276 outs() << I->Name << "\n";
281 if ((NType & MachO::N_TYPE) == MachO::N_INDR)
282 strcpy(SymbolAddrStr, printBlanks);
283 outs() << SymbolAddrStr << ' ';
286 switch (NType & MachO::N_TYPE) {
289 outs() << "(common) ";
290 if (MachO::GET_COMM_ALIGN(NDesc) != 0)
291 outs() << "(alignment 2^" << (int)MachO::GET_COMM_ALIGN(NDesc) << ") ";
293 if ((NType & MachO::N_TYPE) == MachO::N_PBUD)
294 outs() << "(prebound ";
297 if ((NDesc & MachO::REFERENCE_TYPE) ==
298 MachO::REFERENCE_FLAG_UNDEFINED_LAZY)
299 outs() << "undefined [lazy bound]) ";
300 else if ((NDesc & MachO::REFERENCE_TYPE) ==
301 MachO::REFERENCE_FLAG_UNDEFINED_LAZY)
302 outs() << "undefined [private lazy bound]) ";
303 else if ((NDesc & MachO::REFERENCE_TYPE) ==
304 MachO::REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY)
305 outs() << "undefined [private]) ";
307 outs() << "undefined) ";
311 outs() << "(absolute) ";
314 outs() << "(indirect) ";
316 case MachO::N_SECT: {
317 section_iterator Sec = MachO->section_end();
318 MachO->getSymbolSection(I->Sym.getRawDataRefImpl(), Sec);
319 DataRefImpl Ref = Sec->getRawDataRefImpl();
320 StringRef SectionName;
321 MachO->getSectionName(Ref, SectionName);
322 StringRef SegmentName = MachO->getSectionFinalSegmentName(Ref);
323 outs() << "(" << SegmentName << "," << SectionName << ") ";
331 if (NType & MachO::N_EXT) {
332 if (NDesc & MachO::REFERENCED_DYNAMICALLY)
333 outs() << "[referenced dynamically] ";
334 if (NType & MachO::N_PEXT) {
335 if ((NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF)
336 outs() << "weak private external ";
338 outs() << "private external ";
340 if ((NDesc & MachO::N_WEAK_REF) == MachO::N_WEAK_REF ||
341 (NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF) {
342 if ((NDesc & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF)) ==
343 (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
344 outs() << "weak external automatically hidden ";
346 outs() << "weak external ";
348 outs() << "external ";
351 if (NType & MachO::N_PEXT)
352 outs() << "non-external (was a private external) ";
354 outs() << "non-external ";
357 if (Filetype == MachO::MH_OBJECT &&
358 (NDesc & MachO::N_NO_DEAD_STRIP) == MachO::N_NO_DEAD_STRIP)
359 outs() << "[no dead strip] ";
361 if (Filetype == MachO::MH_OBJECT &&
362 ((NType & MachO::N_TYPE) != MachO::N_UNDF) &&
363 (NDesc & MachO::N_SYMBOL_RESOLVER) == MachO::N_SYMBOL_RESOLVER)
364 outs() << "[symbol resolver] ";
366 if (Filetype == MachO::MH_OBJECT &&
367 ((NType & MachO::N_TYPE) != MachO::N_UNDF) &&
368 (NDesc & MachO::N_ALT_ENTRY) == MachO::N_ALT_ENTRY)
369 outs() << "[alt entry] ";
371 if ((NDesc & MachO::N_ARM_THUMB_DEF) == MachO::N_ARM_THUMB_DEF)
372 outs() << "[Thumb] ";
374 if ((NType & MachO::N_TYPE) == MachO::N_INDR) {
375 outs() << I->Name << " (for ";
376 StringRef IndirectName;
377 if (MachO->getIndirectName(I->Sym.getRawDataRefImpl(), IndirectName))
380 outs() << IndirectName << ")";
384 if ((Flags & MachO::MH_TWOLEVEL) == MachO::MH_TWOLEVEL &&
385 (((NType & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0) ||
386 (NType & MachO::N_TYPE) == MachO::N_PBUD)) {
387 uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(NDesc);
388 if (LibraryOrdinal != 0) {
389 if (LibraryOrdinal == MachO::EXECUTABLE_ORDINAL)
390 outs() << " (from executable)";
391 else if (LibraryOrdinal == MachO::DYNAMIC_LOOKUP_ORDINAL)
392 outs() << " (dynamically looked up)";
394 StringRef LibraryName;
395 if (MachO->getLibraryShortNameByIndex(LibraryOrdinal - 1, LibraryName))
396 outs() << " (from bad library ordinal " << LibraryOrdinal << ")";
398 outs() << " (from " << LibraryName << ")";
406 // Table that maps Darwin's Mach-O stab constants to strings to allow printing.
407 struct DarwinStabName {
411 static const struct DarwinStabName DarwinStabNames[] = {
412 {MachO::N_GSYM, "GSYM"},
413 {MachO::N_FNAME, "FNAME"},
414 {MachO::N_FUN, "FUN"},
415 {MachO::N_STSYM, "STSYM"},
416 {MachO::N_LCSYM, "LCSYM"},
417 {MachO::N_BNSYM, "BNSYM"},
419 {MachO::N_AST, "AST"},
420 {MachO::N_OPT, "OPT"},
421 {MachO::N_RSYM, "RSYM"},
422 {MachO::N_SLINE, "SLINE"},
423 {MachO::N_ENSYM, "ENSYM"},
424 {MachO::N_SSYM, "SSYM"},
426 {MachO::N_OSO, "OSO"},
427 {MachO::N_LSYM, "LSYM"},
428 {MachO::N_BINCL, "BINCL"},
429 {MachO::N_SOL, "SOL"},
430 {MachO::N_PARAMS, "PARAM"},
431 {MachO::N_VERSION, "VERS"},
432 {MachO::N_OLEVEL, "OLEV"},
433 {MachO::N_PSYM, "PSYM"},
434 {MachO::N_EINCL, "EINCL"},
435 {MachO::N_ENTRY, "ENTRY"},
436 {MachO::N_LBRAC, "LBRAC"},
437 {MachO::N_EXCL, "EXCL"},
438 {MachO::N_RBRAC, "RBRAC"},
439 {MachO::N_BCOMM, "BCOMM"},
440 {MachO::N_ECOMM, "ECOMM"},
441 {MachO::N_ECOML, "ECOML"},
442 {MachO::N_LENG, "LENG"},
444 static const char *getDarwinStabString(uint8_t NType) {
445 for (unsigned i = 0; DarwinStabNames[i].Name; i++) {
446 if (DarwinStabNames[i].NType == NType)
447 return DarwinStabNames[i].Name;
452 // darwinPrintStab() prints the n_sect, n_desc along with a symbolic name of
453 // a stab n_type value in a Mach-O file.
454 static void darwinPrintStab(MachOObjectFile *MachO, SymbolListT::iterator I) {
455 MachO::nlist_64 STE_64;
460 DataRefImpl SymDRI = I->Sym.getRawDataRefImpl();
461 if (MachO->is64Bit()) {
462 STE_64 = MachO->getSymbol64TableEntry(SymDRI);
463 NType = STE_64.n_type;
464 NSect = STE_64.n_sect;
465 NDesc = STE_64.n_desc;
467 STE = MachO->getSymbolTableEntry(SymDRI);
474 format("%02x", NSect).print(Str, sizeof(Str));
475 outs() << ' ' << Str << ' ';
476 format("%04x", NDesc).print(Str, sizeof(Str));
477 outs() << Str << ' ';
478 if (const char *stabString = getDarwinStabString(NType))
479 format("%5.5s", stabString).print(Str, sizeof(Str));
481 format(" %02x", NType).print(Str, sizeof(Str));
485 static void sortAndPrintSymbolList(SymbolicFile &Obj, bool printName,
486 std::string ArchiveName,
487 std::string ArchitectureName) {
489 std::function<bool(const NMSymbol &, const NMSymbol &)> Cmp;
491 Cmp = compareSymbolAddress;
493 Cmp = compareSymbolSize;
495 Cmp = compareSymbolName;
498 Cmp = [=](const NMSymbol &A, const NMSymbol &B) { return Cmp(B, A); };
499 std::sort(SymbolList.begin(), SymbolList.end(), Cmp);
502 if (!PrintFileName) {
503 if (OutputFormat == posix && MultipleFiles && printName) {
504 outs() << '\n' << CurrentFilename << ":\n";
505 } else if (OutputFormat == bsd && MultipleFiles && printName) {
506 outs() << "\n" << CurrentFilename << ":\n";
507 } else if (OutputFormat == sysv) {
508 outs() << "\n\nSymbols from " << CurrentFilename << ":\n\n"
509 << "Name Value Class Type"
510 << " Size Line Section\n";
514 const char *printBlanks, *printFormat;
515 if (isSymbolList64Bit(Obj)) {
517 printFormat = "%016" PRIx64;
520 printFormat = "%08" PRIx64;
523 for (SymbolListT::iterator I = SymbolList.begin(), E = SymbolList.end();
525 uint32_t SymFlags = I->Sym.getFlags();
526 bool Undefined = SymFlags & SymbolRef::SF_Undefined;
527 if (!Undefined && UndefinedOnly)
529 if (Undefined && DefinedOnly)
531 if (SizeSort && !PrintAddress)
534 if (!ArchitectureName.empty())
535 outs() << "(for architecture " << ArchitectureName << "):";
536 if (!ArchiveName.empty())
537 outs() << ArchiveName << ":";
538 outs() << CurrentFilename << ": ";
540 if (JustSymbolName || (UndefinedOnly && isa<MachOObjectFile>(Obj))) {
541 outs() << I->Name << "\n";
545 char SymbolAddrStr[18] = "";
546 char SymbolSizeStr[18] = "";
548 if (OutputFormat == sysv || I->TypeChar == 'U')
549 strcpy(SymbolAddrStr, printBlanks);
550 if (OutputFormat == sysv)
551 strcpy(SymbolSizeStr, printBlanks);
553 if (I->TypeChar != 'U')
554 format(printFormat, I->Address)
555 .print(SymbolAddrStr, sizeof(SymbolAddrStr));
556 format(printFormat, I->Size).print(SymbolSizeStr, sizeof(SymbolSizeStr));
558 // If OutputFormat is darwin or we are printing Mach-O symbols in hex and
559 // we have a MachOObjectFile, call darwinPrintSymbol to print as darwin's
560 // nm(1) -m output or hex, else if OutputFormat is darwin or we are
561 // printing Mach-O symbols in hex and not a Mach-O object fall back to
562 // OutputFormat bsd (see below).
563 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj);
564 if ((OutputFormat == darwin || FormatMachOasHex) && MachO) {
565 darwinPrintSymbol(MachO, I, SymbolAddrStr, printBlanks);
566 } else if (OutputFormat == posix) {
567 outs() << I->Name << " " << I->TypeChar << " " << SymbolAddrStr
568 << SymbolSizeStr << "\n";
569 } else if (OutputFormat == bsd || (OutputFormat == darwin && !MachO)) {
571 outs() << SymbolAddrStr << ' ';
573 outs() << SymbolSizeStr;
576 outs() << I->TypeChar;
577 if (I->TypeChar == '-' && MachO)
578 darwinPrintStab(MachO, I);
579 outs() << " " << I->Name << "\n";
580 } else if (OutputFormat == sysv) {
581 std::string PaddedName(I->Name);
582 while (PaddedName.length() < 20)
584 outs() << PaddedName << "|" << SymbolAddrStr << "| " << I->TypeChar
585 << " | |" << SymbolSizeStr << "| |\n";
592 static char getSymbolNMTypeChar(ELFObjectFileBase &Obj,
593 basic_symbol_iterator I) {
595 elf_symbol_iterator SymI(I);
597 elf_section_iterator SecI = Obj.section_end();
598 if (error(SymI->getSection(SecI)))
601 if (SecI != Obj.section_end()) {
602 switch (SecI->getType()) {
603 case ELF::SHT_PROGBITS:
604 case ELF::SHT_DYNAMIC:
605 switch (SecI->getFlags()) {
606 case (ELF::SHF_ALLOC | ELF::SHF_EXECINSTR):
608 case (ELF::SHF_TLS | ELF::SHF_ALLOC | ELF::SHF_WRITE):
609 case (ELF::SHF_ALLOC | ELF::SHF_WRITE):
612 case (ELF::SHF_ALLOC | ELF::SHF_MERGE):
613 case (ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS):
617 case ELF::SHT_NOBITS:
622 if (SymI->getELFType() == ELF::STT_SECTION) {
623 ErrorOr<StringRef> Name = SymI->getName();
624 if (error(Name.getError()))
626 return StringSwitch<char>(*Name)
627 .StartsWith(".debug", 'N')
628 .StartsWith(".note", 'n')
635 static char getSymbolNMTypeChar(COFFObjectFile &Obj, symbol_iterator I) {
636 COFFSymbolRef Symb = Obj.getCOFFSymbol(*I);
638 symbol_iterator SymI(I);
640 ErrorOr<StringRef> Name = SymI->getName();
641 if (error(Name.getError()))
644 char Ret = StringSwitch<char>(*Name)
645 .StartsWith(".debug", 'N')
646 .StartsWith(".sxdata", 'N')
652 uint32_t Characteristics = 0;
653 if (!COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
654 section_iterator SecI = Obj.section_end();
655 if (error(SymI->getSection(SecI)))
657 const coff_section *Section = Obj.getCOFFSection(*SecI);
658 Characteristics = Section->Characteristics;
661 switch (Symb.getSectionNumber()) {
662 case COFF::IMAGE_SYM_DEBUG:
665 // Check section type.
666 if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
668 if (Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
669 return Characteristics & COFF::IMAGE_SCN_MEM_WRITE ? 'd' : 'r';
670 if (Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
672 if (Characteristics & COFF::IMAGE_SCN_LNK_INFO)
674 // Check for section symbol.
675 if (Symb.isSectionDefinition())
682 static uint8_t getNType(MachOObjectFile &Obj, DataRefImpl Symb) {
684 MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb);
687 MachO::nlist STE = Obj.getSymbolTableEntry(Symb);
691 static char getSymbolNMTypeChar(MachOObjectFile &Obj, basic_symbol_iterator I) {
692 DataRefImpl Symb = I->getRawDataRefImpl();
693 uint8_t NType = getNType(Obj, Symb);
695 if (NType & MachO::N_STAB)
698 switch (NType & MachO::N_TYPE) {
703 case MachO::N_SECT: {
704 section_iterator Sec = Obj.section_end();
705 Obj.getSymbolSection(Symb, Sec);
706 DataRefImpl Ref = Sec->getRawDataRefImpl();
707 StringRef SectionName;
708 Obj.getSectionName(Ref, SectionName);
709 StringRef SegmentName = Obj.getSectionFinalSegmentName(Ref);
710 if (SegmentName == "__TEXT" && SectionName == "__text")
712 else if (SegmentName == "__DATA" && SectionName == "__data")
714 else if (SegmentName == "__DATA" && SectionName == "__bss")
724 static char getSymbolNMTypeChar(const GlobalValue &GV) {
725 if (GV.getType()->getElementType()->isFunctionTy())
727 // FIXME: should we print 'b'? At the IR level we cannot be sure if this
728 // will be in bss or not, but we could approximate.
732 static char getSymbolNMTypeChar(IRObjectFile &Obj, basic_symbol_iterator I) {
733 const GlobalValue *GV = Obj.getSymbolGV(I->getRawDataRefImpl());
736 return getSymbolNMTypeChar(*GV);
739 static bool isObject(SymbolicFile &Obj, basic_symbol_iterator I) {
740 auto *ELF = dyn_cast<ELFObjectFileBase>(&Obj);
744 return elf_symbol_iterator(I)->getELFType() == ELF::STT_OBJECT;
747 static char getNMTypeChar(SymbolicFile &Obj, basic_symbol_iterator I) {
748 uint32_t Symflags = I->getFlags();
749 if ((Symflags & object::SymbolRef::SF_Weak) && !isa<MachOObjectFile>(Obj)) {
750 char Ret = isObject(Obj, I) ? 'v' : 'w';
751 if (!(Symflags & object::SymbolRef::SF_Undefined))
756 if (Symflags & object::SymbolRef::SF_Undefined)
759 if (Symflags & object::SymbolRef::SF_Common)
763 if (Symflags & object::SymbolRef::SF_Absolute)
765 else if (IRObjectFile *IR = dyn_cast<IRObjectFile>(&Obj))
766 Ret = getSymbolNMTypeChar(*IR, I);
767 else if (COFFObjectFile *COFF = dyn_cast<COFFObjectFile>(&Obj))
768 Ret = getSymbolNMTypeChar(*COFF, I);
769 else if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj))
770 Ret = getSymbolNMTypeChar(*MachO, I);
772 Ret = getSymbolNMTypeChar(cast<ELFObjectFileBase>(Obj), I);
774 if (Symflags & object::SymbolRef::SF_Global)
780 // getNsectForSegSect() is used to implement the Mach-O "-s segname sectname"
781 // option to dump only those symbols from that section in a Mach-O file.
782 // It is called once for each Mach-O file from dumpSymbolNamesFromObject()
783 // to get the section number for that named section from the command line
784 // arguments. It returns the section number for that section in the Mach-O
785 // file or zero it is not present.
786 static unsigned getNsectForSegSect(MachOObjectFile *Obj) {
788 for (section_iterator I = Obj->section_begin(), E = Obj->section_end();
790 DataRefImpl Ref = I->getRawDataRefImpl();
791 StringRef SectionName;
792 Obj->getSectionName(Ref, SectionName);
793 StringRef SegmentName = Obj->getSectionFinalSegmentName(Ref);
794 if (SegmentName == SegSect[0] && SectionName == SegSect[1])
801 // getNsectInMachO() is used to implement the Mach-O "-s segname sectname"
802 // option to dump only those symbols from that section in a Mach-O file.
803 // It is called once for each symbol in a Mach-O file from
804 // dumpSymbolNamesFromObject() and returns the section number for that symbol
805 // if it is in a section, else it returns 0.
806 static unsigned getNsectInMachO(MachOObjectFile &Obj, BasicSymbolRef Sym) {
807 DataRefImpl Symb = Sym.getRawDataRefImpl();
809 MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb);
810 if ((STE.n_type & MachO::N_TYPE) == MachO::N_SECT)
814 MachO::nlist STE = Obj.getSymbolTableEntry(Symb);
815 if ((STE.n_type & MachO::N_TYPE) == MachO::N_SECT)
820 static void dumpSymbolNamesFromObject(SymbolicFile &Obj, bool printName,
821 std::string ArchiveName = std::string(),
822 std::string ArchitectureName =
824 auto Symbols = Obj.symbols();
826 const auto *E = dyn_cast<ELFObjectFileBase>(&Obj);
828 error("File format has no dynamic symbol table", Obj.getFileName());
831 auto DynSymbols = E->getDynamicSymbolIterators();
833 make_range<basic_symbol_iterator>(DynSymbols.begin(), DynSymbols.end());
835 std::string NameBuffer;
836 raw_string_ostream OS(NameBuffer);
837 // If a "-s segname sectname" option was specified and this is a Mach-O
838 // file get the section number for that section in this object file.
839 unsigned int Nsect = 0;
840 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj);
841 if (SegSect.size() != 0 && MachO) {
842 Nsect = getNsectForSegSect(MachO);
843 // If this section is not in the object file no symbols are printed.
847 for (BasicSymbolRef Sym : Symbols) {
848 uint32_t SymFlags = Sym.getFlags();
849 if (!DebugSyms && (SymFlags & SymbolRef::SF_FormatSpecific))
851 if (WithoutAliases) {
852 if (IRObjectFile *IR = dyn_cast<IRObjectFile>(&Obj)) {
853 const GlobalValue *GV = IR->getSymbolGV(Sym.getRawDataRefImpl());
854 if (GV && isa<GlobalAlias>(GV))
858 // If a "-s segname sectname" option was specified and this is a Mach-O
859 // file and this section appears in this file, Nsect will be non-zero then
860 // see if this symbol is a symbol from that section and if not skip it.
861 if (Nsect && Nsect != getNsectInMachO(*MachO, Sym))
867 if (isa<ELFObjectFileBase>(&Obj))
868 S.Size = ELFSymbolRef(Sym).getSize();
870 if (PrintAddress && isa<ObjectFile>(Obj)) {
871 SymbolRef SymRef(Sym);
872 ErrorOr<uint64_t> AddressOrErr = SymRef.getAddress();
873 if (error(AddressOrErr.getError()))
875 S.Address = *AddressOrErr;
877 S.TypeChar = getNMTypeChar(Obj, Sym);
878 if (error(Sym.printName(OS)))
882 SymbolList.push_back(S);
886 const char *P = NameBuffer.c_str();
887 for (unsigned I = 0; I < SymbolList.size(); ++I) {
888 SymbolList[I].Name = P;
892 CurrentFilename = Obj.getFileName();
893 sortAndPrintSymbolList(Obj, printName, ArchiveName, ArchitectureName);
896 // checkMachOAndArchFlags() checks to see if the SymbolicFile is a Mach-O file
897 // and if it is and there is a list of architecture flags is specified then
898 // check to make sure this Mach-O file is one of those architectures or all
899 // architectures was specificed. If not then an error is generated and this
900 // routine returns false. Else it returns true.
901 static bool checkMachOAndArchFlags(SymbolicFile *O, std::string &Filename) {
902 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
904 if (!MachO || ArchAll || ArchFlags.size() == 0)
907 MachO::mach_header H;
908 MachO::mach_header_64 H_64;
910 if (MachO->is64Bit()) {
911 H_64 = MachO->MachOObjectFile::getHeader64();
912 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
914 H = MachO->MachOObjectFile::getHeader();
915 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
918 ArchFlags.begin(), ArchFlags.end(),
919 [&](const std::string &Name) { return Name == T.getArchName(); })) {
920 error("No architecture specified", Filename);
926 static void dumpSymbolNamesFromFile(std::string &Filename) {
927 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
928 MemoryBuffer::getFileOrSTDIN(Filename);
929 if (error(BufferOrErr.getError(), Filename))
932 LLVMContext &Context = getGlobalContext();
933 ErrorOr<std::unique_ptr<Binary>> BinaryOrErr = createBinary(
934 BufferOrErr.get()->getMemBufferRef(), NoLLVMBitcode ? nullptr : &Context);
935 if (error(BinaryOrErr.getError(), Filename))
937 Binary &Bin = *BinaryOrErr.get();
939 if (Archive *A = dyn_cast<Archive>(&Bin)) {
941 Archive::symbol_iterator I = A->symbol_begin();
942 Archive::symbol_iterator E = A->symbol_end();
944 outs() << "Archive map\n";
945 for (; I != E; ++I) {
946 ErrorOr<Archive::child_iterator> C = I->getMember();
947 if (error(C.getError()))
949 ErrorOr<StringRef> FileNameOrErr = C.get()->getName();
950 if (error(FileNameOrErr.getError()))
952 StringRef SymName = I->getName();
953 outs() << SymName << " in " << FileNameOrErr.get() << "\n";
959 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
961 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary(&Context);
962 if (ChildOrErr.getError())
964 if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
965 if (!checkMachOAndArchFlags(O, Filename))
967 if (!PrintFileName) {
969 if (isa<MachOObjectFile>(O)) {
970 outs() << Filename << "(" << O->getFileName() << ")";
972 outs() << O->getFileName();
975 dumpSymbolNamesFromObject(*O, false, Filename);
980 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
981 // If we have a list of architecture flags specified dump only those.
982 if (!ArchAll && ArchFlags.size() != 0) {
983 // Look for a slice in the universal binary that matches each ArchFlag.
985 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
987 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
988 E = UB->end_objects();
990 if (ArchFlags[i] == I->getArchTypeName()) {
992 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
993 I->getAsObjectFile();
994 std::string ArchiveName;
995 std::string ArchitectureName;
997 ArchitectureName.clear();
999 ObjectFile &Obj = *ObjOrErr.get();
1000 if (ArchFlags.size() > 1) {
1002 ArchitectureName = I->getArchTypeName();
1004 outs() << "\n" << Obj.getFileName() << " (for architecture "
1005 << I->getArchTypeName() << ")"
1008 dumpSymbolNamesFromObject(Obj, false, ArchiveName,
1010 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1011 I->getAsArchive()) {
1012 std::unique_ptr<Archive> &A = *AOrErr;
1013 for (Archive::child_iterator AI = A->child_begin(),
1014 AE = A->child_end();
1016 ErrorOr<std::unique_ptr<Binary>> ChildOrErr =
1017 AI->getAsBinary(&Context);
1018 if (ChildOrErr.getError())
1020 if (SymbolicFile *O =
1021 dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1022 if (PrintFileName) {
1023 ArchiveName = A->getFileName();
1024 if (ArchFlags.size() > 1)
1025 ArchitectureName = I->getArchTypeName();
1027 outs() << "\n" << A->getFileName();
1028 outs() << "(" << O->getFileName() << ")";
1029 if (ArchFlags.size() > 1) {
1030 outs() << " (for architecture " << I->getArchTypeName()
1035 dumpSymbolNamesFromObject(*O, false, ArchiveName,
1044 "file: " + Filename + " does not contain architecture");
1050 // No architecture flags were specified so if this contains a slice that
1051 // matches the host architecture dump only that.
1053 StringRef HostArchName = MachOObjectFile::getHostArch().getArchName();
1054 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1055 E = UB->end_objects();
1057 if (HostArchName == I->getArchTypeName()) {
1058 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1059 std::string ArchiveName;
1060 ArchiveName.clear();
1062 ObjectFile &Obj = *ObjOrErr.get();
1063 dumpSymbolNamesFromObject(Obj, false);
1064 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1065 I->getAsArchive()) {
1066 std::unique_ptr<Archive> &A = *AOrErr;
1067 for (Archive::child_iterator AI = A->child_begin(),
1068 AE = A->child_end();
1070 ErrorOr<std::unique_ptr<Binary>> ChildOrErr =
1071 AI->getAsBinary(&Context);
1072 if (ChildOrErr.getError())
1074 if (SymbolicFile *O =
1075 dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1077 ArchiveName = A->getFileName();
1079 outs() << "\n" << A->getFileName() << "(" << O->getFileName()
1082 dumpSymbolNamesFromObject(*O, false, ArchiveName);
1090 // Either all architectures have been specified or none have been specified
1091 // and this does not contain the host architecture so dump all the slices.
1092 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1093 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1094 E = UB->end_objects();
1096 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1097 std::string ArchiveName;
1098 std::string ArchitectureName;
1099 ArchiveName.clear();
1100 ArchitectureName.clear();
1102 ObjectFile &Obj = *ObjOrErr.get();
1103 if (PrintFileName) {
1104 if (isa<MachOObjectFile>(Obj) && moreThanOneArch)
1105 ArchitectureName = I->getArchTypeName();
1107 if (moreThanOneArch)
1109 outs() << Obj.getFileName();
1110 if (isa<MachOObjectFile>(Obj) && moreThanOneArch)
1111 outs() << " (for architecture " << I->getArchTypeName() << ")";
1114 dumpSymbolNamesFromObject(Obj, false, ArchiveName, ArchitectureName);
1115 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1116 std::unique_ptr<Archive> &A = *AOrErr;
1117 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1119 ErrorOr<std::unique_ptr<Binary>> ChildOrErr =
1120 AI->getAsBinary(&Context);
1121 if (ChildOrErr.getError())
1123 if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1124 if (PrintFileName) {
1125 ArchiveName = A->getFileName();
1126 if (isa<MachOObjectFile>(O) && moreThanOneArch)
1127 ArchitectureName = I->getArchTypeName();
1129 outs() << "\n" << A->getFileName();
1130 if (isa<MachOObjectFile>(O)) {
1131 outs() << "(" << O->getFileName() << ")";
1132 if (moreThanOneArch)
1133 outs() << " (for architecture " << I->getArchTypeName()
1136 outs() << ":" << O->getFileName();
1139 dumpSymbolNamesFromObject(*O, false, ArchiveName, ArchitectureName);
1146 if (SymbolicFile *O = dyn_cast<SymbolicFile>(&Bin)) {
1147 if (!checkMachOAndArchFlags(O, Filename))
1149 dumpSymbolNamesFromObject(*O, true);
1152 error("unrecognizable file type", Filename);
1156 int main(int argc, char **argv) {
1157 // Print a stack trace if we signal out.
1158 sys::PrintStackTraceOnErrorSignal();
1159 PrettyStackTraceProgram X(argc, argv);
1161 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1162 cl::ParseCommandLineOptions(argc, argv, "llvm symbol table dumper\n");
1164 // llvm-nm only reads binary files.
1165 if (error(sys::ChangeStdinToBinary()))
1168 llvm::InitializeAllTargetInfos();
1169 llvm::InitializeAllTargetMCs();
1170 llvm::InitializeAllAsmParsers();
1176 OutputFormat = posix;
1178 OutputFormat = darwin;
1180 // The relative order of these is important. If you pass --size-sort it should
1181 // only print out the size. However, if you pass -S --size-sort, it should
1182 // print out both the size and address.
1183 if (SizeSort && !PrintSize)
1184 PrintAddress = false;
1185 if (OutputFormat == sysv || SizeSort)
1188 switch (InputFilenames.size()) {
1190 InputFilenames.push_back("a.out");
1194 MultipleFiles = true;
1197 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1198 if (ArchFlags[i] == "all") {
1201 if (!MachOObjectFile::isValidArch(ArchFlags[i]))
1202 error("Unknown architecture named '" + ArchFlags[i] + "'",
1203 "for the -arch option");
1207 if (SegSect.size() != 0 && SegSect.size() != 2)
1208 error("bad number of arguments (must be two arguments)",
1209 "for the -s option");
1211 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1212 dumpSymbolNamesFromFile);