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/StringSwitch.h" 19 #include "llvm/BinaryFormat/COFF.h" 20 #include "llvm/Demangle/Demangle.h" 21 #include "llvm/IR/Function.h" 22 #include "llvm/IR/LLVMContext.h" 23 #include "llvm/Object/Archive.h" 24 #include "llvm/Object/COFF.h" 25 #include "llvm/Object/COFFImportFile.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/Object/TapiFile.h" 32 #include "llvm/Object/TapiUniversal.h" 33 #include "llvm/Object/Wasm.h" 34 #include "llvm/Support/CommandLine.h" 35 #include "llvm/Support/FileSystem.h" 36 #include "llvm/Support/Format.h" 37 #include "llvm/Support/InitLLVM.h" 38 #include "llvm/Support/MemoryBuffer.h" 39 #include "llvm/Support/Program.h" 40 #include "llvm/Support/Signals.h" 41 #include "llvm/Support/TargetSelect.h" 42 #include "llvm/Support/WithColor.h" 43 #include "llvm/Support/raw_ostream.h" 44 #include <vector> 45 46 using namespace llvm; 47 using namespace object; 48 49 namespace { 50 enum OutputFormatTy { bsd, sysv, posix, darwin, just_symbols }; 51 52 cl::OptionCategory NMCat("llvm-nm Options"); 53 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"), 59 cl::OptionEnumValue{"just-symbols", int(just_symbols), 60 "just symbol names"}), 61 cl::init(bsd), cl::cat(NMCat)); 62 cl::alias OutputFormat2("f", cl::desc("Alias for --format"), 63 cl::aliasopt(OutputFormat)); 64 65 cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<input files>"), 66 cl::ZeroOrMore); 67 68 cl::opt<bool> UndefinedOnly("undefined-only", 69 cl::desc("Show only undefined symbols"), 70 cl::cat(NMCat)); 71 cl::alias UndefinedOnly2("u", cl::desc("Alias for --undefined-only"), 72 cl::aliasopt(UndefinedOnly), cl::Grouping); 73 74 cl::opt<bool> DynamicSyms("dynamic", 75 cl::desc("Display the dynamic symbols instead " 76 "of normal symbols."), 77 cl::cat(NMCat)); 78 cl::alias DynamicSyms2("D", cl::desc("Alias for --dynamic"), 79 cl::aliasopt(DynamicSyms), cl::Grouping); 80 81 cl::opt<bool> DefinedOnly("defined-only", cl::desc("Show only defined symbols"), 82 cl::cat(NMCat)); 83 cl::alias DefinedOnly2("U", cl::desc("Alias for --defined-only"), 84 cl::aliasopt(DefinedOnly), cl::Grouping); 85 86 cl::opt<bool> ExternalOnly("extern-only", 87 cl::desc("Show only external symbols"), 88 cl::ZeroOrMore, cl::cat(NMCat)); 89 cl::alias ExternalOnly2("g", cl::desc("Alias for --extern-only"), 90 cl::aliasopt(ExternalOnly), cl::Grouping, 91 cl::ZeroOrMore); 92 93 cl::opt<bool> NoWeakSymbols("no-weak", cl::desc("Show only non-weak symbols"), 94 cl::cat(NMCat)); 95 cl::alias NoWeakSymbols2("W", cl::desc("Alias for --no-weak"), 96 cl::aliasopt(NoWeakSymbols), cl::Grouping); 97 98 cl::opt<bool> BSDFormat("B", cl::desc("Alias for --format=bsd"), cl::Grouping, 99 cl::cat(NMCat)); 100 cl::opt<bool> POSIXFormat("P", cl::desc("Alias for --format=posix"), 101 cl::Grouping, cl::cat(NMCat)); 102 cl::alias Portability("portability", cl::desc("Alias for --format=posix"), 103 cl::aliasopt(POSIXFormat), cl::NotHidden); 104 cl::opt<bool> DarwinFormat("m", cl::desc("Alias for --format=darwin"), 105 cl::Grouping, cl::cat(NMCat)); 106 107 static cl::list<std::string> 108 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"), 109 cl::ZeroOrMore, cl::cat(NMCat)); 110 bool ArchAll = false; 111 112 cl::opt<bool> PrintFileName( 113 "print-file-name", 114 cl::desc("Precede each symbol with the object file it came from"), 115 cl::cat(NMCat)); 116 117 cl::alias PrintFileNameA("A", cl::desc("Alias for --print-file-name"), 118 cl::aliasopt(PrintFileName), cl::Grouping); 119 cl::alias PrintFileNameo("o", cl::desc("Alias for --print-file-name"), 120 cl::aliasopt(PrintFileName), cl::Grouping); 121 122 cl::opt<bool> Quiet("quiet", cl::desc("Suppress 'no symbols' diagnostic"), 123 cl::cat(NMCat)); 124 125 cl::opt<bool> DebugSyms("debug-syms", 126 cl::desc("Show all symbols, even debugger only"), 127 cl::cat(NMCat)); 128 cl::alias DebugSymsa("a", cl::desc("Alias for --debug-syms"), 129 cl::aliasopt(DebugSyms), cl::Grouping); 130 131 cl::opt<bool> NumericSort("numeric-sort", cl::desc("Sort symbols by address"), 132 cl::cat(NMCat)); 133 cl::alias NumericSortn("n", cl::desc("Alias for --numeric-sort"), 134 cl::aliasopt(NumericSort), cl::Grouping); 135 cl::alias NumericSortv("v", cl::desc("Alias for --numeric-sort"), 136 cl::aliasopt(NumericSort), cl::Grouping); 137 138 cl::opt<bool> NoSort("no-sort", cl::desc("Show symbols in order encountered"), 139 cl::cat(NMCat)); 140 cl::alias NoSortp("p", cl::desc("Alias for --no-sort"), cl::aliasopt(NoSort), 141 cl::Grouping); 142 143 cl::opt<bool> Demangle("demangle", cl::ZeroOrMore, 144 cl::desc("Demangle C++ symbol names"), cl::cat(NMCat)); 145 cl::alias DemangleC("C", cl::desc("Alias for --demangle"), 146 cl::aliasopt(Demangle), cl::Grouping); 147 cl::opt<bool> NoDemangle("no-demangle", cl::init(false), cl::ZeroOrMore, 148 cl::desc("Don't demangle symbol names"), 149 cl::cat(NMCat)); 150 151 cl::opt<bool> ReverseSort("reverse-sort", cl::desc("Sort in reverse order"), 152 cl::cat(NMCat)); 153 cl::alias ReverseSortr("r", cl::desc("Alias for --reverse-sort"), 154 cl::aliasopt(ReverseSort), cl::Grouping); 155 156 cl::opt<bool> PrintSize("print-size", 157 cl::desc("Show symbol size as well as address"), 158 cl::cat(NMCat)); 159 cl::alias PrintSizeS("S", cl::desc("Alias for --print-size"), 160 cl::aliasopt(PrintSize), cl::Grouping); 161 bool MachOPrintSizeWarning = false; 162 163 cl::opt<bool> SizeSort("size-sort", cl::desc("Sort symbols by size"), 164 cl::cat(NMCat)); 165 166 cl::opt<bool> WithoutAliases("without-aliases", cl::Hidden, 167 cl::desc("Exclude aliases from output"), 168 cl::cat(NMCat)); 169 170 cl::opt<bool> ArchiveMap("print-armap", cl::desc("Print the archive map"), 171 cl::cat(NMCat)); 172 cl::alias ArchiveMaps("M", cl::desc("Alias for --print-armap"), 173 cl::aliasopt(ArchiveMap), cl::Grouping); 174 175 enum Radix { d, o, x }; 176 cl::opt<Radix> 177 AddressRadix("radix", cl::desc("Radix (o/d/x) for printing symbol Values"), 178 cl::values(clEnumVal(d, "decimal"), clEnumVal(o, "octal"), 179 clEnumVal(x, "hexadecimal")), 180 cl::init(x), cl::cat(NMCat)); 181 cl::alias RadixAlias("t", cl::desc("Alias for --radix"), 182 cl::aliasopt(AddressRadix)); 183 184 cl::opt<bool> JustSymbolName("just-symbol-name", 185 cl::desc("Alias for --format=just-symbols"), 186 cl::cat(NMCat)); 187 cl::alias JustSymbolNames("j", cl::desc("Alias for --format-just-symbols"), 188 cl::aliasopt(JustSymbolName), cl::Grouping); 189 190 cl::opt<bool> 191 SpecialSyms("special-syms", 192 cl::desc("Do not filter special symbols from the output"), 193 cl::cat(NMCat)); 194 195 cl::list<std::string> SegSect("s", cl::multi_val(2), cl::ZeroOrMore, 196 cl::value_desc("segment section"), cl::Hidden, 197 cl::desc("Dump only symbols from this segment " 198 "and section name, Mach-O only"), 199 cl::cat(NMCat)); 200 201 cl::opt<bool> FormatMachOasHex("x", 202 cl::desc("Print symbol entry in hex, " 203 "Mach-O only"), 204 cl::Grouping, cl::cat(NMCat)); 205 cl::opt<bool> AddDyldInfo("add-dyldinfo", 206 cl::desc("Add symbols from the dyldinfo not already " 207 "in the symbol table, Mach-O only"), 208 cl::cat(NMCat)); 209 cl::opt<bool> NoDyldInfo("no-dyldinfo", 210 cl::desc("Don't add any symbols from the dyldinfo, " 211 "Mach-O only"), 212 cl::cat(NMCat)); 213 cl::opt<bool> DyldInfoOnly("dyldinfo-only", 214 cl::desc("Show only symbols from the dyldinfo, " 215 "Mach-O only"), 216 cl::cat(NMCat)); 217 218 cl::opt<bool> NoLLVMBitcode("no-llvm-bc", 219 cl::desc("Disable LLVM bitcode reader"), 220 cl::cat(NMCat)); 221 222 cl::opt<bool> AddInlinedInfo("add-inlinedinfo", 223 cl::desc("Add symbols from the inlined libraries, " 224 "TBD(Mach-O) only"), 225 cl::cat(NMCat)); 226 227 cl::extrahelp HelpResponse("\nPass @FILE as argument to read options from FILE.\n"); 228 229 bool PrintAddress = true; 230 231 bool MultipleFiles = false; 232 233 bool HadError = false; 234 235 std::string ToolName; 236 } // anonymous namespace 237 238 static void error(Twine Message, Twine Path = Twine()) { 239 HadError = true; 240 WithColor::error(errs(), ToolName) << Path << ": " << Message << "\n"; 241 } 242 243 static bool error(std::error_code EC, Twine Path = Twine()) { 244 if (EC) { 245 error(EC.message(), Path); 246 return true; 247 } 248 return false; 249 } 250 251 // This version of error() prints the archive name and member name, for example: 252 // "libx.a(foo.o)" after the ToolName before the error message. It sets 253 // HadError but returns allowing the code to move on to other archive members. 254 static void error(llvm::Error E, StringRef FileName, const Archive::Child &C, 255 StringRef ArchitectureName = StringRef()) { 256 HadError = true; 257 WithColor::error(errs(), ToolName) << FileName; 258 259 Expected<StringRef> NameOrErr = C.getName(); 260 // TODO: if we have a error getting the name then it would be nice to print 261 // the index of which archive member this is and or its offset in the 262 // archive instead of "???" as the name. 263 if (!NameOrErr) { 264 consumeError(NameOrErr.takeError()); 265 errs() << "(" << "???" << ")"; 266 } else 267 errs() << "(" << NameOrErr.get() << ")"; 268 269 if (!ArchitectureName.empty()) 270 errs() << " (for architecture " << ArchitectureName << ")"; 271 272 std::string Buf; 273 raw_string_ostream OS(Buf); 274 logAllUnhandledErrors(std::move(E), OS); 275 OS.flush(); 276 errs() << ": " << Buf << "\n"; 277 } 278 279 // This version of error() prints the file name and which architecture slice it 280 // is from, for example: "foo.o (for architecture i386)" after the ToolName 281 // before the error message. It sets HadError but returns allowing the code to 282 // move on to other architecture slices. 283 static void error(llvm::Error E, StringRef FileName, 284 StringRef ArchitectureName = StringRef()) { 285 HadError = true; 286 WithColor::error(errs(), ToolName) << FileName; 287 288 if (!ArchitectureName.empty()) 289 errs() << " (for architecture " << ArchitectureName << ")"; 290 291 std::string Buf; 292 raw_string_ostream OS(Buf); 293 logAllUnhandledErrors(std::move(E), OS); 294 OS.flush(); 295 errs() << ": " << Buf << "\n"; 296 } 297 298 namespace { 299 struct NMSymbol { 300 uint64_t Address; 301 uint64_t Size; 302 char TypeChar; 303 std::string Name; 304 StringRef SectionName; 305 StringRef TypeName; 306 BasicSymbolRef Sym; 307 // The Sym field above points to the native symbol in the object file, 308 // for Mach-O when we are creating symbols from the dyld info the above 309 // pointer is null as there is no native symbol. In these cases the fields 310 // below are filled in to represent what would have been a Mach-O nlist 311 // native symbol. 312 uint32_t SymFlags; 313 SectionRef Section; 314 uint8_t NType; 315 uint8_t NSect; 316 uint16_t NDesc; 317 std::string IndirectName; 318 }; 319 } // anonymous namespace 320 321 static bool compareSymbolAddress(const NMSymbol &A, const NMSymbol &B) { 322 bool ADefined; 323 // Symbol flags have been checked in the caller. 324 if (A.Sym.getRawDataRefImpl().p) { 325 uint32_t AFlags = cantFail(A.Sym.getFlags()); 326 ADefined = !(AFlags & SymbolRef::SF_Undefined); 327 } else { 328 ADefined = A.TypeChar != 'U'; 329 } 330 bool BDefined; 331 // Symbol flags have been checked in the caller. 332 if (B.Sym.getRawDataRefImpl().p) { 333 uint32_t BFlags = cantFail(B.Sym.getFlags()); 334 BDefined = !(BFlags & SymbolRef::SF_Undefined); 335 } else { 336 BDefined = B.TypeChar != 'U'; 337 } 338 return std::make_tuple(ADefined, A.Address, A.Name, A.Size) < 339 std::make_tuple(BDefined, B.Address, B.Name, B.Size); 340 } 341 342 static bool compareSymbolSize(const NMSymbol &A, const NMSymbol &B) { 343 return std::make_tuple(A.Size, A.Name, A.Address) < 344 std::make_tuple(B.Size, B.Name, B.Address); 345 } 346 347 static bool compareSymbolName(const NMSymbol &A, const NMSymbol &B) { 348 return std::make_tuple(A.Name, A.Size, A.Address) < 349 std::make_tuple(B.Name, B.Size, B.Address); 350 } 351 352 static char isSymbolList64Bit(SymbolicFile &Obj) { 353 if (auto *IRObj = dyn_cast<IRObjectFile>(&Obj)) 354 return Triple(IRObj->getTargetTriple()).isArch64Bit(); 355 if (isa<COFFObjectFile>(Obj) || isa<COFFImportFile>(Obj)) 356 return false; 357 if (isa<WasmObjectFile>(Obj)) 358 return false; 359 if (TapiFile *Tapi = dyn_cast<TapiFile>(&Obj)) 360 return Tapi->is64Bit(); 361 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj)) 362 return MachO->is64Bit(); 363 return cast<ELFObjectFileBase>(Obj).getBytesInAddress() == 8; 364 } 365 366 static StringRef CurrentFilename; 367 static std::vector<NMSymbol> SymbolList; 368 369 static char getSymbolNMTypeChar(IRObjectFile &Obj, basic_symbol_iterator I); 370 371 // darwinPrintSymbol() is used to print a symbol from a Mach-O file when the 372 // the OutputFormat is darwin or we are printing Mach-O symbols in hex. For 373 // the darwin format it produces the same output as darwin's nm(1) -m output 374 // and when printing Mach-O symbols in hex it produces the same output as 375 // darwin's nm(1) -x format. 376 static void darwinPrintSymbol(SymbolicFile &Obj, const NMSymbol &S, 377 char *SymbolAddrStr, const char *printBlanks, 378 const char *printDashes, 379 const char *printFormat) { 380 MachO::mach_header H; 381 MachO::mach_header_64 H_64; 382 uint32_t Filetype = MachO::MH_OBJECT; 383 uint32_t Flags = 0; 384 uint8_t NType = 0; 385 uint8_t NSect = 0; 386 uint16_t NDesc = 0; 387 uint32_t NStrx = 0; 388 uint64_t NValue = 0; 389 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj); 390 if (Obj.isIR()) { 391 uint32_t SymFlags = cantFail(S.Sym.getFlags()); 392 if (SymFlags & SymbolRef::SF_Global) 393 NType |= MachO::N_EXT; 394 if (SymFlags & SymbolRef::SF_Hidden) 395 NType |= MachO::N_PEXT; 396 if (SymFlags & SymbolRef::SF_Undefined) 397 NType |= MachO::N_EXT | MachO::N_UNDF; 398 else { 399 // Here we have a symbol definition. So to fake out a section name we 400 // use 1, 2 and 3 for section numbers. See below where they are used to 401 // print out fake section names. 402 NType |= MachO::N_SECT; 403 if (SymFlags & SymbolRef::SF_Const) 404 NSect = 3; 405 else if (SymFlags & SymbolRef::SF_Executable) 406 NSect = 1; 407 else 408 NSect = 2; 409 } 410 if (SymFlags & SymbolRef::SF_Weak) 411 NDesc |= MachO::N_WEAK_DEF; 412 } else { 413 DataRefImpl SymDRI = S.Sym.getRawDataRefImpl(); 414 if (MachO->is64Bit()) { 415 H_64 = MachO->MachOObjectFile::getHeader64(); 416 Filetype = H_64.filetype; 417 Flags = H_64.flags; 418 if (SymDRI.p){ 419 MachO::nlist_64 STE_64 = MachO->getSymbol64TableEntry(SymDRI); 420 NType = STE_64.n_type; 421 NSect = STE_64.n_sect; 422 NDesc = STE_64.n_desc; 423 NStrx = STE_64.n_strx; 424 NValue = STE_64.n_value; 425 } else { 426 NType = S.NType; 427 NSect = S.NSect; 428 NDesc = S.NDesc; 429 NStrx = 0; 430 NValue = S.Address; 431 } 432 } else { 433 H = MachO->MachOObjectFile::getHeader(); 434 Filetype = H.filetype; 435 Flags = H.flags; 436 if (SymDRI.p){ 437 MachO::nlist STE = MachO->getSymbolTableEntry(SymDRI); 438 NType = STE.n_type; 439 NSect = STE.n_sect; 440 NDesc = STE.n_desc; 441 NStrx = STE.n_strx; 442 NValue = STE.n_value; 443 } else { 444 NType = S.NType; 445 NSect = S.NSect; 446 NDesc = S.NDesc; 447 NStrx = 0; 448 NValue = S.Address; 449 } 450 } 451 } 452 453 // If we are printing Mach-O symbols in hex do that and return. 454 if (FormatMachOasHex) { 455 outs() << format(printFormat, NValue) << ' ' 456 << format("%02x %02x %04x %08x", NType, NSect, NDesc, NStrx) << ' ' 457 << S.Name; 458 if ((NType & MachO::N_TYPE) == MachO::N_INDR) { 459 outs() << " (indirect for "; 460 outs() << format(printFormat, NValue) << ' '; 461 StringRef IndirectName; 462 if (S.Sym.getRawDataRefImpl().p) { 463 if (MachO->getIndirectName(S.Sym.getRawDataRefImpl(), IndirectName)) 464 outs() << "?)"; 465 else 466 outs() << IndirectName << ")"; 467 } else 468 outs() << S.IndirectName << ")"; 469 } 470 outs() << "\n"; 471 return; 472 } 473 474 if (PrintAddress) { 475 if ((NType & MachO::N_TYPE) == MachO::N_INDR) 476 strcpy(SymbolAddrStr, printBlanks); 477 if (Obj.isIR() && (NType & MachO::N_TYPE) == MachO::N_TYPE) 478 strcpy(SymbolAddrStr, printDashes); 479 outs() << SymbolAddrStr << ' '; 480 } 481 482 switch (NType & MachO::N_TYPE) { 483 case MachO::N_UNDF: 484 if (NValue != 0) { 485 outs() << "(common) "; 486 if (MachO::GET_COMM_ALIGN(NDesc) != 0) 487 outs() << "(alignment 2^" << (int)MachO::GET_COMM_ALIGN(NDesc) << ") "; 488 } else { 489 if ((NType & MachO::N_TYPE) == MachO::N_PBUD) 490 outs() << "(prebound "; 491 else 492 outs() << "("; 493 if ((NDesc & MachO::REFERENCE_TYPE) == 494 MachO::REFERENCE_FLAG_UNDEFINED_LAZY) 495 outs() << "undefined [lazy bound]) "; 496 else if ((NDesc & MachO::REFERENCE_TYPE) == 497 MachO::REFERENCE_FLAG_PRIVATE_UNDEFINED_LAZY) 498 outs() << "undefined [private lazy bound]) "; 499 else if ((NDesc & MachO::REFERENCE_TYPE) == 500 MachO::REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY) 501 outs() << "undefined [private]) "; 502 else 503 outs() << "undefined) "; 504 } 505 break; 506 case MachO::N_ABS: 507 outs() << "(absolute) "; 508 break; 509 case MachO::N_INDR: 510 outs() << "(indirect) "; 511 break; 512 case MachO::N_SECT: { 513 if (Obj.isIR()) { 514 // For llvm bitcode files print out a fake section name using the values 515 // use 1, 2 and 3 for section numbers as set above. 516 if (NSect == 1) 517 outs() << "(LTO,CODE) "; 518 else if (NSect == 2) 519 outs() << "(LTO,DATA) "; 520 else if (NSect == 3) 521 outs() << "(LTO,RODATA) "; 522 else 523 outs() << "(?,?) "; 524 break; 525 } 526 section_iterator Sec = SectionRef(); 527 if (S.Sym.getRawDataRefImpl().p) { 528 Expected<section_iterator> SecOrErr = 529 MachO->getSymbolSection(S.Sym.getRawDataRefImpl()); 530 if (!SecOrErr) { 531 consumeError(SecOrErr.takeError()); 532 outs() << "(?,?) "; 533 break; 534 } 535 Sec = *SecOrErr; 536 if (Sec == MachO->section_end()) { 537 outs() << "(?,?) "; 538 break; 539 } 540 } else { 541 Sec = S.Section; 542 } 543 DataRefImpl Ref = Sec->getRawDataRefImpl(); 544 StringRef SectionName; 545 if (Expected<StringRef> NameOrErr = MachO->getSectionName(Ref)) 546 SectionName = *NameOrErr; 547 StringRef SegmentName = MachO->getSectionFinalSegmentName(Ref); 548 outs() << "(" << SegmentName << "," << SectionName << ") "; 549 break; 550 } 551 default: 552 outs() << "(?) "; 553 break; 554 } 555 556 if (NType & MachO::N_EXT) { 557 if (NDesc & MachO::REFERENCED_DYNAMICALLY) 558 outs() << "[referenced dynamically] "; 559 if (NType & MachO::N_PEXT) { 560 if ((NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF) 561 outs() << "weak private external "; 562 else 563 outs() << "private external "; 564 } else { 565 if ((NDesc & MachO::N_WEAK_REF) == MachO::N_WEAK_REF || 566 (NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF) { 567 if ((NDesc & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF)) == 568 (MachO::N_WEAK_REF | MachO::N_WEAK_DEF)) 569 outs() << "weak external automatically hidden "; 570 else 571 outs() << "weak external "; 572 } else 573 outs() << "external "; 574 } 575 } else { 576 if (NType & MachO::N_PEXT) 577 outs() << "non-external (was a private external) "; 578 else 579 outs() << "non-external "; 580 } 581 582 if (Filetype == MachO::MH_OBJECT) { 583 if (NDesc & MachO::N_NO_DEAD_STRIP) 584 outs() << "[no dead strip] "; 585 if ((NType & MachO::N_TYPE) != MachO::N_UNDF && 586 NDesc & MachO::N_SYMBOL_RESOLVER) 587 outs() << "[symbol resolver] "; 588 if ((NType & MachO::N_TYPE) != MachO::N_UNDF && NDesc & MachO::N_ALT_ENTRY) 589 outs() << "[alt entry] "; 590 if ((NType & MachO::N_TYPE) != MachO::N_UNDF && NDesc & MachO::N_COLD_FUNC) 591 outs() << "[cold func] "; 592 } 593 594 if ((NDesc & MachO::N_ARM_THUMB_DEF) == MachO::N_ARM_THUMB_DEF) 595 outs() << "[Thumb] "; 596 597 if ((NType & MachO::N_TYPE) == MachO::N_INDR) { 598 outs() << S.Name << " (for "; 599 StringRef IndirectName; 600 if (MachO) { 601 if (S.Sym.getRawDataRefImpl().p) { 602 if (MachO->getIndirectName(S.Sym.getRawDataRefImpl(), IndirectName)) 603 outs() << "?)"; 604 else 605 outs() << IndirectName << ")"; 606 } else 607 outs() << S.IndirectName << ")"; 608 } else 609 outs() << "?)"; 610 } else 611 outs() << S.Name; 612 613 if ((Flags & MachO::MH_TWOLEVEL) == MachO::MH_TWOLEVEL && 614 (((NType & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0) || 615 (NType & MachO::N_TYPE) == MachO::N_PBUD)) { 616 uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(NDesc); 617 if (LibraryOrdinal != 0) { 618 if (LibraryOrdinal == MachO::EXECUTABLE_ORDINAL) 619 outs() << " (from executable)"; 620 else if (LibraryOrdinal == MachO::DYNAMIC_LOOKUP_ORDINAL) 621 outs() << " (dynamically looked up)"; 622 else { 623 StringRef LibraryName; 624 if (!MachO || 625 MachO->getLibraryShortNameByIndex(LibraryOrdinal - 1, LibraryName)) 626 outs() << " (from bad library ordinal " << LibraryOrdinal << ")"; 627 else 628 outs() << " (from " << LibraryName << ")"; 629 } 630 } 631 } 632 633 outs() << "\n"; 634 } 635 636 // Table that maps Darwin's Mach-O stab constants to strings to allow printing. 637 struct DarwinStabName { 638 uint8_t NType; 639 const char *Name; 640 }; 641 static const struct DarwinStabName DarwinStabNames[] = { 642 {MachO::N_GSYM, "GSYM"}, 643 {MachO::N_FNAME, "FNAME"}, 644 {MachO::N_FUN, "FUN"}, 645 {MachO::N_STSYM, "STSYM"}, 646 {MachO::N_LCSYM, "LCSYM"}, 647 {MachO::N_BNSYM, "BNSYM"}, 648 {MachO::N_PC, "PC"}, 649 {MachO::N_AST, "AST"}, 650 {MachO::N_OPT, "OPT"}, 651 {MachO::N_RSYM, "RSYM"}, 652 {MachO::N_SLINE, "SLINE"}, 653 {MachO::N_ENSYM, "ENSYM"}, 654 {MachO::N_SSYM, "SSYM"}, 655 {MachO::N_SO, "SO"}, 656 {MachO::N_OSO, "OSO"}, 657 {MachO::N_LSYM, "LSYM"}, 658 {MachO::N_BINCL, "BINCL"}, 659 {MachO::N_SOL, "SOL"}, 660 {MachO::N_PARAMS, "PARAM"}, 661 {MachO::N_VERSION, "VERS"}, 662 {MachO::N_OLEVEL, "OLEV"}, 663 {MachO::N_PSYM, "PSYM"}, 664 {MachO::N_EINCL, "EINCL"}, 665 {MachO::N_ENTRY, "ENTRY"}, 666 {MachO::N_LBRAC, "LBRAC"}, 667 {MachO::N_EXCL, "EXCL"}, 668 {MachO::N_RBRAC, "RBRAC"}, 669 {MachO::N_BCOMM, "BCOMM"}, 670 {MachO::N_ECOMM, "ECOMM"}, 671 {MachO::N_ECOML, "ECOML"}, 672 {MachO::N_LENG, "LENG"}, 673 }; 674 675 static const char *getDarwinStabString(uint8_t NType) { 676 for (auto I : makeArrayRef(DarwinStabNames)) 677 if (I.NType == NType) 678 return I.Name; 679 return nullptr; 680 } 681 682 // darwinPrintStab() prints the n_sect, n_desc along with a symbolic name of 683 // a stab n_type value in a Mach-O file. 684 static void darwinPrintStab(MachOObjectFile *MachO, const NMSymbol &S) { 685 MachO::nlist_64 STE_64; 686 MachO::nlist STE; 687 uint8_t NType; 688 uint8_t NSect; 689 uint16_t NDesc; 690 DataRefImpl SymDRI = S.Sym.getRawDataRefImpl(); 691 if (MachO->is64Bit()) { 692 STE_64 = MachO->getSymbol64TableEntry(SymDRI); 693 NType = STE_64.n_type; 694 NSect = STE_64.n_sect; 695 NDesc = STE_64.n_desc; 696 } else { 697 STE = MachO->getSymbolTableEntry(SymDRI); 698 NType = STE.n_type; 699 NSect = STE.n_sect; 700 NDesc = STE.n_desc; 701 } 702 703 outs() << format(" %02x %04x ", NSect, NDesc); 704 if (const char *stabString = getDarwinStabString(NType)) 705 outs() << format("%5.5s", stabString); 706 else 707 outs() << format(" %02x", NType); 708 } 709 710 static Optional<std::string> demangle(StringRef Name, bool StripUnderscore) { 711 if (StripUnderscore && !Name.empty() && Name[0] == '_') 712 Name = Name.substr(1); 713 714 if (!Name.startswith("_Z")) 715 return None; 716 717 int Status; 718 char *Undecorated = 719 itaniumDemangle(Name.str().c_str(), nullptr, nullptr, &Status); 720 if (Status != 0) 721 return None; 722 723 std::string S(Undecorated); 724 free(Undecorated); 725 return S; 726 } 727 728 static bool symbolIsDefined(const NMSymbol &Sym) { 729 return Sym.TypeChar != 'U' && Sym.TypeChar != 'w' && Sym.TypeChar != 'v'; 730 } 731 732 static void writeFileName(raw_ostream &S, StringRef ArchiveName, 733 StringRef ArchitectureName) { 734 if (!ArchitectureName.empty()) 735 S << "(for architecture " << ArchitectureName << "):"; 736 if (OutputFormat == posix && !ArchiveName.empty()) 737 S << ArchiveName << "[" << CurrentFilename << "]: "; 738 else { 739 if (!ArchiveName.empty()) 740 S << ArchiveName << ":"; 741 S << CurrentFilename << ": "; 742 } 743 } 744 745 static void sortAndPrintSymbolList(SymbolicFile &Obj, bool printName, 746 StringRef ArchiveName, 747 StringRef ArchitectureName) { 748 if (!NoSort) { 749 using Comparator = bool (*)(const NMSymbol &, const NMSymbol &); 750 Comparator Cmp; 751 if (NumericSort) 752 Cmp = &compareSymbolAddress; 753 else if (SizeSort) 754 Cmp = &compareSymbolSize; 755 else 756 Cmp = &compareSymbolName; 757 758 if (ReverseSort) 759 llvm::sort(SymbolList, [=](const NMSymbol &A, const NMSymbol &B) -> bool { 760 return Cmp(B, A); 761 }); 762 else 763 llvm::sort(SymbolList, Cmp); 764 } 765 766 if (!PrintFileName) { 767 if ((OutputFormat == bsd || OutputFormat == posix || 768 OutputFormat == just_symbols) && 769 MultipleFiles && printName) { 770 outs() << '\n' << CurrentFilename << ":\n"; 771 } else if (OutputFormat == sysv) { 772 outs() << "\n\nSymbols from " << CurrentFilename << ":\n\n"; 773 if (isSymbolList64Bit(Obj)) 774 outs() << "Name Value Class Type" 775 << " Size Line Section\n"; 776 else 777 outs() << "Name Value Class Type" 778 << " Size Line Section\n"; 779 } 780 } 781 782 const char *printBlanks, *printDashes, *printFormat; 783 if (isSymbolList64Bit(Obj)) { 784 printBlanks = " "; 785 printDashes = "----------------"; 786 switch (AddressRadix) { 787 case Radix::o: 788 printFormat = OutputFormat == posix ? "%" PRIo64 : "%016" PRIo64; 789 break; 790 case Radix::x: 791 printFormat = OutputFormat == posix ? "%" PRIx64 : "%016" PRIx64; 792 break; 793 default: 794 printFormat = OutputFormat == posix ? "%" PRId64 : "%016" PRId64; 795 } 796 } else { 797 printBlanks = " "; 798 printDashes = "--------"; 799 switch (AddressRadix) { 800 case Radix::o: 801 printFormat = OutputFormat == posix ? "%" PRIo64 : "%08" PRIo64; 802 break; 803 case Radix::x: 804 printFormat = OutputFormat == posix ? "%" PRIx64 : "%08" PRIx64; 805 break; 806 default: 807 printFormat = OutputFormat == posix ? "%" PRId64 : "%08" PRId64; 808 } 809 } 810 811 for (const NMSymbol &S : SymbolList) { 812 uint32_t SymFlags; 813 std::string Name = S.Name; 814 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj); 815 if (Demangle) { 816 if (Optional<std::string> Opt = demangle(S.Name, MachO)) 817 Name = *Opt; 818 } 819 if (S.Sym.getRawDataRefImpl().p) { 820 Expected<uint32_t> SymFlagsOrErr = S.Sym.getFlags(); 821 if (!SymFlagsOrErr) { 822 // TODO: Test this error. 823 error(SymFlagsOrErr.takeError(), Obj.getFileName()); 824 return; 825 } 826 SymFlags = *SymFlagsOrErr; 827 } else 828 SymFlags = S.SymFlags; 829 830 bool Undefined = SymFlags & SymbolRef::SF_Undefined; 831 bool Global = SymFlags & SymbolRef::SF_Global; 832 bool Weak = SymFlags & SymbolRef::SF_Weak; 833 bool FormatSpecific = SymFlags & SymbolRef::SF_FormatSpecific; 834 if ((!Undefined && UndefinedOnly) || (Undefined && DefinedOnly) || 835 (!Global && ExternalOnly) || (Weak && NoWeakSymbols) || 836 (FormatSpecific && !(SpecialSyms || DebugSyms))) 837 continue; 838 if (PrintFileName) 839 writeFileName(outs(), ArchiveName, ArchitectureName); 840 if ((OutputFormat == just_symbols || 841 (UndefinedOnly && MachO && OutputFormat != darwin)) && 842 OutputFormat != posix) { 843 outs() << Name << "\n"; 844 continue; 845 } 846 847 char SymbolAddrStr[23], SymbolSizeStr[23]; 848 849 // If the format is SysV or the symbol isn't defined, then print spaces. 850 if (OutputFormat == sysv || !symbolIsDefined(S)) { 851 if (OutputFormat == posix) { 852 format(printFormat, S.Address) 853 .print(SymbolAddrStr, sizeof(SymbolAddrStr)); 854 format(printFormat, S.Size).print(SymbolSizeStr, sizeof(SymbolSizeStr)); 855 } else { 856 strcpy(SymbolAddrStr, printBlanks); 857 strcpy(SymbolSizeStr, printBlanks); 858 } 859 } 860 861 if (symbolIsDefined(S)) { 862 // Otherwise, print the symbol address and size. 863 if (Obj.isIR()) 864 strcpy(SymbolAddrStr, printDashes); 865 else if (MachO && S.TypeChar == 'I') 866 strcpy(SymbolAddrStr, printBlanks); 867 else 868 format(printFormat, S.Address) 869 .print(SymbolAddrStr, sizeof(SymbolAddrStr)); 870 format(printFormat, S.Size).print(SymbolSizeStr, sizeof(SymbolSizeStr)); 871 } 872 873 // If OutputFormat is darwin or we are printing Mach-O symbols in hex and 874 // we have a MachOObjectFile, call darwinPrintSymbol to print as darwin's 875 // nm(1) -m output or hex, else if OutputFormat is darwin or we are 876 // printing Mach-O symbols in hex and not a Mach-O object fall back to 877 // OutputFormat bsd (see below). 878 if ((OutputFormat == darwin || FormatMachOasHex) && (MachO || Obj.isIR())) { 879 darwinPrintSymbol(Obj, S, SymbolAddrStr, printBlanks, printDashes, 880 printFormat); 881 } else if (OutputFormat == posix) { 882 outs() << Name << " " << S.TypeChar << " " << SymbolAddrStr << " " 883 << (MachO ? "0" : SymbolSizeStr) << "\n"; 884 } else if (OutputFormat == bsd || (OutputFormat == darwin && !MachO)) { 885 if (PrintAddress) 886 outs() << SymbolAddrStr << ' '; 887 if (PrintSize) 888 outs() << SymbolSizeStr << ' '; 889 outs() << S.TypeChar; 890 if (S.TypeChar == '-' && MachO) 891 darwinPrintStab(MachO, S); 892 outs() << " " << Name; 893 if (S.TypeChar == 'I' && MachO) { 894 outs() << " (indirect for "; 895 if (S.Sym.getRawDataRefImpl().p) { 896 StringRef IndirectName; 897 if (MachO->getIndirectName(S.Sym.getRawDataRefImpl(), IndirectName)) 898 outs() << "?)"; 899 else 900 outs() << IndirectName << ")"; 901 } else 902 outs() << S.IndirectName << ")"; 903 } 904 outs() << "\n"; 905 } else if (OutputFormat == sysv) { 906 outs() << left_justify(Name, 20) << "|" << SymbolAddrStr << "| " 907 << S.TypeChar << " |" << right_justify(S.TypeName, 18) << "|" 908 << SymbolSizeStr << "| |" << S.SectionName << "\n"; 909 } 910 } 911 912 SymbolList.clear(); 913 } 914 915 static char getSymbolNMTypeChar(ELFObjectFileBase &Obj, 916 basic_symbol_iterator I) { 917 // OK, this is ELF 918 elf_symbol_iterator SymI(I); 919 920 Expected<elf_section_iterator> SecIOrErr = SymI->getSection(); 921 if (!SecIOrErr) { 922 consumeError(SecIOrErr.takeError()); 923 return '?'; 924 } 925 926 uint8_t Binding = SymI->getBinding(); 927 if (Binding == ELF::STB_GNU_UNIQUE) 928 return 'u'; 929 930 assert(Binding != ELF::STB_WEAK && "STB_WEAK not tested in calling function"); 931 if (Binding != ELF::STB_GLOBAL && Binding != ELF::STB_LOCAL) 932 return '?'; 933 934 elf_section_iterator SecI = *SecIOrErr; 935 if (SecI != Obj.section_end()) { 936 uint32_t Type = SecI->getType(); 937 uint64_t Flags = SecI->getFlags(); 938 if (Flags & ELF::SHF_EXECINSTR) 939 return 't'; 940 if (Type == ELF::SHT_NOBITS) 941 return 'b'; 942 if (Flags & ELF::SHF_ALLOC) 943 return Flags & ELF::SHF_WRITE ? 'd' : 'r'; 944 945 auto NameOrErr = SecI->getName(); 946 if (!NameOrErr) { 947 consumeError(NameOrErr.takeError()); 948 return '?'; 949 } 950 if ((*NameOrErr).startswith(".debug")) 951 return 'N'; 952 if (!(Flags & ELF::SHF_WRITE)) 953 return 'n'; 954 } 955 956 return '?'; 957 } 958 959 static char getSymbolNMTypeChar(COFFObjectFile &Obj, symbol_iterator I) { 960 COFFSymbolRef Symb = Obj.getCOFFSymbol(*I); 961 // OK, this is COFF. 962 symbol_iterator SymI(I); 963 964 Expected<StringRef> Name = SymI->getName(); 965 if (!Name) { 966 consumeError(Name.takeError()); 967 return '?'; 968 } 969 970 char Ret = StringSwitch<char>(*Name) 971 .StartsWith(".debug", 'N') 972 .StartsWith(".sxdata", 'N') 973 .Default('?'); 974 975 if (Ret != '?') 976 return Ret; 977 978 uint32_t Characteristics = 0; 979 if (!COFF::isReservedSectionNumber(Symb.getSectionNumber())) { 980 Expected<section_iterator> SecIOrErr = SymI->getSection(); 981 if (!SecIOrErr) { 982 consumeError(SecIOrErr.takeError()); 983 return '?'; 984 } 985 section_iterator SecI = *SecIOrErr; 986 const coff_section *Section = Obj.getCOFFSection(*SecI); 987 Characteristics = Section->Characteristics; 988 if (Expected<StringRef> NameOrErr = Obj.getSectionName(Section)) 989 if (NameOrErr->startswith(".idata")) 990 return 'i'; 991 } 992 993 switch (Symb.getSectionNumber()) { 994 case COFF::IMAGE_SYM_DEBUG: 995 return 'n'; 996 default: 997 // Check section type. 998 if (Characteristics & COFF::IMAGE_SCN_CNT_CODE) 999 return 't'; 1000 if (Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA) 1001 return Characteristics & COFF::IMAGE_SCN_MEM_WRITE ? 'd' : 'r'; 1002 if (Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) 1003 return 'b'; 1004 if (Characteristics & COFF::IMAGE_SCN_LNK_INFO) 1005 return 'i'; 1006 // Check for section symbol. 1007 if (Symb.isSectionDefinition()) 1008 return 's'; 1009 } 1010 1011 return '?'; 1012 } 1013 1014 static char getSymbolNMTypeChar(COFFImportFile &Obj) { 1015 switch (Obj.getCOFFImportHeader()->getType()) { 1016 case COFF::IMPORT_CODE: 1017 return 't'; 1018 case COFF::IMPORT_DATA: 1019 return 'd'; 1020 case COFF::IMPORT_CONST: 1021 return 'r'; 1022 } 1023 return '?'; 1024 } 1025 1026 static char getSymbolNMTypeChar(MachOObjectFile &Obj, basic_symbol_iterator I) { 1027 DataRefImpl Symb = I->getRawDataRefImpl(); 1028 uint8_t NType = Obj.is64Bit() ? Obj.getSymbol64TableEntry(Symb).n_type 1029 : Obj.getSymbolTableEntry(Symb).n_type; 1030 1031 if (NType & MachO::N_STAB) 1032 return '-'; 1033 1034 switch (NType & MachO::N_TYPE) { 1035 case MachO::N_ABS: 1036 return 's'; 1037 case MachO::N_INDR: 1038 return 'i'; 1039 case MachO::N_SECT: { 1040 Expected<section_iterator> SecOrErr = Obj.getSymbolSection(Symb); 1041 if (!SecOrErr) { 1042 consumeError(SecOrErr.takeError()); 1043 return 's'; 1044 } 1045 section_iterator Sec = *SecOrErr; 1046 if (Sec == Obj.section_end()) 1047 return 's'; 1048 DataRefImpl Ref = Sec->getRawDataRefImpl(); 1049 StringRef SectionName; 1050 if (Expected<StringRef> NameOrErr = Obj.getSectionName(Ref)) 1051 SectionName = *NameOrErr; 1052 StringRef SegmentName = Obj.getSectionFinalSegmentName(Ref); 1053 if (Obj.is64Bit() && Obj.getHeader64().filetype == MachO::MH_KEXT_BUNDLE && 1054 SegmentName == "__TEXT_EXEC" && SectionName == "__text") 1055 return 't'; 1056 if (SegmentName == "__TEXT" && SectionName == "__text") 1057 return 't'; 1058 if (SegmentName == "__DATA" && SectionName == "__data") 1059 return 'd'; 1060 if (SegmentName == "__DATA" && SectionName == "__bss") 1061 return 'b'; 1062 return 's'; 1063 } 1064 } 1065 1066 return '?'; 1067 } 1068 1069 static char getSymbolNMTypeChar(TapiFile &Obj, basic_symbol_iterator I) { 1070 return 's'; 1071 } 1072 1073 static char getSymbolNMTypeChar(WasmObjectFile &Obj, basic_symbol_iterator I) { 1074 uint32_t Flags = cantFail(I->getFlags()); 1075 if (Flags & SymbolRef::SF_Executable) 1076 return 't'; 1077 return 'd'; 1078 } 1079 1080 static char getSymbolNMTypeChar(IRObjectFile &Obj, basic_symbol_iterator I) { 1081 uint32_t Flags = cantFail(I->getFlags()); 1082 // FIXME: should we print 'b'? At the IR level we cannot be sure if this 1083 // will be in bss or not, but we could approximate. 1084 if (Flags & SymbolRef::SF_Executable) 1085 return 't'; 1086 else if (Triple(Obj.getTargetTriple()).isOSDarwin() && 1087 (Flags & SymbolRef::SF_Const)) 1088 return 's'; 1089 else 1090 return 'd'; 1091 } 1092 1093 static bool isObject(SymbolicFile &Obj, basic_symbol_iterator I) { 1094 return isa<ELFObjectFileBase>(&Obj) && 1095 elf_symbol_iterator(I)->getELFType() == ELF::STT_OBJECT; 1096 } 1097 1098 // For ELF object files, Set TypeName to the symbol typename, to be printed 1099 // in the 'Type' column of the SYSV format output. 1100 static StringRef getNMTypeName(SymbolicFile &Obj, basic_symbol_iterator I) { 1101 if (isa<ELFObjectFileBase>(&Obj)) { 1102 elf_symbol_iterator SymI(I); 1103 return SymI->getELFTypeName(); 1104 } 1105 return ""; 1106 } 1107 1108 // Return Posix nm class type tag (single letter), but also set SecName and 1109 // section and name, to be used in format=sysv output. 1110 static char getNMSectionTagAndName(SymbolicFile &Obj, basic_symbol_iterator I, 1111 StringRef &SecName) { 1112 // Symbol Flags have been checked in the caller. 1113 uint32_t Symflags = cantFail(I->getFlags()); 1114 if (ELFObjectFileBase *ELFObj = dyn_cast<ELFObjectFileBase>(&Obj)) { 1115 if (Symflags & object::SymbolRef::SF_Absolute) 1116 SecName = "*ABS*"; 1117 else if (Symflags & object::SymbolRef::SF_Common) 1118 SecName = "*COM*"; 1119 else if (Symflags & object::SymbolRef::SF_Undefined) 1120 SecName = "*UND*"; 1121 else { 1122 elf_symbol_iterator SymI(I); 1123 Expected<elf_section_iterator> SecIOrErr = SymI->getSection(); 1124 if (!SecIOrErr) { 1125 consumeError(SecIOrErr.takeError()); 1126 return '?'; 1127 } 1128 1129 if (*SecIOrErr == ELFObj->section_end()) 1130 return '?'; 1131 1132 Expected<StringRef> NameOrErr = (*SecIOrErr)->getName(); 1133 if (!NameOrErr) { 1134 consumeError(NameOrErr.takeError()); 1135 return '?'; 1136 } 1137 SecName = *NameOrErr; 1138 } 1139 } 1140 1141 if (Symflags & object::SymbolRef::SF_Undefined) { 1142 if (isa<MachOObjectFile>(Obj) || !(Symflags & object::SymbolRef::SF_Weak)) 1143 return 'U'; 1144 return isObject(Obj, I) ? 'v' : 'w'; 1145 } 1146 if (isa<ELFObjectFileBase>(&Obj)) 1147 if (ELFSymbolRef(*I).getELFType() == ELF::STT_GNU_IFUNC) 1148 return 'i'; 1149 if (!isa<MachOObjectFile>(Obj) && (Symflags & object::SymbolRef::SF_Weak)) 1150 return isObject(Obj, I) ? 'V' : 'W'; 1151 1152 if (Symflags & object::SymbolRef::SF_Common) 1153 return 'C'; 1154 1155 char Ret = '?'; 1156 if (Symflags & object::SymbolRef::SF_Absolute) 1157 Ret = 'a'; 1158 else if (IRObjectFile *IR = dyn_cast<IRObjectFile>(&Obj)) 1159 Ret = getSymbolNMTypeChar(*IR, I); 1160 else if (COFFObjectFile *COFF = dyn_cast<COFFObjectFile>(&Obj)) 1161 Ret = getSymbolNMTypeChar(*COFF, I); 1162 else if (COFFImportFile *COFFImport = dyn_cast<COFFImportFile>(&Obj)) 1163 Ret = getSymbolNMTypeChar(*COFFImport); 1164 else if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj)) 1165 Ret = getSymbolNMTypeChar(*MachO, I); 1166 else if (WasmObjectFile *Wasm = dyn_cast<WasmObjectFile>(&Obj)) 1167 Ret = getSymbolNMTypeChar(*Wasm, I); 1168 else if (TapiFile *Tapi = dyn_cast<TapiFile>(&Obj)) 1169 Ret = getSymbolNMTypeChar(*Tapi, I); 1170 else if (ELFObjectFileBase *ELF = dyn_cast<ELFObjectFileBase>(&Obj)) { 1171 Ret = getSymbolNMTypeChar(*ELF, I); 1172 if (ELFSymbolRef(*I).getBinding() == ELF::STB_GNU_UNIQUE) 1173 return Ret; 1174 } else 1175 llvm_unreachable("unknown binary format"); 1176 1177 if (!(Symflags & object::SymbolRef::SF_Global)) 1178 return Ret; 1179 1180 return toupper(Ret); 1181 } 1182 1183 // getNsectForSegSect() is used to implement the Mach-O "-s segname sectname" 1184 // option to dump only those symbols from that section in a Mach-O file. 1185 // It is called once for each Mach-O file from dumpSymbolNamesFromObject() 1186 // to get the section number for that named section from the command line 1187 // arguments. It returns the section number for that section in the Mach-O 1188 // file or zero it is not present. 1189 static unsigned getNsectForSegSect(MachOObjectFile *Obj) { 1190 unsigned Nsect = 1; 1191 for (auto &S : Obj->sections()) { 1192 DataRefImpl Ref = S.getRawDataRefImpl(); 1193 StringRef SectionName; 1194 if (Expected<StringRef> NameOrErr = Obj->getSectionName(Ref)) 1195 SectionName = *NameOrErr; 1196 StringRef SegmentName = Obj->getSectionFinalSegmentName(Ref); 1197 if (SegmentName == SegSect[0] && SectionName == SegSect[1]) 1198 return Nsect; 1199 Nsect++; 1200 } 1201 return 0; 1202 } 1203 1204 // getNsectInMachO() is used to implement the Mach-O "-s segname sectname" 1205 // option to dump only those symbols from that section in a Mach-O file. 1206 // It is called once for each symbol in a Mach-O file from 1207 // dumpSymbolNamesFromObject() and returns the section number for that symbol 1208 // if it is in a section, else it returns 0. 1209 static unsigned getNsectInMachO(MachOObjectFile &Obj, BasicSymbolRef Sym) { 1210 DataRefImpl Symb = Sym.getRawDataRefImpl(); 1211 if (Obj.is64Bit()) { 1212 MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb); 1213 return (STE.n_type & MachO::N_TYPE) == MachO::N_SECT ? STE.n_sect : 0; 1214 } 1215 MachO::nlist STE = Obj.getSymbolTableEntry(Symb); 1216 return (STE.n_type & MachO::N_TYPE) == MachO::N_SECT ? STE.n_sect : 0; 1217 } 1218 1219 static void dumpSymbolsFromDLInfoMachO(MachOObjectFile &MachO) { 1220 size_t I = SymbolList.size(); 1221 std::string ExportsNameBuffer; 1222 raw_string_ostream EOS(ExportsNameBuffer); 1223 std::string BindsNameBuffer; 1224 raw_string_ostream BOS(BindsNameBuffer); 1225 std::string LazysNameBuffer; 1226 raw_string_ostream LOS(LazysNameBuffer); 1227 std::string WeaksNameBuffer; 1228 raw_string_ostream WOS(WeaksNameBuffer); 1229 std::string FunctionStartsNameBuffer; 1230 raw_string_ostream FOS(FunctionStartsNameBuffer); 1231 1232 MachO::mach_header H; 1233 MachO::mach_header_64 H_64; 1234 uint32_t HFlags = 0; 1235 if (MachO.is64Bit()) { 1236 H_64 = MachO.MachOObjectFile::getHeader64(); 1237 HFlags = H_64.flags; 1238 } else { 1239 H = MachO.MachOObjectFile::getHeader(); 1240 HFlags = H.flags; 1241 } 1242 uint64_t BaseSegmentAddress = 0; 1243 for (const auto &Command : MachO.load_commands()) { 1244 if (Command.C.cmd == MachO::LC_SEGMENT) { 1245 MachO::segment_command Seg = MachO.getSegmentLoadCommand(Command); 1246 if (Seg.fileoff == 0 && Seg.filesize != 0) { 1247 BaseSegmentAddress = Seg.vmaddr; 1248 break; 1249 } 1250 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) { 1251 MachO::segment_command_64 Seg = MachO.getSegment64LoadCommand(Command); 1252 if (Seg.fileoff == 0 && Seg.filesize != 0) { 1253 BaseSegmentAddress = Seg.vmaddr; 1254 break; 1255 } 1256 } 1257 } 1258 if (DyldInfoOnly || AddDyldInfo || 1259 HFlags & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) { 1260 unsigned ExportsAdded = 0; 1261 Error Err = Error::success(); 1262 for (const llvm::object::ExportEntry &Entry : MachO.exports(Err)) { 1263 bool found = false; 1264 bool ReExport = false; 1265 if (!DyldInfoOnly) { 1266 for (const NMSymbol &S : SymbolList) 1267 if (S.Address == Entry.address() + BaseSegmentAddress && 1268 S.Name == Entry.name()) { 1269 found = true; 1270 break; 1271 } 1272 } 1273 if (!found) { 1274 NMSymbol S = {}; 1275 S.Address = Entry.address() + BaseSegmentAddress; 1276 S.Size = 0; 1277 S.TypeChar = '\0'; 1278 S.Name = Entry.name().str(); 1279 // There is no symbol in the nlist symbol table for this so we set 1280 // Sym effectivly to null and the rest of code in here must test for 1281 // it and not do things like Sym.getFlags() for it. 1282 S.Sym = BasicSymbolRef(); 1283 S.SymFlags = SymbolRef::SF_Global; 1284 S.Section = SectionRef(); 1285 S.NType = 0; 1286 S.NSect = 0; 1287 S.NDesc = 0; 1288 1289 uint64_t EFlags = Entry.flags(); 1290 bool Abs = ((EFlags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) == 1291 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE); 1292 bool Resolver = (EFlags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER); 1293 ReExport = (EFlags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT); 1294 bool WeakDef = (EFlags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION); 1295 if (WeakDef) 1296 S.NDesc |= MachO::N_WEAK_DEF; 1297 if (Abs) { 1298 S.NType = MachO::N_EXT | MachO::N_ABS; 1299 S.TypeChar = 'A'; 1300 } else if (ReExport) { 1301 S.NType = MachO::N_EXT | MachO::N_INDR; 1302 S.TypeChar = 'I'; 1303 } else { 1304 S.NType = MachO::N_EXT | MachO::N_SECT; 1305 if (Resolver) { 1306 S.Address = Entry.other() + BaseSegmentAddress; 1307 if ((S.Address & 1) != 0 && !MachO.is64Bit() && 1308 H.cputype == MachO::CPU_TYPE_ARM) { 1309 S.Address &= ~1LL; 1310 S.NDesc |= MachO::N_ARM_THUMB_DEF; 1311 } 1312 } else { 1313 S.Address = Entry.address() + BaseSegmentAddress; 1314 } 1315 StringRef SegmentName = StringRef(); 1316 StringRef SectionName = StringRef(); 1317 for (const SectionRef &Section : MachO.sections()) { 1318 S.NSect++; 1319 1320 if (Expected<StringRef> NameOrErr = Section.getName()) 1321 SectionName = *NameOrErr; 1322 else 1323 consumeError(NameOrErr.takeError()); 1324 1325 SegmentName = 1326 MachO.getSectionFinalSegmentName(Section.getRawDataRefImpl()); 1327 if (S.Address >= Section.getAddress() && 1328 S.Address < Section.getAddress() + Section.getSize()) { 1329 S.Section = Section; 1330 break; 1331 } else if (Entry.name() == "__mh_execute_header" && 1332 SegmentName == "__TEXT" && SectionName == "__text") { 1333 S.Section = Section; 1334 S.NDesc |= MachO::REFERENCED_DYNAMICALLY; 1335 break; 1336 } 1337 } 1338 if (SegmentName == "__TEXT" && SectionName == "__text") 1339 S.TypeChar = 'T'; 1340 else if (SegmentName == "__DATA" && SectionName == "__data") 1341 S.TypeChar = 'D'; 1342 else if (SegmentName == "__DATA" && SectionName == "__bss") 1343 S.TypeChar = 'B'; 1344 else 1345 S.TypeChar = 'S'; 1346 } 1347 SymbolList.push_back(S); 1348 1349 EOS << Entry.name(); 1350 EOS << '\0'; 1351 ExportsAdded++; 1352 1353 // For ReExports there are a two more things to do, first add the 1354 // indirect name and second create the undefined symbol using the 1355 // referened dynamic library. 1356 if (ReExport) { 1357 1358 // Add the indirect name. 1359 if (Entry.otherName().empty()) 1360 EOS << Entry.name(); 1361 else 1362 EOS << Entry.otherName(); 1363 EOS << '\0'; 1364 1365 // Now create the undefined symbol using the referened dynamic 1366 // library. 1367 NMSymbol U = {}; 1368 U.Address = 0; 1369 U.Size = 0; 1370 U.TypeChar = 'U'; 1371 if (Entry.otherName().empty()) 1372 U.Name = Entry.name().str(); 1373 else 1374 U.Name = Entry.otherName().str(); 1375 // Again there is no symbol in the nlist symbol table for this so 1376 // we set Sym effectivly to null and the rest of code in here must 1377 // test for it and not do things like Sym.getFlags() for it. 1378 U.Sym = BasicSymbolRef(); 1379 U.SymFlags = SymbolRef::SF_Global | SymbolRef::SF_Undefined; 1380 U.Section = SectionRef(); 1381 U.NType = MachO::N_EXT | MachO::N_UNDF; 1382 U.NSect = 0; 1383 U.NDesc = 0; 1384 // The library ordinal for this undefined symbol is in the export 1385 // trie Entry.other(). 1386 MachO::SET_LIBRARY_ORDINAL(U.NDesc, Entry.other()); 1387 SymbolList.push_back(U); 1388 1389 // Finally add the undefined symbol's name. 1390 if (Entry.otherName().empty()) 1391 EOS << Entry.name(); 1392 else 1393 EOS << Entry.otherName(); 1394 EOS << '\0'; 1395 ExportsAdded++; 1396 } 1397 } 1398 } 1399 if (Err) 1400 error(std::move(Err), MachO.getFileName()); 1401 // Set the symbol names and indirect names for the added symbols. 1402 if (ExportsAdded) { 1403 EOS.flush(); 1404 const char *Q = ExportsNameBuffer.c_str(); 1405 for (unsigned K = 0; K < ExportsAdded; K++) { 1406 SymbolList[I].Name = Q; 1407 Q += strlen(Q) + 1; 1408 if (SymbolList[I].TypeChar == 'I') { 1409 SymbolList[I].IndirectName = Q; 1410 Q += strlen(Q) + 1; 1411 } 1412 I++; 1413 } 1414 } 1415 1416 // Add the undefined symbols from the bind entries. 1417 unsigned BindsAdded = 0; 1418 Error BErr = Error::success(); 1419 StringRef LastSymbolName = StringRef(); 1420 for (const llvm::object::MachOBindEntry &Entry : MachO.bindTable(BErr)) { 1421 bool found = false; 1422 if (LastSymbolName == Entry.symbolName()) 1423 found = true; 1424 else if (!DyldInfoOnly) { 1425 for (unsigned J = 0; J < SymbolList.size() && !found; ++J) { 1426 if (SymbolList[J].Name == Entry.symbolName()) 1427 found = true; 1428 } 1429 } 1430 if (!found) { 1431 LastSymbolName = Entry.symbolName(); 1432 NMSymbol B = {}; 1433 B.Address = 0; 1434 B.Size = 0; 1435 B.TypeChar = 'U'; 1436 // There is no symbol in the nlist symbol table for this so we set 1437 // Sym effectivly to null and the rest of code in here must test for 1438 // it and not do things like Sym.getFlags() for it. 1439 B.Sym = BasicSymbolRef(); 1440 B.SymFlags = SymbolRef::SF_Global | SymbolRef::SF_Undefined; 1441 B.NType = MachO::N_EXT | MachO::N_UNDF; 1442 B.NSect = 0; 1443 B.NDesc = 0; 1444 MachO::SET_LIBRARY_ORDINAL(B.NDesc, Entry.ordinal()); 1445 B.Name = Entry.symbolName().str(); 1446 SymbolList.push_back(B); 1447 BOS << Entry.symbolName(); 1448 BOS << '\0'; 1449 BindsAdded++; 1450 } 1451 } 1452 if (BErr) 1453 error(std::move(BErr), MachO.getFileName()); 1454 // Set the symbol names and indirect names for the added symbols. 1455 if (BindsAdded) { 1456 BOS.flush(); 1457 const char *Q = BindsNameBuffer.c_str(); 1458 for (unsigned K = 0; K < BindsAdded; K++) { 1459 SymbolList[I].Name = Q; 1460 Q += strlen(Q) + 1; 1461 if (SymbolList[I].TypeChar == 'I') { 1462 SymbolList[I].IndirectName = Q; 1463 Q += strlen(Q) + 1; 1464 } 1465 I++; 1466 } 1467 } 1468 1469 // Add the undefined symbols from the lazy bind entries. 1470 unsigned LazysAdded = 0; 1471 Error LErr = Error::success(); 1472 LastSymbolName = StringRef(); 1473 for (const llvm::object::MachOBindEntry &Entry : 1474 MachO.lazyBindTable(LErr)) { 1475 bool found = false; 1476 if (LastSymbolName == Entry.symbolName()) 1477 found = true; 1478 else { 1479 // Here we must check to see it this symbol is already in the 1480 // SymbolList as it might have already have been added above via a 1481 // non-lazy (bind) entry. 1482 for (unsigned J = 0; J < SymbolList.size() && !found; ++J) { 1483 if (SymbolList[J].Name == Entry.symbolName()) 1484 found = true; 1485 } 1486 } 1487 if (!found) { 1488 LastSymbolName = Entry.symbolName(); 1489 NMSymbol L = {}; 1490 L.Name = Entry.symbolName().str(); 1491 L.Address = 0; 1492 L.Size = 0; 1493 L.TypeChar = 'U'; 1494 // There is no symbol in the nlist symbol table for this so we set 1495 // Sym effectivly to null and the rest of code in here must test for 1496 // it and not do things like Sym.getFlags() for it. 1497 L.Sym = BasicSymbolRef(); 1498 L.SymFlags = SymbolRef::SF_Global | SymbolRef::SF_Undefined; 1499 L.NType = MachO::N_EXT | MachO::N_UNDF; 1500 L.NSect = 0; 1501 // The REFERENCE_FLAG_UNDEFINED_LAZY is no longer used but here it 1502 // makes sence since we are creating this from a lazy bind entry. 1503 L.NDesc = MachO::REFERENCE_FLAG_UNDEFINED_LAZY; 1504 MachO::SET_LIBRARY_ORDINAL(L.NDesc, Entry.ordinal()); 1505 SymbolList.push_back(L); 1506 LOS << Entry.symbolName(); 1507 LOS << '\0'; 1508 LazysAdded++; 1509 } 1510 } 1511 if (LErr) 1512 error(std::move(LErr), MachO.getFileName()); 1513 // Set the symbol names and indirect names for the added symbols. 1514 if (LazysAdded) { 1515 LOS.flush(); 1516 const char *Q = LazysNameBuffer.c_str(); 1517 for (unsigned K = 0; K < LazysAdded; K++) { 1518 SymbolList[I].Name = Q; 1519 Q += strlen(Q) + 1; 1520 if (SymbolList[I].TypeChar == 'I') { 1521 SymbolList[I].IndirectName = Q; 1522 Q += strlen(Q) + 1; 1523 } 1524 I++; 1525 } 1526 } 1527 1528 // Add the undefineds symbol from the weak bind entries which are not 1529 // strong symbols. 1530 unsigned WeaksAdded = 0; 1531 Error WErr = Error::success(); 1532 LastSymbolName = StringRef(); 1533 for (const llvm::object::MachOBindEntry &Entry : 1534 MachO.weakBindTable(WErr)) { 1535 bool found = false; 1536 unsigned J = 0; 1537 if (LastSymbolName == Entry.symbolName() || 1538 Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) { 1539 found = true; 1540 } else { 1541 for (J = 0; J < SymbolList.size() && !found; ++J) { 1542 if (SymbolList[J].Name == Entry.symbolName()) { 1543 found = true; 1544 break; 1545 } 1546 } 1547 } 1548 if (!found) { 1549 LastSymbolName = Entry.symbolName(); 1550 NMSymbol W = {}; 1551 W.Name = Entry.symbolName().str(); 1552 W.Address = 0; 1553 W.Size = 0; 1554 W.TypeChar = 'U'; 1555 // There is no symbol in the nlist symbol table for this so we set 1556 // Sym effectivly to null and the rest of code in here must test for 1557 // it and not do things like Sym.getFlags() for it. 1558 W.Sym = BasicSymbolRef(); 1559 W.SymFlags = SymbolRef::SF_Global | SymbolRef::SF_Undefined; 1560 W.NType = MachO::N_EXT | MachO::N_UNDF; 1561 W.NSect = 0; 1562 // Odd that we are using N_WEAK_DEF on an undefined symbol but that is 1563 // what is created in this case by the linker when there are real 1564 // symbols in the nlist structs. 1565 W.NDesc = MachO::N_WEAK_DEF; 1566 SymbolList.push_back(W); 1567 WOS << Entry.symbolName(); 1568 WOS << '\0'; 1569 WeaksAdded++; 1570 } else { 1571 // This is the case the symbol was previously been found and it could 1572 // have been added from a bind or lazy bind symbol. If so and not 1573 // a definition also mark it as weak. 1574 if (SymbolList[J].TypeChar == 'U') 1575 // See comment above about N_WEAK_DEF. 1576 SymbolList[J].NDesc |= MachO::N_WEAK_DEF; 1577 } 1578 } 1579 if (WErr) 1580 error(std::move(WErr), MachO.getFileName()); 1581 // Set the symbol names and indirect names for the added symbols. 1582 if (WeaksAdded) { 1583 WOS.flush(); 1584 const char *Q = WeaksNameBuffer.c_str(); 1585 for (unsigned K = 0; K < WeaksAdded; K++) { 1586 SymbolList[I].Name = Q; 1587 Q += strlen(Q) + 1; 1588 if (SymbolList[I].TypeChar == 'I') { 1589 SymbolList[I].IndirectName = Q; 1590 Q += strlen(Q) + 1; 1591 } 1592 I++; 1593 } 1594 } 1595 1596 // Trying adding symbol from the function starts table and LC_MAIN entry 1597 // point. 1598 SmallVector<uint64_t, 8> FoundFns; 1599 uint64_t lc_main_offset = UINT64_MAX; 1600 for (const auto &Command : MachO.load_commands()) { 1601 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) { 1602 // We found a function starts segment, parse the addresses for 1603 // consumption. 1604 MachO::linkedit_data_command LLC = 1605 MachO.getLinkeditDataLoadCommand(Command); 1606 1607 MachO.ReadULEB128s(LLC.dataoff, FoundFns); 1608 } else if (Command.C.cmd == MachO::LC_MAIN) { 1609 MachO::entry_point_command LCmain = MachO.getEntryPointCommand(Command); 1610 lc_main_offset = LCmain.entryoff; 1611 } 1612 } 1613 // See if these addresses are already in the symbol table. 1614 unsigned FunctionStartsAdded = 0; 1615 for (uint64_t f = 0; f < FoundFns.size(); f++) { 1616 bool found = false; 1617 for (unsigned J = 0; J < SymbolList.size() && !found; ++J) { 1618 if (SymbolList[J].Address == FoundFns[f] + BaseSegmentAddress) 1619 found = true; 1620 } 1621 // See this address is not already in the symbol table fake up an 1622 // nlist for it. 1623 if (!found) { 1624 NMSymbol F = {}; 1625 F.Name = "<redacted function X>"; 1626 F.Address = FoundFns[f] + BaseSegmentAddress; 1627 F.Size = 0; 1628 // There is no symbol in the nlist symbol table for this so we set 1629 // Sym effectivly to null and the rest of code in here must test for 1630 // it and not do things like Sym.getFlags() for it. 1631 F.Sym = BasicSymbolRef(); 1632 F.SymFlags = 0; 1633 F.NType = MachO::N_SECT; 1634 F.NSect = 0; 1635 StringRef SegmentName = StringRef(); 1636 StringRef SectionName = StringRef(); 1637 for (const SectionRef &Section : MachO.sections()) { 1638 if (Expected<StringRef> NameOrErr = Section.getName()) 1639 SectionName = *NameOrErr; 1640 else 1641 consumeError(NameOrErr.takeError()); 1642 1643 SegmentName = 1644 MachO.getSectionFinalSegmentName(Section.getRawDataRefImpl()); 1645 F.NSect++; 1646 if (F.Address >= Section.getAddress() && 1647 F.Address < Section.getAddress() + Section.getSize()) { 1648 F.Section = Section; 1649 break; 1650 } 1651 } 1652 if (SegmentName == "__TEXT" && SectionName == "__text") 1653 F.TypeChar = 't'; 1654 else if (SegmentName == "__DATA" && SectionName == "__data") 1655 F.TypeChar = 'd'; 1656 else if (SegmentName == "__DATA" && SectionName == "__bss") 1657 F.TypeChar = 'b'; 1658 else 1659 F.TypeChar = 's'; 1660 F.NDesc = 0; 1661 SymbolList.push_back(F); 1662 if (FoundFns[f] == lc_main_offset) 1663 FOS << "<redacted LC_MAIN>"; 1664 else 1665 FOS << "<redacted function " << f << ">"; 1666 FOS << '\0'; 1667 FunctionStartsAdded++; 1668 } 1669 } 1670 if (FunctionStartsAdded) { 1671 FOS.flush(); 1672 const char *Q = FunctionStartsNameBuffer.c_str(); 1673 for (unsigned K = 0; K < FunctionStartsAdded; K++) { 1674 SymbolList[I].Name = Q; 1675 Q += strlen(Q) + 1; 1676 if (SymbolList[I].TypeChar == 'I') { 1677 SymbolList[I].IndirectName = Q; 1678 Q += strlen(Q) + 1; 1679 } 1680 I++; 1681 } 1682 } 1683 } 1684 } 1685 1686 namespace { 1687 struct SymbolVersion { 1688 std::string Name; 1689 bool IsDefault; 1690 }; 1691 } // namespace 1692 1693 template <class ELFT> 1694 static Expected<std::vector<SymbolVersion>> 1695 readSymbolVersionsELF(const ELFFile<ELFT> &Obj, StringRef FileName, 1696 ELFObjectFileBase::elf_symbol_iterator_range Symbols) { 1697 using Elf_Shdr = typename ELFT::Shdr; 1698 1699 // We called sections() earlier, so can't fail here. 1700 typename ELFT::ShdrRange SectionsOrErr = cantFail(Obj.sections()); 1701 const Elf_Shdr *SymVerSec = nullptr; 1702 const Elf_Shdr *SymVerNeedSec = nullptr; 1703 const Elf_Shdr *SymVerDefSec = nullptr; 1704 for (const Elf_Shdr &Sec : SectionsOrErr) { 1705 if (Sec.sh_type == ELF::SHT_GNU_versym) 1706 SymVerSec = &Sec; 1707 else if (Sec.sh_type == ELF::SHT_GNU_verdef) 1708 SymVerDefSec = &Sec; 1709 else if (Sec.sh_type == ELF::SHT_GNU_verneed) 1710 SymVerNeedSec = &Sec; 1711 } 1712 1713 if (!SymVerSec) 1714 return std::vector<SymbolVersion>{}; 1715 1716 Expected<SmallVector<Optional<VersionEntry>, 0>> MapOrErr = 1717 Obj.loadVersionMap(SymVerNeedSec, SymVerDefSec); 1718 if (!MapOrErr) 1719 return MapOrErr.takeError(); 1720 1721 std::vector<SymbolVersion> Ret; 1722 size_t I = 0; 1723 for (auto It = Symbols.begin(), E = Symbols.end(); It != E; ++It) { 1724 ++I; 1725 Expected<const typename ELFT::Versym *> VerEntryOrErr = 1726 Obj.template getEntry<typename ELFT::Versym>(*SymVerSec, I); 1727 if (!VerEntryOrErr) 1728 return createError("unable to read an entry with index " + Twine(I) + 1729 " from " + describe(Obj, *SymVerSec) + ": " + 1730 toString(VerEntryOrErr.takeError())); 1731 1732 Expected<uint32_t> FlagsOrErr = It->getFlags(); 1733 if (!FlagsOrErr) 1734 return createError("unable to read flags for symbol with index " + 1735 Twine(I) + ": " + toString(FlagsOrErr.takeError())); 1736 1737 bool IsDefault; 1738 Expected<StringRef> VerOrErr = Obj.getSymbolVersionByIndex( 1739 (*VerEntryOrErr)->vs_index, IsDefault, *MapOrErr, 1740 (*FlagsOrErr) & SymbolRef::SF_Undefined); 1741 if (!VerOrErr) 1742 return createError("unable to get a version for entry " + Twine(I) + 1743 " of " + describe(Obj, *SymVerSec) + ": " + 1744 toString(VerOrErr.takeError())); 1745 1746 Ret.push_back({(*VerOrErr).str(), IsDefault}); 1747 } 1748 1749 return Ret; 1750 } 1751 1752 static Expected<std::vector<SymbolVersion>> 1753 readSymbolVersionsELF(const ELFObjectFileBase &Obj, 1754 ELFObjectFileBase::elf_symbol_iterator_range Symbols) { 1755 if (const auto *ELF = dyn_cast<ELF32LEObjectFile>(&Obj)) 1756 return readSymbolVersionsELF(ELF->getELFFile(), Obj.getFileName(), Symbols); 1757 else if (const auto *ELF = dyn_cast<ELF32BEObjectFile>(&Obj)) 1758 return readSymbolVersionsELF(ELF->getELFFile(), Obj.getFileName(), Symbols); 1759 else if (const auto *ELF = dyn_cast<ELF64LEObjectFile>(&Obj)) 1760 return readSymbolVersionsELF(ELF->getELFFile(), Obj.getFileName(), Symbols); 1761 return readSymbolVersionsELF(cast<ELF64BEObjectFile>(&Obj)->getELFFile(), 1762 Obj.getFileName(), Symbols); 1763 } 1764 1765 static void dumpSymbolNamesFromObject(SymbolicFile &Obj, bool printName, 1766 StringRef ArchiveName = {}, 1767 StringRef ArchitectureName = {}) { 1768 auto Symbols = Obj.symbols(); 1769 std::vector<SymbolVersion> SymbolVersions; 1770 if (DynamicSyms) { 1771 const auto *E = dyn_cast<ELFObjectFileBase>(&Obj); 1772 if (!E) { 1773 error("File format has no dynamic symbol table", Obj.getFileName()); 1774 return; 1775 } 1776 Symbols = E->getDynamicSymbolIterators(); 1777 1778 if (Expected<std::vector<SymbolVersion>> VersionsOrErr = 1779 readSymbolVersionsELF(*E, Symbols)) 1780 SymbolVersions = std::move(*VersionsOrErr); 1781 else 1782 WithColor::warning(errs(), ToolName) 1783 << "unable to read symbol versions: " 1784 << toString(VersionsOrErr.takeError()) << "\n"; 1785 } 1786 1787 // If a "-s segname sectname" option was specified and this is a Mach-O 1788 // file get the section number for that section in this object file. 1789 unsigned int Nsect = 0; 1790 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj); 1791 if (!SegSect.empty() && MachO) { 1792 Nsect = getNsectForSegSect(MachO); 1793 // If this section is not in the object file no symbols are printed. 1794 if (Nsect == 0) 1795 return; 1796 } 1797 if (!(MachO && DyldInfoOnly)) { 1798 size_t I = -1; 1799 for (BasicSymbolRef Sym : Symbols) { 1800 ++I; 1801 Expected<uint32_t> SymFlagsOrErr = Sym.getFlags(); 1802 if (!SymFlagsOrErr) { 1803 error(SymFlagsOrErr.takeError(), Obj.getFileName()); 1804 return; 1805 } 1806 1807 // Don't drop format specifc symbols for ARM and AArch64 ELF targets, they 1808 // are used to repesent mapping symbols and needed to honor the 1809 // --special-syms option. 1810 auto *ELFObj = dyn_cast<ELFObjectFileBase>(&Obj); 1811 if ((!ELFObj || (ELFObj->getEMachine() != ELF::EM_ARM && 1812 ELFObj->getEMachine() != ELF::EM_AARCH64)) && 1813 !DebugSyms && (*SymFlagsOrErr & SymbolRef::SF_FormatSpecific)) 1814 continue; 1815 if (WithoutAliases && (*SymFlagsOrErr & SymbolRef::SF_Indirect)) 1816 continue; 1817 // If a "-s segname sectname" option was specified and this is a Mach-O 1818 // file and this section appears in this file, Nsect will be non-zero then 1819 // see if this symbol is a symbol from that section and if not skip it. 1820 if (Nsect && Nsect != getNsectInMachO(*MachO, Sym)) 1821 continue; 1822 NMSymbol S = {}; 1823 S.Size = 0; 1824 S.Address = 0; 1825 if (isa<ELFObjectFileBase>(&Obj)) 1826 S.Size = ELFSymbolRef(Sym).getSize(); 1827 if (PrintAddress && isa<ObjectFile>(Obj)) { 1828 SymbolRef SymRef(Sym); 1829 Expected<uint64_t> AddressOrErr = SymRef.getAddress(); 1830 if (!AddressOrErr) { 1831 consumeError(AddressOrErr.takeError()); 1832 break; 1833 } 1834 S.Address = *AddressOrErr; 1835 } 1836 S.TypeName = getNMTypeName(Obj, Sym); 1837 S.TypeChar = getNMSectionTagAndName(Obj, Sym, S.SectionName); 1838 1839 raw_string_ostream OS(S.Name); 1840 if (Error E = Sym.printName(OS)) { 1841 if (MachO) { 1842 OS << "bad string index"; 1843 consumeError(std::move(E)); 1844 } else 1845 error(std::move(E), Obj.getFileName()); 1846 } 1847 if (!SymbolVersions.empty() && !SymbolVersions[I].Name.empty()) 1848 S.Name += 1849 (SymbolVersions[I].IsDefault ? "@@" : "@") + SymbolVersions[I].Name; 1850 1851 S.Sym = Sym; 1852 SymbolList.push_back(S); 1853 } 1854 } 1855 1856 // If this is a Mach-O file where the nlist symbol table is out of sync 1857 // with the dyld export trie then look through exports and fake up symbols 1858 // for the ones that are missing (also done with the -add-dyldinfo flag). 1859 // This is needed if strip(1) -T is run on a binary containing swift 1860 // language symbols for example. The option -only-dyldinfo will fake up 1861 // all symbols from the dyld export trie as well as the bind info. 1862 if (MachO && !NoDyldInfo) 1863 dumpSymbolsFromDLInfoMachO(*MachO); 1864 1865 CurrentFilename = Obj.getFileName(); 1866 1867 if (Symbols.empty() && SymbolList.empty() && !Quiet) { 1868 writeFileName(errs(), ArchiveName, ArchitectureName); 1869 errs() << "no symbols\n"; 1870 } 1871 1872 sortAndPrintSymbolList(Obj, printName, ArchiveName, ArchitectureName); 1873 } 1874 1875 // checkMachOAndArchFlags() checks to see if the SymbolicFile is a Mach-O file 1876 // and if it is and there is a list of architecture flags is specified then 1877 // check to make sure this Mach-O file is one of those architectures or all 1878 // architectures was specificed. If not then an error is generated and this 1879 // routine returns false. Else it returns true. 1880 static bool checkMachOAndArchFlags(SymbolicFile *O, std::string &Filename) { 1881 auto *MachO = dyn_cast<MachOObjectFile>(O); 1882 1883 if (!MachO || ArchAll || ArchFlags.empty()) 1884 return true; 1885 1886 MachO::mach_header H; 1887 MachO::mach_header_64 H_64; 1888 Triple T; 1889 const char *McpuDefault, *ArchFlag; 1890 if (MachO->is64Bit()) { 1891 H_64 = MachO->MachOObjectFile::getHeader64(); 1892 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype, 1893 &McpuDefault, &ArchFlag); 1894 } else { 1895 H = MachO->MachOObjectFile::getHeader(); 1896 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype, 1897 &McpuDefault, &ArchFlag); 1898 } 1899 const std::string ArchFlagName(ArchFlag); 1900 if (!llvm::is_contained(ArchFlags, ArchFlagName)) { 1901 error("No architecture specified", Filename); 1902 return false; 1903 } 1904 return true; 1905 } 1906 1907 static void dumpSymbolNamesFromFile(std::string &Filename) { 1908 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr = 1909 MemoryBuffer::getFileOrSTDIN(Filename); 1910 if (error(BufferOrErr.getError(), Filename)) 1911 return; 1912 1913 LLVMContext Context; 1914 LLVMContext *ContextPtr = NoLLVMBitcode ? nullptr : &Context; 1915 Expected<std::unique_ptr<Binary>> BinaryOrErr = 1916 createBinary(BufferOrErr.get()->getMemBufferRef(), ContextPtr); 1917 if (!BinaryOrErr) { 1918 error(BinaryOrErr.takeError(), Filename); 1919 return; 1920 } 1921 Binary &Bin = *BinaryOrErr.get(); 1922 1923 if (Archive *A = dyn_cast<Archive>(&Bin)) { 1924 if (ArchiveMap) { 1925 Archive::symbol_iterator I = A->symbol_begin(); 1926 Archive::symbol_iterator E = A->symbol_end(); 1927 if (I != E) { 1928 outs() << "Archive map\n"; 1929 for (; I != E; ++I) { 1930 Expected<Archive::Child> C = I->getMember(); 1931 if (!C) { 1932 error(C.takeError(), Filename); 1933 break; 1934 } 1935 Expected<StringRef> FileNameOrErr = C->getName(); 1936 if (!FileNameOrErr) { 1937 error(FileNameOrErr.takeError(), Filename); 1938 break; 1939 } 1940 StringRef SymName = I->getName(); 1941 outs() << SymName << " in " << FileNameOrErr.get() << "\n"; 1942 } 1943 outs() << "\n"; 1944 } 1945 } 1946 1947 { 1948 Error Err = Error::success(); 1949 for (auto &C : A->children(Err)) { 1950 Expected<std::unique_ptr<Binary>> ChildOrErr = 1951 C.getAsBinary(ContextPtr); 1952 if (!ChildOrErr) { 1953 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 1954 error(std::move(E), Filename, C); 1955 continue; 1956 } 1957 if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) { 1958 if (!MachOPrintSizeWarning && PrintSize && isa<MachOObjectFile>(O)) { 1959 WithColor::warning(errs(), ToolName) 1960 << "sizes with -print-size for Mach-O files are always zero.\n"; 1961 MachOPrintSizeWarning = true; 1962 } 1963 if (!checkMachOAndArchFlags(O, Filename)) 1964 return; 1965 if (!PrintFileName) { 1966 outs() << "\n"; 1967 if (isa<MachOObjectFile>(O)) { 1968 outs() << Filename << "(" << O->getFileName() << ")"; 1969 } else 1970 outs() << O->getFileName(); 1971 outs() << ":\n"; 1972 } 1973 dumpSymbolNamesFromObject(*O, false, Filename); 1974 } 1975 } 1976 if (Err) 1977 error(std::move(Err), A->getFileName()); 1978 } 1979 return; 1980 } 1981 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) { 1982 // If we have a list of architecture flags specified dump only those. 1983 if (!ArchAll && !ArchFlags.empty()) { 1984 // Look for a slice in the universal binary that matches each ArchFlag. 1985 bool ArchFound; 1986 for (unsigned i = 0; i < ArchFlags.size(); ++i) { 1987 ArchFound = false; 1988 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), 1989 E = UB->end_objects(); 1990 I != E; ++I) { 1991 if (ArchFlags[i] == I->getArchFlagName()) { 1992 ArchFound = true; 1993 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = 1994 I->getAsObjectFile(); 1995 std::string ArchiveName; 1996 std::string ArchitectureName; 1997 ArchiveName.clear(); 1998 ArchitectureName.clear(); 1999 if (ObjOrErr) { 2000 ObjectFile &Obj = *ObjOrErr.get(); 2001 if (ArchFlags.size() > 1) { 2002 if (PrintFileName) 2003 ArchitectureName = I->getArchFlagName(); 2004 else 2005 outs() << "\n" << Obj.getFileName() << " (for architecture " 2006 << I->getArchFlagName() << ")" 2007 << ":\n"; 2008 } 2009 dumpSymbolNamesFromObject(Obj, false, ArchiveName, 2010 ArchitectureName); 2011 } else if (auto E = isNotObjectErrorInvalidFileType( 2012 ObjOrErr.takeError())) { 2013 error(std::move(E), Filename, ArchFlags.size() > 1 ? 2014 StringRef(I->getArchFlagName()) : StringRef()); 2015 continue; 2016 } else if (Expected<std::unique_ptr<Archive>> AOrErr = 2017 I->getAsArchive()) { 2018 std::unique_ptr<Archive> &A = *AOrErr; 2019 Error Err = Error::success(); 2020 for (auto &C : A->children(Err)) { 2021 Expected<std::unique_ptr<Binary>> ChildOrErr = 2022 C.getAsBinary(ContextPtr); 2023 if (!ChildOrErr) { 2024 if (auto E = isNotObjectErrorInvalidFileType( 2025 ChildOrErr.takeError())) { 2026 error(std::move(E), Filename, C, ArchFlags.size() > 1 ? 2027 StringRef(I->getArchFlagName()) : StringRef()); 2028 } 2029 continue; 2030 } 2031 if (SymbolicFile *O = 2032 dyn_cast<SymbolicFile>(&*ChildOrErr.get())) { 2033 if (PrintFileName) { 2034 ArchiveName = std::string(A->getFileName()); 2035 if (ArchFlags.size() > 1) 2036 ArchitectureName = I->getArchFlagName(); 2037 } else { 2038 outs() << "\n" << A->getFileName(); 2039 outs() << "(" << O->getFileName() << ")"; 2040 if (ArchFlags.size() > 1) { 2041 outs() << " (for architecture " << I->getArchFlagName() 2042 << ")"; 2043 } 2044 outs() << ":\n"; 2045 } 2046 dumpSymbolNamesFromObject(*O, false, ArchiveName, 2047 ArchitectureName); 2048 } 2049 } 2050 if (Err) 2051 error(std::move(Err), A->getFileName()); 2052 } else { 2053 consumeError(AOrErr.takeError()); 2054 error(Filename + " for architecture " + 2055 StringRef(I->getArchFlagName()) + 2056 " is not a Mach-O file or an archive file", 2057 "Mach-O universal file"); 2058 } 2059 } 2060 } 2061 if (!ArchFound) { 2062 error(ArchFlags[i], 2063 "file: " + Filename + " does not contain architecture"); 2064 return; 2065 } 2066 } 2067 return; 2068 } 2069 // No architecture flags were specified so if this contains a slice that 2070 // matches the host architecture dump only that. 2071 if (!ArchAll) { 2072 Triple HostTriple = MachOObjectFile::getHostArch(); 2073 StringRef HostArchName = HostTriple.getArchName(); 2074 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), 2075 E = UB->end_objects(); 2076 I != E; ++I) { 2077 if (HostArchName == I->getArchFlagName()) { 2078 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile(); 2079 std::string ArchiveName; 2080 if (ObjOrErr) { 2081 ObjectFile &Obj = *ObjOrErr.get(); 2082 dumpSymbolNamesFromObject(Obj, false); 2083 } else if (auto E = isNotObjectErrorInvalidFileType( 2084 ObjOrErr.takeError())) { 2085 error(std::move(E), Filename); 2086 return; 2087 } else if (Expected<std::unique_ptr<Archive>> AOrErr = 2088 I->getAsArchive()) { 2089 std::unique_ptr<Archive> &A = *AOrErr; 2090 Error Err = Error::success(); 2091 for (auto &C : A->children(Err)) { 2092 Expected<std::unique_ptr<Binary>> ChildOrErr = 2093 C.getAsBinary(ContextPtr); 2094 if (!ChildOrErr) { 2095 if (auto E = isNotObjectErrorInvalidFileType( 2096 ChildOrErr.takeError())) 2097 error(std::move(E), Filename, C); 2098 continue; 2099 } 2100 if (SymbolicFile *O = 2101 dyn_cast<SymbolicFile>(&*ChildOrErr.get())) { 2102 if (PrintFileName) 2103 ArchiveName = std::string(A->getFileName()); 2104 else 2105 outs() << "\n" << A->getFileName() << "(" << O->getFileName() 2106 << ")" 2107 << ":\n"; 2108 dumpSymbolNamesFromObject(*O, false, ArchiveName); 2109 } 2110 } 2111 if (Err) 2112 error(std::move(Err), A->getFileName()); 2113 } else { 2114 consumeError(AOrErr.takeError()); 2115 error(Filename + " for architecture " + 2116 StringRef(I->getArchFlagName()) + 2117 " is not a Mach-O file or an archive file", 2118 "Mach-O universal file"); 2119 } 2120 return; 2121 } 2122 } 2123 } 2124 // Either all architectures have been specified or none have been specified 2125 // and this does not contain the host architecture so dump all the slices. 2126 bool moreThanOneArch = UB->getNumberOfObjects() > 1; 2127 for (const MachOUniversalBinary::ObjectForArch &O : UB->objects()) { 2128 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = O.getAsObjectFile(); 2129 std::string ArchiveName; 2130 std::string ArchitectureName; 2131 ArchiveName.clear(); 2132 ArchitectureName.clear(); 2133 if (ObjOrErr) { 2134 ObjectFile &Obj = *ObjOrErr.get(); 2135 if (PrintFileName) { 2136 if (isa<MachOObjectFile>(Obj) && moreThanOneArch) 2137 ArchitectureName = O.getArchFlagName(); 2138 } else { 2139 if (moreThanOneArch) 2140 outs() << "\n"; 2141 outs() << Obj.getFileName(); 2142 if (isa<MachOObjectFile>(Obj) && moreThanOneArch) 2143 outs() << " (for architecture " << O.getArchFlagName() << ")"; 2144 outs() << ":\n"; 2145 } 2146 dumpSymbolNamesFromObject(Obj, false, ArchiveName, ArchitectureName); 2147 } else if (auto E = isNotObjectErrorInvalidFileType( 2148 ObjOrErr.takeError())) { 2149 error(std::move(E), Filename, moreThanOneArch ? 2150 StringRef(O.getArchFlagName()) : StringRef()); 2151 continue; 2152 } else if (Expected<std::unique_ptr<Archive>> AOrErr = 2153 O.getAsArchive()) { 2154 std::unique_ptr<Archive> &A = *AOrErr; 2155 Error Err = Error::success(); 2156 for (auto &C : A->children(Err)) { 2157 Expected<std::unique_ptr<Binary>> ChildOrErr = 2158 C.getAsBinary(ContextPtr); 2159 if (!ChildOrErr) { 2160 if (auto E = isNotObjectErrorInvalidFileType( 2161 ChildOrErr.takeError())) 2162 error(std::move(E), Filename, C, moreThanOneArch ? 2163 StringRef(ArchitectureName) : StringRef()); 2164 continue; 2165 } 2166 if (SymbolicFile *F = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) { 2167 if (PrintFileName) { 2168 ArchiveName = std::string(A->getFileName()); 2169 if (isa<MachOObjectFile>(F) && moreThanOneArch) 2170 ArchitectureName = O.getArchFlagName(); 2171 } else { 2172 outs() << "\n" << A->getFileName(); 2173 if (isa<MachOObjectFile>(F)) { 2174 outs() << "(" << F->getFileName() << ")"; 2175 if (moreThanOneArch) 2176 outs() << " (for architecture " << O.getArchFlagName() 2177 << ")"; 2178 } else 2179 outs() << ":" << F->getFileName(); 2180 outs() << ":\n"; 2181 } 2182 dumpSymbolNamesFromObject(*F, false, ArchiveName, ArchitectureName); 2183 } 2184 } 2185 if (Err) 2186 error(std::move(Err), A->getFileName()); 2187 } else { 2188 consumeError(AOrErr.takeError()); 2189 error(Filename + " for architecture " + 2190 StringRef(O.getArchFlagName()) + 2191 " is not a Mach-O file or an archive file", 2192 "Mach-O universal file"); 2193 } 2194 } 2195 return; 2196 } 2197 2198 if (TapiUniversal *TU = dyn_cast<TapiUniversal>(&Bin)) { 2199 for (const TapiUniversal::ObjectForArch &I : TU->objects()) { 2200 StringRef ArchName = I.getArchFlagName(); 2201 const bool ShowArch = 2202 ArchFlags.empty() || llvm::is_contained(ArchFlags, ArchName); 2203 if (!ShowArch) 2204 continue; 2205 if (!AddInlinedInfo && !I.isTopLevelLib()) 2206 continue; 2207 if (auto ObjOrErr = I.getAsObjectFile()) { 2208 outs() << "\n" 2209 << I.getInstallName() << " (for architecture " << ArchName << ")" 2210 << ":\n"; 2211 dumpSymbolNamesFromObject(*ObjOrErr.get(), false, {}, ArchName); 2212 } else if (Error E = 2213 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) { 2214 error(std::move(E), Filename, ArchName); 2215 } 2216 } 2217 2218 return; 2219 } 2220 2221 if (SymbolicFile *O = dyn_cast<SymbolicFile>(&Bin)) { 2222 if (!MachOPrintSizeWarning && PrintSize && isa<MachOObjectFile>(O)) { 2223 WithColor::warning(errs(), ToolName) 2224 << "sizes with --print-size for Mach-O files are always zero.\n"; 2225 MachOPrintSizeWarning = true; 2226 } 2227 if (!checkMachOAndArchFlags(O, Filename)) 2228 return; 2229 dumpSymbolNamesFromObject(*O, true); 2230 } 2231 } 2232 2233 int main(int argc, char **argv) { 2234 InitLLVM X(argc, argv); 2235 cl::HideUnrelatedOptions(NMCat); 2236 cl::ParseCommandLineOptions(argc, argv, "llvm symbol table dumper\n"); 2237 2238 // llvm-nm only reads binary files. 2239 if (error(sys::ChangeStdinToBinary())) 2240 return 1; 2241 2242 // These calls are needed so that we can read bitcode correctly. 2243 llvm::InitializeAllTargetInfos(); 2244 llvm::InitializeAllTargetMCs(); 2245 llvm::InitializeAllAsmParsers(); 2246 2247 ToolName = argv[0]; 2248 if (BSDFormat) 2249 OutputFormat = bsd; 2250 if (POSIXFormat) 2251 OutputFormat = posix; 2252 if (DarwinFormat) 2253 OutputFormat = darwin; 2254 if (JustSymbolName) 2255 OutputFormat = just_symbols; 2256 2257 // The relative order of these is important. If you pass --size-sort it should 2258 // only print out the size. However, if you pass -S --size-sort, it should 2259 // print out both the size and address. 2260 if (SizeSort && !PrintSize) 2261 PrintAddress = false; 2262 if (OutputFormat == sysv || SizeSort) 2263 PrintSize = true; 2264 if (InputFilenames.empty()) 2265 InputFilenames.push_back("a.out"); 2266 if (InputFilenames.size() > 1) 2267 MultipleFiles = true; 2268 2269 // If both --demangle and --no-demangle are specified then pick the last one. 2270 if (NoDemangle.getPosition() > Demangle.getPosition()) 2271 Demangle = !NoDemangle; 2272 2273 for (unsigned i = 0; i < ArchFlags.size(); ++i) { 2274 if (ArchFlags[i] == "all") { 2275 ArchAll = true; 2276 } else { 2277 if (!MachOObjectFile::isValidArch(ArchFlags[i])) 2278 error("Unknown architecture named '" + ArchFlags[i] + "'", 2279 "for the --arch option"); 2280 } 2281 } 2282 2283 if (!SegSect.empty() && SegSect.size() != 2) 2284 error("bad number of arguments (must be two arguments)", 2285 "for the -s option"); 2286 2287 if (NoDyldInfo && (AddDyldInfo || DyldInfoOnly)) 2288 error("--no-dyldinfo can't be used with --add-dyldinfo or --dyldinfo-only"); 2289 2290 llvm::for_each(InputFilenames, dumpSymbolNamesFromFile); 2291 2292 if (HadError) 2293 return 1; 2294 } 2295