1 //===-- llvm-nm.cpp - Symbol table dumping utility for llvm ---------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This program is a utility that works like traditional Unix "nm", that is, it 11 // prints out the names of symbols in a bitcode or object file, along with some 12 // information about each symbol. 13 // 14 // This "nm" supports many of the features of GNU "nm", including its different 15 // output formats. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/IR/Function.h" 20 #include "llvm/IR/GlobalAlias.h" 21 #include "llvm/IR/GlobalVariable.h" 22 #include "llvm/IR/LLVMContext.h" 23 #include "llvm/IR/Module.h" 24 #include "llvm/Object/Archive.h" 25 #include "llvm/Object/COFF.h" 26 #include "llvm/Object/ELFObjectFile.h" 27 #include "llvm/Object/IRObjectFile.h" 28 #include "llvm/Object/MachO.h" 29 #include "llvm/Object/MachOUniversal.h" 30 #include "llvm/Object/ObjectFile.h" 31 #include "llvm/Support/COFF.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/FileSystem.h" 34 #include "llvm/Support/Format.h" 35 #include "llvm/Support/ManagedStatic.h" 36 #include "llvm/Support/MemoryBuffer.h" 37 #include "llvm/Support/PrettyStackTrace.h" 38 #include "llvm/Support/Program.h" 39 #include "llvm/Support/Signals.h" 40 #include "llvm/Support/TargetSelect.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include <algorithm> 43 #include <cctype> 44 #include <cerrno> 45 #include <cstring> 46 #include <system_error> 47 #include <vector> 48 49 using namespace llvm; 50 using namespace object; 51 52 namespace { 53 enum OutputFormatTy { bsd, sysv, posix, darwin }; 54 cl::opt<OutputFormatTy> OutputFormat( 55 "format", cl::desc("Specify output format"), 56 cl::values(clEnumVal(bsd, "BSD format"), clEnumVal(sysv, "System V format"), 57 clEnumVal(posix, "POSIX.2 format"), 58 clEnumVal(darwin, "Darwin -m format"), clEnumValEnd), 59 cl::init(bsd)); 60 cl::alias OutputFormat2("f", cl::desc("Alias for --format"), 61 cl::aliasopt(OutputFormat)); 62 63 cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<input files>"), 64 cl::ZeroOrMore); 65 66 cl::opt<bool> UndefinedOnly("undefined-only", 67 cl::desc("Show only undefined symbols")); 68 cl::alias UndefinedOnly2("u", cl::desc("Alias for --undefined-only"), 69 cl::aliasopt(UndefinedOnly), cl::Grouping); 70 71 cl::opt<bool> DynamicSyms("dynamic", 72 cl::desc("Display the dynamic symbols instead " 73 "of normal symbols.")); 74 cl::alias DynamicSyms2("D", cl::desc("Alias for --dynamic"), 75 cl::aliasopt(DynamicSyms), cl::Grouping); 76 77 cl::opt<bool> DefinedOnly("defined-only", 78 cl::desc("Show only defined symbols")); 79 cl::alias DefinedOnly2("U", cl::desc("Alias for --defined-only"), 80 cl::aliasopt(DefinedOnly), cl::Grouping); 81 82 cl::opt<bool> ExternalOnly("extern-only", 83 cl::desc("Show only external symbols")); 84 cl::alias ExternalOnly2("g", cl::desc("Alias for --extern-only"), 85 cl::aliasopt(ExternalOnly), cl::Grouping); 86 87 cl::opt<bool> BSDFormat("B", cl::desc("Alias for --format=bsd"), 88 cl::Grouping); 89 cl::opt<bool> POSIXFormat("P", cl::desc("Alias for --format=posix"), 90 cl::Grouping); 91 cl::opt<bool> DarwinFormat("m", cl::desc("Alias for --format=darwin"), 92 cl::Grouping); 93 94 static cl::list<std::string> 95 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"), 96 cl::ZeroOrMore); 97 bool ArchAll = false; 98 99 cl::opt<bool> PrintFileName( 100 "print-file-name", 101 cl::desc("Precede each symbol with the object file it came from")); 102 103 cl::alias PrintFileNameA("A", cl::desc("Alias for --print-file-name"), 104 cl::aliasopt(PrintFileName), cl::Grouping); 105 cl::alias PrintFileNameo("o", cl::desc("Alias for --print-file-name"), 106 cl::aliasopt(PrintFileName), cl::Grouping); 107 108 cl::opt<bool> DebugSyms("debug-syms", 109 cl::desc("Show all symbols, even debugger only")); 110 cl::alias DebugSymsa("a", cl::desc("Alias for --debug-syms"), 111 cl::aliasopt(DebugSyms), cl::Grouping); 112 113 cl::opt<bool> NumericSort("numeric-sort", cl::desc("Sort symbols by address")); 114 cl::alias NumericSortn("n", cl::desc("Alias for --numeric-sort"), 115 cl::aliasopt(NumericSort), cl::Grouping); 116 cl::alias NumericSortv("v", cl::desc("Alias for --numeric-sort"), 117 cl::aliasopt(NumericSort), cl::Grouping); 118 119 cl::opt<bool> NoSort("no-sort", cl::desc("Show symbols in order encountered")); 120 cl::alias NoSortp("p", cl::desc("Alias for --no-sort"), cl::aliasopt(NoSort), 121 cl::Grouping); 122 123 cl::opt<bool> ReverseSort("reverse-sort", cl::desc("Sort in reverse order")); 124 cl::alias ReverseSortr("r", cl::desc("Alias for --reverse-sort"), 125 cl::aliasopt(ReverseSort), cl::Grouping); 126 127 cl::opt<bool> PrintSize("print-size", 128 cl::desc("Show symbol size instead of address")); 129 cl::alias PrintSizeS("S", cl::desc("Alias for --print-size"), 130 cl::aliasopt(PrintSize), cl::Grouping); 131 132 cl::opt<bool> SizeSort("size-sort", cl::desc("Sort symbols by size")); 133 134 cl::opt<bool> WithoutAliases("without-aliases", cl::Hidden, 135 cl::desc("Exclude aliases from output")); 136 137 cl::opt<bool> ArchiveMap("print-armap", cl::desc("Print the archive map")); 138 cl::alias ArchiveMaps("M", cl::desc("Alias for --print-armap"), 139 cl::aliasopt(ArchiveMap), cl::Grouping); 140 141 enum Radix { d, o, x }; 142 cl::opt<Radix> 143 AddressRadix("radix", cl::desc("Radix (o/d/x) for printing symbol Values"), 144 cl::values(clEnumVal(d, "decimal"), clEnumVal(o, "octal"), 145 clEnumVal(x, "hexadecimal"), clEnumValEnd), 146 cl::init(x)); 147 cl::alias RadixAlias("t", cl::desc("Alias for --radix"), 148 cl::aliasopt(AddressRadix)); 149 150 cl::opt<bool> JustSymbolName("just-symbol-name", 151 cl::desc("Print just the symbol's name")); 152 cl::alias JustSymbolNames("j", cl::desc("Alias for --just-symbol-name"), 153 cl::aliasopt(JustSymbolName), cl::Grouping); 154 155 // FIXME: This option takes exactly two strings and should be allowed anywhere 156 // on the command line. Such that "llvm-nm -s __TEXT __text foo.o" would work. 157 // But that does not as the CommandLine Library does not have a way to make 158 // this work. For now the "-s __TEXT __text" has to be last on the command 159 // line. 160 cl::list<std::string> SegSect("s", cl::Positional, cl::ZeroOrMore, 161 cl::desc("Dump only symbols from this segment " 162 "and section name, Mach-O only")); 163 164 cl::opt<bool> FormatMachOasHex("x", cl::desc("Print symbol entry in hex, " 165 "Mach-O only"), cl::Grouping); 166 167 cl::opt<bool> NoLLVMBitcode("no-llvm-bc", 168 cl::desc("Disable LLVM bitcode reader")); 169 170 bool PrintAddress = true; 171 172 bool MultipleFiles = false; 173 174 bool HadError = false; 175 176 std::string ToolName; 177 } // anonymous namespace 178 179 static void error(Twine Message, Twine Path = Twine()) { 180 HadError = true; 181 errs() << ToolName << ": " << Path << ": " << Message << ".\n"; 182 } 183 184 static bool error(std::error_code EC, Twine Path = Twine()) { 185 if (EC) { 186 error(EC.message(), Path); 187 return true; 188 } 189 return false; 190 } 191 192 namespace { 193 struct NMSymbol { 194 uint64_t Address; 195 uint64_t Size; 196 char TypeChar; 197 StringRef Name; 198 BasicSymbolRef Sym; 199 }; 200 } // anonymous namespace 201 202 static bool compareSymbolAddress(const NMSymbol &A, const NMSymbol &B) { 203 bool ADefined = !(A.Sym.getFlags() & SymbolRef::SF_Undefined); 204 bool BDefined = !(B.Sym.getFlags() & SymbolRef::SF_Undefined); 205 return std::make_tuple(ADefined, A.Address, A.Name, A.Size) < 206 std::make_tuple(BDefined, B.Address, B.Name, B.Size); 207 } 208 209 static bool compareSymbolSize(const NMSymbol &A, const NMSymbol &B) { 210 return std::make_tuple(A.Size, A.Name, A.Address) < 211 std::make_tuple(B.Size, B.Name, B.Address); 212 } 213 214 static bool compareSymbolName(const NMSymbol &A, const NMSymbol &B) { 215 return std::make_tuple(A.Name, A.Size, A.Address) < 216 std::make_tuple(B.Name, B.Size, B.Address); 217 } 218 219 static char isSymbolList64Bit(SymbolicFile &Obj) { 220 if (isa<IRObjectFile>(Obj)) { 221 IRObjectFile *IRobj = dyn_cast<IRObjectFile>(&Obj); 222 Module &M = IRobj->getModule(); 223 if (M.getTargetTriple().empty()) 224 return false; 225 Triple T(M.getTargetTriple()); 226 return T.isArch64Bit(); 227 } 228 if (isa<COFFObjectFile>(Obj)) 229 return false; 230 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj)) 231 return MachO->is64Bit(); 232 return cast<ELFObjectFileBase>(Obj).getBytesInAddress() == 8; 233 } 234 235 static StringRef CurrentFilename; 236 typedef std::vector<NMSymbol> SymbolListT; 237 static SymbolListT SymbolList; 238 239 static char getSymbolNMTypeChar(IRObjectFile &Obj, basic_symbol_iterator I); 240 241 // darwinPrintSymbol() is used to print a symbol from a Mach-O file when the 242 // the OutputFormat is darwin or we are printing Mach-O symbols in hex. For 243 // the darwin format it produces the same output as darwin's nm(1) -m output 244 // and when printing Mach-O symbols in hex it produces the same output as 245 // darwin's nm(1) -x format. 246 static void darwinPrintSymbol(SymbolicFile &Obj, SymbolListT::iterator I, 247 char *SymbolAddrStr, const char *printBlanks, 248 const char *printDashes, const char *printFormat) { 249 MachO::mach_header H; 250 MachO::mach_header_64 H_64; 251 uint32_t Filetype = MachO::MH_OBJECT; 252 uint32_t Flags = 0; 253 uint8_t NType = 0; 254 uint8_t NSect = 0; 255 uint16_t NDesc = 0; 256 uint32_t NStrx = 0; 257 uint64_t NValue = 0; 258 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj); 259 if (Obj.isIR()) { 260 uint32_t SymFlags = I->Sym.getFlags(); 261 if (SymFlags & SymbolRef::SF_Global) 262 NType |= MachO::N_EXT; 263 if (SymFlags & SymbolRef::SF_Hidden) 264 NType |= MachO::N_PEXT; 265 if (SymFlags & SymbolRef::SF_Undefined) 266 NType |= MachO::N_EXT | MachO::N_UNDF; 267 else { 268 // Here we have a symbol definition. So to fake out a section name we 269 // use 1, 2 and 3 for section numbers. See below where they are used to 270 // print out fake section names. 271 NType |= MachO::N_SECT; 272 if (SymFlags & SymbolRef::SF_Const) 273 NSect = 3; 274 else { 275 IRObjectFile *IRobj = dyn_cast<IRObjectFile>(&Obj); 276 NSect = (getSymbolNMTypeChar(*IRobj, I->Sym) == 't') ? 1 : 2; 277 } 278 } 279 if (SymFlags & SymbolRef::SF_Weak) 280 NDesc |= MachO::N_WEAK_DEF; 281 } else { 282 DataRefImpl SymDRI = I->Sym.getRawDataRefImpl(); 283 if (MachO->is64Bit()) { 284 H_64 = MachO->MachOObjectFile::getHeader64(); 285 Filetype = H_64.filetype; 286 Flags = H_64.flags; 287 MachO::nlist_64 STE_64 = MachO->getSymbol64TableEntry(SymDRI); 288 NType = STE_64.n_type; 289 NSect = STE_64.n_sect; 290 NDesc = STE_64.n_desc; 291 NStrx = STE_64.n_strx; 292 NValue = STE_64.n_value; 293 } else { 294 H = MachO->MachOObjectFile::getHeader(); 295 Filetype = H.filetype; 296 Flags = H.flags; 297 MachO::nlist STE = MachO->getSymbolTableEntry(SymDRI); 298 NType = STE.n_type; 299 NSect = STE.n_sect; 300 NDesc = STE.n_desc; 301 NStrx = STE.n_strx; 302 NValue = STE.n_value; 303 } 304 } 305 306 // If we are printing Mach-O symbols in hex do that and return. 307 if (FormatMachOasHex) { 308 char Str[18] = ""; 309 format(printFormat, NValue).print(Str, sizeof(Str)); 310 outs() << Str << ' '; 311 format("%02x", NType).print(Str, sizeof(Str)); 312 outs() << Str << ' '; 313 format("%02x", NSect).print(Str, sizeof(Str)); 314 outs() << Str << ' '; 315 format("%04x", NDesc).print(Str, sizeof(Str)); 316 outs() << Str << ' '; 317 format("%08x", NStrx).print(Str, sizeof(Str)); 318 outs() << Str << ' '; 319 outs() << I->Name << "\n"; 320 return; 321 } 322 323 if (PrintAddress) { 324 if ((NType & MachO::N_TYPE) == MachO::N_INDR) 325 strcpy(SymbolAddrStr, printBlanks); 326 if (Obj.isIR() && (NType & MachO::N_TYPE) == MachO::N_TYPE) 327 strcpy(SymbolAddrStr, printDashes); 328 outs() << SymbolAddrStr << ' '; 329 } 330 331 switch (NType & MachO::N_TYPE) { 332 case MachO::N_UNDF: 333 if (NValue != 0) { 334 outs() << "(common) "; 335 if (MachO::GET_COMM_ALIGN(NDesc) != 0) 336 outs() << "(alignment 2^" << (int)MachO::GET_COMM_ALIGN(NDesc) << ") "; 337 } else { 338 if ((NType & MachO::N_TYPE) == MachO::N_PBUD) 339 outs() << "(prebound "; 340 else 341 outs() << "("; 342 if ((NDesc & MachO::REFERENCE_TYPE) == 343 MachO::REFERENCE_FLAG_UNDEFINED_LAZY) 344 outs() << "undefined [lazy bound]) "; 345 else if ((NDesc & MachO::REFERENCE_TYPE) == 346 MachO::REFERENCE_FLAG_UNDEFINED_LAZY) 347 outs() << "undefined [private lazy bound]) "; 348 else if ((NDesc & MachO::REFERENCE_TYPE) == 349 MachO::REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY) 350 outs() << "undefined [private]) "; 351 else 352 outs() << "undefined) "; 353 } 354 break; 355 case MachO::N_ABS: 356 outs() << "(absolute) "; 357 break; 358 case MachO::N_INDR: 359 outs() << "(indirect) "; 360 break; 361 case MachO::N_SECT: { 362 if (Obj.isIR()) { 363 // For llvm bitcode files print out a fake section name using the values 364 // use 1, 2 and 3 for section numbers as set above. 365 if (NSect == 1) 366 outs() << "(LTO,CODE) "; 367 else if (NSect == 2) 368 outs() << "(LTO,DATA) "; 369 else if (NSect == 3) 370 outs() << "(LTO,RODATA) "; 371 else 372 outs() << "(?,?) "; 373 break; 374 } 375 ErrorOr<section_iterator> SecOrErr = 376 MachO->getSymbolSection(I->Sym.getRawDataRefImpl()); 377 if (SecOrErr.getError()) { 378 outs() << "(?,?) "; 379 break; 380 } 381 section_iterator Sec = *SecOrErr; 382 DataRefImpl Ref = Sec->getRawDataRefImpl(); 383 StringRef SectionName; 384 MachO->getSectionName(Ref, SectionName); 385 StringRef SegmentName = MachO->getSectionFinalSegmentName(Ref); 386 outs() << "(" << SegmentName << "," << SectionName << ") "; 387 break; 388 } 389 default: 390 outs() << "(?) "; 391 break; 392 } 393 394 if (NType & MachO::N_EXT) { 395 if (NDesc & MachO::REFERENCED_DYNAMICALLY) 396 outs() << "[referenced dynamically] "; 397 if (NType & MachO::N_PEXT) { 398 if ((NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF) 399 outs() << "weak private external "; 400 else 401 outs() << "private external "; 402 } else { 403 if ((NDesc & MachO::N_WEAK_REF) == MachO::N_WEAK_REF || 404 (NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF) { 405 if ((NDesc & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF)) == 406 (MachO::N_WEAK_REF | MachO::N_WEAK_DEF)) 407 outs() << "weak external automatically hidden "; 408 else 409 outs() << "weak external "; 410 } else 411 outs() << "external "; 412 } 413 } else { 414 if (NType & MachO::N_PEXT) 415 outs() << "non-external (was a private external) "; 416 else 417 outs() << "non-external "; 418 } 419 420 if (Filetype == MachO::MH_OBJECT && 421 (NDesc & MachO::N_NO_DEAD_STRIP) == MachO::N_NO_DEAD_STRIP) 422 outs() << "[no dead strip] "; 423 424 if (Filetype == MachO::MH_OBJECT && 425 ((NType & MachO::N_TYPE) != MachO::N_UNDF) && 426 (NDesc & MachO::N_SYMBOL_RESOLVER) == MachO::N_SYMBOL_RESOLVER) 427 outs() << "[symbol resolver] "; 428 429 if (Filetype == MachO::MH_OBJECT && 430 ((NType & MachO::N_TYPE) != MachO::N_UNDF) && 431 (NDesc & MachO::N_ALT_ENTRY) == MachO::N_ALT_ENTRY) 432 outs() << "[alt entry] "; 433 434 if ((NDesc & MachO::N_ARM_THUMB_DEF) == MachO::N_ARM_THUMB_DEF) 435 outs() << "[Thumb] "; 436 437 if ((NType & MachO::N_TYPE) == MachO::N_INDR) { 438 outs() << I->Name << " (for "; 439 StringRef IndirectName; 440 if (!MachO || 441 MachO->getIndirectName(I->Sym.getRawDataRefImpl(), IndirectName)) 442 outs() << "?)"; 443 else 444 outs() << IndirectName << ")"; 445 } else 446 outs() << I->Name; 447 448 if ((Flags & MachO::MH_TWOLEVEL) == MachO::MH_TWOLEVEL && 449 (((NType & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0) || 450 (NType & MachO::N_TYPE) == MachO::N_PBUD)) { 451 uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(NDesc); 452 if (LibraryOrdinal != 0) { 453 if (LibraryOrdinal == MachO::EXECUTABLE_ORDINAL) 454 outs() << " (from executable)"; 455 else if (LibraryOrdinal == MachO::DYNAMIC_LOOKUP_ORDINAL) 456 outs() << " (dynamically looked up)"; 457 else { 458 StringRef LibraryName; 459 if (!MachO || 460 MachO->getLibraryShortNameByIndex(LibraryOrdinal - 1, LibraryName)) 461 outs() << " (from bad library ordinal " << LibraryOrdinal << ")"; 462 else 463 outs() << " (from " << LibraryName << ")"; 464 } 465 } 466 } 467 468 outs() << "\n"; 469 } 470 471 // Table that maps Darwin's Mach-O stab constants to strings to allow printing. 472 struct DarwinStabName { 473 uint8_t NType; 474 const char *Name; 475 }; 476 static const struct DarwinStabName DarwinStabNames[] = { 477 {MachO::N_GSYM, "GSYM"}, 478 {MachO::N_FNAME, "FNAME"}, 479 {MachO::N_FUN, "FUN"}, 480 {MachO::N_STSYM, "STSYM"}, 481 {MachO::N_LCSYM, "LCSYM"}, 482 {MachO::N_BNSYM, "BNSYM"}, 483 {MachO::N_PC, "PC"}, 484 {MachO::N_AST, "AST"}, 485 {MachO::N_OPT, "OPT"}, 486 {MachO::N_RSYM, "RSYM"}, 487 {MachO::N_SLINE, "SLINE"}, 488 {MachO::N_ENSYM, "ENSYM"}, 489 {MachO::N_SSYM, "SSYM"}, 490 {MachO::N_SO, "SO"}, 491 {MachO::N_OSO, "OSO"}, 492 {MachO::N_LSYM, "LSYM"}, 493 {MachO::N_BINCL, "BINCL"}, 494 {MachO::N_SOL, "SOL"}, 495 {MachO::N_PARAMS, "PARAM"}, 496 {MachO::N_VERSION, "VERS"}, 497 {MachO::N_OLEVEL, "OLEV"}, 498 {MachO::N_PSYM, "PSYM"}, 499 {MachO::N_EINCL, "EINCL"}, 500 {MachO::N_ENTRY, "ENTRY"}, 501 {MachO::N_LBRAC, "LBRAC"}, 502 {MachO::N_EXCL, "EXCL"}, 503 {MachO::N_RBRAC, "RBRAC"}, 504 {MachO::N_BCOMM, "BCOMM"}, 505 {MachO::N_ECOMM, "ECOMM"}, 506 {MachO::N_ECOML, "ECOML"}, 507 {MachO::N_LENG, "LENG"}, 508 {0, nullptr}}; 509 510 static const char *getDarwinStabString(uint8_t NType) { 511 for (unsigned i = 0; DarwinStabNames[i].Name; i++) { 512 if (DarwinStabNames[i].NType == NType) 513 return DarwinStabNames[i].Name; 514 } 515 return nullptr; 516 } 517 518 // darwinPrintStab() prints the n_sect, n_desc along with a symbolic name of 519 // a stab n_type value in a Mach-O file. 520 static void darwinPrintStab(MachOObjectFile *MachO, SymbolListT::iterator I) { 521 MachO::nlist_64 STE_64; 522 MachO::nlist STE; 523 uint8_t NType; 524 uint8_t NSect; 525 uint16_t NDesc; 526 DataRefImpl SymDRI = I->Sym.getRawDataRefImpl(); 527 if (MachO->is64Bit()) { 528 STE_64 = MachO->getSymbol64TableEntry(SymDRI); 529 NType = STE_64.n_type; 530 NSect = STE_64.n_sect; 531 NDesc = STE_64.n_desc; 532 } else { 533 STE = MachO->getSymbolTableEntry(SymDRI); 534 NType = STE.n_type; 535 NSect = STE.n_sect; 536 NDesc = STE.n_desc; 537 } 538 539 char Str[18] = ""; 540 format("%02x", NSect).print(Str, sizeof(Str)); 541 outs() << ' ' << Str << ' '; 542 format("%04x", NDesc).print(Str, sizeof(Str)); 543 outs() << Str << ' '; 544 if (const char *stabString = getDarwinStabString(NType)) 545 format("%5.5s", stabString).print(Str, sizeof(Str)); 546 else 547 format(" %02x", NType).print(Str, sizeof(Str)); 548 outs() << Str; 549 } 550 551 static void sortAndPrintSymbolList(SymbolicFile &Obj, bool printName, 552 std::string ArchiveName, 553 std::string ArchitectureName) { 554 if (!NoSort) { 555 std::function<bool(const NMSymbol &, const NMSymbol &)> Cmp; 556 if (NumericSort) 557 Cmp = compareSymbolAddress; 558 else if (SizeSort) 559 Cmp = compareSymbolSize; 560 else 561 Cmp = compareSymbolName; 562 563 if (ReverseSort) 564 Cmp = [=](const NMSymbol &A, const NMSymbol &B) { return Cmp(B, A); }; 565 std::sort(SymbolList.begin(), SymbolList.end(), Cmp); 566 } 567 568 if (!PrintFileName) { 569 if (OutputFormat == posix && MultipleFiles && printName) { 570 outs() << '\n' << CurrentFilename << ":\n"; 571 } else if (OutputFormat == bsd && MultipleFiles && printName) { 572 outs() << "\n" << CurrentFilename << ":\n"; 573 } else if (OutputFormat == sysv) { 574 outs() << "\n\nSymbols from " << CurrentFilename << ":\n\n" 575 << "Name Value Class Type" 576 << " Size Line Section\n"; 577 } 578 } 579 580 const char *printBlanks, *printDashes, *printFormat; 581 if (isSymbolList64Bit(Obj)) { 582 printBlanks = " "; 583 printDashes = "----------------"; 584 switch (AddressRadix) { 585 case Radix::o: 586 printFormat = "%016" PRIo64; 587 break; 588 case Radix::x: 589 printFormat = "%016" PRIx64; 590 break; 591 default: 592 printFormat = "%016" PRId64; 593 } 594 } else { 595 printBlanks = " "; 596 printDashes = "--------"; 597 switch (AddressRadix) { 598 case Radix::o: 599 printFormat = "%08" PRIo64; 600 break; 601 case Radix::x: 602 printFormat = "%08" PRIx64; 603 break; 604 default: 605 printFormat = "%08" PRId64; 606 } 607 } 608 609 for (SymbolListT::iterator I = SymbolList.begin(), E = SymbolList.end(); 610 I != E; ++I) { 611 uint32_t SymFlags = I->Sym.getFlags(); 612 bool Undefined = SymFlags & SymbolRef::SF_Undefined; 613 bool Global = SymFlags & SymbolRef::SF_Global; 614 if ((!Undefined && UndefinedOnly) || (Undefined && DefinedOnly) || 615 (!Global && ExternalOnly) || (SizeSort && !PrintAddress)) 616 continue; 617 if (PrintFileName) { 618 if (!ArchitectureName.empty()) 619 outs() << "(for architecture " << ArchitectureName << "):"; 620 if (!ArchiveName.empty()) 621 outs() << ArchiveName << ":"; 622 outs() << CurrentFilename << ": "; 623 } 624 if ((JustSymbolName || (UndefinedOnly && isa<MachOObjectFile>(Obj) && 625 OutputFormat != darwin)) && OutputFormat != posix) { 626 outs() << I->Name << "\n"; 627 continue; 628 } 629 630 char SymbolAddrStr[18] = ""; 631 char SymbolSizeStr[18] = ""; 632 633 if (OutputFormat == sysv || I->TypeChar == 'U') 634 strcpy(SymbolAddrStr, printBlanks); 635 if (OutputFormat == sysv) 636 strcpy(SymbolSizeStr, printBlanks); 637 638 if (I->TypeChar != 'U') { 639 if (Obj.isIR()) 640 strcpy(SymbolAddrStr, printDashes); 641 else 642 format(printFormat, I->Address) 643 .print(SymbolAddrStr, sizeof(SymbolAddrStr)); 644 } 645 format(printFormat, I->Size).print(SymbolSizeStr, sizeof(SymbolSizeStr)); 646 647 // If OutputFormat is darwin or we are printing Mach-O symbols in hex and 648 // we have a MachOObjectFile, call darwinPrintSymbol to print as darwin's 649 // nm(1) -m output or hex, else if OutputFormat is darwin or we are 650 // printing Mach-O symbols in hex and not a Mach-O object fall back to 651 // OutputFormat bsd (see below). 652 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj); 653 if ((OutputFormat == darwin || FormatMachOasHex) && (MachO || Obj.isIR())) { 654 darwinPrintSymbol(Obj, I, SymbolAddrStr, printBlanks, printDashes, 655 printFormat); 656 } else if (OutputFormat == posix) { 657 outs() << I->Name << " " << I->TypeChar << " "; 658 if (MachO) 659 outs() << I->Address << " " << "0" /* SymbolSizeStr */ << "\n"; 660 else 661 outs() << SymbolAddrStr << " " << SymbolSizeStr << "\n"; 662 } else if (OutputFormat == bsd || (OutputFormat == darwin && !MachO)) { 663 if (PrintAddress) 664 outs() << SymbolAddrStr << ' '; 665 if (PrintSize) { 666 outs() << SymbolSizeStr; 667 outs() << ' '; 668 } 669 outs() << I->TypeChar; 670 if (I->TypeChar == '-' && MachO) 671 darwinPrintStab(MachO, I); 672 outs() << " " << I->Name << "\n"; 673 } else if (OutputFormat == sysv) { 674 std::string PaddedName(I->Name); 675 while (PaddedName.length() < 20) 676 PaddedName += " "; 677 outs() << PaddedName << "|" << SymbolAddrStr << "| " << I->TypeChar 678 << " | |" << SymbolSizeStr << "| |\n"; 679 } 680 } 681 682 SymbolList.clear(); 683 } 684 685 static char getSymbolNMTypeChar(ELFObjectFileBase &Obj, 686 basic_symbol_iterator I) { 687 // OK, this is ELF 688 elf_symbol_iterator SymI(I); 689 690 ErrorOr<elf_section_iterator> SecIOrErr = SymI->getSection(); 691 if (error(SecIOrErr.getError())) 692 return '?'; 693 694 elf_section_iterator SecI = *SecIOrErr; 695 if (SecI != Obj.section_end()) { 696 switch (SecI->getType()) { 697 case ELF::SHT_PROGBITS: 698 case ELF::SHT_DYNAMIC: 699 switch (SecI->getFlags()) { 700 case (ELF::SHF_ALLOC | ELF::SHF_EXECINSTR): 701 return 't'; 702 case (ELF::SHF_TLS | ELF::SHF_ALLOC | ELF::SHF_WRITE): 703 case (ELF::SHF_ALLOC | ELF::SHF_WRITE): 704 return 'd'; 705 case ELF::SHF_ALLOC: 706 case (ELF::SHF_ALLOC | ELF::SHF_MERGE): 707 case (ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS): 708 return 'r'; 709 } 710 break; 711 case ELF::SHT_NOBITS: 712 return 'b'; 713 } 714 } 715 716 if (SymI->getELFType() == ELF::STT_SECTION) { 717 ErrorOr<StringRef> Name = SymI->getName(); 718 if (error(Name.getError())) 719 return '?'; 720 return StringSwitch<char>(*Name) 721 .StartsWith(".debug", 'N') 722 .StartsWith(".note", 'n') 723 .Default('?'); 724 } 725 726 return 'n'; 727 } 728 729 static char getSymbolNMTypeChar(COFFObjectFile &Obj, symbol_iterator I) { 730 COFFSymbolRef Symb = Obj.getCOFFSymbol(*I); 731 // OK, this is COFF. 732 symbol_iterator SymI(I); 733 734 ErrorOr<StringRef> Name = SymI->getName(); 735 if (error(Name.getError())) 736 return '?'; 737 738 char Ret = StringSwitch<char>(*Name) 739 .StartsWith(".debug", 'N') 740 .StartsWith(".sxdata", 'N') 741 .Default('?'); 742 743 if (Ret != '?') 744 return Ret; 745 746 uint32_t Characteristics = 0; 747 if (!COFF::isReservedSectionNumber(Symb.getSectionNumber())) { 748 ErrorOr<section_iterator> SecIOrErr = SymI->getSection(); 749 if (error(SecIOrErr.getError())) 750 return '?'; 751 section_iterator SecI = *SecIOrErr; 752 const coff_section *Section = Obj.getCOFFSection(*SecI); 753 Characteristics = Section->Characteristics; 754 } 755 756 switch (Symb.getSectionNumber()) { 757 case COFF::IMAGE_SYM_DEBUG: 758 return 'n'; 759 default: 760 // Check section type. 761 if (Characteristics & COFF::IMAGE_SCN_CNT_CODE) 762 return 't'; 763 if (Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA) 764 return Characteristics & COFF::IMAGE_SCN_MEM_WRITE ? 'd' : 'r'; 765 if (Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) 766 return 'b'; 767 if (Characteristics & COFF::IMAGE_SCN_LNK_INFO) 768 return 'i'; 769 // Check for section symbol. 770 if (Symb.isSectionDefinition()) 771 return 's'; 772 } 773 774 return '?'; 775 } 776 777 static char getSymbolNMTypeChar(MachOObjectFile &Obj, basic_symbol_iterator I) { 778 DataRefImpl Symb = I->getRawDataRefImpl(); 779 uint8_t NType = Obj.is64Bit() ? Obj.getSymbol64TableEntry(Symb).n_type 780 : Obj.getSymbolTableEntry(Symb).n_type; 781 782 if (NType & MachO::N_STAB) 783 return '-'; 784 785 switch (NType & MachO::N_TYPE) { 786 case MachO::N_ABS: 787 return 's'; 788 case MachO::N_INDR: 789 return 'i'; 790 case MachO::N_SECT: { 791 ErrorOr<section_iterator> SecOrErr = Obj.getSymbolSection(Symb); 792 if (SecOrErr.getError()) 793 return 's'; 794 section_iterator Sec = *SecOrErr; 795 DataRefImpl Ref = Sec->getRawDataRefImpl(); 796 StringRef SectionName; 797 Obj.getSectionName(Ref, SectionName); 798 StringRef SegmentName = Obj.getSectionFinalSegmentName(Ref); 799 if (SegmentName == "__TEXT" && SectionName == "__text") 800 return 't'; 801 if (SegmentName == "__DATA" && SectionName == "__data") 802 return 'd'; 803 if (SegmentName == "__DATA" && SectionName == "__bss") 804 return 'b'; 805 return 's'; 806 } 807 } 808 809 return '?'; 810 } 811 812 static char getSymbolNMTypeChar(const GlobalValue &GV) { 813 // FIXME: should we print 'b'? At the IR level we cannot be sure if this 814 // will be in bss or not, but we could approximate. 815 return GV.getValueType()->isFunctionTy() ? 't' : 'd'; 816 } 817 818 static char getSymbolNMTypeChar(IRObjectFile &Obj, basic_symbol_iterator I) { 819 const GlobalValue *GV = Obj.getSymbolGV(I->getRawDataRefImpl()); 820 return !GV ? 't' : getSymbolNMTypeChar(*GV); 821 } 822 823 static bool isObject(SymbolicFile &Obj, basic_symbol_iterator I) { 824 return !dyn_cast<ELFObjectFileBase>(&Obj) 825 ? false 826 : elf_symbol_iterator(I)->getELFType() == ELF::STT_OBJECT; 827 } 828 829 static char getNMTypeChar(SymbolicFile &Obj, basic_symbol_iterator I) { 830 uint32_t Symflags = I->getFlags(); 831 if ((Symflags & object::SymbolRef::SF_Weak) && !isa<MachOObjectFile>(Obj)) { 832 char Ret = isObject(Obj, I) ? 'v' : 'w'; 833 return (!(Symflags & object::SymbolRef::SF_Undefined)) ? toupper(Ret) : Ret; 834 } 835 836 if (Symflags & object::SymbolRef::SF_Undefined) 837 return 'U'; 838 839 if (Symflags & object::SymbolRef::SF_Common) 840 return 'C'; 841 842 char Ret = '?'; 843 if (Symflags & object::SymbolRef::SF_Absolute) 844 Ret = 'a'; 845 else if (IRObjectFile *IR = dyn_cast<IRObjectFile>(&Obj)) { 846 Ret = getSymbolNMTypeChar(*IR, I); 847 Triple Host(sys::getDefaultTargetTriple()); 848 if (Ret == 'd' && Host.isOSDarwin() && Symflags & SymbolRef::SF_Const) 849 Ret = 's'; 850 } 851 else if (COFFObjectFile *COFF = dyn_cast<COFFObjectFile>(&Obj)) 852 Ret = getSymbolNMTypeChar(*COFF, I); 853 else if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj)) 854 Ret = getSymbolNMTypeChar(*MachO, I); 855 else 856 Ret = getSymbolNMTypeChar(cast<ELFObjectFileBase>(Obj), I); 857 858 if (Symflags & object::SymbolRef::SF_Global) 859 Ret = toupper(Ret); 860 861 return Ret; 862 } 863 864 // getNsectForSegSect() is used to implement the Mach-O "-s segname sectname" 865 // option to dump only those symbols from that section in a Mach-O file. 866 // It is called once for each Mach-O file from dumpSymbolNamesFromObject() 867 // to get the section number for that named section from the command line 868 // arguments. It returns the section number for that section in the Mach-O 869 // file or zero it is not present. 870 static unsigned getNsectForSegSect(MachOObjectFile *Obj) { 871 unsigned Nsect = 1; 872 for (auto &S : Obj->sections()) { 873 DataRefImpl Ref = S.getRawDataRefImpl(); 874 StringRef SectionName; 875 Obj->getSectionName(Ref, SectionName); 876 StringRef SegmentName = Obj->getSectionFinalSegmentName(Ref); 877 if (SegmentName == SegSect[0] && SectionName == SegSect[1]) 878 return Nsect; 879 Nsect++; 880 } 881 return 0; 882 } 883 884 // getNsectInMachO() is used to implement the Mach-O "-s segname sectname" 885 // option to dump only those symbols from that section in a Mach-O file. 886 // It is called once for each symbol in a Mach-O file from 887 // dumpSymbolNamesFromObject() and returns the section number for that symbol 888 // if it is in a section, else it returns 0. 889 static unsigned getNsectInMachO(MachOObjectFile &Obj, BasicSymbolRef Sym) { 890 DataRefImpl Symb = Sym.getRawDataRefImpl(); 891 if (Obj.is64Bit()) { 892 MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb); 893 return (STE.n_type & MachO::N_TYPE) == MachO::N_SECT ? STE.n_sect : 0; 894 } 895 MachO::nlist STE = Obj.getSymbolTableEntry(Symb); 896 return (STE.n_type & MachO::N_TYPE) == MachO::N_SECT ? STE.n_sect : 0; 897 } 898 899 static void dumpSymbolNamesFromObject(SymbolicFile &Obj, bool printName, 900 std::string ArchiveName = std::string(), 901 std::string ArchitectureName = 902 std::string()) { 903 auto Symbols = Obj.symbols(); 904 if (DynamicSyms) { 905 const auto *E = dyn_cast<ELFObjectFileBase>(&Obj); 906 if (!E) { 907 error("File format has no dynamic symbol table", Obj.getFileName()); 908 return; 909 } 910 auto DynSymbols = E->getDynamicSymbolIterators(); 911 Symbols = 912 make_range<basic_symbol_iterator>(DynSymbols.begin(), DynSymbols.end()); 913 } 914 std::string NameBuffer; 915 raw_string_ostream OS(NameBuffer); 916 // If a "-s segname sectname" option was specified and this is a Mach-O 917 // file get the section number for that section in this object file. 918 unsigned int Nsect = 0; 919 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj); 920 if (SegSect.size() != 0 && MachO) { 921 Nsect = getNsectForSegSect(MachO); 922 // If this section is not in the object file no symbols are printed. 923 if (Nsect == 0) 924 return; 925 } 926 for (BasicSymbolRef Sym : Symbols) { 927 uint32_t SymFlags = Sym.getFlags(); 928 if (!DebugSyms && (SymFlags & SymbolRef::SF_FormatSpecific)) 929 continue; 930 if (WithoutAliases) { 931 if (IRObjectFile *IR = dyn_cast<IRObjectFile>(&Obj)) { 932 const GlobalValue *GV = IR->getSymbolGV(Sym.getRawDataRefImpl()); 933 if (GV && isa<GlobalAlias>(GV)) 934 continue; 935 } 936 } 937 // If a "-s segname sectname" option was specified and this is a Mach-O 938 // file and this section appears in this file, Nsect will be non-zero then 939 // see if this symbol is a symbol from that section and if not skip it. 940 if (Nsect && Nsect != getNsectInMachO(*MachO, Sym)) 941 continue; 942 NMSymbol S; 943 S.Size = 0; 944 S.Address = 0; 945 if (PrintSize) { 946 if (isa<ELFObjectFileBase>(&Obj)) 947 S.Size = ELFSymbolRef(Sym).getSize(); 948 } 949 if (PrintAddress && isa<ObjectFile>(Obj)) { 950 SymbolRef SymRef(Sym); 951 ErrorOr<uint64_t> AddressOrErr = SymRef.getAddress(); 952 if (error(AddressOrErr.getError())) 953 break; 954 S.Address = *AddressOrErr; 955 } 956 S.TypeChar = getNMTypeChar(Obj, Sym); 957 std::error_code EC = Sym.printName(OS); 958 if (EC && MachO) 959 OS << "bad string index"; 960 else 961 error(EC); 962 OS << '\0'; 963 S.Sym = Sym; 964 SymbolList.push_back(S); 965 } 966 967 OS.flush(); 968 const char *P = NameBuffer.c_str(); 969 for (unsigned I = 0; I < SymbolList.size(); ++I) { 970 SymbolList[I].Name = P; 971 P += strlen(P) + 1; 972 } 973 974 CurrentFilename = Obj.getFileName(); 975 sortAndPrintSymbolList(Obj, printName, ArchiveName, ArchitectureName); 976 } 977 978 // checkMachOAndArchFlags() checks to see if the SymbolicFile is a Mach-O file 979 // and if it is and there is a list of architecture flags is specified then 980 // check to make sure this Mach-O file is one of those architectures or all 981 // architectures was specificed. If not then an error is generated and this 982 // routine returns false. Else it returns true. 983 static bool checkMachOAndArchFlags(SymbolicFile *O, std::string &Filename) { 984 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O); 985 986 if (!MachO || ArchAll || ArchFlags.size() == 0) 987 return true; 988 989 MachO::mach_header H; 990 MachO::mach_header_64 H_64; 991 Triple T; 992 if (MachO->is64Bit()) { 993 H_64 = MachO->MachOObjectFile::getHeader64(); 994 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype); 995 } else { 996 H = MachO->MachOObjectFile::getHeader(); 997 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype); 998 } 999 if (std::none_of( 1000 ArchFlags.begin(), ArchFlags.end(), 1001 [&](const std::string &Name) { return Name == T.getArchName(); })) { 1002 error("No architecture specified", Filename); 1003 return false; 1004 } 1005 return true; 1006 } 1007 1008 static void dumpSymbolNamesFromFile(std::string &Filename) { 1009 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr = 1010 MemoryBuffer::getFileOrSTDIN(Filename); 1011 if (error(BufferOrErr.getError(), Filename)) 1012 return; 1013 1014 LLVMContext &Context = getGlobalContext(); 1015 ErrorOr<std::unique_ptr<Binary>> BinaryOrErr = createBinary( 1016 BufferOrErr.get()->getMemBufferRef(), NoLLVMBitcode ? nullptr : &Context); 1017 if (error(BinaryOrErr.getError(), Filename)) 1018 return; 1019 Binary &Bin = *BinaryOrErr.get(); 1020 1021 if (Archive *A = dyn_cast<Archive>(&Bin)) { 1022 if (ArchiveMap) { 1023 Archive::symbol_iterator I = A->symbol_begin(); 1024 Archive::symbol_iterator E = A->symbol_end(); 1025 if (I != E) { 1026 outs() << "Archive map\n"; 1027 for (; I != E; ++I) { 1028 ErrorOr<Archive::Child> C = I->getMember(); 1029 if (error(C.getError())) 1030 return; 1031 ErrorOr<StringRef> FileNameOrErr = C->getName(); 1032 if (error(FileNameOrErr.getError())) 1033 return; 1034 StringRef SymName = I->getName(); 1035 outs() << SymName << " in " << FileNameOrErr.get() << "\n"; 1036 } 1037 outs() << "\n"; 1038 } 1039 } 1040 1041 for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); 1042 I != E; ++I) { 1043 if (error(I->getError())) 1044 return; 1045 auto &C = I->get(); 1046 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(&Context); 1047 if (ChildOrErr.getError()) 1048 continue; 1049 if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) { 1050 if (!checkMachOAndArchFlags(O, Filename)) 1051 return; 1052 if (!PrintFileName) { 1053 outs() << "\n"; 1054 if (isa<MachOObjectFile>(O)) { 1055 outs() << Filename << "(" << O->getFileName() << ")"; 1056 } else 1057 outs() << O->getFileName(); 1058 outs() << ":\n"; 1059 } 1060 dumpSymbolNamesFromObject(*O, false, Filename); 1061 } 1062 } 1063 return; 1064 } 1065 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) { 1066 // If we have a list of architecture flags specified dump only those. 1067 if (!ArchAll && ArchFlags.size() != 0) { 1068 // Look for a slice in the universal binary that matches each ArchFlag. 1069 bool ArchFound; 1070 for (unsigned i = 0; i < ArchFlags.size(); ++i) { 1071 ArchFound = false; 1072 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), 1073 E = UB->end_objects(); 1074 I != E; ++I) { 1075 if (ArchFlags[i] == I->getArchTypeName()) { 1076 ArchFound = true; 1077 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = 1078 I->getAsObjectFile(); 1079 std::string ArchiveName; 1080 std::string ArchitectureName; 1081 ArchiveName.clear(); 1082 ArchitectureName.clear(); 1083 if (ObjOrErr) { 1084 ObjectFile &Obj = *ObjOrErr.get(); 1085 if (ArchFlags.size() > 1) { 1086 if (PrintFileName) 1087 ArchitectureName = I->getArchTypeName(); 1088 else 1089 outs() << "\n" << Obj.getFileName() << " (for architecture " 1090 << I->getArchTypeName() << ")" 1091 << ":\n"; 1092 } 1093 dumpSymbolNamesFromObject(Obj, false, ArchiveName, 1094 ArchitectureName); 1095 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = 1096 I->getAsArchive()) { 1097 std::unique_ptr<Archive> &A = *AOrErr; 1098 for (Archive::child_iterator AI = A->child_begin(), 1099 AE = A->child_end(); 1100 AI != AE; ++AI) { 1101 if (error(AI->getError())) 1102 return; 1103 auto &C = AI->get(); 1104 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = 1105 C.getAsBinary(&Context); 1106 if (ChildOrErr.getError()) 1107 continue; 1108 if (SymbolicFile *O = 1109 dyn_cast<SymbolicFile>(&*ChildOrErr.get())) { 1110 if (PrintFileName) { 1111 ArchiveName = A->getFileName(); 1112 if (ArchFlags.size() > 1) 1113 ArchitectureName = I->getArchTypeName(); 1114 } else { 1115 outs() << "\n" << A->getFileName(); 1116 outs() << "(" << O->getFileName() << ")"; 1117 if (ArchFlags.size() > 1) { 1118 outs() << " (for architecture " << I->getArchTypeName() 1119 << ")"; 1120 } 1121 outs() << ":\n"; 1122 } 1123 dumpSymbolNamesFromObject(*O, false, ArchiveName, 1124 ArchitectureName); 1125 } 1126 } 1127 } 1128 } 1129 } 1130 if (!ArchFound) { 1131 error(ArchFlags[i], 1132 "file: " + Filename + " does not contain architecture"); 1133 return; 1134 } 1135 } 1136 return; 1137 } 1138 // No architecture flags were specified so if this contains a slice that 1139 // matches the host architecture dump only that. 1140 if (!ArchAll) { 1141 StringRef HostArchName = MachOObjectFile::getHostArch().getArchName(); 1142 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), 1143 E = UB->end_objects(); 1144 I != E; ++I) { 1145 if (HostArchName == I->getArchTypeName()) { 1146 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile(); 1147 std::string ArchiveName; 1148 ArchiveName.clear(); 1149 if (ObjOrErr) { 1150 ObjectFile &Obj = *ObjOrErr.get(); 1151 dumpSymbolNamesFromObject(Obj, false); 1152 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = 1153 I->getAsArchive()) { 1154 std::unique_ptr<Archive> &A = *AOrErr; 1155 for (Archive::child_iterator AI = A->child_begin(), 1156 AE = A->child_end(); 1157 AI != AE; ++AI) { 1158 if (error(AI->getError())) 1159 return; 1160 auto &C = AI->get(); 1161 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = 1162 C.getAsBinary(&Context); 1163 if (ChildOrErr.getError()) 1164 continue; 1165 if (SymbolicFile *O = 1166 dyn_cast<SymbolicFile>(&*ChildOrErr.get())) { 1167 if (PrintFileName) 1168 ArchiveName = A->getFileName(); 1169 else 1170 outs() << "\n" << A->getFileName() << "(" << O->getFileName() 1171 << ")" 1172 << ":\n"; 1173 dumpSymbolNamesFromObject(*O, false, ArchiveName); 1174 } 1175 } 1176 } 1177 return; 1178 } 1179 } 1180 } 1181 // Either all architectures have been specified or none have been specified 1182 // and this does not contain the host architecture so dump all the slices. 1183 bool moreThanOneArch = UB->getNumberOfObjects() > 1; 1184 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), 1185 E = UB->end_objects(); 1186 I != E; ++I) { 1187 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile(); 1188 std::string ArchiveName; 1189 std::string ArchitectureName; 1190 ArchiveName.clear(); 1191 ArchitectureName.clear(); 1192 if (ObjOrErr) { 1193 ObjectFile &Obj = *ObjOrErr.get(); 1194 if (PrintFileName) { 1195 if (isa<MachOObjectFile>(Obj) && moreThanOneArch) 1196 ArchitectureName = I->getArchTypeName(); 1197 } else { 1198 if (moreThanOneArch) 1199 outs() << "\n"; 1200 outs() << Obj.getFileName(); 1201 if (isa<MachOObjectFile>(Obj) && moreThanOneArch) 1202 outs() << " (for architecture " << I->getArchTypeName() << ")"; 1203 outs() << ":\n"; 1204 } 1205 dumpSymbolNamesFromObject(Obj, false, ArchiveName, ArchitectureName); 1206 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) { 1207 std::unique_ptr<Archive> &A = *AOrErr; 1208 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end(); 1209 AI != AE; ++AI) { 1210 if (error(AI->getError())) 1211 return; 1212 auto &C = AI->get(); 1213 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(&Context); 1214 if (ChildOrErr.getError()) 1215 continue; 1216 if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) { 1217 if (PrintFileName) { 1218 ArchiveName = A->getFileName(); 1219 if (isa<MachOObjectFile>(O) && moreThanOneArch) 1220 ArchitectureName = I->getArchTypeName(); 1221 } else { 1222 outs() << "\n" << A->getFileName(); 1223 if (isa<MachOObjectFile>(O)) { 1224 outs() << "(" << O->getFileName() << ")"; 1225 if (moreThanOneArch) 1226 outs() << " (for architecture " << I->getArchTypeName() 1227 << ")"; 1228 } else 1229 outs() << ":" << O->getFileName(); 1230 outs() << ":\n"; 1231 } 1232 dumpSymbolNamesFromObject(*O, false, ArchiveName, ArchitectureName); 1233 } 1234 } 1235 } 1236 } 1237 return; 1238 } 1239 if (SymbolicFile *O = dyn_cast<SymbolicFile>(&Bin)) { 1240 if (!checkMachOAndArchFlags(O, Filename)) 1241 return; 1242 dumpSymbolNamesFromObject(*O, true); 1243 } 1244 } 1245 1246 int main(int argc, char **argv) { 1247 // Print a stack trace if we signal out. 1248 sys::PrintStackTraceOnErrorSignal(); 1249 PrettyStackTraceProgram X(argc, argv); 1250 1251 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 1252 cl::ParseCommandLineOptions(argc, argv, "llvm symbol table dumper\n"); 1253 1254 // llvm-nm only reads binary files. 1255 if (error(sys::ChangeStdinToBinary())) 1256 return 1; 1257 1258 // These calls are needed so that we can read bitcode correctly. 1259 llvm::InitializeAllTargetInfos(); 1260 llvm::InitializeAllTargetMCs(); 1261 llvm::InitializeAllAsmParsers(); 1262 1263 ToolName = argv[0]; 1264 if (BSDFormat) 1265 OutputFormat = bsd; 1266 if (POSIXFormat) 1267 OutputFormat = posix; 1268 if (DarwinFormat) 1269 OutputFormat = darwin; 1270 1271 // The relative order of these is important. If you pass --size-sort it should 1272 // only print out the size. However, if you pass -S --size-sort, it should 1273 // print out both the size and address. 1274 if (SizeSort && !PrintSize) 1275 PrintAddress = false; 1276 if (OutputFormat == sysv || SizeSort) 1277 PrintSize = true; 1278 if (InputFilenames.empty()) 1279 InputFilenames.push_back("a.out"); 1280 if (InputFilenames.size() > 1) 1281 MultipleFiles = true; 1282 1283 for (unsigned i = 0; i < ArchFlags.size(); ++i) { 1284 if (ArchFlags[i] == "all") { 1285 ArchAll = true; 1286 } else { 1287 if (!MachOObjectFile::isValidArch(ArchFlags[i])) 1288 error("Unknown architecture named '" + ArchFlags[i] + "'", 1289 "for the -arch option"); 1290 } 1291 } 1292 1293 if (SegSect.size() != 0 && SegSect.size() != 2) 1294 error("bad number of arguments (must be two arguments)", 1295 "for the -s option"); 1296 1297 std::for_each(InputFilenames.begin(), InputFilenames.end(), 1298 dumpSymbolNamesFromFile); 1299 1300 if (HadError) 1301 return 1; 1302 } 1303