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/ADT/StringSwitch.h"
20 #include "llvm/BinaryFormat/COFF.h"
21 #include "llvm/Demangle/Demangle.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/Object/Archive.h"
25 #include "llvm/Object/COFF.h"
26 #include "llvm/Object/COFFImportFile.h"
27 #include "llvm/Object/ELFObjectFile.h"
28 #include "llvm/Object/IRObjectFile.h"
29 #include "llvm/Object/MachO.h"
30 #include "llvm/Object/MachOUniversal.h"
31 #include "llvm/Object/ObjectFile.h"
32 #include "llvm/Object/Wasm.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/FileSystem.h"
35 #include "llvm/Support/Format.h"
36 #include "llvm/Support/InitLLVM.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/Program.h"
39 #include "llvm/Support/Signals.h"
40 #include "llvm/Support/TargetSelect.h"
41 #include "llvm/Support/raw_ostream.h"
45 using namespace object;
48 enum OutputFormatTy { bsd, sysv, posix, darwin };
49 cl::opt<OutputFormatTy> OutputFormat(
50 "format", cl::desc("Specify output format"),
51 cl::values(clEnumVal(bsd, "BSD format"), clEnumVal(sysv, "System V format"),
52 clEnumVal(posix, "POSIX.2 format"),
53 clEnumVal(darwin, "Darwin -m format")),
55 cl::alias OutputFormat2("f", cl::desc("Alias for --format"),
56 cl::aliasopt(OutputFormat));
58 cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<input files>"),
61 cl::opt<bool> UndefinedOnly("undefined-only",
62 cl::desc("Show only undefined symbols"));
63 cl::alias UndefinedOnly2("u", cl::desc("Alias for --undefined-only"),
64 cl::aliasopt(UndefinedOnly), cl::Grouping);
66 cl::opt<bool> DynamicSyms("dynamic",
67 cl::desc("Display the dynamic symbols instead "
68 "of normal symbols."));
69 cl::alias DynamicSyms2("D", cl::desc("Alias for --dynamic"),
70 cl::aliasopt(DynamicSyms), cl::Grouping);
72 cl::opt<bool> DefinedOnly("defined-only",
73 cl::desc("Show only defined symbols"));
74 cl::alias DefinedOnly2("U", cl::desc("Alias for --defined-only"),
75 cl::aliasopt(DefinedOnly), cl::Grouping);
77 cl::opt<bool> ExternalOnly("extern-only",
78 cl::desc("Show only external symbols"),
80 cl::alias ExternalOnly2("g", cl::desc("Alias for --extern-only"),
81 cl::aliasopt(ExternalOnly), cl::Grouping,
84 cl::opt<bool> NoWeakSymbols("no-weak",
85 cl::desc("Show only non-weak symbols"));
86 cl::alias NoWeakSymbols2("W", cl::desc("Alias for --no-weak"),
87 cl::aliasopt(NoWeakSymbols), cl::Grouping);
89 cl::opt<bool> BSDFormat("B", cl::desc("Alias for --format=bsd"),
91 cl::opt<bool> POSIXFormat("P", cl::desc("Alias for --format=posix"),
93 cl::opt<bool> DarwinFormat("m", cl::desc("Alias for --format=darwin"),
96 static cl::list<std::string>
97 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
101 cl::opt<bool> PrintFileName(
103 cl::desc("Precede each symbol with the object file it came from"));
105 cl::alias PrintFileNameA("A", cl::desc("Alias for --print-file-name"),
106 cl::aliasopt(PrintFileName), cl::Grouping);
107 cl::alias PrintFileNameo("o", cl::desc("Alias for --print-file-name"),
108 cl::aliasopt(PrintFileName), cl::Grouping);
110 cl::opt<bool> DebugSyms("debug-syms",
111 cl::desc("Show all symbols, even debugger only"));
112 cl::alias DebugSymsa("a", cl::desc("Alias for --debug-syms"),
113 cl::aliasopt(DebugSyms), cl::Grouping);
115 cl::opt<bool> NumericSort("numeric-sort", cl::desc("Sort symbols by address"));
116 cl::alias NumericSortn("n", cl::desc("Alias for --numeric-sort"),
117 cl::aliasopt(NumericSort), cl::Grouping);
118 cl::alias NumericSortv("v", cl::desc("Alias for --numeric-sort"),
119 cl::aliasopt(NumericSort), cl::Grouping);
121 cl::opt<bool> NoSort("no-sort", cl::desc("Show symbols in order encountered"));
122 cl::alias NoSortp("p", cl::desc("Alias for --no-sort"), cl::aliasopt(NoSort),
125 cl::opt<bool> Demangle("demangle", cl::desc("Demangle C++ symbol names"));
126 cl::alias DemangleC("C", cl::desc("Alias for --demangle"), cl::aliasopt(Demangle),
129 cl::opt<bool> ReverseSort("reverse-sort", cl::desc("Sort in reverse order"));
130 cl::alias ReverseSortr("r", cl::desc("Alias for --reverse-sort"),
131 cl::aliasopt(ReverseSort), cl::Grouping);
133 cl::opt<bool> PrintSize("print-size",
134 cl::desc("Show symbol size instead of address"));
135 cl::alias PrintSizeS("S", cl::desc("Alias for --print-size"),
136 cl::aliasopt(PrintSize), cl::Grouping);
137 bool MachOPrintSizeWarning = false;
139 cl::opt<bool> SizeSort("size-sort", cl::desc("Sort symbols by size"));
141 cl::opt<bool> WithoutAliases("without-aliases", cl::Hidden,
142 cl::desc("Exclude aliases from output"));
144 cl::opt<bool> ArchiveMap("print-armap", cl::desc("Print the archive map"));
145 cl::alias ArchiveMaps("M", cl::desc("Alias for --print-armap"),
146 cl::aliasopt(ArchiveMap), cl::Grouping);
148 enum Radix { d, o, x };
150 AddressRadix("radix", cl::desc("Radix (o/d/x) for printing symbol Values"),
151 cl::values(clEnumVal(d, "decimal"), clEnumVal(o, "octal"),
152 clEnumVal(x, "hexadecimal")),
154 cl::alias RadixAlias("t", cl::desc("Alias for --radix"),
155 cl::aliasopt(AddressRadix));
157 cl::opt<bool> JustSymbolName("just-symbol-name",
158 cl::desc("Print just the symbol's name"));
159 cl::alias JustSymbolNames("j", cl::desc("Alias for --just-symbol-name"),
160 cl::aliasopt(JustSymbolName), cl::Grouping);
162 // FIXME: This option takes exactly two strings and should be allowed anywhere
163 // on the command line. Such that "llvm-nm -s __TEXT __text foo.o" would work.
164 // But that does not as the CommandLine Library does not have a way to make
165 // this work. For now the "-s __TEXT __text" has to be last on the command
167 cl::list<std::string> SegSect("s", cl::Positional, cl::ZeroOrMore,
168 cl::desc("Dump only symbols from this segment "
169 "and section name, Mach-O only"));
171 cl::opt<bool> FormatMachOasHex("x", cl::desc("Print symbol entry in hex, "
172 "Mach-O only"), cl::Grouping);
173 cl::opt<bool> AddDyldInfo("add-dyldinfo",
174 cl::desc("Add symbols from the dyldinfo not already "
175 "in the symbol table, Mach-O only"));
176 cl::opt<bool> NoDyldInfo("no-dyldinfo",
177 cl::desc("Don't add any symbols from the dyldinfo, "
179 cl::opt<bool> DyldInfoOnly("dyldinfo-only",
180 cl::desc("Show only symbols from the dyldinfo, "
183 cl::opt<bool> NoLLVMBitcode("no-llvm-bc",
184 cl::desc("Disable LLVM bitcode reader"));
186 bool PrintAddress = true;
188 bool MultipleFiles = false;
190 bool HadError = false;
192 std::string ToolName;
193 } // anonymous namespace
195 static void error(Twine Message, Twine Path = Twine()) {
197 errs() << ToolName << ": " << Path << ": " << Message << ".\n";
200 static bool error(std::error_code EC, Twine Path = Twine()) {
202 error(EC.message(), Path);
208 // This version of error() prints the archive name and member name, for example:
209 // "libx.a(foo.o)" after the ToolName before the error message. It sets
210 // HadError but returns allowing the code to move on to other archive members.
211 static void error(llvm::Error E, StringRef FileName, const Archive::Child &C,
212 StringRef ArchitectureName = StringRef()) {
214 errs() << ToolName << ": " << FileName;
216 Expected<StringRef> NameOrErr = C.getName();
217 // TODO: if we have a error getting the name then it would be nice to print
218 // the index of which archive member this is and or its offset in the
219 // archive instead of "???" as the name.
221 consumeError(NameOrErr.takeError());
222 errs() << "(" << "???" << ")";
224 errs() << "(" << NameOrErr.get() << ")";
226 if (!ArchitectureName.empty())
227 errs() << " (for architecture " << ArchitectureName << ") ";
230 raw_string_ostream OS(Buf);
231 logAllUnhandledErrors(std::move(E), OS, "");
233 errs() << " " << Buf << "\n";
236 // This version of error() prints the file name and which architecture slice it
237 // is from, for example: "foo.o (for architecture i386)" after the ToolName
238 // before the error message. It sets HadError but returns allowing the code to
239 // move on to other architecture slices.
240 static void error(llvm::Error E, StringRef FileName,
241 StringRef ArchitectureName = StringRef()) {
243 errs() << ToolName << ": " << FileName;
245 if (!ArchitectureName.empty())
246 errs() << " (for architecture " << ArchitectureName << ") ";
249 raw_string_ostream OS(Buf);
250 logAllUnhandledErrors(std::move(E), OS, "");
252 errs() << " " << Buf << "\n";
262 // The Sym field above points to the native symbol in the object file,
263 // for Mach-O when we are creating symbols from the dyld info the above
264 // pointer is null as there is no native symbol. In these cases the fields
265 // below are filled in to represent what would have been a Mach-O nlist
272 StringRef IndirectName;
274 } // anonymous namespace
276 static bool compareSymbolAddress(const NMSymbol &A, const NMSymbol &B) {
278 if (A.Sym.getRawDataRefImpl().p)
279 ADefined = !(A.Sym.getFlags() & SymbolRef::SF_Undefined);
281 ADefined = A.TypeChar != 'U';
283 if (B.Sym.getRawDataRefImpl().p)
284 BDefined = !(B.Sym.getFlags() & SymbolRef::SF_Undefined);
286 BDefined = B.TypeChar != 'U';
287 return std::make_tuple(ADefined, A.Address, A.Name, A.Size) <
288 std::make_tuple(BDefined, B.Address, B.Name, B.Size);
291 static bool compareSymbolSize(const NMSymbol &A, const NMSymbol &B) {
292 return std::make_tuple(A.Size, A.Name, A.Address) <
293 std::make_tuple(B.Size, B.Name, B.Address);
296 static bool compareSymbolName(const NMSymbol &A, const NMSymbol &B) {
297 return std::make_tuple(A.Name, A.Size, A.Address) <
298 std::make_tuple(B.Name, B.Size, B.Address);
301 static char isSymbolList64Bit(SymbolicFile &Obj) {
302 if (auto *IRObj = dyn_cast<IRObjectFile>(&Obj))
303 return Triple(IRObj->getTargetTriple()).isArch64Bit();
304 if (isa<COFFObjectFile>(Obj) || isa<COFFImportFile>(Obj))
306 if (isa<WasmObjectFile>(Obj))
308 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj))
309 return MachO->is64Bit();
310 return cast<ELFObjectFileBase>(Obj).getBytesInAddress() == 8;
313 static StringRef CurrentFilename;
314 typedef std::vector<NMSymbol> SymbolListT;
315 static SymbolListT SymbolList;
317 static char getSymbolNMTypeChar(IRObjectFile &Obj, basic_symbol_iterator I);
319 // darwinPrintSymbol() is used to print a symbol from a Mach-O file when the
320 // the OutputFormat is darwin or we are printing Mach-O symbols in hex. For
321 // the darwin format it produces the same output as darwin's nm(1) -m output
322 // and when printing Mach-O symbols in hex it produces the same output as
323 // darwin's nm(1) -x format.
324 static void darwinPrintSymbol(SymbolicFile &Obj, SymbolListT::iterator I,
325 char *SymbolAddrStr, const char *printBlanks,
326 const char *printDashes, const char *printFormat) {
327 MachO::mach_header H;
328 MachO::mach_header_64 H_64;
329 uint32_t Filetype = MachO::MH_OBJECT;
336 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj);
338 uint32_t SymFlags = I->Sym.getFlags();
339 if (SymFlags & SymbolRef::SF_Global)
340 NType |= MachO::N_EXT;
341 if (SymFlags & SymbolRef::SF_Hidden)
342 NType |= MachO::N_PEXT;
343 if (SymFlags & SymbolRef::SF_Undefined)
344 NType |= MachO::N_EXT | MachO::N_UNDF;
346 // Here we have a symbol definition. So to fake out a section name we
347 // use 1, 2 and 3 for section numbers. See below where they are used to
348 // print out fake section names.
349 NType |= MachO::N_SECT;
350 if (SymFlags & SymbolRef::SF_Const)
352 else if (SymFlags & SymbolRef::SF_Executable)
357 if (SymFlags & SymbolRef::SF_Weak)
358 NDesc |= MachO::N_WEAK_DEF;
360 DataRefImpl SymDRI = I->Sym.getRawDataRefImpl();
361 if (MachO->is64Bit()) {
362 H_64 = MachO->MachOObjectFile::getHeader64();
363 Filetype = H_64.filetype;
366 MachO::nlist_64 STE_64 = MachO->getSymbol64TableEntry(SymDRI);
367 NType = STE_64.n_type;
368 NSect = STE_64.n_sect;
369 NDesc = STE_64.n_desc;
370 NStrx = STE_64.n_strx;
371 NValue = STE_64.n_value;
380 H = MachO->MachOObjectFile::getHeader();
381 Filetype = H.filetype;
384 MachO::nlist STE = MachO->getSymbolTableEntry(SymDRI);
389 NValue = STE.n_value;
400 // If we are printing Mach-O symbols in hex do that and return.
401 if (FormatMachOasHex) {
403 format(printFormat, NValue).print(Str, sizeof(Str));
404 outs() << Str << ' ';
405 format("%02x", NType).print(Str, sizeof(Str));
406 outs() << Str << ' ';
407 format("%02x", NSect).print(Str, sizeof(Str));
408 outs() << Str << ' ';
409 format("%04x", NDesc).print(Str, sizeof(Str));
410 outs() << Str << ' ';
411 format("%08x", NStrx).print(Str, sizeof(Str));
412 outs() << Str << ' ';
414 if ((NType & MachO::N_TYPE) == MachO::N_INDR) {
415 outs() << " (indirect for ";
416 format(printFormat, NValue).print(Str, sizeof(Str));
417 outs() << Str << ' ';
418 StringRef IndirectName;
419 if (I->Sym.getRawDataRefImpl().p) {
420 if (MachO->getIndirectName(I->Sym.getRawDataRefImpl(), IndirectName))
423 outs() << IndirectName << ")";
426 outs() << I->IndirectName << ")";
433 if ((NType & MachO::N_TYPE) == MachO::N_INDR)
434 strcpy(SymbolAddrStr, printBlanks);
435 if (Obj.isIR() && (NType & MachO::N_TYPE) == MachO::N_TYPE)
436 strcpy(SymbolAddrStr, printDashes);
437 outs() << SymbolAddrStr << ' ';
440 switch (NType & MachO::N_TYPE) {
443 outs() << "(common) ";
444 if (MachO::GET_COMM_ALIGN(NDesc) != 0)
445 outs() << "(alignment 2^" << (int)MachO::GET_COMM_ALIGN(NDesc) << ") ";
447 if ((NType & MachO::N_TYPE) == MachO::N_PBUD)
448 outs() << "(prebound ";
451 if ((NDesc & MachO::REFERENCE_TYPE) ==
452 MachO::REFERENCE_FLAG_UNDEFINED_LAZY)
453 outs() << "undefined [lazy bound]) ";
454 else if ((NDesc & MachO::REFERENCE_TYPE) ==
455 MachO::REFERENCE_FLAG_PRIVATE_UNDEFINED_LAZY)
456 outs() << "undefined [private lazy bound]) ";
457 else if ((NDesc & MachO::REFERENCE_TYPE) ==
458 MachO::REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY)
459 outs() << "undefined [private]) ";
461 outs() << "undefined) ";
465 outs() << "(absolute) ";
468 outs() << "(indirect) ";
470 case MachO::N_SECT: {
472 // For llvm bitcode files print out a fake section name using the values
473 // use 1, 2 and 3 for section numbers as set above.
475 outs() << "(LTO,CODE) ";
477 outs() << "(LTO,DATA) ";
479 outs() << "(LTO,RODATA) ";
484 section_iterator Sec = SectionRef();
485 if (I->Sym.getRawDataRefImpl().p) {
486 Expected<section_iterator> SecOrErr =
487 MachO->getSymbolSection(I->Sym.getRawDataRefImpl());
489 consumeError(SecOrErr.takeError());
494 if (Sec == MachO->section_end()) {
501 DataRefImpl Ref = Sec->getRawDataRefImpl();
502 StringRef SectionName;
503 MachO->getSectionName(Ref, SectionName);
504 StringRef SegmentName = MachO->getSectionFinalSegmentName(Ref);
505 outs() << "(" << SegmentName << "," << SectionName << ") ";
513 if (NType & MachO::N_EXT) {
514 if (NDesc & MachO::REFERENCED_DYNAMICALLY)
515 outs() << "[referenced dynamically] ";
516 if (NType & MachO::N_PEXT) {
517 if ((NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF)
518 outs() << "weak private external ";
520 outs() << "private external ";
522 if ((NDesc & MachO::N_WEAK_REF) == MachO::N_WEAK_REF ||
523 (NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF) {
524 if ((NDesc & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF)) ==
525 (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
526 outs() << "weak external automatically hidden ";
528 outs() << "weak external ";
530 outs() << "external ";
533 if (NType & MachO::N_PEXT)
534 outs() << "non-external (was a private external) ";
536 outs() << "non-external ";
539 if (Filetype == MachO::MH_OBJECT &&
540 (NDesc & MachO::N_NO_DEAD_STRIP) == MachO::N_NO_DEAD_STRIP)
541 outs() << "[no dead strip] ";
543 if (Filetype == MachO::MH_OBJECT &&
544 ((NType & MachO::N_TYPE) != MachO::N_UNDF) &&
545 (NDesc & MachO::N_SYMBOL_RESOLVER) == MachO::N_SYMBOL_RESOLVER)
546 outs() << "[symbol resolver] ";
548 if (Filetype == MachO::MH_OBJECT &&
549 ((NType & MachO::N_TYPE) != MachO::N_UNDF) &&
550 (NDesc & MachO::N_ALT_ENTRY) == MachO::N_ALT_ENTRY)
551 outs() << "[alt entry] ";
553 if ((NDesc & MachO::N_ARM_THUMB_DEF) == MachO::N_ARM_THUMB_DEF)
554 outs() << "[Thumb] ";
556 if ((NType & MachO::N_TYPE) == MachO::N_INDR) {
557 outs() << I->Name << " (for ";
558 StringRef IndirectName;
560 if (I->Sym.getRawDataRefImpl().p) {
561 if (MachO->getIndirectName(I->Sym.getRawDataRefImpl(), IndirectName))
564 outs() << IndirectName << ")";
567 outs() << I->IndirectName << ")";
573 if ((Flags & MachO::MH_TWOLEVEL) == MachO::MH_TWOLEVEL &&
574 (((NType & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0) ||
575 (NType & MachO::N_TYPE) == MachO::N_PBUD)) {
576 uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(NDesc);
577 if (LibraryOrdinal != 0) {
578 if (LibraryOrdinal == MachO::EXECUTABLE_ORDINAL)
579 outs() << " (from executable)";
580 else if (LibraryOrdinal == MachO::DYNAMIC_LOOKUP_ORDINAL)
581 outs() << " (dynamically looked up)";
583 StringRef LibraryName;
585 MachO->getLibraryShortNameByIndex(LibraryOrdinal - 1, LibraryName))
586 outs() << " (from bad library ordinal " << LibraryOrdinal << ")";
588 outs() << " (from " << LibraryName << ")";
596 // Table that maps Darwin's Mach-O stab constants to strings to allow printing.
597 struct DarwinStabName {
601 static const struct DarwinStabName DarwinStabNames[] = {
602 {MachO::N_GSYM, "GSYM"},
603 {MachO::N_FNAME, "FNAME"},
604 {MachO::N_FUN, "FUN"},
605 {MachO::N_STSYM, "STSYM"},
606 {MachO::N_LCSYM, "LCSYM"},
607 {MachO::N_BNSYM, "BNSYM"},
609 {MachO::N_AST, "AST"},
610 {MachO::N_OPT, "OPT"},
611 {MachO::N_RSYM, "RSYM"},
612 {MachO::N_SLINE, "SLINE"},
613 {MachO::N_ENSYM, "ENSYM"},
614 {MachO::N_SSYM, "SSYM"},
616 {MachO::N_OSO, "OSO"},
617 {MachO::N_LSYM, "LSYM"},
618 {MachO::N_BINCL, "BINCL"},
619 {MachO::N_SOL, "SOL"},
620 {MachO::N_PARAMS, "PARAM"},
621 {MachO::N_VERSION, "VERS"},
622 {MachO::N_OLEVEL, "OLEV"},
623 {MachO::N_PSYM, "PSYM"},
624 {MachO::N_EINCL, "EINCL"},
625 {MachO::N_ENTRY, "ENTRY"},
626 {MachO::N_LBRAC, "LBRAC"},
627 {MachO::N_EXCL, "EXCL"},
628 {MachO::N_RBRAC, "RBRAC"},
629 {MachO::N_BCOMM, "BCOMM"},
630 {MachO::N_ECOMM, "ECOMM"},
631 {MachO::N_ECOML, "ECOML"},
632 {MachO::N_LENG, "LENG"},
635 static const char *getDarwinStabString(uint8_t NType) {
636 for (unsigned i = 0; DarwinStabNames[i].Name; i++) {
637 if (DarwinStabNames[i].NType == NType)
638 return DarwinStabNames[i].Name;
643 // darwinPrintStab() prints the n_sect, n_desc along with a symbolic name of
644 // a stab n_type value in a Mach-O file.
645 static void darwinPrintStab(MachOObjectFile *MachO, SymbolListT::iterator I) {
646 MachO::nlist_64 STE_64;
651 DataRefImpl SymDRI = I->Sym.getRawDataRefImpl();
652 if (MachO->is64Bit()) {
653 STE_64 = MachO->getSymbol64TableEntry(SymDRI);
654 NType = STE_64.n_type;
655 NSect = STE_64.n_sect;
656 NDesc = STE_64.n_desc;
658 STE = MachO->getSymbolTableEntry(SymDRI);
665 format("%02x", NSect).print(Str, sizeof(Str));
666 outs() << ' ' << Str << ' ';
667 format("%04x", NDesc).print(Str, sizeof(Str));
668 outs() << Str << ' ';
669 if (const char *stabString = getDarwinStabString(NType))
670 format("%5.5s", stabString).print(Str, sizeof(Str));
672 format(" %02x", NType).print(Str, sizeof(Str));
676 static Optional<std::string> demangle(StringRef Name, bool StripUnderscore) {
677 if (StripUnderscore && Name.size() > 0 && Name[0] == '_')
678 Name = Name.substr(1);
680 if (!Name.startswith("_Z"))
685 itaniumDemangle(Name.str().c_str(), nullptr, nullptr, &Status);
689 std::string S(Undecorated);
694 static bool symbolIsDefined(const NMSymbol &Sym) {
695 return Sym.TypeChar != 'U' && Sym.TypeChar != 'w' && Sym.TypeChar != 'v';
698 static void sortAndPrintSymbolList(SymbolicFile &Obj, bool printName,
699 const std::string &ArchiveName,
700 const std::string &ArchitectureName) {
702 std::function<bool(const NMSymbol &, const NMSymbol &)> Cmp;
704 Cmp = compareSymbolAddress;
706 Cmp = compareSymbolSize;
708 Cmp = compareSymbolName;
711 Cmp = [=](const NMSymbol &A, const NMSymbol &B) { return Cmp(B, A); };
712 llvm::sort(SymbolList.begin(), SymbolList.end(), Cmp);
715 if (!PrintFileName) {
716 if (OutputFormat == posix && MultipleFiles && printName) {
717 outs() << '\n' << CurrentFilename << ":\n";
718 } else if (OutputFormat == bsd && MultipleFiles && printName) {
719 outs() << "\n" << CurrentFilename << ":\n";
720 } else if (OutputFormat == sysv) {
721 outs() << "\n\nSymbols from " << CurrentFilename << ":\n\n";
722 if (isSymbolList64Bit(Obj))
723 outs() << "Name Value Class Type"
724 << " Size Line Section\n";
726 outs() << "Name Value Class Type"
727 << " Size Line Section\n";
731 const char *printBlanks, *printDashes, *printFormat;
732 if (isSymbolList64Bit(Obj)) {
734 printDashes = "----------------";
735 switch (AddressRadix) {
737 printFormat = OutputFormat == posix ? "%" PRIo64 : "%016" PRIo64;
740 printFormat = OutputFormat == posix ? "%" PRIx64 : "%016" PRIx64;
743 printFormat = OutputFormat == posix ? "%" PRId64 : "%016" PRId64;
747 printDashes = "--------";
748 switch (AddressRadix) {
750 printFormat = OutputFormat == posix ? "%" PRIo64 : "%08" PRIo64;
753 printFormat = OutputFormat == posix ? "%" PRIx64 : "%08" PRIx64;
756 printFormat = OutputFormat == posix ? "%" PRId64 : "%08" PRId64;
760 for (SymbolListT::iterator I = SymbolList.begin(), E = SymbolList.end();
763 std::string Name = I->Name.str();
764 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj);
766 if (Optional<std::string> Opt = demangle(I->Name, MachO))
769 if (I->Sym.getRawDataRefImpl().p)
770 SymFlags = I->Sym.getFlags();
772 SymFlags = I->SymFlags;
774 bool Undefined = SymFlags & SymbolRef::SF_Undefined;
775 bool Global = SymFlags & SymbolRef::SF_Global;
776 bool Weak = SymFlags & SymbolRef::SF_Weak;
777 if ((!Undefined && UndefinedOnly) || (Undefined && DefinedOnly) ||
778 (!Global && ExternalOnly) || (SizeSort && !PrintAddress) ||
779 (Weak && NoWeakSymbols))
782 if (!ArchitectureName.empty())
783 outs() << "(for architecture " << ArchitectureName << "):";
784 if (OutputFormat == posix && !ArchiveName.empty())
785 outs() << ArchiveName << "[" << CurrentFilename << "]: ";
787 if (!ArchiveName.empty())
788 outs() << ArchiveName << ":";
789 outs() << CurrentFilename << ": ";
792 if ((JustSymbolName ||
793 (UndefinedOnly && MachO && OutputFormat != darwin)) &&
794 OutputFormat != posix) {
795 outs() << Name << "\n";
799 char SymbolAddrStr[18] = "";
800 char SymbolSizeStr[18] = "";
802 // If the format is SysV or the symbol isn't defined, then print spaces.
803 if (OutputFormat == sysv || !symbolIsDefined(*I)) {
804 if (OutputFormat == posix) {
805 format(printFormat, I->Address)
806 .print(SymbolAddrStr, sizeof(SymbolAddrStr));
807 format(printFormat, I->Size)
808 .print(SymbolSizeStr, sizeof(SymbolSizeStr));
810 strcpy(SymbolAddrStr, printBlanks);
811 strcpy(SymbolSizeStr, printBlanks);
815 // Otherwise, print the symbol address and size.
816 if (symbolIsDefined(*I)) {
818 strcpy(SymbolAddrStr, printDashes);
819 else if(MachO && I->TypeChar == 'I')
820 strcpy(SymbolAddrStr, printBlanks);
822 format(printFormat, I->Address)
823 .print(SymbolAddrStr, sizeof(SymbolAddrStr));
824 format(printFormat, I->Size).print(SymbolSizeStr, sizeof(SymbolSizeStr));
827 // If OutputFormat is darwin or we are printing Mach-O symbols in hex and
828 // we have a MachOObjectFile, call darwinPrintSymbol to print as darwin's
829 // nm(1) -m output or hex, else if OutputFormat is darwin or we are
830 // printing Mach-O symbols in hex and not a Mach-O object fall back to
831 // OutputFormat bsd (see below).
832 if ((OutputFormat == darwin || FormatMachOasHex) && (MachO || Obj.isIR())) {
833 darwinPrintSymbol(Obj, I, SymbolAddrStr, printBlanks, printDashes,
835 } else if (OutputFormat == posix) {
836 outs() << Name << " " << I->TypeChar << " ";
838 outs() << SymbolAddrStr << " " << "0" /* SymbolSizeStr */ << "\n";
840 outs() << SymbolAddrStr << " " << SymbolSizeStr << "\n";
841 } else if (OutputFormat == bsd || (OutputFormat == darwin && !MachO)) {
843 outs() << SymbolAddrStr << ' ';
845 outs() << SymbolSizeStr;
848 outs() << I->TypeChar;
849 if (I->TypeChar == '-' && MachO)
850 darwinPrintStab(MachO, I);
851 outs() << " " << Name;
852 if (I->TypeChar == 'I' && MachO) {
853 outs() << " (indirect for ";
854 if (I->Sym.getRawDataRefImpl().p) {
855 StringRef IndirectName;
856 if (MachO->getIndirectName(I->Sym.getRawDataRefImpl(), IndirectName))
859 outs() << IndirectName << ")";
861 outs() << I->IndirectName << ")";
864 } else if (OutputFormat == sysv) {
865 std::string PaddedName(Name);
866 while (PaddedName.length() < 20)
868 outs() << PaddedName << "|" << SymbolAddrStr << "| " << I->TypeChar
869 << " | |" << SymbolSizeStr << "| |\n";
876 static char getSymbolNMTypeChar(ELFObjectFileBase &Obj,
877 basic_symbol_iterator I) {
879 elf_symbol_iterator SymI(I);
881 Expected<elf_section_iterator> SecIOrErr = SymI->getSection();
883 consumeError(SecIOrErr.takeError());
887 elf_section_iterator SecI = *SecIOrErr;
888 if (SecI != Obj.section_end()) {
889 switch (SecI->getType()) {
890 case ELF::SHT_PROGBITS:
891 case ELF::SHT_DYNAMIC:
892 switch (SecI->getFlags()) {
893 case (ELF::SHF_ALLOC | ELF::SHF_EXECINSTR):
895 case (ELF::SHF_TLS | ELF::SHF_ALLOC | ELF::SHF_WRITE):
896 case (ELF::SHF_ALLOC | ELF::SHF_WRITE):
899 case (ELF::SHF_ALLOC | ELF::SHF_MERGE):
900 case (ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS):
904 case ELF::SHT_NOBITS:
906 case ELF::SHT_INIT_ARRAY:
907 case ELF::SHT_FINI_ARRAY:
912 if (SymI->getELFType() == ELF::STT_SECTION) {
913 Expected<StringRef> Name = SymI->getName();
915 consumeError(Name.takeError());
918 return StringSwitch<char>(*Name)
919 .StartsWith(".debug", 'N')
920 .StartsWith(".note", 'n')
927 static char getSymbolNMTypeChar(COFFObjectFile &Obj, symbol_iterator I) {
928 COFFSymbolRef Symb = Obj.getCOFFSymbol(*I);
930 symbol_iterator SymI(I);
932 Expected<StringRef> Name = SymI->getName();
934 consumeError(Name.takeError());
938 char Ret = StringSwitch<char>(*Name)
939 .StartsWith(".debug", 'N')
940 .StartsWith(".sxdata", 'N')
946 uint32_t Characteristics = 0;
947 if (!COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
948 Expected<section_iterator> SecIOrErr = SymI->getSection();
950 consumeError(SecIOrErr.takeError());
953 section_iterator SecI = *SecIOrErr;
954 const coff_section *Section = Obj.getCOFFSection(*SecI);
955 Characteristics = Section->Characteristics;
956 StringRef SectionName;
957 Obj.getSectionName(Section, SectionName);
958 if (SectionName.startswith(".idata"))
962 switch (Symb.getSectionNumber()) {
963 case COFF::IMAGE_SYM_DEBUG:
966 // Check section type.
967 if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
969 if (Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
970 return Characteristics & COFF::IMAGE_SCN_MEM_WRITE ? 'd' : 'r';
971 if (Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
973 if (Characteristics & COFF::IMAGE_SCN_LNK_INFO)
975 // Check for section symbol.
976 if (Symb.isSectionDefinition())
983 static char getSymbolNMTypeChar(COFFImportFile &Obj) {
984 switch (Obj.getCOFFImportHeader()->getType()) {
985 case COFF::IMPORT_CODE:
987 case COFF::IMPORT_DATA:
989 case COFF::IMPORT_CONST:
995 static char getSymbolNMTypeChar(MachOObjectFile &Obj, basic_symbol_iterator I) {
996 DataRefImpl Symb = I->getRawDataRefImpl();
997 uint8_t NType = Obj.is64Bit() ? Obj.getSymbol64TableEntry(Symb).n_type
998 : Obj.getSymbolTableEntry(Symb).n_type;
1000 if (NType & MachO::N_STAB)
1003 switch (NType & MachO::N_TYPE) {
1008 case MachO::N_SECT: {
1009 Expected<section_iterator> SecOrErr = Obj.getSymbolSection(Symb);
1011 consumeError(SecOrErr.takeError());
1014 section_iterator Sec = *SecOrErr;
1015 if (Sec == Obj.section_end())
1017 DataRefImpl Ref = Sec->getRawDataRefImpl();
1018 StringRef SectionName;
1019 Obj.getSectionName(Ref, SectionName);
1020 StringRef SegmentName = Obj.getSectionFinalSegmentName(Ref);
1021 if (Obj.is64Bit() &&
1022 Obj.getHeader64().filetype == MachO::MH_KEXT_BUNDLE &&
1023 SegmentName == "__TEXT_EXEC" && SectionName == "__text")
1025 if (SegmentName == "__TEXT" && SectionName == "__text")
1027 if (SegmentName == "__DATA" && SectionName == "__data")
1029 if (SegmentName == "__DATA" && SectionName == "__bss")
1038 static char getSymbolNMTypeChar(WasmObjectFile &Obj, basic_symbol_iterator I) {
1039 uint32_t Flags = I->getFlags();
1040 if (Flags & SymbolRef::SF_Executable)
1045 static char getSymbolNMTypeChar(IRObjectFile &Obj, basic_symbol_iterator I) {
1046 uint32_t Flags = I->getFlags();
1047 // FIXME: should we print 'b'? At the IR level we cannot be sure if this
1048 // will be in bss or not, but we could approximate.
1049 if (Flags & SymbolRef::SF_Executable)
1051 else if (Triple(Obj.getTargetTriple()).isOSDarwin() &&
1052 (Flags & SymbolRef::SF_Const))
1058 static bool isObject(SymbolicFile &Obj, basic_symbol_iterator I) {
1059 return !dyn_cast<ELFObjectFileBase>(&Obj)
1061 : elf_symbol_iterator(I)->getELFType() == ELF::STT_OBJECT;
1064 static char getNMTypeChar(SymbolicFile &Obj, basic_symbol_iterator I) {
1065 uint32_t Symflags = I->getFlags();
1066 if ((Symflags & object::SymbolRef::SF_Weak) && !isa<MachOObjectFile>(Obj)) {
1067 char Ret = isObject(Obj, I) ? 'v' : 'w';
1068 return (!(Symflags & object::SymbolRef::SF_Undefined)) ? toupper(Ret) : Ret;
1071 if (Symflags & object::SymbolRef::SF_Undefined)
1074 if (Symflags & object::SymbolRef::SF_Common)
1078 if (Symflags & object::SymbolRef::SF_Absolute)
1080 else if (IRObjectFile *IR = dyn_cast<IRObjectFile>(&Obj))
1081 Ret = getSymbolNMTypeChar(*IR, I);
1082 else if (COFFObjectFile *COFF = dyn_cast<COFFObjectFile>(&Obj))
1083 Ret = getSymbolNMTypeChar(*COFF, I);
1084 else if (COFFImportFile *COFFImport = dyn_cast<COFFImportFile>(&Obj))
1085 Ret = getSymbolNMTypeChar(*COFFImport);
1086 else if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj))
1087 Ret = getSymbolNMTypeChar(*MachO, I);
1088 else if (WasmObjectFile *Wasm = dyn_cast<WasmObjectFile>(&Obj))
1089 Ret = getSymbolNMTypeChar(*Wasm, I);
1091 Ret = getSymbolNMTypeChar(cast<ELFObjectFileBase>(Obj), I);
1093 if (Symflags & object::SymbolRef::SF_Global)
1099 // getNsectForSegSect() is used to implement the Mach-O "-s segname sectname"
1100 // option to dump only those symbols from that section in a Mach-O file.
1101 // It is called once for each Mach-O file from dumpSymbolNamesFromObject()
1102 // to get the section number for that named section from the command line
1103 // arguments. It returns the section number for that section in the Mach-O
1104 // file or zero it is not present.
1105 static unsigned getNsectForSegSect(MachOObjectFile *Obj) {
1107 for (auto &S : Obj->sections()) {
1108 DataRefImpl Ref = S.getRawDataRefImpl();
1109 StringRef SectionName;
1110 Obj->getSectionName(Ref, SectionName);
1111 StringRef SegmentName = Obj->getSectionFinalSegmentName(Ref);
1112 if (SegmentName == SegSect[0] && SectionName == SegSect[1])
1119 // getNsectInMachO() is used to implement the Mach-O "-s segname sectname"
1120 // option to dump only those symbols from that section in a Mach-O file.
1121 // It is called once for each symbol in a Mach-O file from
1122 // dumpSymbolNamesFromObject() and returns the section number for that symbol
1123 // if it is in a section, else it returns 0.
1124 static unsigned getNsectInMachO(MachOObjectFile &Obj, BasicSymbolRef Sym) {
1125 DataRefImpl Symb = Sym.getRawDataRefImpl();
1126 if (Obj.is64Bit()) {
1127 MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb);
1128 return (STE.n_type & MachO::N_TYPE) == MachO::N_SECT ? STE.n_sect : 0;
1130 MachO::nlist STE = Obj.getSymbolTableEntry(Symb);
1131 return (STE.n_type & MachO::N_TYPE) == MachO::N_SECT ? STE.n_sect : 0;
1135 dumpSymbolNamesFromObject(SymbolicFile &Obj, bool printName,
1136 const std::string &ArchiveName = std::string(),
1137 const std::string &ArchitectureName = std::string()) {
1138 auto Symbols = Obj.symbols();
1140 const auto *E = dyn_cast<ELFObjectFileBase>(&Obj);
1142 error("File format has no dynamic symbol table", Obj.getFileName());
1145 auto DynSymbols = E->getDynamicSymbolIterators();
1147 make_range<basic_symbol_iterator>(DynSymbols.begin(), DynSymbols.end());
1149 std::string NameBuffer;
1150 raw_string_ostream OS(NameBuffer);
1151 // If a "-s segname sectname" option was specified and this is a Mach-O
1152 // file get the section number for that section in this object file.
1153 unsigned int Nsect = 0;
1154 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj);
1155 if (SegSect.size() != 0 && MachO) {
1156 Nsect = getNsectForSegSect(MachO);
1157 // If this section is not in the object file no symbols are printed.
1161 if (!MachO || !DyldInfoOnly) {
1162 for (BasicSymbolRef Sym : Symbols) {
1163 uint32_t SymFlags = Sym.getFlags();
1164 if (!DebugSyms && (SymFlags & SymbolRef::SF_FormatSpecific))
1166 if (WithoutAliases && (SymFlags & SymbolRef::SF_Indirect))
1168 // If a "-s segname sectname" option was specified and this is a Mach-O
1169 // file and this section appears in this file, Nsect will be non-zero then
1170 // see if this symbol is a symbol from that section and if not skip it.
1171 if (Nsect && Nsect != getNsectInMachO(*MachO, Sym))
1174 memset(&S, '\0', sizeof(S));
1178 if (isa<ELFObjectFileBase>(&Obj))
1179 S.Size = ELFSymbolRef(Sym).getSize();
1181 if (PrintAddress && isa<ObjectFile>(Obj)) {
1182 SymbolRef SymRef(Sym);
1183 Expected<uint64_t> AddressOrErr = SymRef.getAddress();
1184 if (!AddressOrErr) {
1185 consumeError(AddressOrErr.takeError());
1188 S.Address = *AddressOrErr;
1190 S.TypeChar = getNMTypeChar(Obj, Sym);
1191 std::error_code EC = Sym.printName(OS);
1193 OS << "bad string index";
1198 SymbolList.push_back(S);
1203 const char *P = NameBuffer.c_str();
1205 for (I = 0; I < SymbolList.size(); ++I) {
1206 SymbolList[I].Name = P;
1210 // If this is a Mach-O file where the nlist symbol table is out of sync
1211 // with the dyld export trie then look through exports and fake up symbols
1212 // for the ones that are missing (also done with the -add-dyldinfo flag).
1213 // This is needed if strip(1) -T is run on a binary containing swift
1214 // language symbols for example. The option -only-dyldinfo will fake up
1215 // all symbols from the dyld export trie as well as the bind info.
1216 std::string ExportsNameBuffer;
1217 raw_string_ostream EOS(ExportsNameBuffer);
1218 std::string BindsNameBuffer;
1219 raw_string_ostream BOS(BindsNameBuffer);
1220 std::string LazysNameBuffer;
1221 raw_string_ostream LOS(LazysNameBuffer);
1222 std::string WeaksNameBuffer;
1223 raw_string_ostream WOS(WeaksNameBuffer);
1224 std::string FunctionStartsNameBuffer;
1225 raw_string_ostream FOS(FunctionStartsNameBuffer);
1226 if (MachO && !NoDyldInfo) {
1227 MachO::mach_header H;
1228 MachO::mach_header_64 H_64;
1229 uint32_t HFlags = 0;
1230 if (MachO->is64Bit()) {
1231 H_64 = MachO->MachOObjectFile::getHeader64();
1232 HFlags = H_64.flags;
1234 H = MachO->MachOObjectFile::getHeader();
1237 uint64_t BaseSegmentAddress = 0;
1238 for (const auto &Command : MachO->load_commands()) {
1239 if (Command.C.cmd == MachO::LC_SEGMENT) {
1240 MachO::segment_command Seg = MachO->getSegmentLoadCommand(Command);
1241 if (Seg.fileoff == 0 && Seg.filesize != 0) {
1242 BaseSegmentAddress = Seg.vmaddr;
1245 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
1246 MachO::segment_command_64 Seg = MachO->getSegment64LoadCommand(Command);
1247 if (Seg.fileoff == 0 && Seg.filesize != 0) {
1248 BaseSegmentAddress = Seg.vmaddr;
1253 if (DyldInfoOnly || AddDyldInfo ||
1254 HFlags & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
1255 unsigned ExportsAdded = 0;
1256 Error Err = Error::success();
1257 for (const llvm::object::ExportEntry &Entry : MachO->exports(Err)) {
1259 bool ReExport = false;
1260 if (!DyldInfoOnly) {
1261 for (unsigned J = 0; J < SymbolList.size() && !found; ++J) {
1262 if (SymbolList[J].Address == Entry.address() + BaseSegmentAddress &&
1263 SymbolList[J].Name == Entry.name())
1269 memset(&S, '\0', sizeof(NMSymbol));
1270 S.Address = Entry.address() + BaseSegmentAddress;
1273 S.Name = Entry.name();
1274 // There is no symbol in the nlist symbol table for this so we set
1275 // Sym effectivly to null and the rest of code in here must test for
1276 // it and not do things like Sym.getFlags() for it.
1277 S.Sym = BasicSymbolRef();
1278 S.SymFlags = SymbolRef::SF_Global;
1279 S.Section = SectionRef();
1283 S.IndirectName = StringRef();
1285 uint64_t EFlags = Entry.flags();
1286 bool Abs = ((EFlags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
1287 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
1288 bool Resolver = (EFlags &
1289 MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
1290 ReExport = (EFlags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
1291 bool WeakDef = (EFlags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
1293 S.NDesc |= MachO::N_WEAK_DEF;
1295 S.NType = MachO::N_EXT | MachO::N_ABS;
1297 } else if (ReExport) {
1298 S.NType = MachO::N_EXT | MachO::N_INDR;
1301 S.NType = MachO::N_EXT | MachO::N_SECT;
1303 S.Address = Entry.other() + BaseSegmentAddress;
1304 if ((S.Address & 1) != 0 &&
1305 !MachO->is64Bit() && H.cputype == MachO::CPU_TYPE_ARM){
1307 S.NDesc |= MachO::N_ARM_THUMB_DEF;
1310 S.Address = Entry.address() + BaseSegmentAddress;
1312 StringRef SegmentName = StringRef();
1313 StringRef SectionName = StringRef();
1314 for (const SectionRef &Section : MachO->sections()) {
1316 Section.getName(SectionName);
1317 SegmentName = MachO->getSectionFinalSegmentName(
1318 Section.getRawDataRefImpl());
1319 if (S.Address >= Section.getAddress() &&
1320 S.Address < Section.getAddress() + Section.getSize()) {
1321 S.Section = Section;
1323 } else if (Entry.name() == "__mh_execute_header" &&
1324 SegmentName == "__TEXT" && SectionName == "__text") {
1325 S.Section = Section;
1326 S.NDesc |= MachO::REFERENCED_DYNAMICALLY;
1330 if (SegmentName == "__TEXT" && SectionName == "__text")
1332 else if (SegmentName == "__DATA" && SectionName == "__data")
1334 else if (SegmentName == "__DATA" && SectionName == "__bss")
1339 SymbolList.push_back(S);
1341 EOS << Entry.name();
1345 // For ReExports there are a two more things to do, first add the
1346 // indirect name and second create the undefined symbol using the
1347 // referened dynamic library.
1350 // Add the indirect name.
1351 if (Entry.otherName().empty())
1352 EOS << Entry.name();
1354 EOS << Entry.otherName();
1357 // Now create the undefined symbol using the referened dynamic
1360 memset(&U, '\0', sizeof(NMSymbol));
1364 if (Entry.otherName().empty())
1365 U.Name = Entry.name();
1367 U.Name = Entry.otherName();
1368 // Again there is no symbol in the nlist symbol table for this so
1369 // we set Sym effectivly to null and the rest of code in here must
1370 // test for it and not do things like Sym.getFlags() for it.
1371 U.Sym = BasicSymbolRef();
1372 U.SymFlags = SymbolRef::SF_Global | SymbolRef::SF_Undefined;
1373 U.Section = SectionRef();
1374 U.NType = MachO::N_EXT | MachO::N_UNDF;
1377 // The library ordinal for this undefined symbol is in the export
1378 // trie Entry.other().
1379 MachO::SET_LIBRARY_ORDINAL(U.NDesc, Entry.other());
1380 U.IndirectName = StringRef();
1381 SymbolList.push_back(U);
1383 // Finally add the undefined symbol's name.
1384 if (Entry.otherName().empty())
1385 EOS << Entry.name();
1387 EOS << Entry.otherName();
1394 error(std::move(Err), MachO->getFileName());
1395 // Set the symbol names and indirect names for the added symbols.
1398 const char *Q = ExportsNameBuffer.c_str();
1399 for (unsigned K = 0; K < ExportsAdded; K++) {
1400 SymbolList[I].Name = Q;
1402 if (SymbolList[I].TypeChar == 'I') {
1403 SymbolList[I].IndirectName = Q;
1410 // Add the undefined symbols from the bind entries.
1411 unsigned BindsAdded = 0;
1412 Error BErr = Error::success();
1413 StringRef LastSymbolName = StringRef();
1414 for (const llvm::object::MachOBindEntry &Entry : MachO->bindTable(BErr)) {
1416 if (LastSymbolName == Entry.symbolName())
1418 else if(!DyldInfoOnly) {
1419 for (unsigned J = 0; J < SymbolList.size() && !found; ++J) {
1420 if (SymbolList[J].Name == Entry.symbolName())
1425 LastSymbolName = Entry.symbolName();
1427 memset(&B, '\0', sizeof(NMSymbol));
1431 // There is no symbol in the nlist symbol table for this so we set
1432 // Sym effectivly to null and the rest of code in here must test for
1433 // it and not do things like Sym.getFlags() for it.
1434 B.Sym = BasicSymbolRef();
1435 B.SymFlags = SymbolRef::SF_Global | SymbolRef::SF_Undefined;
1436 B.NType = MachO::N_EXT | MachO::N_UNDF;
1440 MachO::SET_LIBRARY_ORDINAL(B.NDesc, Entry.ordinal());
1441 B.IndirectName = StringRef();
1442 B.Name = Entry.symbolName();
1443 SymbolList.push_back(B);
1444 BOS << Entry.symbolName();
1450 error(std::move(BErr), MachO->getFileName());
1451 // Set the symbol names and indirect names for the added symbols.
1454 const char *Q = BindsNameBuffer.c_str();
1455 for (unsigned K = 0; K < BindsAdded; K++) {
1456 SymbolList[I].Name = Q;
1458 if (SymbolList[I].TypeChar == 'I') {
1459 SymbolList[I].IndirectName = Q;
1466 // Add the undefined symbols from the lazy bind entries.
1467 unsigned LazysAdded = 0;
1468 Error LErr = Error::success();
1469 LastSymbolName = StringRef();
1470 for (const llvm::object::MachOBindEntry &Entry :
1471 MachO->lazyBindTable(LErr)) {
1473 if (LastSymbolName == Entry.symbolName())
1476 // Here we must check to see it this symbol is already in the
1477 // SymbolList as it might have already have been added above via a
1478 // non-lazy (bind) entry.
1479 for (unsigned J = 0; J < SymbolList.size() && !found; ++J) {
1480 if (SymbolList[J].Name == Entry.symbolName())
1485 LastSymbolName = Entry.symbolName();
1487 memset(&L, '\0', sizeof(NMSymbol));
1488 L.Name = Entry.symbolName();
1492 // There is no symbol in the nlist symbol table for this so we set
1493 // Sym effectivly to null and the rest of code in here must test for
1494 // it and not do things like Sym.getFlags() for it.
1495 L.Sym = BasicSymbolRef();
1496 L.SymFlags = SymbolRef::SF_Global | SymbolRef::SF_Undefined;
1497 L.NType = MachO::N_EXT | MachO::N_UNDF;
1499 // The REFERENCE_FLAG_UNDEFINED_LAZY is no longer used but here it
1500 // makes sence since we are creating this from a lazy bind entry.
1501 L.NDesc = MachO::REFERENCE_FLAG_UNDEFINED_LAZY;
1502 MachO::SET_LIBRARY_ORDINAL(L.NDesc, Entry.ordinal());
1503 L.IndirectName = StringRef();
1504 SymbolList.push_back(L);
1505 LOS << Entry.symbolName();
1511 error(std::move(LErr), MachO->getFileName());
1512 // Set the symbol names and indirect names for the added symbols.
1515 const char *Q = LazysNameBuffer.c_str();
1516 for (unsigned K = 0; K < LazysAdded; K++) {
1517 SymbolList[I].Name = Q;
1519 if (SymbolList[I].TypeChar == 'I') {
1520 SymbolList[I].IndirectName = Q;
1527 // Add the undefineds symbol from the weak bind entries which are not
1529 unsigned WeaksAdded = 0;
1530 Error WErr = Error::success();
1531 LastSymbolName = StringRef();
1532 for (const llvm::object::MachOBindEntry &Entry :
1533 MachO->weakBindTable(WErr)) {
1536 if (LastSymbolName == Entry.symbolName() ||
1537 Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
1540 for (J = 0; J < SymbolList.size() && !found; ++J) {
1541 if (SymbolList[J].Name == Entry.symbolName()) {
1548 LastSymbolName = Entry.symbolName();
1550 memset(&W, '\0', sizeof(NMSymbol));
1551 W.Name = Entry.symbolName();
1555 // There is no symbol in the nlist symbol table for this so we set
1556 // Sym effectivly to null and the rest of code in here must test for
1557 // it and not do things like Sym.getFlags() for it.
1558 W.Sym = BasicSymbolRef();
1559 W.SymFlags = SymbolRef::SF_Global | SymbolRef::SF_Undefined;
1560 W.NType = MachO::N_EXT | MachO::N_UNDF;
1562 // Odd that we are using N_WEAK_DEF on an undefined symbol but that is
1563 // what is created in this case by the linker when there are real
1564 // symbols in the nlist structs.
1565 W.NDesc = MachO::N_WEAK_DEF;
1566 W.IndirectName = StringRef();
1567 SymbolList.push_back(W);
1568 WOS << Entry.symbolName();
1572 // This is the case the symbol was previously been found and it could
1573 // have been added from a bind or lazy bind symbol. If so and not
1574 // a definition also mark it as weak.
1575 if (SymbolList[J].TypeChar == 'U')
1576 // See comment above about N_WEAK_DEF.
1577 SymbolList[J].NDesc |= MachO::N_WEAK_DEF;
1581 error(std::move(WErr), MachO->getFileName());
1582 // Set the symbol names and indirect names for the added symbols.
1585 const char *Q = WeaksNameBuffer.c_str();
1586 for (unsigned K = 0; K < WeaksAdded; K++) {
1587 SymbolList[I].Name = Q;
1589 if (SymbolList[I].TypeChar == 'I') {
1590 SymbolList[I].IndirectName = Q;
1597 // Trying adding symbol from the function starts table and LC_MAIN entry
1599 SmallVector<uint64_t, 8> FoundFns;
1600 uint64_t lc_main_offset = UINT64_MAX;
1601 for (const auto &Command : MachO->load_commands()) {
1602 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
1603 // We found a function starts segment, parse the addresses for
1605 MachO::linkedit_data_command LLC =
1606 MachO->getLinkeditDataLoadCommand(Command);
1608 MachO->ReadULEB128s(LLC.dataoff, FoundFns);
1609 } else if (Command.C.cmd == MachO::LC_MAIN) {
1610 MachO::entry_point_command LCmain =
1611 MachO->getEntryPointCommand(Command);
1612 lc_main_offset = LCmain.entryoff;
1615 // See if these addresses are already in the symbol table.
1616 unsigned FunctionStartsAdded = 0;
1617 for (uint64_t f = 0; f < FoundFns.size(); f++) {
1619 for (unsigned J = 0; J < SymbolList.size() && !found; ++J) {
1620 if (SymbolList[J].Address == FoundFns[f] + BaseSegmentAddress)
1623 // See this address is not already in the symbol table fake up an
1627 memset(&F, '\0', sizeof(NMSymbol));
1628 F.Name = "<redacted function X>";
1629 F.Address = FoundFns[f] + BaseSegmentAddress;
1631 // There is no symbol in the nlist symbol table for this so we set
1632 // Sym effectivly to null and the rest of code in here must test for
1633 // it and not do things like Sym.getFlags() for it.
1634 F.Sym = BasicSymbolRef();
1636 F.NType = MachO::N_SECT;
1638 StringRef SegmentName = StringRef();
1639 StringRef SectionName = StringRef();
1640 for (const SectionRef &Section : MachO->sections()) {
1641 Section.getName(SectionName);
1642 SegmentName = MachO->getSectionFinalSegmentName(
1643 Section.getRawDataRefImpl());
1645 if (F.Address >= Section.getAddress() &&
1646 F.Address < Section.getAddress() + Section.getSize()) {
1647 F.Section = Section;
1651 if (SegmentName == "__TEXT" && SectionName == "__text")
1653 else if (SegmentName == "__DATA" && SectionName == "__data")
1655 else if (SegmentName == "__DATA" && SectionName == "__bss")
1660 F.IndirectName = StringRef();
1661 SymbolList.push_back(F);
1662 if (FoundFns[f] == lc_main_offset)
1663 FOS << "<redacted LC_MAIN>";
1665 FOS << "<redacted function " << f << ">";
1667 FunctionStartsAdded++;
1670 if (FunctionStartsAdded) {
1672 const char *Q = FunctionStartsNameBuffer.c_str();
1673 for (unsigned K = 0; K < FunctionStartsAdded; K++) {
1674 SymbolList[I].Name = Q;
1676 if (SymbolList[I].TypeChar == 'I') {
1677 SymbolList[I].IndirectName = Q;
1686 CurrentFilename = Obj.getFileName();
1687 sortAndPrintSymbolList(Obj, printName, ArchiveName, ArchitectureName);
1690 // checkMachOAndArchFlags() checks to see if the SymbolicFile is a Mach-O file
1691 // and if it is and there is a list of architecture flags is specified then
1692 // check to make sure this Mach-O file is one of those architectures or all
1693 // architectures was specificed. If not then an error is generated and this
1694 // routine returns false. Else it returns true.
1695 static bool checkMachOAndArchFlags(SymbolicFile *O, std::string &Filename) {
1696 auto *MachO = dyn_cast<MachOObjectFile>(O);
1698 if (!MachO || ArchAll || ArchFlags.empty())
1701 MachO::mach_header H;
1702 MachO::mach_header_64 H_64;
1704 const char *McpuDefault, *ArchFlag;
1705 if (MachO->is64Bit()) {
1706 H_64 = MachO->MachOObjectFile::getHeader64();
1707 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1708 &McpuDefault, &ArchFlag);
1710 H = MachO->MachOObjectFile::getHeader();
1711 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1712 &McpuDefault, &ArchFlag);
1714 const std::string ArchFlagName(ArchFlag);
1715 if (none_of(ArchFlags, [&](const std::string &Name) {
1716 return Name == ArchFlagName;
1718 error("No architecture specified", Filename);
1724 static void dumpSymbolNamesFromFile(std::string &Filename) {
1725 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
1726 MemoryBuffer::getFileOrSTDIN(Filename);
1727 if (error(BufferOrErr.getError(), Filename))
1730 LLVMContext Context;
1731 Expected<std::unique_ptr<Binary>> BinaryOrErr = createBinary(
1732 BufferOrErr.get()->getMemBufferRef(), NoLLVMBitcode ? nullptr : &Context);
1734 error(BinaryOrErr.takeError(), Filename);
1737 Binary &Bin = *BinaryOrErr.get();
1739 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1741 Archive::symbol_iterator I = A->symbol_begin();
1742 Archive::symbol_iterator E = A->symbol_end();
1744 outs() << "Archive map\n";
1745 for (; I != E; ++I) {
1746 Expected<Archive::Child> C = I->getMember();
1748 error(C.takeError(), Filename);
1749 Expected<StringRef> FileNameOrErr = C->getName();
1750 if (!FileNameOrErr) {
1751 error(FileNameOrErr.takeError(), Filename);
1754 StringRef SymName = I->getName();
1755 outs() << SymName << " in " << FileNameOrErr.get() << "\n";
1762 Error Err = Error::success();
1763 for (auto &C : A->children(Err)) {
1764 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(&Context);
1766 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1767 error(std::move(E), Filename, C);
1770 if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1771 if (!MachOPrintSizeWarning && PrintSize && isa<MachOObjectFile>(O)) {
1772 errs() << ToolName << ": warning sizes with -print-size for Mach-O "
1773 "files are always zero.\n";
1774 MachOPrintSizeWarning = true;
1776 if (!checkMachOAndArchFlags(O, Filename))
1778 if (!PrintFileName) {
1780 if (isa<MachOObjectFile>(O)) {
1781 outs() << Filename << "(" << O->getFileName() << ")";
1783 outs() << O->getFileName();
1786 dumpSymbolNamesFromObject(*O, false, Filename);
1790 error(std::move(Err), A->getFileName());
1794 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1795 // If we have a list of architecture flags specified dump only those.
1796 if (!ArchAll && ArchFlags.size() != 0) {
1797 // Look for a slice in the universal binary that matches each ArchFlag.
1799 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1801 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1802 E = UB->end_objects();
1804 if (ArchFlags[i] == I->getArchFlagName()) {
1806 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
1807 I->getAsObjectFile();
1808 std::string ArchiveName;
1809 std::string ArchitectureName;
1810 ArchiveName.clear();
1811 ArchitectureName.clear();
1813 ObjectFile &Obj = *ObjOrErr.get();
1814 if (ArchFlags.size() > 1) {
1816 ArchitectureName = I->getArchFlagName();
1818 outs() << "\n" << Obj.getFileName() << " (for architecture "
1819 << I->getArchFlagName() << ")"
1822 dumpSymbolNamesFromObject(Obj, false, ArchiveName,
1824 } else if (auto E = isNotObjectErrorInvalidFileType(
1825 ObjOrErr.takeError())) {
1826 error(std::move(E), Filename, ArchFlags.size() > 1 ?
1827 StringRef(I->getArchFlagName()) : StringRef());
1829 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
1830 I->getAsArchive()) {
1831 std::unique_ptr<Archive> &A = *AOrErr;
1832 Error Err = Error::success();
1833 for (auto &C : A->children(Err)) {
1834 Expected<std::unique_ptr<Binary>> ChildOrErr =
1835 C.getAsBinary(&Context);
1837 if (auto E = isNotObjectErrorInvalidFileType(
1838 ChildOrErr.takeError())) {
1839 error(std::move(E), Filename, C, ArchFlags.size() > 1 ?
1840 StringRef(I->getArchFlagName()) : StringRef());
1844 if (SymbolicFile *O =
1845 dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1846 if (PrintFileName) {
1847 ArchiveName = A->getFileName();
1848 if (ArchFlags.size() > 1)
1849 ArchitectureName = I->getArchFlagName();
1851 outs() << "\n" << A->getFileName();
1852 outs() << "(" << O->getFileName() << ")";
1853 if (ArchFlags.size() > 1) {
1854 outs() << " (for architecture " << I->getArchFlagName()
1859 dumpSymbolNamesFromObject(*O, false, ArchiveName,
1864 error(std::move(Err), A->getFileName());
1866 consumeError(AOrErr.takeError());
1867 error(Filename + " for architecture " +
1868 StringRef(I->getArchFlagName()) +
1869 " is not a Mach-O file or an archive file",
1870 "Mach-O universal file");
1876 "file: " + Filename + " does not contain architecture");
1882 // No architecture flags were specified so if this contains a slice that
1883 // matches the host architecture dump only that.
1885 StringRef HostArchName = MachOObjectFile::getHostArch().getArchName();
1886 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1887 E = UB->end_objects();
1889 if (HostArchName == I->getArchFlagName()) {
1890 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1891 std::string ArchiveName;
1892 ArchiveName.clear();
1894 ObjectFile &Obj = *ObjOrErr.get();
1895 dumpSymbolNamesFromObject(Obj, false);
1896 } else if (auto E = isNotObjectErrorInvalidFileType(
1897 ObjOrErr.takeError())) {
1898 error(std::move(E), Filename);
1900 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
1901 I->getAsArchive()) {
1902 std::unique_ptr<Archive> &A = *AOrErr;
1903 Error Err = Error::success();
1904 for (auto &C : A->children(Err)) {
1905 Expected<std::unique_ptr<Binary>> ChildOrErr =
1906 C.getAsBinary(&Context);
1908 if (auto E = isNotObjectErrorInvalidFileType(
1909 ChildOrErr.takeError()))
1910 error(std::move(E), Filename, C);
1913 if (SymbolicFile *O =
1914 dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1916 ArchiveName = A->getFileName();
1918 outs() << "\n" << A->getFileName() << "(" << O->getFileName()
1921 dumpSymbolNamesFromObject(*O, false, ArchiveName);
1925 error(std::move(Err), A->getFileName());
1927 consumeError(AOrErr.takeError());
1928 error(Filename + " for architecture " +
1929 StringRef(I->getArchFlagName()) +
1930 " is not a Mach-O file or an archive file",
1931 "Mach-O universal file");
1937 // Either all architectures have been specified or none have been specified
1938 // and this does not contain the host architecture so dump all the slices.
1939 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1940 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1941 E = UB->end_objects();
1943 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1944 std::string ArchiveName;
1945 std::string ArchitectureName;
1946 ArchiveName.clear();
1947 ArchitectureName.clear();
1949 ObjectFile &Obj = *ObjOrErr.get();
1950 if (PrintFileName) {
1951 if (isa<MachOObjectFile>(Obj) && moreThanOneArch)
1952 ArchitectureName = I->getArchFlagName();
1954 if (moreThanOneArch)
1956 outs() << Obj.getFileName();
1957 if (isa<MachOObjectFile>(Obj) && moreThanOneArch)
1958 outs() << " (for architecture " << I->getArchFlagName() << ")";
1961 dumpSymbolNamesFromObject(Obj, false, ArchiveName, ArchitectureName);
1962 } else if (auto E = isNotObjectErrorInvalidFileType(
1963 ObjOrErr.takeError())) {
1964 error(std::move(E), Filename, moreThanOneArch ?
1965 StringRef(I->getArchFlagName()) : StringRef());
1967 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
1968 I->getAsArchive()) {
1969 std::unique_ptr<Archive> &A = *AOrErr;
1970 Error Err = Error::success();
1971 for (auto &C : A->children(Err)) {
1972 Expected<std::unique_ptr<Binary>> ChildOrErr =
1973 C.getAsBinary(&Context);
1975 if (auto E = isNotObjectErrorInvalidFileType(
1976 ChildOrErr.takeError()))
1977 error(std::move(E), Filename, C, moreThanOneArch ?
1978 StringRef(ArchitectureName) : StringRef());
1981 if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
1982 if (PrintFileName) {
1983 ArchiveName = A->getFileName();
1984 if (isa<MachOObjectFile>(O) && moreThanOneArch)
1985 ArchitectureName = I->getArchFlagName();
1987 outs() << "\n" << A->getFileName();
1988 if (isa<MachOObjectFile>(O)) {
1989 outs() << "(" << O->getFileName() << ")";
1990 if (moreThanOneArch)
1991 outs() << " (for architecture " << I->getArchFlagName()
1994 outs() << ":" << O->getFileName();
1997 dumpSymbolNamesFromObject(*O, false, ArchiveName, ArchitectureName);
2001 error(std::move(Err), A->getFileName());
2003 consumeError(AOrErr.takeError());
2004 error(Filename + " for architecture " +
2005 StringRef(I->getArchFlagName()) +
2006 " is not a Mach-O file or an archive file",
2007 "Mach-O universal file");
2012 if (SymbolicFile *O = dyn_cast<SymbolicFile>(&Bin)) {
2013 if (!MachOPrintSizeWarning && PrintSize && isa<MachOObjectFile>(O)) {
2014 errs() << ToolName << ": warning sizes with -print-size for Mach-O files "
2015 "are always zero.\n";
2016 MachOPrintSizeWarning = true;
2018 if (!checkMachOAndArchFlags(O, Filename))
2020 dumpSymbolNamesFromObject(*O, true);
2024 int main(int argc, char **argv) {
2025 InitLLVM X(argc, argv);
2026 cl::ParseCommandLineOptions(argc, argv, "llvm symbol table dumper\n");
2028 // llvm-nm only reads binary files.
2029 if (error(sys::ChangeStdinToBinary()))
2032 // These calls are needed so that we can read bitcode correctly.
2033 llvm::InitializeAllTargetInfos();
2034 llvm::InitializeAllTargetMCs();
2035 llvm::InitializeAllAsmParsers();
2041 OutputFormat = posix;
2043 OutputFormat = darwin;
2045 // The relative order of these is important. If you pass --size-sort it should
2046 // only print out the size. However, if you pass -S --size-sort, it should
2047 // print out both the size and address.
2048 if (SizeSort && !PrintSize)
2049 PrintAddress = false;
2050 if (OutputFormat == sysv || SizeSort)
2052 if (InputFilenames.empty())
2053 InputFilenames.push_back("a.out");
2054 if (InputFilenames.size() > 1)
2055 MultipleFiles = true;
2057 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2058 if (ArchFlags[i] == "all") {
2061 if (!MachOObjectFile::isValidArch(ArchFlags[i]))
2062 error("Unknown architecture named '" + ArchFlags[i] + "'",
2063 "for the -arch option");
2067 if (SegSect.size() != 0 && SegSect.size() != 2)
2068 error("bad number of arguments (must be two arguments)",
2069 "for the -s option");
2071 if (NoDyldInfo && (AddDyldInfo || DyldInfoOnly))
2072 error("-no-dyldinfo can't be used with -add-dyldinfo or -dyldinfo-only");
2074 llvm::for_each(InputFilenames, dumpSymbolNamesFromFile);