1//===-- llvm-nm.cpp - Symbol table dumping utility for llvm ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This program is a utility that works like traditional Unix "nm", that is, it
10// prints out the names of symbols in a bitcode or object file, along with some
11// information about each symbol.
12//
13// This "nm" supports many of the features of GNU "nm", including its different
14// output formats.
15//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/StringSwitch.h"
20#include "llvm/BinaryFormat/COFF.h"
21#include "llvm/BinaryFormat/MachO.h"
22#include "llvm/BinaryFormat/XCOFF.h"
23#include "llvm/DebugInfo/Symbolize/Symbolize.h"
24#include "llvm/Demangle/Demangle.h"
25#include "llvm/IR/Function.h"
26#include "llvm/IR/LLVMContext.h"
27#include "llvm/Object/Archive.h"
28#include "llvm/Object/COFF.h"
29#include "llvm/Object/COFFImportFile.h"
30#include "llvm/Object/ELFObjectFile.h"
31#include "llvm/Object/GOFFObjectFile.h"
32#include "llvm/Object/IRObjectFile.h"
33#include "llvm/Object/MachO.h"
34#include "llvm/Object/MachOUniversal.h"
35#include "llvm/Object/ObjectFile.h"
36#include "llvm/Object/SymbolicFile.h"
37#include "llvm/Object/TapiFile.h"
38#include "llvm/Object/TapiUniversal.h"
39#include "llvm/Object/Wasm.h"
40#include "llvm/Object/XCOFFObjectFile.h"
41#include "llvm/Option/Arg.h"
42#include "llvm/Option/ArgList.h"
43#include "llvm/Option/Option.h"
44#include "llvm/Support/CommandLine.h"
45#include "llvm/Support/Driver.h"
46#include "llvm/Support/Format.h"
47#include "llvm/Support/MemoryBuffer.h"
48#include "llvm/Support/Program.h"
49#include "llvm/Support/Signals.h"
50#include "llvm/Support/TargetSelect.h"
51#include "llvm/Support/WithColor.h"
52#include "llvm/Support/raw_ostream.h"
53#include "llvm/TargetParser/Host.h"
54#include "llvm/TargetParser/Triple.h"
55#include <vector>
56
57using namespace llvm;
58using namespace object;
59
60namespace {
61using namespace llvm::opt; // for HelpHidden in Opts.inc
62enum ID {
63 OPT_INVALID = 0, // This is not an option ID.
64#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
65#include "Opts.inc"
66#undef OPTION
67};
68
69#define OPTTABLE_CODE
70#include "Opts.inc"
71
72class NmOptTable : public opt::OptTable {
73public:
74 NmOptTable() : opt::OptTable(optionTables()) { setGroupedShortOptions(true); }
75};
76
77enum OutputFormatTy { bsd, sysv, posix, darwin, just_symbols };
78enum class BitModeTy { Bit32, Bit64, Bit32_64, Any };
79} // namespace
80
81static bool ArchiveMap;
82static BitModeTy BitMode;
83static bool DebugSyms;
84static bool DefinedOnly;
85static bool Demangle;
86static bool DynamicSyms;
87static bool ExportSymbols;
88static bool ExternalOnly;
89static bool LineNumbers;
90static OutputFormatTy OutputFormat;
91static bool NoLLVMBitcode;
92static bool NoSort;
93static bool NoWeakSymbols;
94static bool NumericSort;
95static bool PrintFileName;
96static bool PrintSize;
97static bool Quiet;
98static bool ReverseSort;
99static bool SpecialSyms;
100static bool SizeSort;
101static bool UndefinedOnly;
102static bool WithoutAliases;
103
104// XCOFF-specific options.
105static bool NoRsrc;
106
107namespace {
108enum Radix { d, o, x };
109} // namespace
110static Radix AddressRadix;
111
112// Mach-O specific options.
113static bool ArchAll = false;
114static std::vector<StringRef> ArchFlags;
115static bool AddDyldInfo;
116static bool AddInlinedInfo;
117static bool DyldInfoOnly;
118static bool FormatMachOasHex;
119static bool NoDyldInfo;
120static std::vector<StringRef> SegSect;
121static bool MachOPrintSizeWarning = false;
122
123// Miscellaneous states.
124static bool PrintAddress = true;
125static bool MultipleFiles = false;
126static bool HadError = false;
127
128static StringRef ToolName;
129
130static void warn(Error Err, Twine FileName, Twine Context = Twine(),
131 Twine Archive = Twine()) {
132 assert(Err);
133
134 // Flush the standard output so that the warning isn't interleaved with other
135 // output if stdout and stderr are writing to the same place.
136 outs().flush();
137
138 handleAllErrors(E: std::move(Err), Handlers: [&](const ErrorInfoBase &EI) {
139 WithColor::warning(OS&: errs(), Prefix: ToolName)
140 << (Archive.str().empty() ? FileName : Archive + "(" + FileName + ")")
141 << ": " << (Context.str().empty() ? "" : Context + ": ") << EI.message()
142 << "\n";
143 });
144}
145
146static void error(Twine Message, Twine Path = Twine()) {
147 HadError = true;
148 WithColor::error(OS&: errs(), Prefix: ToolName) << Path << ": " << Message << "\n";
149}
150
151static bool error(std::error_code EC, Twine Path = Twine()) {
152 if (EC) {
153 error(Message: EC.message(), Path);
154 return true;
155 }
156 return false;
157}
158
159// This version of error() prints the archive name and member name, for example:
160// "libx.a(foo.o)" after the ToolName before the error message. It sets
161// HadError but returns allowing the code to move on to other archive members.
162static void error(llvm::Error E, StringRef FileName, const Archive::Child &C,
163 StringRef ArchitectureName = StringRef()) {
164 HadError = true;
165 WithColor::error(OS&: errs(), Prefix: ToolName) << FileName;
166
167 Expected<StringRef> NameOrErr = C.getName();
168 // TODO: if we have a error getting the name then it would be nice to print
169 // the index of which archive member this is and or its offset in the
170 // archive instead of "???" as the name.
171 if (!NameOrErr) {
172 consumeError(Err: NameOrErr.takeError());
173 errs() << "(" << "???" << ")";
174 } else
175 errs() << "(" << NameOrErr.get() << ")";
176
177 if (!ArchitectureName.empty())
178 errs() << " (for architecture " << ArchitectureName << ")";
179
180 std::string Buf;
181 raw_string_ostream OS(Buf);
182 logAllUnhandledErrors(E: std::move(E), OS);
183 errs() << ": " << Buf << "\n";
184}
185
186// This version of error() prints the file name and which architecture slice it
187// is from, for example: "foo.o (for architecture i386)" after the ToolName
188// before the error message. It sets HadError but returns allowing the code to
189// move on to other architecture slices.
190static void error(llvm::Error E, StringRef FileName,
191 StringRef ArchitectureName = StringRef()) {
192 HadError = true;
193 WithColor::error(OS&: errs(), Prefix: ToolName) << FileName;
194
195 if (!ArchitectureName.empty())
196 errs() << " (for architecture " << ArchitectureName << ")";
197
198 std::string Buf;
199 raw_string_ostream OS(Buf);
200 logAllUnhandledErrors(E: std::move(E), OS);
201 errs() << ": " << Buf << "\n";
202}
203
204namespace {
205struct NMSymbol {
206 uint64_t Address;
207 uint64_t Size;
208 char TypeChar;
209 std::string Name;
210 StringRef SectionName;
211 StringRef TypeName;
212 BasicSymbolRef Sym;
213 StringRef Visibility;
214
215 // The Sym field above points to the native symbol in the object file,
216 // for Mach-O when we are creating symbols from the dyld info the above
217 // pointer is null as there is no native symbol. In these cases the fields
218 // below are filled in to represent what would have been a Mach-O nlist
219 // native symbol.
220 uint32_t SymFlags;
221 SectionRef Section;
222 uint8_t NType;
223 uint8_t NSect;
224 uint16_t NDesc;
225 std::string IndirectName;
226
227 bool isDefined() const {
228 if (Sym.getRawDataRefImpl().p)
229 return !(SymFlags & SymbolRef::SF_Undefined);
230 return TypeChar != 'U';
231 }
232
233 bool initializeFlags(const SymbolicFile &Obj) {
234 Expected<uint32_t> SymFlagsOrErr = Sym.getFlags();
235 if (!SymFlagsOrErr) {
236 // TODO: Test this error.
237 error(E: SymFlagsOrErr.takeError(), FileName: Obj.getFileName());
238 return false;
239 }
240 SymFlags = *SymFlagsOrErr;
241 return true;
242 }
243
244 bool shouldPrint() const {
245 bool Undefined = SymFlags & SymbolRef::SF_Undefined;
246 bool Global = SymFlags & SymbolRef::SF_Global;
247 bool Weak = SymFlags & SymbolRef::SF_Weak;
248 bool FormatSpecific = SymFlags & SymbolRef::SF_FormatSpecific;
249 if ((!Undefined && UndefinedOnly) || (Undefined && DefinedOnly) ||
250 (!Global && ExternalOnly) || (Weak && NoWeakSymbols) ||
251 (FormatSpecific && !(SpecialSyms || DebugSyms)))
252 return false;
253 return true;
254 }
255};
256
257bool operator<(const NMSymbol &A, const NMSymbol &B) {
258 if (NumericSort)
259 return std::make_tuple(args: A.isDefined(), args: A.Address, args: A.Name, args: A.Size) <
260 std::make_tuple(args: B.isDefined(), args: B.Address, args: B.Name, args: B.Size);
261 if (SizeSort)
262 return std::make_tuple(args: A.Size, args: A.Name, args: A.Address) <
263 std::make_tuple(args: B.Size, args: B.Name, args: B.Address);
264 if (ExportSymbols)
265 return std::make_tuple(args: A.Name, args: A.Visibility) <
266 std::make_tuple(args: B.Name, args: B.Visibility);
267 return std::make_tuple(args: A.Name, args: A.Size, args: A.Address) <
268 std::make_tuple(args: B.Name, args: B.Size, args: B.Address);
269}
270
271bool operator>(const NMSymbol &A, const NMSymbol &B) { return B < A; }
272bool operator==(const NMSymbol &A, const NMSymbol &B) {
273 return !(A < B) && !(B < A);
274}
275} // anonymous namespace
276
277static StringRef CurrentFilename;
278
279static char getSymbolNMTypeChar(IRObjectFile &Obj, basic_symbol_iterator I);
280
281// darwinPrintSymbol() is used to print a symbol from a Mach-O file when the
282// the OutputFormat is darwin or we are printing Mach-O symbols in hex. For
283// the darwin format it produces the same output as darwin's nm(1) -m output
284// and when printing Mach-O symbols in hex it produces the same output as
285// darwin's nm(1) -x format.
286static void darwinPrintSymbol(SymbolicFile &Obj, const NMSymbol &S,
287 char *SymbolAddrStr, const char *printBlanks,
288 const char *printDashes,
289 const char *printFormat) {
290 MachO::mach_header H;
291 MachO::mach_header_64 H_64;
292 uint32_t Filetype = MachO::MH_OBJECT;
293 uint32_t Flags = 0;
294 uint8_t NType = 0;
295 uint8_t NSect = 0;
296 uint16_t NDesc = 0;
297 uint32_t NStrx = 0;
298 uint64_t NValue = 0;
299 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: &Obj);
300 if (Obj.isIR()) {
301 uint32_t SymFlags = cantFail(ValOrErr: S.Sym.getFlags());
302 if (SymFlags & SymbolRef::SF_Global)
303 NType |= MachO::N_EXT;
304 if (SymFlags & SymbolRef::SF_Hidden)
305 NType |= MachO::N_PEXT;
306 if (SymFlags & SymbolRef::SF_Undefined)
307 NType |= MachO::N_EXT | MachO::N_UNDF;
308 else {
309 // Here we have a symbol definition. So to fake out a section name we
310 // use 1, 2 and 3 for section numbers. See below where they are used to
311 // print out fake section names.
312 NType |= MachO::N_SECT;
313 if (SymFlags & SymbolRef::SF_Const)
314 NSect = 3;
315 else if (SymFlags & SymbolRef::SF_Executable)
316 NSect = 1;
317 else
318 NSect = 2;
319 }
320 if (SymFlags & SymbolRef::SF_Weak)
321 NDesc |= MachO::N_WEAK_DEF;
322 } else {
323 DataRefImpl SymDRI = S.Sym.getRawDataRefImpl();
324 if (MachO->is64Bit()) {
325 H_64 = MachO->MachOObjectFile::getHeader64();
326 Filetype = H_64.filetype;
327 Flags = H_64.flags;
328 if (SymDRI.p){
329 MachO::nlist_64 STE_64 = MachO->getSymbol64TableEntry(DRI: SymDRI);
330 NType = STE_64.n_type;
331 NSect = STE_64.n_sect;
332 NDesc = STE_64.n_desc;
333 NStrx = STE_64.n_strx;
334 NValue = STE_64.n_value;
335 } else {
336 NType = S.NType;
337 NSect = S.NSect;
338 NDesc = S.NDesc;
339 NStrx = 0;
340 NValue = S.Address;
341 }
342 } else {
343 H = MachO->MachOObjectFile::getHeader();
344 Filetype = H.filetype;
345 Flags = H.flags;
346 if (SymDRI.p){
347 MachO::nlist STE = MachO->getSymbolTableEntry(DRI: SymDRI);
348 NType = STE.n_type;
349 NSect = STE.n_sect;
350 NDesc = STE.n_desc;
351 NStrx = STE.n_strx;
352 NValue = STE.n_value;
353 } else {
354 NType = S.NType;
355 NSect = S.NSect;
356 NDesc = S.NDesc;
357 NStrx = 0;
358 NValue = S.Address;
359 }
360 }
361 }
362
363 // If we are printing Mach-O symbols in hex do that and return.
364 if (FormatMachOasHex) {
365 outs() << format(Fmt: printFormat, Vals: NValue) << ' '
366 << format(Fmt: "%02x %02x %04x %08x", Vals: NType, Vals: NSect, Vals: NDesc, Vals: NStrx) << ' '
367 << S.Name;
368 if ((NType & MachO::N_TYPE) == MachO::N_INDR) {
369 outs() << " (indirect for ";
370 outs() << format(Fmt: printFormat, Vals: NValue) << ' ';
371 StringRef IndirectName;
372 if (S.Sym.getRawDataRefImpl().p) {
373 if (MachO->getIndirectName(Symb: S.Sym.getRawDataRefImpl(), Res&: IndirectName))
374 outs() << "?)";
375 else
376 outs() << IndirectName << ")";
377 } else
378 outs() << S.IndirectName << ")";
379 }
380 outs() << "\n";
381 return;
382 }
383
384 if (PrintAddress) {
385 if ((NType & MachO::N_TYPE) == MachO::N_INDR)
386 strcpy(dest: SymbolAddrStr, src: printBlanks);
387 if (Obj.isIR() && (NType & MachO::N_TYPE) == MachO::N_TYPE)
388 strcpy(dest: SymbolAddrStr, src: printDashes);
389 outs() << SymbolAddrStr << ' ';
390 }
391
392 switch (NType & MachO::N_TYPE) {
393 case MachO::N_UNDF:
394 if (NValue != 0) {
395 outs() << "(common) ";
396 if (MachO::GET_COMM_ALIGN(n_desc: NDesc) != 0)
397 outs() << "(alignment 2^" << (int)MachO::GET_COMM_ALIGN(n_desc: NDesc) << ") ";
398 } else {
399 if ((NType & MachO::N_TYPE) == MachO::N_PBUD)
400 outs() << "(prebound ";
401 else
402 outs() << "(";
403 if ((NDesc & MachO::REFERENCE_TYPE) ==
404 MachO::REFERENCE_FLAG_UNDEFINED_LAZY)
405 outs() << "undefined [lazy bound]) ";
406 else if ((NDesc & MachO::REFERENCE_TYPE) ==
407 MachO::REFERENCE_FLAG_PRIVATE_UNDEFINED_LAZY)
408 outs() << "undefined [private lazy bound]) ";
409 else if ((NDesc & MachO::REFERENCE_TYPE) ==
410 MachO::REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY)
411 outs() << "undefined [private]) ";
412 else
413 outs() << "undefined) ";
414 }
415 break;
416 case MachO::N_ABS:
417 outs() << "(absolute) ";
418 break;
419 case MachO::N_INDR:
420 outs() << "(indirect) ";
421 break;
422 case MachO::N_SECT: {
423 if (Obj.isIR()) {
424 // For llvm bitcode files print out a fake section name using the values
425 // use 1, 2 and 3 for section numbers as set above.
426 if (NSect == 1)
427 outs() << "(LTO,CODE) ";
428 else if (NSect == 2)
429 outs() << "(LTO,DATA) ";
430 else if (NSect == 3)
431 outs() << "(LTO,RODATA) ";
432 else
433 outs() << "(?,?) ";
434 break;
435 }
436 section_iterator Sec = SectionRef();
437 if (S.Sym.getRawDataRefImpl().p) {
438 Expected<section_iterator> SecOrErr =
439 MachO->getSymbolSection(Symb: S.Sym.getRawDataRefImpl());
440 if (!SecOrErr) {
441 consumeError(Err: SecOrErr.takeError());
442 outs() << "(?,?) ";
443 break;
444 }
445 Sec = *SecOrErr;
446 if (Sec == MachO->section_end()) {
447 outs() << "(?,?) ";
448 break;
449 }
450 } else {
451 Sec = S.Section;
452 }
453 DataRefImpl Ref = Sec->getRawDataRefImpl();
454 StringRef SectionName;
455 if (Expected<StringRef> NameOrErr = MachO->getSectionName(Sec: Ref))
456 SectionName = *NameOrErr;
457 StringRef SegmentName = MachO->getSectionFinalSegmentName(Sec: Ref);
458 outs() << "(" << SegmentName << "," << SectionName << ") ";
459 break;
460 }
461 default:
462 outs() << "(?) ";
463 break;
464 }
465
466 if (NType & MachO::N_EXT) {
467 if (NDesc & MachO::REFERENCED_DYNAMICALLY)
468 outs() << "[referenced dynamically] ";
469 if (NType & MachO::N_PEXT) {
470 if ((NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF)
471 outs() << "weak private external ";
472 else
473 outs() << "private external ";
474 } else {
475 if ((NDesc & MachO::N_WEAK_REF) == MachO::N_WEAK_REF ||
476 (NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF) {
477 if ((NDesc & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF)) ==
478 (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
479 outs() << "weak external automatically hidden ";
480 else
481 outs() << "weak external ";
482 } else
483 outs() << "external ";
484 }
485 } else {
486 if (NType & MachO::N_PEXT)
487 outs() << "non-external (was a private external) ";
488 else
489 outs() << "non-external ";
490 }
491
492 if (Filetype == MachO::MH_OBJECT) {
493 if (NDesc & MachO::N_NO_DEAD_STRIP)
494 outs() << "[no dead strip] ";
495 if ((NType & MachO::N_TYPE) != MachO::N_UNDF &&
496 NDesc & MachO::N_SYMBOL_RESOLVER)
497 outs() << "[symbol resolver] ";
498 if ((NType & MachO::N_TYPE) != MachO::N_UNDF && NDesc & MachO::N_ALT_ENTRY)
499 outs() << "[alt entry] ";
500 if ((NType & MachO::N_TYPE) != MachO::N_UNDF && NDesc & MachO::N_COLD_FUNC)
501 outs() << "[cold func] ";
502 }
503
504 if ((NDesc & MachO::N_ARM_THUMB_DEF) == MachO::N_ARM_THUMB_DEF)
505 outs() << "[Thumb] ";
506
507 if ((NType & MachO::N_TYPE) == MachO::N_INDR) {
508 outs() << S.Name << " (for ";
509 StringRef IndirectName;
510 if (MachO) {
511 if (S.Sym.getRawDataRefImpl().p) {
512 if (MachO->getIndirectName(Symb: S.Sym.getRawDataRefImpl(), Res&: IndirectName))
513 outs() << "?)";
514 else
515 outs() << IndirectName << ")";
516 } else
517 outs() << S.IndirectName << ")";
518 } else
519 outs() << "?)";
520 } else
521 outs() << S.Name;
522
523 if ((Flags & MachO::MH_TWOLEVEL) == MachO::MH_TWOLEVEL &&
524 (((NType & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0) ||
525 (NType & MachO::N_TYPE) == MachO::N_PBUD)) {
526 uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(n_desc: NDesc);
527 if (LibraryOrdinal != 0) {
528 if (LibraryOrdinal == MachO::EXECUTABLE_ORDINAL)
529 outs() << " (from executable)";
530 else if (LibraryOrdinal == MachO::DYNAMIC_LOOKUP_ORDINAL)
531 outs() << " (dynamically looked up)";
532 else {
533 StringRef LibraryName;
534 if (!MachO ||
535 MachO->getLibraryShortNameByIndex(Index: LibraryOrdinal - 1, LibraryName))
536 outs() << " (from bad library ordinal " << LibraryOrdinal << ")";
537 else
538 outs() << " (from " << LibraryName << ")";
539 }
540 }
541 }
542}
543
544// Table that maps Darwin's Mach-O stab constants to strings to allow printing.
545struct DarwinStabName {
546 uint8_t NType;
547 const char *Name;
548};
549const struct DarwinStabName DarwinStabNames[] = {
550 {.NType: MachO::N_GSYM, .Name: "GSYM"}, {.NType: MachO::N_FNAME, .Name: "FNAME"},
551 {.NType: MachO::N_FUN, .Name: "FUN"}, {.NType: MachO::N_STSYM, .Name: "STSYM"},
552 {.NType: MachO::N_LCSYM, .Name: "LCSYM"}, {.NType: MachO::N_BNSYM, .Name: "BNSYM"},
553 {.NType: MachO::N_PC, .Name: "PC"}, {.NType: MachO::N_AST, .Name: "AST"},
554 {.NType: MachO::N_OPT, .Name: "OPT"}, {.NType: MachO::N_RSYM, .Name: "RSYM"},
555 {.NType: MachO::N_SLINE, .Name: "SLINE"}, {.NType: MachO::N_ENSYM, .Name: "ENSYM"},
556 {.NType: MachO::N_SSYM, .Name: "SSYM"}, {.NType: MachO::N_SO, .Name: "SO"},
557 {.NType: MachO::N_OSO, .Name: "OSO"}, {.NType: MachO::N_LIB, .Name: "LIB"},
558 {.NType: MachO::N_LSYM, .Name: "LSYM"}, {.NType: MachO::N_BINCL, .Name: "BINCL"},
559 {.NType: MachO::N_SOL, .Name: "SOL"}, {.NType: MachO::N_PARAMS, .Name: "PARAM"},
560 {.NType: MachO::N_VERSION, .Name: "VERS"}, {.NType: MachO::N_OLEVEL, .Name: "OLEV"},
561 {.NType: MachO::N_PSYM, .Name: "PSYM"}, {.NType: MachO::N_EINCL, .Name: "EINCL"},
562 {.NType: MachO::N_ENTRY, .Name: "ENTRY"}, {.NType: MachO::N_LBRAC, .Name: "LBRAC"},
563 {.NType: MachO::N_EXCL, .Name: "EXCL"}, {.NType: MachO::N_RBRAC, .Name: "RBRAC"},
564 {.NType: MachO::N_BCOMM, .Name: "BCOMM"}, {.NType: MachO::N_ECOMM, .Name: "ECOMM"},
565 {.NType: MachO::N_ECOML, .Name: "ECOML"}, {.NType: MachO::N_LENG, .Name: "LENG"},
566};
567
568static const char *getDarwinStabString(uint8_t NType) {
569 for (auto I : ArrayRef(DarwinStabNames))
570 if (I.NType == NType)
571 return I.Name;
572 return nullptr;
573}
574
575// darwinPrintStab() prints the n_sect, n_desc along with a symbolic name of
576// a stab n_type value in a Mach-O file.
577static void darwinPrintStab(MachOObjectFile *MachO, const NMSymbol &S) {
578 MachO::nlist_64 STE_64;
579 MachO::nlist STE;
580 uint8_t NType;
581 uint8_t NSect;
582 uint16_t NDesc;
583 DataRefImpl SymDRI = S.Sym.getRawDataRefImpl();
584 if (MachO->is64Bit()) {
585 STE_64 = MachO->getSymbol64TableEntry(DRI: SymDRI);
586 NType = STE_64.n_type;
587 NSect = STE_64.n_sect;
588 NDesc = STE_64.n_desc;
589 } else {
590 STE = MachO->getSymbolTableEntry(DRI: SymDRI);
591 NType = STE.n_type;
592 NSect = STE.n_sect;
593 NDesc = STE.n_desc;
594 }
595
596 outs() << format(Fmt: " %02x %04x ", Vals: NSect, Vals: NDesc);
597 if (const char *stabString = getDarwinStabString(NType))
598 outs() << format(Fmt: "%5.5s", Vals: stabString);
599 else
600 outs() << format(Fmt: " %02x", Vals: NType);
601}
602
603static bool symbolIsDefined(const NMSymbol &Sym) {
604 return Sym.TypeChar != 'U' && Sym.TypeChar != 'w' && Sym.TypeChar != 'v';
605}
606
607static void writeFileName(raw_ostream &S, StringRef ArchiveName,
608 StringRef ArchitectureName) {
609 if (!ArchitectureName.empty())
610 S << "(for architecture " << ArchitectureName << "):";
611 if (OutputFormat == posix && !ArchiveName.empty())
612 S << ArchiveName << "[" << CurrentFilename << "]: ";
613 else {
614 if (!ArchiveName.empty())
615 S << ArchiveName << ":";
616 S << CurrentFilename << ": ";
617 }
618}
619
620static void sortSymbolList(std::vector<NMSymbol> &SymbolList) {
621 if (NoSort)
622 return;
623
624 if (ReverseSort)
625 llvm::sort(C&: SymbolList, Comp: std::greater<>());
626 else
627 llvm::sort(C&: SymbolList);
628}
629
630static void printExportSymbolList(const std::vector<NMSymbol> &SymbolList) {
631 for (const NMSymbol &Sym : SymbolList) {
632 outs() << Sym.Name;
633 if (!Sym.Visibility.empty())
634 outs() << ' ' << Sym.Visibility;
635 outs() << '\n';
636 }
637}
638
639static void printLineNumbers(symbolize::LLVMSymbolizer &Symbolizer,
640 const NMSymbol &S) {
641 const auto *Obj = dyn_cast<ObjectFile>(Val: S.Sym.getObject());
642 if (!Obj)
643 return;
644 const SymbolRef Sym(S.Sym);
645 uint64_t SectionIndex = object::SectionedAddress::UndefSection;
646 section_iterator Sec = cantFail(ValOrErr: Sym.getSection());
647 if (Sec != Obj->section_end())
648 SectionIndex = Sec->getIndex();
649 object::SectionedAddress Address = {.Address: cantFail(ValOrErr: Sym.getAddress()), .SectionIndex: SectionIndex};
650
651 std::string FileName;
652 uint32_t Line;
653 switch (S.TypeChar) {
654 // For undefined symbols, find the first relocation for that symbol with a
655 // line number.
656 case 'U': {
657 for (const SectionRef RelocsSec : Obj->sections()) {
658 if (RelocsSec.relocations().empty())
659 continue;
660 SectionRef TextSec = *cantFail(ValOrErr: RelocsSec.getRelocatedSection());
661 if (!TextSec.isText())
662 continue;
663 for (const RelocationRef R : RelocsSec.relocations()) {
664 if (R.getSymbol() != Sym)
665 continue;
666 Expected<DILineInfo> ResOrErr = Symbolizer.symbolizeCode(
667 Obj: *Obj, ModuleOffset: {.Address: TextSec.getAddress() + R.getOffset(), .SectionIndex: SectionIndex});
668 if (!ResOrErr) {
669 error(E: ResOrErr.takeError(), FileName: Obj->getFileName());
670 return;
671 }
672 if (ResOrErr->FileName == DILineInfo::BadString)
673 return;
674 FileName = std::move(ResOrErr->FileName);
675 Line = ResOrErr->Line;
676 break;
677 }
678 if (!FileName.empty())
679 break;
680 }
681 if (FileName.empty())
682 return;
683 break;
684 }
685 case 't':
686 case 'T': {
687 Expected<DILineInfo> ResOrErr = Symbolizer.symbolizeCode(Obj: *Obj, ModuleOffset: Address);
688 if (!ResOrErr) {
689 error(E: ResOrErr.takeError(), FileName: Obj->getFileName());
690 return;
691 }
692 if (ResOrErr->FileName == DILineInfo::BadString)
693 return;
694 FileName = std::move(ResOrErr->FileName);
695 Line = ResOrErr->Line;
696 break;
697 }
698 default: {
699 Expected<DIGlobal> ResOrErr = Symbolizer.symbolizeData(Obj: *Obj, ModuleOffset: Address);
700 if (!ResOrErr) {
701 error(E: ResOrErr.takeError(), FileName: Obj->getFileName());
702 return;
703 }
704 if (ResOrErr->DeclFile.empty())
705 return;
706 FileName = std::move(ResOrErr->DeclFile);
707 Line = ResOrErr->DeclLine;
708 break;
709 }
710 }
711 outs() << '\t' << FileName << ':' << Line;
712}
713
714static void printSymbolList(SymbolicFile &Obj,
715 std::vector<NMSymbol> &SymbolList, bool printName,
716 StringRef ArchiveName, StringRef ArchitectureName) {
717 std::optional<symbolize::LLVMSymbolizer> Symbolizer;
718 if (LineNumbers)
719 Symbolizer.emplace();
720
721 if (!PrintFileName) {
722 if ((OutputFormat == bsd || OutputFormat == posix ||
723 OutputFormat == just_symbols) &&
724 MultipleFiles && printName) {
725 outs() << '\n' << CurrentFilename << ":\n";
726 } else if (OutputFormat == sysv) {
727 outs() << "\n\nSymbols from " << CurrentFilename << ":\n\n";
728 if (Obj.is64Bit())
729 outs() << "Name Value Class Type"
730 << " Size Line Section\n";
731 else
732 outs() << "Name Value Class Type"
733 << " Size Line Section\n";
734 }
735 }
736
737 const char *printBlanks, *printDashes, *printFormat;
738 if (Obj.is64Bit()) {
739 printBlanks = " ";
740 printDashes = "----------------";
741 switch (AddressRadix) {
742 case Radix::o:
743 printFormat = OutputFormat == posix ? "%" PRIo64 : "%016" PRIo64;
744 break;
745 case Radix::x:
746 printFormat = OutputFormat == posix ? "%" PRIx64 : "%016" PRIx64;
747 break;
748 default:
749 printFormat = OutputFormat == posix ? "%" PRId64 : "%016" PRId64;
750 }
751 } else {
752 printBlanks = " ";
753 printDashes = "--------";
754 switch (AddressRadix) {
755 case Radix::o:
756 printFormat = OutputFormat == posix ? "%" PRIo64 : "%08" PRIo64;
757 break;
758 case Radix::x:
759 printFormat = OutputFormat == posix ? "%" PRIx64 : "%08" PRIx64;
760 break;
761 default:
762 printFormat = OutputFormat == posix ? "%" PRId64 : "%08" PRId64;
763 }
764 }
765
766 for (const NMSymbol &S : SymbolList) {
767 if (!S.shouldPrint())
768 continue;
769
770 std::string Name = S.Name;
771 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: &Obj);
772 if (Demangle)
773 Name = demangle(MangledName: Name);
774
775 if (PrintFileName)
776 writeFileName(S&: outs(), ArchiveName, ArchitectureName);
777 if ((OutputFormat == just_symbols ||
778 (UndefinedOnly && MachO && OutputFormat != darwin)) &&
779 OutputFormat != posix) {
780 outs() << Name << "\n";
781 continue;
782 }
783
784 char SymbolAddrStr[23], SymbolSizeStr[23];
785
786 // If the format is SysV or the symbol isn't defined, then print spaces.
787 if (OutputFormat == sysv || !symbolIsDefined(Sym: S)) {
788 if (OutputFormat == posix) {
789 format(Fmt: printFormat, Vals: S.Address)
790 .snprint(Buffer: SymbolAddrStr, BufferSize: sizeof(SymbolAddrStr));
791 format(Fmt: printFormat, Vals: S.Size)
792 .snprint(Buffer: SymbolSizeStr, BufferSize: sizeof(SymbolSizeStr));
793 } else {
794 strcpy(dest: SymbolAddrStr, src: printBlanks);
795 strcpy(dest: SymbolSizeStr, src: printBlanks);
796 }
797 }
798
799 if (symbolIsDefined(Sym: S)) {
800 // Otherwise, print the symbol address and size.
801 if (Obj.isIR())
802 strcpy(dest: SymbolAddrStr, src: printDashes);
803 else if (MachO && S.TypeChar == 'I')
804 strcpy(dest: SymbolAddrStr, src: printBlanks);
805 else
806 format(Fmt: printFormat, Vals: S.Address)
807 .snprint(Buffer: SymbolAddrStr, BufferSize: sizeof(SymbolAddrStr));
808 format(Fmt: printFormat, Vals: S.Size).snprint(Buffer: SymbolSizeStr, BufferSize: sizeof(SymbolSizeStr));
809 }
810
811 // If OutputFormat is darwin or we are printing Mach-O symbols in hex and
812 // we have a MachOObjectFile, call darwinPrintSymbol to print as darwin's
813 // nm(1) -m output or hex, else if OutputFormat is darwin or we are
814 // printing Mach-O symbols in hex and not a Mach-O object fall back to
815 // OutputFormat bsd (see below).
816 if ((OutputFormat == darwin || FormatMachOasHex) && (MachO || Obj.isIR())) {
817 darwinPrintSymbol(Obj, S, SymbolAddrStr, printBlanks, printDashes,
818 printFormat);
819 } else if (OutputFormat == posix) {
820 outs() << Name << " " << S.TypeChar << " " << SymbolAddrStr << " "
821 << (MachO ? "0" : SymbolSizeStr);
822 } else if (OutputFormat == bsd || (OutputFormat == darwin && !MachO)) {
823 if (PrintAddress)
824 outs() << SymbolAddrStr << ' ';
825 if (PrintSize)
826 outs() << SymbolSizeStr << ' ';
827 outs() << S.TypeChar;
828 if (S.TypeChar == '-' && MachO)
829 darwinPrintStab(MachO, S);
830 outs() << " " << Name;
831 if (S.TypeChar == 'I' && MachO) {
832 outs() << " (indirect for ";
833 if (S.Sym.getRawDataRefImpl().p) {
834 StringRef IndirectName;
835 if (MachO->getIndirectName(Symb: S.Sym.getRawDataRefImpl(), Res&: IndirectName))
836 outs() << "?)";
837 else
838 outs() << IndirectName << ")";
839 } else
840 outs() << S.IndirectName << ")";
841 }
842 } else if (OutputFormat == sysv) {
843 outs() << left_justify(Str: Name, Width: 20) << "|" << SymbolAddrStr << "| "
844 << S.TypeChar << " |" << right_justify(Str: S.TypeName, Width: 18) << "|"
845 << SymbolSizeStr << "| |" << S.SectionName;
846 }
847 if (LineNumbers)
848 printLineNumbers(Symbolizer&: *Symbolizer, S);
849 outs() << '\n';
850 }
851
852 SymbolList.clear();
853}
854
855static char getSymbolNMTypeChar(ELFObjectFileBase &Obj,
856 basic_symbol_iterator I) {
857 // OK, this is ELF
858 elf_symbol_iterator SymI(I);
859
860 Expected<elf_section_iterator> SecIOrErr = SymI->getSection();
861 if (!SecIOrErr) {
862 consumeError(Err: SecIOrErr.takeError());
863 return '?';
864 }
865
866 uint8_t Binding = SymI->getBinding();
867 if (Binding == ELF::STB_GNU_UNIQUE)
868 return 'u';
869
870 assert(Binding != ELF::STB_WEAK && "STB_WEAK not tested in calling function");
871 if (Binding != ELF::STB_GLOBAL && Binding != ELF::STB_LOCAL)
872 return '?';
873
874 elf_section_iterator SecI = *SecIOrErr;
875 if (SecI != Obj.section_end()) {
876 uint32_t Type = SecI->getType();
877 uint64_t Flags = SecI->getFlags();
878 if (Flags & ELF::SHF_EXECINSTR)
879 return 't';
880 if (Type == ELF::SHT_NOBITS)
881 return 'b';
882 if (Flags & ELF::SHF_ALLOC)
883 return Flags & ELF::SHF_WRITE ? 'd' : 'r';
884
885 auto NameOrErr = SecI->getName();
886 if (!NameOrErr) {
887 consumeError(Err: NameOrErr.takeError());
888 return '?';
889 }
890 if ((*NameOrErr).starts_with(Prefix: ".debug"))
891 return 'N';
892 if (!(Flags & ELF::SHF_WRITE))
893 return 'n';
894 }
895
896 return '?';
897}
898
899static char getSymbolNMTypeChar(COFFObjectFile &Obj, symbol_iterator I) {
900 COFFSymbolRef Symb = Obj.getCOFFSymbol(Symbol: *I);
901 // OK, this is COFF.
902 symbol_iterator SymI(I);
903
904 Expected<StringRef> Name = SymI->getName();
905 if (!Name) {
906 consumeError(Err: Name.takeError());
907 return '?';
908 }
909
910 char Ret = StringSwitch<char>(*Name)
911 .StartsWith(S: ".debug", Value: 'N')
912 .StartsWith(S: ".sxdata", Value: 'N')
913 .Default(Value: '?');
914
915 if (Ret != '?')
916 return Ret;
917
918 uint32_t Characteristics = 0;
919 if (!COFF::isReservedSectionNumber(SectionNumber: Symb.getSectionNumber())) {
920 Expected<section_iterator> SecIOrErr = SymI->getSection();
921 if (!SecIOrErr) {
922 consumeError(Err: SecIOrErr.takeError());
923 return '?';
924 }
925 section_iterator SecI = *SecIOrErr;
926 const coff_section *Section = Obj.getCOFFSection(Section: *SecI);
927 Characteristics = Section->Characteristics;
928 if (Expected<StringRef> NameOrErr = Obj.getSectionName(Sec: Section))
929 if (NameOrErr->starts_with(Prefix: ".idata"))
930 return 'i';
931 }
932
933 switch (Symb.getSectionNumber()) {
934 case COFF::IMAGE_SYM_DEBUG:
935 return 'n';
936 default:
937 // Check section type.
938 if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
939 return 't';
940 if (Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
941 return Characteristics & COFF::IMAGE_SCN_MEM_WRITE ? 'd' : 'r';
942 if (Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
943 return 'b';
944 if (Characteristics & COFF::IMAGE_SCN_LNK_INFO)
945 return 'i';
946 // Check for section symbol.
947 if (Symb.isSectionDefinition())
948 return 's';
949 }
950
951 return '?';
952}
953
954static char getSymbolNMTypeChar(XCOFFObjectFile &Obj, symbol_iterator I) {
955 Expected<uint32_t> TypeOrErr = I->getType();
956 if (!TypeOrErr) {
957 warn(Err: TypeOrErr.takeError(), FileName: Obj.getFileName(),
958 Context: "for symbol with index " +
959 Twine(Obj.getSymbolIndex(SymEntPtr: I->getRawDataRefImpl().p)));
960 return '?';
961 }
962
963 uint32_t SymType = *TypeOrErr;
964
965 if (SymType == SymbolRef::ST_File)
966 return 'f';
967
968 // If the I->getSection() call would return an error, the earlier I->getType()
969 // call will already have returned the same error first.
970 section_iterator SecIter = cantFail(ValOrErr: I->getSection());
971
972 if (SecIter == Obj.section_end())
973 return '?';
974
975 if (Obj.isDebugSection(Sec: SecIter->getRawDataRefImpl()))
976 return 'N';
977
978 if (SecIter->isText())
979 return 't';
980
981 if (SecIter->isData())
982 return 'd';
983
984 if (SecIter->isBSS())
985 return 'b';
986
987 return '?';
988}
989
990static char getSymbolNMTypeChar(COFFImportFile &Obj) {
991 switch (Obj.getCOFFImportHeader()->getType()) {
992 case COFF::IMPORT_CODE:
993 return 't';
994 case COFF::IMPORT_DATA:
995 return 'd';
996 case COFF::IMPORT_CONST:
997 return 'r';
998 }
999 return '?';
1000}
1001
1002static char getSymbolNMTypeChar(GOFFObjectFile &, basic_symbol_iterator I) {
1003 GOFFSymbolRef Ref(*I);
1004 Expected<SymbolRef::Type> Type = Ref.getSymbolGOFFType();
1005 // TODO: Add a test using yaml2obj once GOFF ESD record support is
1006 // available in yaml2obj.
1007 if (!Type) {
1008 consumeError(Err: Type.takeError());
1009 return '?';
1010 }
1011 switch (*Type) {
1012 case SymbolRef::ST_Data:
1013 return 'd';
1014 case SymbolRef::ST_Function:
1015 return 't';
1016 default:
1017 llvm_unreachable("GOFFObjectFile::getSymbolType returned unexpected type");
1018 }
1019}
1020
1021static char getSymbolNMTypeChar(MachOObjectFile &Obj, basic_symbol_iterator I) {
1022 DataRefImpl Symb = I->getRawDataRefImpl();
1023 uint8_t NType = Obj.is64Bit() ? Obj.getSymbol64TableEntry(DRI: Symb).n_type
1024 : Obj.getSymbolTableEntry(DRI: Symb).n_type;
1025
1026 if (NType & MachO::N_STAB)
1027 return '-';
1028
1029 switch (NType & MachO::N_TYPE) {
1030 case MachO::N_ABS:
1031 return 's';
1032 case MachO::N_INDR:
1033 return 'i';
1034 case MachO::N_SECT: {
1035 Expected<section_iterator> SecOrErr = Obj.getSymbolSection(Symb);
1036 if (!SecOrErr) {
1037 consumeError(Err: SecOrErr.takeError());
1038 return 's';
1039 }
1040 section_iterator Sec = *SecOrErr;
1041 if (Sec == Obj.section_end())
1042 return 's';
1043 DataRefImpl Ref = Sec->getRawDataRefImpl();
1044 StringRef SectionName;
1045 if (Expected<StringRef> NameOrErr = Obj.getSectionName(Sec: Ref))
1046 SectionName = *NameOrErr;
1047 StringRef SegmentName = Obj.getSectionFinalSegmentName(Sec: Ref);
1048 if (Obj.is64Bit() && Obj.getHeader64().filetype == MachO::MH_KEXT_BUNDLE &&
1049 SegmentName == "__TEXT_EXEC" && SectionName == "__text")
1050 return 't';
1051 if (SegmentName == "__TEXT" && SectionName == "__text")
1052 return 't';
1053 if (SegmentName == "__DATA" && SectionName == "__data")
1054 return 'd';
1055 if (SegmentName == "__DATA" && SectionName == "__bss")
1056 return 'b';
1057 return 's';
1058 }
1059 }
1060
1061 return '?';
1062}
1063
1064static char getSymbolNMTypeChar(TapiFile &Obj, basic_symbol_iterator I) {
1065 auto Type = cantFail(ValOrErr: Obj.getSymbolType(DRI: I->getRawDataRefImpl()));
1066 switch (Type) {
1067 case SymbolRef::ST_Function:
1068 return 't';
1069 case SymbolRef::ST_Data:
1070 if (Obj.hasSegmentInfo())
1071 return 'd';
1072 [[fallthrough]];
1073 default:
1074 return 's';
1075 }
1076}
1077
1078static char getSymbolNMTypeChar(WasmObjectFile &Obj, basic_symbol_iterator I) {
1079 uint32_t Flags = cantFail(ValOrErr: I->getFlags());
1080 if (Flags & SymbolRef::SF_Executable)
1081 return 't';
1082 return 'd';
1083}
1084
1085static char getSymbolNMTypeChar(IRObjectFile &Obj, basic_symbol_iterator I) {
1086 uint32_t Flags = cantFail(ValOrErr: I->getFlags());
1087 // FIXME: should we print 'b'? At the IR level we cannot be sure if this
1088 // will be in bss or not, but we could approximate.
1089 if (Flags & SymbolRef::SF_Executable)
1090 return 't';
1091 else if (Triple(Obj.getTargetTriple()).isOSDarwin() &&
1092 (Flags & SymbolRef::SF_Const))
1093 return 's';
1094 else
1095 return 'd';
1096}
1097
1098static bool isObject(SymbolicFile &Obj, basic_symbol_iterator I) {
1099 return isa<ELFObjectFileBase>(Val: &Obj) &&
1100 elf_symbol_iterator(I)->getELFType() == ELF::STT_OBJECT;
1101}
1102
1103// For ELF object files, Set TypeName to the symbol typename, to be printed
1104// in the 'Type' column of the SYSV format output.
1105static StringRef getNMTypeName(SymbolicFile &Obj, basic_symbol_iterator I) {
1106 if (isa<ELFObjectFileBase>(Val: &Obj)) {
1107 elf_symbol_iterator SymI(I);
1108 return SymI->getELFTypeName();
1109 }
1110 return "";
1111}
1112
1113// Return Posix nm class type tag (single letter), but also set SecName and
1114// section and name, to be used in format=sysv output.
1115static char getNMSectionTagAndName(SymbolicFile &Obj, basic_symbol_iterator I,
1116 StringRef &SecName) {
1117 // Symbol Flags have been checked in the caller.
1118 uint32_t Symflags = cantFail(ValOrErr: I->getFlags());
1119 if (ELFObjectFileBase *ELFObj = dyn_cast<ELFObjectFileBase>(Val: &Obj)) {
1120 if (Symflags & object::SymbolRef::SF_Absolute)
1121 SecName = "*ABS*";
1122 else if (Symflags & object::SymbolRef::SF_Common)
1123 SecName = "*COM*";
1124 else if (Symflags & object::SymbolRef::SF_Undefined)
1125 SecName = "*UND*";
1126 else {
1127 elf_symbol_iterator SymI(I);
1128 Expected<elf_section_iterator> SecIOrErr = SymI->getSection();
1129 if (!SecIOrErr) {
1130 consumeError(Err: SecIOrErr.takeError());
1131 return '?';
1132 }
1133
1134 if (*SecIOrErr == ELFObj->section_end())
1135 return '?';
1136
1137 Expected<StringRef> NameOrErr = (*SecIOrErr)->getName();
1138 if (!NameOrErr) {
1139 consumeError(Err: NameOrErr.takeError());
1140 return '?';
1141 }
1142 SecName = *NameOrErr;
1143 }
1144 }
1145
1146 if (Symflags & object::SymbolRef::SF_Undefined) {
1147 if (isa<MachOObjectFile>(Val: Obj) || !(Symflags & object::SymbolRef::SF_Weak))
1148 return 'U';
1149 return isObject(Obj, I) ? 'v' : 'w';
1150 }
1151 if (isa<ELFObjectFileBase>(Val: &Obj))
1152 if (ELFSymbolRef(*I).getELFType() == ELF::STT_GNU_IFUNC)
1153 return 'i';
1154 if (!isa<MachOObjectFile>(Val: Obj) && (Symflags & object::SymbolRef::SF_Weak))
1155 return isObject(Obj, I) ? 'V' : 'W';
1156
1157 if (Symflags & object::SymbolRef::SF_Common)
1158 return 'C';
1159
1160 char Ret = '?';
1161 if (Symflags & object::SymbolRef::SF_Absolute)
1162 Ret = 'a';
1163 else if (IRObjectFile *IR = dyn_cast<IRObjectFile>(Val: &Obj))
1164 Ret = getSymbolNMTypeChar(Obj&: *IR, I);
1165 else if (COFFObjectFile *COFF = dyn_cast<COFFObjectFile>(Val: &Obj))
1166 Ret = getSymbolNMTypeChar(Obj&: *COFF, I);
1167 else if (XCOFFObjectFile *XCOFF = dyn_cast<XCOFFObjectFile>(Val: &Obj))
1168 Ret = getSymbolNMTypeChar(Obj&: *XCOFF, I);
1169 else if (COFFImportFile *COFFImport = dyn_cast<COFFImportFile>(Val: &Obj))
1170 Ret = getSymbolNMTypeChar(Obj&: *COFFImport);
1171 else if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: &Obj))
1172 Ret = getSymbolNMTypeChar(Obj&: *MachO, I);
1173 else if (WasmObjectFile *Wasm = dyn_cast<WasmObjectFile>(Val: &Obj))
1174 Ret = getSymbolNMTypeChar(Obj&: *Wasm, I);
1175 else if (TapiFile *Tapi = dyn_cast<TapiFile>(Val: &Obj))
1176 Ret = getSymbolNMTypeChar(Obj&: *Tapi, I);
1177 else if (ELFObjectFileBase *ELF = dyn_cast<ELFObjectFileBase>(Val: &Obj)) {
1178 Ret = getSymbolNMTypeChar(Obj&: *ELF, I);
1179 if (ELFSymbolRef(*I).getBinding() == ELF::STB_GNU_UNIQUE)
1180 return Ret;
1181 } else if (GOFFObjectFile *GOFF = dyn_cast<GOFFObjectFile>(Val: &Obj)) {
1182 Ret = getSymbolNMTypeChar(*GOFF, I);
1183 } else
1184 llvm_unreachable("unknown binary format");
1185
1186 if (!(Symflags & object::SymbolRef::SF_Global))
1187 return Ret;
1188
1189 return toupper(c: Ret);
1190}
1191
1192// getNsectForSegSect() is used to implement the Mach-O "-s segname sectname"
1193// option to dump only those symbols from that section in a Mach-O file.
1194// It is called once for each Mach-O file from getSymbolNamesFromObject()
1195// to get the section number for that named section from the command line
1196// arguments. It returns the section number for that section in the Mach-O
1197// file or zero it is not present.
1198static unsigned getNsectForSegSect(MachOObjectFile *Obj) {
1199 unsigned Nsect = 1;
1200 for (auto &S : Obj->sections()) {
1201 DataRefImpl Ref = S.getRawDataRefImpl();
1202 StringRef SectionName;
1203 if (Expected<StringRef> NameOrErr = Obj->getSectionName(Sec: Ref))
1204 SectionName = *NameOrErr;
1205 StringRef SegmentName = Obj->getSectionFinalSegmentName(Sec: Ref);
1206 if (SegmentName == SegSect[0] && SectionName == SegSect[1])
1207 return Nsect;
1208 Nsect++;
1209 }
1210 return 0;
1211}
1212
1213// getNsectInMachO() is used to implement the Mach-O "-s segname sectname"
1214// option to dump only those symbols from that section in a Mach-O file.
1215// It is called once for each symbol in a Mach-O file from
1216// getSymbolNamesFromObject() and returns the section number for that symbol
1217// if it is in a section, else it returns 0.
1218static unsigned getNsectInMachO(MachOObjectFile &Obj, BasicSymbolRef Sym) {
1219 DataRefImpl Symb = Sym.getRawDataRefImpl();
1220 if (Obj.is64Bit()) {
1221 MachO::nlist_64 STE = Obj.getSymbol64TableEntry(DRI: Symb);
1222 return (STE.n_type & MachO::N_TYPE) == MachO::N_SECT ? STE.n_sect : 0;
1223 }
1224 MachO::nlist STE = Obj.getSymbolTableEntry(DRI: Symb);
1225 return (STE.n_type & MachO::N_TYPE) == MachO::N_SECT ? STE.n_sect : 0;
1226}
1227
1228static void dumpSymbolsFromDLInfoMachO(MachOObjectFile &MachO,
1229 std::vector<NMSymbol> &SymbolList) {
1230 size_t I = SymbolList.size();
1231 std::string ExportsNameBuffer;
1232 raw_string_ostream EOS(ExportsNameBuffer);
1233 std::string BindsNameBuffer;
1234 raw_string_ostream BOS(BindsNameBuffer);
1235 std::string LazysNameBuffer;
1236 raw_string_ostream LOS(LazysNameBuffer);
1237 std::string WeaksNameBuffer;
1238 raw_string_ostream WOS(WeaksNameBuffer);
1239 std::string FunctionStartsNameBuffer;
1240 raw_string_ostream FOS(FunctionStartsNameBuffer);
1241
1242 MachO::mach_header H;
1243 MachO::mach_header_64 H_64;
1244 uint32_t HFlags = 0;
1245 if (MachO.is64Bit()) {
1246 H_64 = MachO.MachOObjectFile::getHeader64();
1247 HFlags = H_64.flags;
1248 } else {
1249 H = MachO.MachOObjectFile::getHeader();
1250 HFlags = H.flags;
1251 }
1252 uint64_t BaseSegmentAddress = 0;
1253 for (const auto &Command : MachO.load_commands()) {
1254 if (Command.C.cmd == MachO::LC_SEGMENT) {
1255 MachO::segment_command Seg = MachO.getSegmentLoadCommand(L: Command);
1256 if (Seg.fileoff == 0 && Seg.filesize != 0) {
1257 BaseSegmentAddress = Seg.vmaddr;
1258 break;
1259 }
1260 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
1261 MachO::segment_command_64 Seg = MachO.getSegment64LoadCommand(L: Command);
1262 if (Seg.fileoff == 0 && Seg.filesize != 0) {
1263 BaseSegmentAddress = Seg.vmaddr;
1264 break;
1265 }
1266 }
1267 }
1268 if (DyldInfoOnly || AddDyldInfo ||
1269 HFlags & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
1270 unsigned ExportsAdded = 0;
1271 Error Err = Error::success();
1272 for (const llvm::object::ExportEntry &Entry : MachO.exports(Err)) {
1273 bool found = false;
1274 bool ReExport = false;
1275 if (!DyldInfoOnly) {
1276 for (const NMSymbol &S : SymbolList)
1277 if (S.Address == Entry.address() + BaseSegmentAddress &&
1278 S.Name == Entry.name()) {
1279 found = true;
1280 break;
1281 }
1282 }
1283 if (!found) {
1284 NMSymbol S = {};
1285 S.Address = Entry.address() + BaseSegmentAddress;
1286 S.Size = 0;
1287 S.TypeChar = '\0';
1288 S.Name = Entry.name().str();
1289 // There is no symbol in the nlist symbol table for this so we set
1290 // Sym effectivly to null and the rest of code in here must test for
1291 // it and not do things like Sym.getFlags() for it.
1292 S.Sym = BasicSymbolRef();
1293 S.SymFlags = SymbolRef::SF_Global;
1294 S.Section = SectionRef();
1295 S.NType = 0;
1296 S.NSect = 0;
1297 S.NDesc = 0;
1298
1299 uint64_t EFlags = Entry.flags();
1300 bool Abs = ((EFlags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
1301 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
1302 bool Resolver = (EFlags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
1303 ReExport = (EFlags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
1304 bool WeakDef = (EFlags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
1305 if (WeakDef)
1306 S.NDesc |= MachO::N_WEAK_DEF;
1307 if (Abs) {
1308 S.NType = MachO::N_EXT | MachO::N_ABS;
1309 S.TypeChar = 'A';
1310 } else if (ReExport) {
1311 S.NType = MachO::N_EXT | MachO::N_INDR;
1312 S.TypeChar = 'I';
1313 } else {
1314 S.NType = MachO::N_EXT | MachO::N_SECT;
1315 if (Resolver) {
1316 S.Address = Entry.other() + BaseSegmentAddress;
1317 if ((S.Address & 1) != 0 && !MachO.is64Bit() &&
1318 H.cputype == MachO::CPU_TYPE_ARM) {
1319 S.Address &= ~1LL;
1320 S.NDesc |= MachO::N_ARM_THUMB_DEF;
1321 }
1322 } else {
1323 S.Address = Entry.address() + BaseSegmentAddress;
1324 }
1325 StringRef SegmentName = StringRef();
1326 StringRef SectionName = StringRef();
1327 for (const SectionRef &Section : MachO.sections()) {
1328 S.NSect++;
1329
1330 if (Expected<StringRef> NameOrErr = Section.getName())
1331 SectionName = *NameOrErr;
1332 else
1333 consumeError(Err: NameOrErr.takeError());
1334
1335 SegmentName =
1336 MachO.getSectionFinalSegmentName(Sec: Section.getRawDataRefImpl());
1337 if (S.Address >= Section.getAddress() &&
1338 S.Address < Section.getAddress() + Section.getSize()) {
1339 S.Section = Section;
1340 break;
1341 } else if (Entry.name() == "__mh_execute_header" &&
1342 SegmentName == "__TEXT" && SectionName == "__text") {
1343 S.Section = Section;
1344 S.NDesc |= MachO::REFERENCED_DYNAMICALLY;
1345 break;
1346 }
1347 }
1348 if (SegmentName == "__TEXT" && SectionName == "__text")
1349 S.TypeChar = 'T';
1350 else if (SegmentName == "__DATA" && SectionName == "__data")
1351 S.TypeChar = 'D';
1352 else if (SegmentName == "__DATA" && SectionName == "__bss")
1353 S.TypeChar = 'B';
1354 else
1355 S.TypeChar = 'S';
1356 }
1357 SymbolList.push_back(x: S);
1358
1359 EOS << Entry.name();
1360 EOS << '\0';
1361 ExportsAdded++;
1362
1363 // For ReExports there are a two more things to do, first add the
1364 // indirect name and second create the undefined symbol using the
1365 // referened dynamic library.
1366 if (ReExport) {
1367
1368 // Add the indirect name.
1369 if (Entry.otherName().empty())
1370 EOS << Entry.name();
1371 else
1372 EOS << Entry.otherName();
1373 EOS << '\0';
1374
1375 // Now create the undefined symbol using the referened dynamic
1376 // library.
1377 NMSymbol U = {};
1378 U.Address = 0;
1379 U.Size = 0;
1380 U.TypeChar = 'U';
1381 if (Entry.otherName().empty())
1382 U.Name = Entry.name().str();
1383 else
1384 U.Name = Entry.otherName().str();
1385 // Again there is no symbol in the nlist symbol table for this so
1386 // we set Sym effectivly to null and the rest of code in here must
1387 // test for it and not do things like Sym.getFlags() for it.
1388 U.Sym = BasicSymbolRef();
1389 U.SymFlags = SymbolRef::SF_Global | SymbolRef::SF_Undefined;
1390 U.Section = SectionRef();
1391 U.NType = MachO::N_EXT | MachO::N_UNDF;
1392 U.NSect = 0;
1393 U.NDesc = 0;
1394 // The library ordinal for this undefined symbol is in the export
1395 // trie Entry.other().
1396 MachO::SET_LIBRARY_ORDINAL(n_desc&: U.NDesc, ordinal: Entry.other());
1397 SymbolList.push_back(x: U);
1398
1399 // Finally add the undefined symbol's name.
1400 if (Entry.otherName().empty())
1401 EOS << Entry.name();
1402 else
1403 EOS << Entry.otherName();
1404 EOS << '\0';
1405 ExportsAdded++;
1406 }
1407 }
1408 }
1409 if (Err)
1410 error(E: std::move(Err), FileName: MachO.getFileName());
1411 // Set the symbol names and indirect names for the added symbols.
1412 if (ExportsAdded) {
1413 const char *Q = ExportsNameBuffer.c_str();
1414 for (unsigned K = 0; K < ExportsAdded; K++) {
1415 SymbolList[I].Name = Q;
1416 Q += strlen(s: Q) + 1;
1417 if (SymbolList[I].TypeChar == 'I') {
1418 SymbolList[I].IndirectName = Q;
1419 Q += strlen(s: Q) + 1;
1420 }
1421 I++;
1422 }
1423 }
1424
1425 // Add the undefined symbols from the bind entries.
1426 unsigned BindsAdded = 0;
1427 Error BErr = Error::success();
1428 StringRef LastSymbolName = StringRef();
1429 for (const llvm::object::MachOBindEntry &Entry : MachO.bindTable(Err&: BErr)) {
1430 bool found = false;
1431 if (LastSymbolName == Entry.symbolName())
1432 found = true;
1433 else if (!DyldInfoOnly) {
1434 for (unsigned J = 0; J < SymbolList.size() && !found; ++J) {
1435 if (SymbolList[J].Name == Entry.symbolName())
1436 found = true;
1437 }
1438 }
1439 if (!found) {
1440 LastSymbolName = Entry.symbolName();
1441 NMSymbol B = {};
1442 B.Address = 0;
1443 B.Size = 0;
1444 B.TypeChar = 'U';
1445 // There is no symbol in the nlist symbol table for this so we set
1446 // Sym effectivly to null and the rest of code in here must test for
1447 // it and not do things like Sym.getFlags() for it.
1448 B.Sym = BasicSymbolRef();
1449 B.SymFlags = SymbolRef::SF_Global | SymbolRef::SF_Undefined;
1450 B.NType = MachO::N_EXT | MachO::N_UNDF;
1451 B.NSect = 0;
1452 B.NDesc = 0;
1453 MachO::SET_LIBRARY_ORDINAL(n_desc&: B.NDesc, ordinal: Entry.ordinal());
1454 B.Name = Entry.symbolName().str();
1455 SymbolList.push_back(x: B);
1456 BOS << Entry.symbolName();
1457 BOS << '\0';
1458 BindsAdded++;
1459 }
1460 }
1461 if (BErr)
1462 error(E: std::move(BErr), FileName: MachO.getFileName());
1463 // Set the symbol names and indirect names for the added symbols.
1464 if (BindsAdded) {
1465 const char *Q = BindsNameBuffer.c_str();
1466 for (unsigned K = 0; K < BindsAdded; K++) {
1467 SymbolList[I].Name = Q;
1468 Q += strlen(s: Q) + 1;
1469 if (SymbolList[I].TypeChar == 'I') {
1470 SymbolList[I].IndirectName = Q;
1471 Q += strlen(s: Q) + 1;
1472 }
1473 I++;
1474 }
1475 }
1476
1477 // Add the undefined symbols from the lazy bind entries.
1478 unsigned LazysAdded = 0;
1479 Error LErr = Error::success();
1480 LastSymbolName = StringRef();
1481 for (const llvm::object::MachOBindEntry &Entry :
1482 MachO.lazyBindTable(Err&: LErr)) {
1483 bool found = false;
1484 if (LastSymbolName == Entry.symbolName())
1485 found = true;
1486 else {
1487 // Here we must check to see it this symbol is already in the
1488 // SymbolList as it might have already have been added above via a
1489 // non-lazy (bind) entry.
1490 for (unsigned J = 0; J < SymbolList.size() && !found; ++J) {
1491 if (SymbolList[J].Name == Entry.symbolName())
1492 found = true;
1493 }
1494 }
1495 if (!found) {
1496 LastSymbolName = Entry.symbolName();
1497 NMSymbol L = {};
1498 L.Name = Entry.symbolName().str();
1499 L.Address = 0;
1500 L.Size = 0;
1501 L.TypeChar = 'U';
1502 // There is no symbol in the nlist symbol table for this so we set
1503 // Sym effectivly to null and the rest of code in here must test for
1504 // it and not do things like Sym.getFlags() for it.
1505 L.Sym = BasicSymbolRef();
1506 L.SymFlags = SymbolRef::SF_Global | SymbolRef::SF_Undefined;
1507 L.NType = MachO::N_EXT | MachO::N_UNDF;
1508 L.NSect = 0;
1509 // The REFERENCE_FLAG_UNDEFINED_LAZY is no longer used but here it
1510 // makes sence since we are creating this from a lazy bind entry.
1511 L.NDesc = MachO::REFERENCE_FLAG_UNDEFINED_LAZY;
1512 MachO::SET_LIBRARY_ORDINAL(n_desc&: L.NDesc, ordinal: Entry.ordinal());
1513 SymbolList.push_back(x: L);
1514 LOS << Entry.symbolName();
1515 LOS << '\0';
1516 LazysAdded++;
1517 }
1518 }
1519 if (LErr)
1520 error(E: std::move(LErr), FileName: MachO.getFileName());
1521 // Set the symbol names and indirect names for the added symbols.
1522 if (LazysAdded) {
1523 const char *Q = LazysNameBuffer.c_str();
1524 for (unsigned K = 0; K < LazysAdded; K++) {
1525 SymbolList[I].Name = Q;
1526 Q += strlen(s: Q) + 1;
1527 if (SymbolList[I].TypeChar == 'I') {
1528 SymbolList[I].IndirectName = Q;
1529 Q += strlen(s: Q) + 1;
1530 }
1531 I++;
1532 }
1533 }
1534
1535 // Add the undefineds symbol from the weak bind entries which are not
1536 // strong symbols.
1537 unsigned WeaksAdded = 0;
1538 Error WErr = Error::success();
1539 LastSymbolName = StringRef();
1540 for (const llvm::object::MachOBindEntry &Entry :
1541 MachO.weakBindTable(Err&: WErr)) {
1542 bool found = false;
1543 unsigned J = 0;
1544 if (LastSymbolName == Entry.symbolName() ||
1545 Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
1546 found = true;
1547 } else {
1548 for (J = 0; J < SymbolList.size() && !found; ++J) {
1549 if (SymbolList[J].Name == Entry.symbolName()) {
1550 found = true;
1551 break;
1552 }
1553 }
1554 }
1555 if (!found) {
1556 LastSymbolName = Entry.symbolName();
1557 NMSymbol W = {};
1558 W.Name = Entry.symbolName().str();
1559 W.Address = 0;
1560 W.Size = 0;
1561 W.TypeChar = 'U';
1562 // There is no symbol in the nlist symbol table for this so we set
1563 // Sym effectivly to null and the rest of code in here must test for
1564 // it and not do things like Sym.getFlags() for it.
1565 W.Sym = BasicSymbolRef();
1566 W.SymFlags = SymbolRef::SF_Global | SymbolRef::SF_Undefined;
1567 W.NType = MachO::N_EXT | MachO::N_UNDF;
1568 W.NSect = 0;
1569 // Odd that we are using N_WEAK_DEF on an undefined symbol but that is
1570 // what is created in this case by the linker when there are real
1571 // symbols in the nlist structs.
1572 W.NDesc = MachO::N_WEAK_DEF;
1573 SymbolList.push_back(x: W);
1574 WOS << Entry.symbolName();
1575 WOS << '\0';
1576 WeaksAdded++;
1577 } else {
1578 // This is the case the symbol was previously been found and it could
1579 // have been added from a bind or lazy bind symbol. If so and not
1580 // a definition also mark it as weak.
1581 if (SymbolList[J].TypeChar == 'U')
1582 // See comment above about N_WEAK_DEF.
1583 SymbolList[J].NDesc |= MachO::N_WEAK_DEF;
1584 }
1585 }
1586 if (WErr)
1587 error(E: std::move(WErr), FileName: MachO.getFileName());
1588 // Set the symbol names and indirect names for the added symbols.
1589 if (WeaksAdded) {
1590 const char *Q = WeaksNameBuffer.c_str();
1591 for (unsigned K = 0; K < WeaksAdded; K++) {
1592 SymbolList[I].Name = Q;
1593 Q += strlen(s: Q) + 1;
1594 if (SymbolList[I].TypeChar == 'I') {
1595 SymbolList[I].IndirectName = Q;
1596 Q += strlen(s: Q) + 1;
1597 }
1598 I++;
1599 }
1600 }
1601
1602 // Trying adding symbol from the function starts table and LC_MAIN entry
1603 // point.
1604 SmallVector<uint64_t, 8> FoundFns;
1605 uint64_t lc_main_offset = UINT64_MAX;
1606 for (const auto &Command : MachO.load_commands()) {
1607 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
1608 // We found a function starts segment, parse the addresses for
1609 // consumption.
1610 MachO::linkedit_data_command LLC =
1611 MachO.getLinkeditDataLoadCommand(L: Command);
1612
1613 MachO.ReadULEB128s(Index: LLC.dataoff, Out&: FoundFns);
1614 } else if (Command.C.cmd == MachO::LC_MAIN) {
1615 MachO::entry_point_command LCmain = MachO.getEntryPointCommand(L: Command);
1616 lc_main_offset = LCmain.entryoff;
1617 }
1618 }
1619 // See if these addresses are already in the symbol table.
1620 unsigned FunctionStartsAdded = 0;
1621 // The addresses from FoundFns come from LC_FUNCTION_STARTS. Its contents
1622 // are delta encoded addresses from the start of __TEXT, ending when zero
1623 // is found. Because of this, the addresses should be unique, and even if
1624 // we create fake entries on SymbolList in the second loop, SymbolAddresses
1625 // should not need to be updated there.
1626 SmallSet<uint64_t, 32> SymbolAddresses;
1627 for (const auto &S : SymbolList)
1628 SymbolAddresses.insert(V: S.Address);
1629 for (uint64_t f = 0; f < FoundFns.size(); f++) {
1630 // See if this address is already in the symbol table, otherwise fake up
1631 // an nlist for it.
1632 if (!SymbolAddresses.contains(V: FoundFns[f] + BaseSegmentAddress)) {
1633 NMSymbol F = {};
1634 F.Name = "<redacted function X>";
1635 F.Address = FoundFns[f] + BaseSegmentAddress;
1636 F.Size = 0;
1637 // There is no symbol in the nlist symbol table for this so we set
1638 // Sym effectivly to null and the rest of code in here must test for
1639 // it and not do things like Sym.getFlags() for it.
1640 F.Sym = BasicSymbolRef();
1641 F.SymFlags = 0;
1642 F.NType = MachO::N_SECT;
1643 F.NSect = 0;
1644 StringRef SegmentName = StringRef();
1645 StringRef SectionName = StringRef();
1646 for (const SectionRef &Section : MachO.sections()) {
1647 if (Expected<StringRef> NameOrErr = Section.getName())
1648 SectionName = *NameOrErr;
1649 else
1650 consumeError(Err: NameOrErr.takeError());
1651
1652 SegmentName =
1653 MachO.getSectionFinalSegmentName(Sec: Section.getRawDataRefImpl());
1654 F.NSect++;
1655 if (F.Address >= Section.getAddress() &&
1656 F.Address < Section.getAddress() + Section.getSize()) {
1657 F.Section = Section;
1658 break;
1659 }
1660 }
1661 if (SegmentName == "__TEXT" && SectionName == "__text")
1662 F.TypeChar = 't';
1663 else if (SegmentName == "__DATA" && SectionName == "__data")
1664 F.TypeChar = 'd';
1665 else if (SegmentName == "__DATA" && SectionName == "__bss")
1666 F.TypeChar = 'b';
1667 else
1668 F.TypeChar = 's';
1669 F.NDesc = 0;
1670 SymbolList.push_back(x: F);
1671 if (FoundFns[f] == lc_main_offset)
1672 FOS << "<redacted LC_MAIN>";
1673 else
1674 FOS << "<redacted function " << f << ">";
1675 FOS << '\0';
1676 FunctionStartsAdded++;
1677 }
1678 }
1679 if (FunctionStartsAdded) {
1680 const char *Q = FunctionStartsNameBuffer.c_str();
1681 for (unsigned K = 0; K < FunctionStartsAdded; K++) {
1682 SymbolList[I].Name = Q;
1683 Q += strlen(s: Q) + 1;
1684 if (SymbolList[I].TypeChar == 'I') {
1685 SymbolList[I].IndirectName = Q;
1686 Q += strlen(s: Q) + 1;
1687 }
1688 I++;
1689 }
1690 }
1691 }
1692}
1693
1694static bool shouldDump(SymbolicFile &Obj) {
1695 // The -X option is currently only implemented for XCOFF, ELF, and IR object
1696 // files. The option isn't fundamentally impossible with other formats, just
1697 // isn't implemented.
1698 if (!isa<XCOFFObjectFile>(Val: Obj) && !isa<ELFObjectFileBase>(Val: Obj) &&
1699 !isa<IRObjectFile>(Val: Obj))
1700 return true;
1701
1702 return Obj.is64Bit() ? BitMode != BitModeTy::Bit32
1703 : BitMode != BitModeTy::Bit64;
1704}
1705
1706static void getXCOFFExports(XCOFFObjectFile *XCOFFObj,
1707 std::vector<NMSymbol> &SymbolList,
1708 StringRef ArchiveName) {
1709 // Skip Shared object file.
1710 if (XCOFFObj->getFlags() & XCOFF::F_SHROBJ)
1711 return;
1712
1713 for (SymbolRef Sym : XCOFFObj->symbols()) {
1714 // There is no visibility in old 32 bit XCOFF object file interpret.
1715 bool HasVisibilityAttr =
1716 XCOFFObj->is64Bit() || (XCOFFObj->auxiliaryHeader32() &&
1717 (XCOFFObj->auxiliaryHeader32()->getVersion() ==
1718 XCOFF::NEW_XCOFF_INTERPRET));
1719
1720 if (HasVisibilityAttr) {
1721 XCOFFSymbolRef XCOFFSym = XCOFFObj->toSymbolRef(Ref: Sym.getRawDataRefImpl());
1722 uint16_t SymType = XCOFFSym.getSymbolType();
1723 if ((SymType & XCOFF::VISIBILITY_MASK) == XCOFF::SYM_V_INTERNAL)
1724 continue;
1725 if ((SymType & XCOFF::VISIBILITY_MASK) == XCOFF::SYM_V_HIDDEN)
1726 continue;
1727 }
1728
1729 Expected<section_iterator> SymSecOrErr = Sym.getSection();
1730 if (!SymSecOrErr) {
1731 warn(Err: SymSecOrErr.takeError(), FileName: XCOFFObj->getFileName(),
1732 Context: "for symbol with index " +
1733 Twine(XCOFFObj->getSymbolIndex(SymEntPtr: Sym.getRawDataRefImpl().p)),
1734 Archive: ArchiveName);
1735 continue;
1736 }
1737 section_iterator SecIter = *SymSecOrErr;
1738 // If the symbol is not in a text or data section, it is not exported.
1739 if (SecIter == XCOFFObj->section_end())
1740 continue;
1741 if (!(SecIter->isText() || SecIter->isData() || SecIter->isBSS()))
1742 continue;
1743
1744 StringRef SymName = cantFail(ValOrErr: Sym.getName());
1745 if (SymName.empty())
1746 continue;
1747 if (SymName.starts_with(Prefix: "__sinit") || SymName.starts_with(Prefix: "__sterm") ||
1748 SymName.front() == '.' || SymName.front() == '(')
1749 continue;
1750
1751 // Check the SymName regex matching with "^__[0-9]+__".
1752 if (SymName.size() > 4 && SymName.starts_with(Prefix: "__") &&
1753 SymName.ends_with(Suffix: "__")) {
1754 if (std::all_of(first: SymName.begin() + 2, last: SymName.end() - 2, pred: isDigit))
1755 continue;
1756 }
1757
1758 if (SymName == "__rsrc" && NoRsrc)
1759 continue;
1760
1761 if (SymName.starts_with(Prefix: "__tf1"))
1762 SymName = SymName.substr(Start: 6);
1763 else if (SymName.starts_with(Prefix: "__tf9"))
1764 SymName = SymName.substr(Start: 14);
1765
1766 NMSymbol S = {};
1767 S.Name = SymName.str();
1768 S.Sym = Sym;
1769
1770 if (HasVisibilityAttr) {
1771 XCOFFSymbolRef XCOFFSym = XCOFFObj->toSymbolRef(Ref: Sym.getRawDataRefImpl());
1772 uint16_t SymType = XCOFFSym.getSymbolType();
1773 if ((SymType & XCOFF::VISIBILITY_MASK) == XCOFF::SYM_V_PROTECTED)
1774 S.Visibility = "protected";
1775 else if ((SymType & XCOFF::VISIBILITY_MASK) == XCOFF::SYM_V_EXPORTED)
1776 S.Visibility = "export";
1777 }
1778 if (S.initializeFlags(Obj: *XCOFFObj))
1779 SymbolList.push_back(x: S);
1780 }
1781}
1782
1783static Expected<SymbolicFile::basic_symbol_iterator_range>
1784getDynamicSyms(SymbolicFile &Obj) {
1785 const auto *E = dyn_cast<ELFObjectFileBase>(Val: &Obj);
1786 if (!E)
1787 return createError(Err: "File format has no dynamic symbol table");
1788 return E->getDynamicSymbolIterators();
1789}
1790
1791// Returns false if there is error found or true otherwise.
1792static bool getSymbolNamesFromObject(SymbolicFile &Obj,
1793 std::vector<NMSymbol> &SymbolList) {
1794 auto Symbols = Obj.symbols();
1795 std::vector<VersionEntry> SymbolVersions;
1796
1797 if (DynamicSyms) {
1798 Expected<SymbolicFile::basic_symbol_iterator_range> SymbolsOrErr =
1799 getDynamicSyms(Obj);
1800 if (!SymbolsOrErr) {
1801 error(E: SymbolsOrErr.takeError(), FileName: Obj.getFileName());
1802 return false;
1803 }
1804 Symbols = *SymbolsOrErr;
1805 if (const auto *E = dyn_cast<ELFObjectFileBase>(Val: &Obj)) {
1806 if (Expected<std::vector<VersionEntry>> VersionsOrErr =
1807 E->readDynsymVersions())
1808 SymbolVersions = std::move(*VersionsOrErr);
1809 else
1810 WithColor::warning(OS&: errs(), Prefix: ToolName)
1811 << "unable to read symbol versions: "
1812 << toString(E: VersionsOrErr.takeError()) << "\n";
1813 }
1814 }
1815 // If a "-s segname sectname" option was specified and this is a Mach-O
1816 // file get the section number for that section in this object file.
1817 unsigned int Nsect = 0;
1818 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: &Obj);
1819 if (!SegSect.empty() && MachO) {
1820 Nsect = getNsectForSegSect(Obj: MachO);
1821 // If this section is not in the object file no symbols are printed.
1822 if (Nsect == 0)
1823 return false;
1824 }
1825
1826 if (!(MachO && DyldInfoOnly)) {
1827 size_t I = -1;
1828 for (BasicSymbolRef Sym : Symbols) {
1829 ++I;
1830 Expected<uint32_t> SymFlagsOrErr = Sym.getFlags();
1831 if (!SymFlagsOrErr) {
1832 error(E: SymFlagsOrErr.takeError(), FileName: Obj.getFileName());
1833 return false;
1834 }
1835
1836 // Drop format-specific symbols (STT_FILE, STT_SECTION, etc.) but
1837 // retain mapping symbols (STT_NOTYPE such as $d, $x) on ARM, AArch64,
1838 // CSKY, and RISC-V targets to honor the --special-syms option.
1839 if (!DebugSyms && (*SymFlagsOrErr & SymbolRef::SF_FormatSpecific)) {
1840 auto *ELFObj = dyn_cast<ELFObjectFileBase>(Val: &Obj);
1841 bool IsMappingSymbol =
1842 ELFObj &&
1843 llvm::is_contained(
1844 Set: {ELF::EM_ARM, ELF::EM_AARCH64, ELF::EM_CSKY, ELF::EM_RISCV},
1845 Element: ELFObj->getEMachine()) &&
1846 ELFSymbolRef(Sym).getELFType() == ELF::STT_NOTYPE;
1847 if (!IsMappingSymbol)
1848 continue;
1849 }
1850 if (WithoutAliases && (*SymFlagsOrErr & SymbolRef::SF_Indirect))
1851 continue;
1852 // If a "-s segname sectname" option was specified and this is a Mach-O
1853 // file and this section appears in this file, Nsect will be non-zero then
1854 // see if this symbol is a symbol from that section and if not skip it.
1855 if (Nsect && Nsect != getNsectInMachO(Obj&: *MachO, Sym))
1856 continue;
1857 NMSymbol S = {};
1858 S.Size = 0;
1859 S.Address = 0;
1860 if (isa<ELFObjectFileBase>(Val: &Obj))
1861 S.Size = ELFSymbolRef(Sym).getSize();
1862 else if (isa<GOFFObjectFile>(Val: &Obj))
1863 S.Size = GOFFSymbolRef(Sym).getSize();
1864
1865 if (const XCOFFObjectFile *XCOFFObj =
1866 dyn_cast<const XCOFFObjectFile>(Val: &Obj))
1867 S.Size = XCOFFObj->getSymbolSize(Symb: Sym.getRawDataRefImpl());
1868
1869 if (const WasmObjectFile *WasmObj = dyn_cast<WasmObjectFile>(Val: &Obj))
1870 S.Size = WasmObj->getSymbolSize(Sym);
1871
1872 if (PrintAddress && isa<ObjectFile>(Val: Obj)) {
1873 SymbolRef SymRef(Sym);
1874 Expected<uint64_t> AddressOrErr = SymRef.getAddress();
1875 if (!AddressOrErr) {
1876 consumeError(Err: AddressOrErr.takeError());
1877 break;
1878 }
1879 S.Address = *AddressOrErr;
1880 }
1881 S.TypeName = getNMTypeName(Obj, I: Sym);
1882 S.TypeChar = getNMSectionTagAndName(Obj, I: Sym, SecName&: S.SectionName);
1883
1884 raw_string_ostream OS(S.Name);
1885 if (Error E = Sym.printName(OS)) {
1886 if (MachO) {
1887 OS << "bad string index";
1888 consumeError(Err: std::move(E));
1889 } else
1890 error(E: std::move(E), FileName: Obj.getFileName());
1891 }
1892 if (!SymbolVersions.empty() && !SymbolVersions[I].Name.empty())
1893 S.Name +=
1894 (SymbolVersions[I].IsVerDef ? "@@" : "@") + SymbolVersions[I].Name;
1895
1896 S.Sym = Sym;
1897 if (S.initializeFlags(Obj))
1898 SymbolList.push_back(x: S);
1899 }
1900 }
1901
1902 // If this is a Mach-O file where the nlist symbol table is out of sync
1903 // with the dyld export trie then look through exports and fake up symbols
1904 // for the ones that are missing (also done with the -add-dyldinfo flag).
1905 // This is needed if strip(1) -T is run on a binary containing swift
1906 // language symbols for example. The option -only-dyldinfo will fake up
1907 // all symbols from the dyld export trie as well as the bind info.
1908 if (MachO && !NoDyldInfo)
1909 dumpSymbolsFromDLInfoMachO(MachO&: *MachO, SymbolList);
1910
1911 return true;
1912}
1913
1914static void printObjectLabel(bool PrintArchiveName, StringRef ArchiveName,
1915 StringRef ArchitectureName,
1916 StringRef ObjectFileName) {
1917 outs() << "\n";
1918 if (ArchiveName.empty() || !PrintArchiveName)
1919 outs() << ObjectFileName;
1920 else
1921 outs() << ArchiveName << "(" << ObjectFileName << ")";
1922 if (!ArchitectureName.empty())
1923 outs() << " (for architecture " << ArchitectureName << ")";
1924 outs() << ":\n";
1925}
1926
1927static Expected<bool> hasSymbols(SymbolicFile &Obj) {
1928 if (DynamicSyms) {
1929 Expected<SymbolicFile::basic_symbol_iterator_range> DynamicSymsOrErr =
1930 getDynamicSyms(Obj);
1931 if (!DynamicSymsOrErr)
1932 return DynamicSymsOrErr.takeError();
1933 return !DynamicSymsOrErr->empty();
1934 }
1935 return !Obj.symbols().empty();
1936}
1937
1938static void printSymbolNamesFromObject(
1939 SymbolicFile &Obj, std::vector<NMSymbol> &SymbolList,
1940 bool PrintSymbolObject, bool PrintObjectLabel, StringRef ArchiveName = {},
1941 StringRef ArchitectureName = {}, StringRef ObjectName = {},
1942 bool PrintArchiveName = true) {
1943
1944 if (PrintObjectLabel && !ExportSymbols)
1945 printObjectLabel(PrintArchiveName, ArchiveName, ArchitectureName,
1946 ObjectFileName: ObjectName.empty() ? Obj.getFileName() : ObjectName);
1947
1948 if (!getSymbolNamesFromObject(Obj, SymbolList) || ExportSymbols)
1949 return;
1950
1951 // If there is an error in hasSymbols(), the error should be encountered in
1952 // function getSymbolNamesFromObject first.
1953 if (!cantFail(ValOrErr: hasSymbols(Obj)) && SymbolList.empty() && !Quiet) {
1954 writeFileName(S&: errs(), ArchiveName, ArchitectureName);
1955 errs() << "no symbols\n";
1956 }
1957
1958 sortSymbolList(SymbolList);
1959 printSymbolList(Obj, SymbolList, printName: PrintSymbolObject, ArchiveName,
1960 ArchitectureName);
1961}
1962
1963static void dumpSymbolsNameFromMachOFilesetEntry(
1964 MachOObjectFile *Obj, std::vector<NMSymbol> &SymbolList,
1965 bool PrintSymbolObject, bool PrintObjectLabel) {
1966 auto Buf = Obj->getMemoryBufferRef();
1967 const auto *End = Obj->load_commands().end();
1968 for (const auto *It = Obj->load_commands().begin(); It != End; ++It) {
1969 const auto &Command = *It;
1970 if (Command.C.cmd != MachO::LC_FILESET_ENTRY)
1971 continue;
1972
1973 MachO::fileset_entry_command Entry =
1974 Obj->getFilesetEntryLoadCommand(L: Command);
1975 auto MaybeMachO =
1976 MachOObjectFile::createMachOObjectFile(Object: Buf, UniversalCputype: 0, UniversalIndex: 0, MachOFilesetEntryOffset: Entry.fileoff);
1977
1978 if (Error Err = MaybeMachO.takeError())
1979 report_fatal_error(Err: std::move(Err));
1980
1981 const char *EntryName = Command.Ptr + Entry.entry_id.offset;
1982 if (EntryName)
1983 outs() << "Symbols for " << EntryName << ": \n";
1984
1985 std::unique_ptr<MachOObjectFile> EntryMachO = std::move(MaybeMachO.get());
1986 printSymbolNamesFromObject(Obj&: *EntryMachO, SymbolList, PrintSymbolObject,
1987 PrintObjectLabel);
1988
1989 if (std::next(x: It) != End)
1990 outs() << "\n";
1991 }
1992}
1993
1994static void dumpSymbolNamesFromObject(
1995 SymbolicFile &Obj, std::vector<NMSymbol> &SymbolList,
1996 bool PrintSymbolObject, bool PrintObjectLabel, StringRef ArchiveName = {},
1997 StringRef ArchitectureName = {}, StringRef ObjectName = {},
1998 bool PrintArchiveName = true) {
1999 if (!shouldDump(Obj))
2000 return;
2001
2002 if (ExportSymbols && Obj.isXCOFF()) {
2003 XCOFFObjectFile *XCOFFObj = cast<XCOFFObjectFile>(Val: &Obj);
2004 getXCOFFExports(XCOFFObj, SymbolList, ArchiveName);
2005 return;
2006 }
2007
2008 CurrentFilename = Obj.getFileName();
2009
2010 // Are we handling a MachO of type MH_FILESET?
2011 if (Obj.isMachO() && Obj.is64Bit() &&
2012 cast<MachOObjectFile>(Val: &Obj)->getHeader64().filetype ==
2013 MachO::MH_FILESET) {
2014 dumpSymbolsNameFromMachOFilesetEntry(Obj: cast<MachOObjectFile>(Val: &Obj),
2015 SymbolList, PrintSymbolObject,
2016 PrintObjectLabel);
2017 return;
2018 }
2019
2020 printSymbolNamesFromObject(Obj, SymbolList, PrintSymbolObject,
2021 PrintObjectLabel, ArchiveName, ArchitectureName,
2022 ObjectName, PrintArchiveName);
2023}
2024
2025// checkMachOAndArchFlags() checks to see if the SymbolicFile is a Mach-O file
2026// and if it is and there is a list of architecture flags is specified then
2027// check to make sure this Mach-O file is one of those architectures or all
2028// architectures was specificed. If not then an error is generated and this
2029// routine returns false. Else it returns true.
2030static bool checkMachOAndArchFlags(SymbolicFile *O, StringRef Filename) {
2031 auto *MachO = dyn_cast<MachOObjectFile>(Val: O);
2032
2033 if (!MachO || ArchAll || ArchFlags.empty())
2034 return true;
2035
2036 MachO::mach_header H;
2037 MachO::mach_header_64 H_64;
2038 Triple T;
2039 const char *McpuDefault, *ArchFlag;
2040 if (MachO->is64Bit()) {
2041 H_64 = MachO->MachOObjectFile::getHeader64();
2042 T = MachOObjectFile::getArchTriple(CPUType: H_64.cputype, CPUSubType: H_64.cpusubtype,
2043 McpuDefault: &McpuDefault, ArchFlag: &ArchFlag);
2044 } else {
2045 H = MachO->MachOObjectFile::getHeader();
2046 T = MachOObjectFile::getArchTriple(CPUType: H.cputype, CPUSubType: H.cpusubtype,
2047 McpuDefault: &McpuDefault, ArchFlag: &ArchFlag);
2048 }
2049 const std::string ArchFlagName(ArchFlag);
2050 if (!llvm::is_contained(Range&: ArchFlags, Element: ArchFlagName)) {
2051 error(Message: "No architecture specified", Path: Filename);
2052 return false;
2053 }
2054 return true;
2055}
2056
2057/// Decode the low 3 bits of a z/OS archive symbol attribute word into a
2058/// human-readable description written to OS, e.g. "[64-bit + XPLink]".
2059/// Any bits above the known 3-bit mask produce a trailing "?" flag.
2060static void decodeZOSAttributes(raw_ostream &OS, uint32_t Attrs) {
2061 bool Unknown = (Attrs & ~Archive::Symbol::ZOSKnownAttrMask) != 0;
2062 bool Is64Bit = (Attrs & Archive::Symbol::ZOSAttr64Bit) != 0;
2063 bool IsXPLink = (Attrs & Archive::Symbol::ZOSAttrXPLink) != 0;
2064 bool IsWSA = (Attrs & Archive::Symbol::ZOSAttrWSA) != 0;
2065
2066 OS << "[";
2067 bool NeedPlus = false;
2068 auto Append = [&](const char *S) {
2069 if (NeedPlus)
2070 OS << " + ";
2071 OS << S;
2072 NeedPlus = true;
2073 };
2074 if (Is64Bit)
2075 Append("64-bit");
2076 if (IsXPLink)
2077 Append("XPLink");
2078 if (IsWSA)
2079 Append("WSA");
2080 if (Unknown)
2081 Append("?");
2082 if (!NeedPlus)
2083 Append("none");
2084 OS << "]";
2085}
2086
2087static void printArchiveMap(iterator_range<Archive::symbol_iterator> &Map,
2088 StringRef Filename, Archive::Kind Kind) {
2089 for (auto I : Map) {
2090 Expected<Archive::Child> C = I.getMember();
2091 if (!C) {
2092 error(E: C.takeError(), FileName: Filename);
2093 break;
2094 }
2095 Expected<StringRef> FileNameOrErr = C->getName();
2096 if (!FileNameOrErr) {
2097 error(E: FileNameOrErr.takeError(), FileName: Filename);
2098 break;
2099 }
2100 StringRef SymName = I.getName();
2101 outs() << SymName << " in " << FileNameOrErr.get();
2102 if (Kind == Archive::K_ZOS) {
2103 uint32_t Attrs = I.getZOSAttributes();
2104 outs() << format(Fmt: " (flags: 0x%08x ", Vals: Attrs);
2105 decodeZOSAttributes(OS&: outs(), Attrs);
2106 outs() << ")";
2107 }
2108 outs() << "\n";
2109 }
2110
2111 outs() << "\n";
2112}
2113
2114static void dumpArchiveMap(Archive *A, StringRef Filename) {
2115 auto Map = A->symbols();
2116 if (!Map.empty()) {
2117 outs() << "Archive map\n";
2118 printArchiveMap(Map, Filename, Kind: A->kind());
2119 }
2120
2121 auto ECMap = A->ec_symbols();
2122 if (!ECMap) {
2123 warn(Err: ECMap.takeError(), FileName: Filename);
2124 } else if (!ECMap->empty()) {
2125 outs() << "Archive EC map\n";
2126 printArchiveMap(Map&: *ECMap, Filename, Kind: A->kind());
2127 }
2128}
2129
2130static void dumpArchive(Archive *A, std::vector<NMSymbol> &SymbolList,
2131 StringRef Filename, LLVMContext *ContextPtr) {
2132 if (ArchiveMap)
2133 dumpArchiveMap(A, Filename);
2134
2135 Error Err = Error::success();
2136 for (auto &C : A->children(Err)) {
2137 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(Context: ContextPtr);
2138 if (!ChildOrErr) {
2139 if (auto E = isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
2140 error(E: std::move(E), FileName: Filename, C);
2141 continue;
2142 }
2143 if (SymbolicFile *O = dyn_cast<SymbolicFile>(Val: &*ChildOrErr.get())) {
2144 if (!MachOPrintSizeWarning && PrintSize && isa<MachOObjectFile>(Val: O)) {
2145 WithColor::warning(OS&: errs(), Prefix: ToolName)
2146 << "sizes with -print-size for Mach-O files are always zero.\n";
2147 MachOPrintSizeWarning = true;
2148 }
2149 if (!checkMachOAndArchFlags(O, Filename))
2150 return;
2151 dumpSymbolNamesFromObject(Obj&: *O, SymbolList, /*PrintSymbolObject=*/false,
2152 PrintObjectLabel: !PrintFileName, ArchiveName: Filename,
2153 /*ArchitectureName=*/{}, ObjectName: O->getFileName(),
2154 /*PrintArchiveName=*/false);
2155 }
2156 }
2157 if (Err)
2158 error(E: std::move(Err), FileName: A->getFileName());
2159}
2160
2161static void dumpMachOUniversalBinaryMatchArchFlags(
2162 MachOUniversalBinary *UB, std::vector<NMSymbol> &SymbolList,
2163 StringRef Filename, LLVMContext *ContextPtr) {
2164 // Look for a slice in the universal binary that matches each ArchFlag.
2165 bool ArchFound;
2166 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2167 ArchFound = false;
2168 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2169 E = UB->end_objects();
2170 I != E; ++I) {
2171 if (ArchFlags[i] == I->getArchFlagName()) {
2172 ArchFound = true;
2173 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2174 std::string ArchiveName;
2175 std::string ArchitectureName;
2176 ArchiveName.clear();
2177 ArchitectureName.clear();
2178 if (ObjOrErr) {
2179 ObjectFile &Obj = *ObjOrErr.get();
2180 if (ArchFlags.size() > 1)
2181 ArchitectureName = I->getArchFlagName();
2182 dumpSymbolNamesFromObject(Obj, SymbolList,
2183 /*PrintSymbolObject=*/false,
2184 PrintObjectLabel: (ArchFlags.size() > 1) && !PrintFileName,
2185 ArchiveName, ArchitectureName);
2186 } else if (auto E =
2187 isNotObjectErrorInvalidFileType(Err: ObjOrErr.takeError())) {
2188 error(E: std::move(E), FileName: Filename,
2189 ArchitectureName: ArchFlags.size() > 1 ? StringRef(I->getArchFlagName())
2190 : StringRef());
2191 continue;
2192 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2193 I->getAsArchive()) {
2194 std::unique_ptr<Archive> &A = *AOrErr;
2195 Error Err = Error::success();
2196 for (auto &C : A->children(Err)) {
2197 Expected<std::unique_ptr<Binary>> ChildOrErr =
2198 C.getAsBinary(Context: ContextPtr);
2199 if (!ChildOrErr) {
2200 if (auto E =
2201 isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError())) {
2202 error(E: std::move(E), FileName: Filename, C,
2203 ArchitectureName: ArchFlags.size() > 1 ? StringRef(I->getArchFlagName())
2204 : StringRef());
2205 }
2206 continue;
2207 }
2208 if (SymbolicFile *O = dyn_cast<SymbolicFile>(Val: &*ChildOrErr.get())) {
2209 ArchiveName = std::string(A->getFileName());
2210 if (ArchFlags.size() > 1)
2211 ArchitectureName = I->getArchFlagName();
2212 dumpSymbolNamesFromObject(
2213 Obj&: *O, SymbolList, /*PrintSymbolObject=*/false, PrintObjectLabel: !PrintFileName,
2214 ArchiveName, ArchitectureName);
2215 }
2216 }
2217 if (Err)
2218 error(E: std::move(Err), FileName: A->getFileName());
2219 } else {
2220 consumeError(Err: AOrErr.takeError());
2221 error(Message: Filename + " for architecture " +
2222 StringRef(I->getArchFlagName()) +
2223 " is not a Mach-O file or an archive file",
2224 Path: "Mach-O universal file");
2225 }
2226 }
2227 }
2228 if (!ArchFound) {
2229 error(Message: ArchFlags[i],
2230 Path: "file: " + Filename + " does not contain architecture");
2231 return;
2232 }
2233 }
2234}
2235
2236// Returns true If the binary contains a slice that matches the host
2237// architecture, or false otherwise.
2238static bool dumpMachOUniversalBinaryMatchHost(MachOUniversalBinary *UB,
2239 std::vector<NMSymbol> &SymbolList,
2240 StringRef Filename,
2241 LLVMContext *ContextPtr) {
2242 Triple HostTriple = MachOObjectFile::getHostArch();
2243 StringRef HostArchName = HostTriple.getArchName();
2244 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2245 E = UB->end_objects();
2246 I != E; ++I) {
2247 if (HostArchName == I->getArchFlagName()) {
2248 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2249 std::string ArchiveName;
2250 if (ObjOrErr) {
2251 ObjectFile &Obj = *ObjOrErr.get();
2252 dumpSymbolNamesFromObject(Obj, SymbolList, /*PrintSymbolObject=*/false,
2253 /*PrintObjectLabel=*/false);
2254 } else if (auto E = isNotObjectErrorInvalidFileType(Err: ObjOrErr.takeError()))
2255 error(E: std::move(E), FileName: Filename);
2256 else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
2257 std::unique_ptr<Archive> &A = *AOrErr;
2258 Error Err = Error::success();
2259 for (auto &C : A->children(Err)) {
2260 Expected<std::unique_ptr<Binary>> ChildOrErr =
2261 C.getAsBinary(Context: ContextPtr);
2262 if (!ChildOrErr) {
2263 if (auto E =
2264 isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
2265 error(E: std::move(E), FileName: Filename, C);
2266 continue;
2267 }
2268 if (SymbolicFile *O = dyn_cast<SymbolicFile>(Val: &*ChildOrErr.get())) {
2269 ArchiveName = std::string(A->getFileName());
2270 dumpSymbolNamesFromObject(Obj&: *O, SymbolList,
2271 /*PrintSymbolObject=*/false,
2272 PrintObjectLabel: !PrintFileName, ArchiveName);
2273 }
2274 }
2275 if (Err)
2276 error(E: std::move(Err), FileName: A->getFileName());
2277 } else {
2278 consumeError(Err: AOrErr.takeError());
2279 error(Message: Filename + " for architecture " +
2280 StringRef(I->getArchFlagName()) +
2281 " is not a Mach-O file or an archive file",
2282 Path: "Mach-O universal file");
2283 }
2284 return true;
2285 }
2286 }
2287 return false;
2288}
2289
2290static void dumpMachOUniversalBinaryArchAll(MachOUniversalBinary *UB,
2291 std::vector<NMSymbol> &SymbolList,
2292 StringRef Filename,
2293 LLVMContext *ContextPtr) {
2294 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2295 for (const MachOUniversalBinary::ObjectForArch &O : UB->objects()) {
2296 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = O.getAsObjectFile();
2297 std::string ArchiveName;
2298 std::string ArchitectureName;
2299 ArchiveName.clear();
2300 ArchitectureName.clear();
2301 if (ObjOrErr) {
2302 ObjectFile &Obj = *ObjOrErr.get();
2303 if (isa<MachOObjectFile>(Val: Obj) && moreThanOneArch)
2304 ArchitectureName = O.getArchFlagName();
2305 dumpSymbolNamesFromObject(Obj, SymbolList, /*PrintSymbolObject=*/false,
2306 PrintObjectLabel: !PrintFileName, ArchiveName, ArchitectureName);
2307 } else if (auto E = isNotObjectErrorInvalidFileType(Err: ObjOrErr.takeError())) {
2308 error(E: std::move(E), FileName: Filename,
2309 ArchitectureName: moreThanOneArch ? StringRef(O.getArchFlagName()) : StringRef());
2310 continue;
2311 } else if (Expected<std::unique_ptr<Archive>> AOrErr = O.getAsArchive()) {
2312 std::unique_ptr<Archive> &A = *AOrErr;
2313 Error Err = Error::success();
2314 for (auto &C : A->children(Err)) {
2315 Expected<std::unique_ptr<Binary>> ChildOrErr =
2316 C.getAsBinary(Context: ContextPtr);
2317 if (!ChildOrErr) {
2318 if (auto E = isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
2319 error(E: std::move(E), FileName: Filename, C,
2320 ArchitectureName: moreThanOneArch ? StringRef(ArchitectureName) : StringRef());
2321 continue;
2322 }
2323 if (SymbolicFile *F = dyn_cast<SymbolicFile>(Val: &*ChildOrErr.get())) {
2324 ArchiveName = std::string(A->getFileName());
2325 if (isa<MachOObjectFile>(Val: F) && moreThanOneArch)
2326 ArchitectureName = O.getArchFlagName();
2327 dumpSymbolNamesFromObject(Obj&: *F, SymbolList, /*PrintSymbolObject=*/false,
2328 PrintObjectLabel: !PrintFileName, ArchiveName,
2329 ArchitectureName);
2330 }
2331 }
2332 if (Err)
2333 error(E: std::move(Err), FileName: A->getFileName());
2334 } else {
2335 consumeError(Err: AOrErr.takeError());
2336 error(Message: Filename + " for architecture " + StringRef(O.getArchFlagName()) +
2337 " is not a Mach-O file or an archive file",
2338 Path: "Mach-O universal file");
2339 }
2340 }
2341}
2342
2343static void dumpMachOUniversalBinary(MachOUniversalBinary *UB,
2344 std::vector<NMSymbol> &SymbolList,
2345 StringRef Filename,
2346 LLVMContext *ContextPtr) {
2347 // If we have a list of architecture flags specified dump only those.
2348 if (!ArchAll && !ArchFlags.empty()) {
2349 dumpMachOUniversalBinaryMatchArchFlags(UB, SymbolList, Filename,
2350 ContextPtr);
2351 return;
2352 }
2353
2354 // No architecture flags were specified so if this contains a slice that
2355 // matches the host architecture dump only that.
2356 if (!ArchAll &&
2357 dumpMachOUniversalBinaryMatchHost(UB, SymbolList, Filename, ContextPtr))
2358 return;
2359
2360 // Either all architectures have been specified or none have been specified
2361 // and this does not contain the host architecture so dump all the slices.
2362 dumpMachOUniversalBinaryArchAll(UB, SymbolList, Filename, ContextPtr);
2363}
2364
2365static void dumpTapiUniversal(TapiUniversal *TU,
2366 std::vector<NMSymbol> &SymbolList,
2367 StringRef Filename) {
2368 for (const TapiUniversal::ObjectForArch &I : TU->objects()) {
2369 StringRef ArchName = I.getArchFlagName();
2370 const bool ShowArch =
2371 ArchFlags.empty() || llvm::is_contained(Range&: ArchFlags, Element: ArchName);
2372 if (!ShowArch)
2373 continue;
2374 if (!AddInlinedInfo && !I.isTopLevelLib())
2375 continue;
2376 if (auto ObjOrErr = I.getAsObjectFile())
2377 dumpSymbolNamesFromObject(
2378 Obj&: *ObjOrErr.get(), SymbolList, /*PrintSymbolObject=*/false,
2379 /*PrintObjectLabel=*/true,
2380 /*ArchiveName=*/{}, ArchitectureName: ArchName, ObjectName: I.getInstallName());
2381 else if (Error E = isNotObjectErrorInvalidFileType(Err: ObjOrErr.takeError())) {
2382 error(E: std::move(E), FileName: Filename, ArchitectureName: ArchName);
2383 }
2384 }
2385}
2386
2387static void dumpSymbolicFile(SymbolicFile *O, std::vector<NMSymbol> &SymbolList,
2388 StringRef Filename) {
2389 if (!MachOPrintSizeWarning && PrintSize && isa<MachOObjectFile>(Val: O)) {
2390 WithColor::warning(OS&: errs(), Prefix: ToolName)
2391 << "sizes with --print-size for Mach-O files are always zero.\n";
2392 MachOPrintSizeWarning = true;
2393 }
2394 if (!checkMachOAndArchFlags(O, Filename))
2395 return;
2396 dumpSymbolNamesFromObject(Obj&: *O, SymbolList, /*PrintSymbolObject=*/true,
2397 /*PrintObjectLabel=*/false);
2398}
2399
2400static std::vector<NMSymbol> dumpSymbolNamesFromFile(StringRef Filename) {
2401 std::vector<NMSymbol> SymbolList;
2402 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
2403 MemoryBuffer::getFileOrSTDIN(Filename);
2404 if (error(EC: BufferOrErr.getError(), Path: Filename))
2405 return SymbolList;
2406
2407 // Ignore AIX linker import files (these files start with "#!"), when
2408 // exporting symbols.
2409 const char *BuffStart = (*BufferOrErr)->getBufferStart();
2410 size_t BufferSize = (*BufferOrErr)->getBufferSize();
2411 if (ExportSymbols && BufferSize >= 2 && BuffStart[0] == '#' &&
2412 BuffStart[1] == '!')
2413 return SymbolList;
2414
2415 LLVMContext Context;
2416 LLVMContext *ContextPtr = NoLLVMBitcode ? nullptr : &Context;
2417 Expected<std::unique_ptr<Binary>> BinaryOrErr =
2418 createBinary(Source: BufferOrErr.get()->getMemBufferRef(), Context: ContextPtr);
2419 if (!BinaryOrErr) {
2420 error(E: BinaryOrErr.takeError(), FileName: Filename);
2421 return SymbolList;
2422 }
2423 Binary &Bin = *BinaryOrErr.get();
2424 if (Archive *A = dyn_cast<Archive>(Val: &Bin))
2425 dumpArchive(A, SymbolList, Filename, ContextPtr);
2426 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Val: &Bin))
2427 dumpMachOUniversalBinary(UB, SymbolList, Filename, ContextPtr);
2428 else if (TapiUniversal *TU = dyn_cast<TapiUniversal>(Val: &Bin))
2429 dumpTapiUniversal(TU, SymbolList, Filename);
2430 else if (SymbolicFile *O = dyn_cast<SymbolicFile>(Val: &Bin))
2431 dumpSymbolicFile(O, SymbolList, Filename);
2432 return SymbolList;
2433}
2434
2435static void
2436exportSymbolNamesFromFiles(const std::vector<std::string> &InputFilenames) {
2437 std::vector<NMSymbol> SymbolList;
2438 for (const auto &FileName : InputFilenames) {
2439 std::vector<NMSymbol> FileSymList = dumpSymbolNamesFromFile(Filename: FileName);
2440 llvm::append_range(C&: SymbolList, R&: FileSymList);
2441 }
2442
2443 // Delete symbols which should not be printed from SymolList.
2444 llvm::erase_if(C&: SymbolList,
2445 P: [](const NMSymbol &s) { return !s.shouldPrint(); });
2446 sortSymbolList(SymbolList);
2447 SymbolList.erase(first: llvm::unique(R&: SymbolList), last: SymbolList.end());
2448 printExportSymbolList(SymbolList);
2449}
2450
2451int llvm_nm_main(int argc, char **argv, const llvm::ToolContext &) {
2452 BumpPtrAllocator A;
2453 StringSaver Saver(A);
2454 NmOptTable Tbl;
2455 ToolName = argv[0];
2456 opt::InputArgList Args =
2457 Tbl.parseArgs(Argc: argc, Argv: argv, Unknown: OPT_UNKNOWN, Saver, ErrorFn: [&](StringRef Msg) {
2458 error(Message: Msg);
2459 exit(status: 1);
2460 });
2461 if (Args.hasArg(Ids: OPT_help)) {
2462 Tbl.printHelp(
2463 OS&: outs(),
2464 Usage: (Twine(ToolName) + " [options] <input object files>").str().c_str(),
2465 Title: "LLVM symbol table dumper");
2466 // TODO Replace this with OptTable API once it adds extrahelp support.
2467 outs() << "\nPass @FILE as argument to read options from FILE.\n";
2468 return 0;
2469 }
2470 if (Args.hasArg(Ids: OPT_version)) {
2471 // This needs to contain the word "GNU", libtool looks for that string.
2472 outs() << "llvm-nm, compatible with GNU nm" << '\n';
2473 cl::PrintVersionMessage();
2474 return 0;
2475 }
2476
2477 DebugSyms = Args.hasArg(Ids: OPT_debug_syms);
2478 DefinedOnly = Args.hasArg(Ids: OPT_defined_only);
2479 Demangle = Args.hasFlag(Pos: OPT_demangle, Neg: OPT_no_demangle, Default: false);
2480 DynamicSyms = Args.hasArg(Ids: OPT_dynamic);
2481 ExternalOnly = Args.hasArg(Ids: OPT_extern_only);
2482 StringRef V = Args.getLastArgValue(Id: OPT_format_EQ, Default: "bsd");
2483 if (V == "bsd")
2484 OutputFormat = bsd;
2485 else if (V == "posix")
2486 OutputFormat = posix;
2487 else if (V == "sysv")
2488 OutputFormat = sysv;
2489 else if (V == "darwin")
2490 OutputFormat = darwin;
2491 else if (V == "just-symbols")
2492 OutputFormat = just_symbols;
2493 else
2494 error(Message: "--format value should be one of: bsd, posix, sysv, darwin, "
2495 "just-symbols");
2496 LineNumbers = Args.hasArg(Ids: OPT_line_numbers);
2497 NoLLVMBitcode = Args.hasArg(Ids: OPT_no_llvm_bc);
2498 NoSort = Args.hasArg(Ids: OPT_no_sort);
2499 NoWeakSymbols = Args.hasArg(Ids: OPT_no_weak);
2500 NumericSort = Args.hasArg(Ids: OPT_numeric_sort);
2501 ArchiveMap = Args.hasArg(Ids: OPT_print_armap);
2502 PrintFileName = Args.hasArg(Ids: OPT_print_file_name);
2503 PrintSize = Args.hasArg(Ids: OPT_print_size);
2504 ReverseSort = Args.hasArg(Ids: OPT_reverse_sort);
2505 ExportSymbols = Args.hasArg(Ids: OPT_export_symbols);
2506 if (ExportSymbols) {
2507 ExternalOnly = true;
2508 DefinedOnly = true;
2509 }
2510
2511 Quiet = Args.hasArg(Ids: OPT_quiet);
2512 V = Args.getLastArgValue(Id: OPT_radix_EQ, Default: "x");
2513 if (V == "o")
2514 AddressRadix = Radix::o;
2515 else if (V == "d")
2516 AddressRadix = Radix::d;
2517 else if (V == "x")
2518 AddressRadix = Radix::x;
2519 else
2520 error(Message: "--radix value should be one of: 'o' (octal), 'd' (decimal), 'x' "
2521 "(hexadecimal)");
2522 SizeSort = Args.hasArg(Ids: OPT_size_sort);
2523 SpecialSyms = Args.hasArg(Ids: OPT_special_syms);
2524 UndefinedOnly = Args.hasArg(Ids: OPT_undefined_only);
2525 WithoutAliases = Args.hasArg(Ids: OPT_without_aliases);
2526
2527 // Get BitMode from enviornment variable "OBJECT_MODE" for AIX OS, if
2528 // specified.
2529 Triple HostTriple(sys::getProcessTriple());
2530 if (HostTriple.isOSAIX()) {
2531 BitMode = StringSwitch<BitModeTy>(getenv(name: "OBJECT_MODE"))
2532 .Case(S: "32", Value: BitModeTy::Bit32)
2533 .Case(S: "64", Value: BitModeTy::Bit64)
2534 .Case(S: "32_64", Value: BitModeTy::Bit32_64)
2535 .Case(S: "any", Value: BitModeTy::Any)
2536 .Default(Value: BitModeTy::Bit32);
2537 } else
2538 BitMode = BitModeTy::Any;
2539
2540 if (Arg *A = Args.getLastArg(Ids: OPT_X)) {
2541 StringRef Mode = A->getValue();
2542 if (Mode == "32")
2543 BitMode = BitModeTy::Bit32;
2544 else if (Mode == "64")
2545 BitMode = BitModeTy::Bit64;
2546 else if (Mode == "32_64")
2547 BitMode = BitModeTy::Bit32_64;
2548 else if (Mode == "any")
2549 BitMode = BitModeTy::Any;
2550 else
2551 error(Message: "-X value should be one of: 32, 64, 32_64, (default) any");
2552 }
2553
2554 // Mach-O specific options.
2555 FormatMachOasHex = Args.hasArg(Ids: OPT_x);
2556 AddDyldInfo = Args.hasArg(Ids: OPT_add_dyldinfo);
2557 AddInlinedInfo = Args.hasArg(Ids: OPT_add_inlinedinfo);
2558 DyldInfoOnly = Args.hasArg(Ids: OPT_dyldinfo_only);
2559 NoDyldInfo = Args.hasArg(Ids: OPT_no_dyldinfo);
2560
2561 // XCOFF specific options.
2562 NoRsrc = Args.hasArg(Ids: OPT_no_rsrc);
2563
2564 // llvm-nm only reads binary files.
2565 if (error(EC: sys::ChangeStdinToBinary()))
2566 return 1;
2567
2568 // These calls are needed so that we can read bitcode correctly.
2569 llvm::InitializeAllTargetInfos();
2570 llvm::InitializeAllTargetMCs();
2571 llvm::InitializeAllAsmParsers();
2572
2573 // The relative order of these is important. If you pass --size-sort it should
2574 // only print out the size. However, if you pass -S --size-sort, it should
2575 // print out both the size and address.
2576 if (SizeSort && !PrintSize)
2577 PrintAddress = false;
2578 if (OutputFormat == sysv || SizeSort)
2579 PrintSize = true;
2580
2581 for (const auto *A : Args.filtered(Ids: OPT_arch_EQ)) {
2582 SmallVector<StringRef, 2> Values;
2583 llvm::SplitString(Source: A->getValue(), OutFragments&: Values, Delimiters: ",");
2584 for (StringRef V : Values) {
2585 if (V == "all")
2586 ArchAll = true;
2587 else if (MachOObjectFile::isValidArch(ArchFlag: V))
2588 ArchFlags.push_back(x: V);
2589 else
2590 error(Message: "Unknown architecture named '" + V + "'",
2591 Path: "for the --arch option");
2592 }
2593 }
2594
2595 // Mach-O takes -s to accept two arguments. We emulate this by iterating over
2596 // both OPT_s and OPT_INPUT.
2597 std::vector<std::string> InputFilenames;
2598 int SegSectArgs = 0;
2599 for (opt::Arg *A : Args.filtered(Ids: OPT_s, Ids: OPT_INPUT)) {
2600 if (SegSectArgs > 0) {
2601 --SegSectArgs;
2602 SegSect.push_back(x: A->getValue());
2603 } else if (A->getOption().matches(ID: OPT_s)) {
2604 SegSectArgs = 2;
2605 } else {
2606 InputFilenames.push_back(x: A->getValue());
2607 }
2608 }
2609 if (!SegSect.empty() && SegSect.size() != 2)
2610 error(Message: "bad number of arguments (must be two arguments)",
2611 Path: "for the -s option");
2612
2613 if (InputFilenames.empty())
2614 InputFilenames.push_back(x: "a.out");
2615 if (InputFilenames.size() > 1)
2616 MultipleFiles = true;
2617
2618 if (NoDyldInfo && (AddDyldInfo || DyldInfoOnly))
2619 error(Message: "--no-dyldinfo can't be used with --add-dyldinfo or --dyldinfo-only");
2620
2621 if (ExportSymbols)
2622 exportSymbolNamesFromFiles(InputFilenames);
2623 else
2624 llvm::for_each(Range&: InputFilenames, F: dumpSymbolNamesFromFile);
2625
2626 if (HadError)
2627 return 1;
2628 return 0;
2629}
2630