1 //===--- Core.cpp - Core ORC APIs (MaterializationUnit, JITDylib, etc.) ---===// 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 #include "llvm/ExecutionEngine/Orc/Core.h" 11 #include "llvm/Config/llvm-config.h" 12 #include "llvm/ExecutionEngine/Orc/OrcError.h" 13 #include "llvm/IR/Mangler.h" 14 #include "llvm/Support/CommandLine.h" 15 #include "llvm/Support/Debug.h" 16 #include "llvm/Support/Format.h" 17 18 #if LLVM_ENABLE_THREADS 19 #include <future> 20 #endif 21 22 #define DEBUG_TYPE "orc" 23 24 using namespace llvm; 25 26 namespace { 27 28 #ifndef NDEBUG 29 30 cl::opt<bool> PrintHidden("debug-orc-print-hidden", cl::init(false), 31 cl::desc("debug print hidden symbols defined by " 32 "materialization units"), 33 cl::Hidden); 34 35 cl::opt<bool> PrintCallable("debug-orc-print-callable", cl::init(false), 36 cl::desc("debug print callable symbols defined by " 37 "materialization units"), 38 cl::Hidden); 39 40 cl::opt<bool> PrintData("debug-orc-print-data", cl::init(false), 41 cl::desc("debug print data symbols defined by " 42 "materialization units"), 43 cl::Hidden); 44 45 #endif // NDEBUG 46 47 // SetPrinter predicate that prints every element. 48 template <typename T> struct PrintAll { 49 bool operator()(const T &E) { return true; } 50 }; 51 52 bool anyPrintSymbolOptionSet() { 53 #ifndef NDEBUG 54 return PrintHidden || PrintCallable || PrintData; 55 #else 56 return false; 57 #endif // NDEBUG 58 } 59 60 bool flagsMatchCLOpts(const JITSymbolFlags &Flags) { 61 #ifndef NDEBUG 62 // Bail out early if this is a hidden symbol and we're not printing hiddens. 63 if (!PrintHidden && !Flags.isExported()) 64 return false; 65 66 // Return true if this is callable and we're printing callables. 67 if (PrintCallable && Flags.isCallable()) 68 return true; 69 70 // Return true if this is data and we're printing data. 71 if (PrintData && !Flags.isCallable()) 72 return true; 73 74 // otherwise return false. 75 return false; 76 #else 77 return false; 78 #endif // NDEBUG 79 } 80 81 // Prints a set of items, filtered by an user-supplied predicate. 82 template <typename Set, typename Pred = PrintAll<typename Set::value_type>> 83 class SetPrinter { 84 public: 85 SetPrinter(const Set &S, Pred ShouldPrint = Pred()) 86 : S(S), ShouldPrint(std::move(ShouldPrint)) {} 87 88 void printTo(llvm::raw_ostream &OS) const { 89 bool PrintComma = false; 90 OS << "{"; 91 for (auto &E : S) { 92 if (ShouldPrint(E)) { 93 if (PrintComma) 94 OS << ','; 95 OS << ' ' << E; 96 PrintComma = true; 97 } 98 } 99 OS << " }"; 100 } 101 102 private: 103 const Set &S; 104 mutable Pred ShouldPrint; 105 }; 106 107 template <typename Set, typename Pred> 108 SetPrinter<Set, Pred> printSet(const Set &S, Pred P = Pred()) { 109 return SetPrinter<Set, Pred>(S, std::move(P)); 110 } 111 112 // Render a SetPrinter by delegating to its printTo method. 113 template <typename Set, typename Pred> 114 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, 115 const SetPrinter<Set, Pred> &Printer) { 116 Printer.printTo(OS); 117 return OS; 118 } 119 120 struct PrintSymbolFlagsMapElemsMatchingCLOpts { 121 bool operator()(const orc::SymbolFlagsMap::value_type &KV) { 122 return flagsMatchCLOpts(KV.second); 123 } 124 }; 125 126 struct PrintSymbolMapElemsMatchingCLOpts { 127 bool operator()(const orc::SymbolMap::value_type &KV) { 128 return flagsMatchCLOpts(KV.second.getFlags()); 129 } 130 }; 131 132 } // end anonymous namespace 133 134 namespace llvm { 135 namespace orc { 136 137 SymbolStringPool::PoolMapEntry SymbolStringPtr::Tombstone(0); 138 139 char FailedToMaterialize::ID = 0; 140 char SymbolsNotFound::ID = 0; 141 char SymbolsCouldNotBeRemoved::ID = 0; 142 143 RegisterDependenciesFunction NoDependenciesToRegister = 144 RegisterDependenciesFunction(); 145 146 void MaterializationUnit::anchor() {} 147 148 raw_ostream &operator<<(raw_ostream &OS, const SymbolStringPtr &Sym) { 149 return OS << *Sym; 150 } 151 152 raw_ostream &operator<<(raw_ostream &OS, const SymbolNameSet &Symbols) { 153 return OS << printSet(Symbols, PrintAll<SymbolStringPtr>()); 154 } 155 156 raw_ostream &operator<<(raw_ostream &OS, const JITSymbolFlags &Flags) { 157 if (Flags.isCallable()) 158 OS << "[Callable]"; 159 else 160 OS << "[Data]"; 161 if (Flags.isWeak()) 162 OS << "[Weak]"; 163 else if (Flags.isCommon()) 164 OS << "[Common]"; 165 166 if (!Flags.isExported()) 167 OS << "[Hidden]"; 168 169 return OS; 170 } 171 172 raw_ostream &operator<<(raw_ostream &OS, const JITEvaluatedSymbol &Sym) { 173 return OS << format("0x%016x", Sym.getAddress()) << " " << Sym.getFlags(); 174 } 175 176 raw_ostream &operator<<(raw_ostream &OS, const SymbolFlagsMap::value_type &KV) { 177 return OS << "(\"" << KV.first << "\", " << KV.second << ")"; 178 } 179 180 raw_ostream &operator<<(raw_ostream &OS, const SymbolMap::value_type &KV) { 181 return OS << "(\"" << KV.first << "\": " << KV.second << ")"; 182 } 183 184 raw_ostream &operator<<(raw_ostream &OS, const SymbolFlagsMap &SymbolFlags) { 185 return OS << printSet(SymbolFlags, PrintSymbolFlagsMapElemsMatchingCLOpts()); 186 } 187 188 raw_ostream &operator<<(raw_ostream &OS, const SymbolMap &Symbols) { 189 return OS << printSet(Symbols, PrintSymbolMapElemsMatchingCLOpts()); 190 } 191 192 raw_ostream &operator<<(raw_ostream &OS, 193 const SymbolDependenceMap::value_type &KV) { 194 return OS << "(" << KV.first << ", " << KV.second << ")"; 195 } 196 197 raw_ostream &operator<<(raw_ostream &OS, const SymbolDependenceMap &Deps) { 198 return OS << printSet(Deps, PrintAll<SymbolDependenceMap::value_type>()); 199 } 200 201 raw_ostream &operator<<(raw_ostream &OS, const MaterializationUnit &MU) { 202 OS << "MU@" << &MU << " (\"" << MU.getName() << "\""; 203 if (anyPrintSymbolOptionSet()) 204 OS << ", " << MU.getSymbols(); 205 return OS << ")"; 206 } 207 208 raw_ostream &operator<<(raw_ostream &OS, const JITDylibSearchList &JDs) { 209 OS << "["; 210 if (!JDs.empty()) { 211 assert(JDs.front().first && "JITDylibList entries must not be null"); 212 OS << " (\"" << JDs.front().first->getName() << "\", " 213 << (JDs.front().second ? "true" : "false") << ")"; 214 for (auto &KV : make_range(std::next(JDs.begin()), JDs.end())) { 215 assert(KV.first && "JITDylibList entries must not be null"); 216 OS << ", (\"" << KV.first->getName() << "\", " 217 << (KV.second ? "true" : "false") << ")"; 218 } 219 } 220 OS << " ]"; 221 return OS; 222 } 223 224 FailedToMaterialize::FailedToMaterialize(SymbolNameSet Symbols) 225 : Symbols(std::move(Symbols)) { 226 assert(!this->Symbols.empty() && "Can not fail to resolve an empty set"); 227 } 228 229 std::error_code FailedToMaterialize::convertToErrorCode() const { 230 return orcError(OrcErrorCode::UnknownORCError); 231 } 232 233 void FailedToMaterialize::log(raw_ostream &OS) const { 234 OS << "Failed to materialize symbols: " << Symbols; 235 } 236 237 SymbolsNotFound::SymbolsNotFound(SymbolNameSet Symbols) 238 : Symbols(std::move(Symbols)) { 239 assert(!this->Symbols.empty() && "Can not fail to resolve an empty set"); 240 } 241 242 std::error_code SymbolsNotFound::convertToErrorCode() const { 243 return orcError(OrcErrorCode::UnknownORCError); 244 } 245 246 void SymbolsNotFound::log(raw_ostream &OS) const { 247 OS << "Symbols not found: " << Symbols; 248 } 249 250 SymbolsCouldNotBeRemoved::SymbolsCouldNotBeRemoved(SymbolNameSet Symbols) 251 : Symbols(std::move(Symbols)) { 252 assert(!this->Symbols.empty() && "Can not fail to resolve an empty set"); 253 } 254 255 std::error_code SymbolsCouldNotBeRemoved::convertToErrorCode() const { 256 return orcError(OrcErrorCode::UnknownORCError); 257 } 258 259 void SymbolsCouldNotBeRemoved::log(raw_ostream &OS) const { 260 OS << "Symbols could not be removed: " << Symbols; 261 } 262 263 AsynchronousSymbolQuery::AsynchronousSymbolQuery( 264 const SymbolNameSet &Symbols, SymbolsResolvedCallback NotifySymbolsResolved, 265 SymbolsReadyCallback NotifySymbolsReady) 266 : NotifySymbolsResolved(std::move(NotifySymbolsResolved)), 267 NotifySymbolsReady(std::move(NotifySymbolsReady)) { 268 NotYetResolvedCount = NotYetReadyCount = Symbols.size(); 269 270 for (auto &S : Symbols) 271 ResolvedSymbols[S] = nullptr; 272 } 273 274 void AsynchronousSymbolQuery::resolve(const SymbolStringPtr &Name, 275 JITEvaluatedSymbol Sym) { 276 auto I = ResolvedSymbols.find(Name); 277 assert(I != ResolvedSymbols.end() && 278 "Resolving symbol outside the requested set"); 279 assert(I->second.getAddress() == 0 && "Redundantly resolving symbol Name"); 280 I->second = std::move(Sym); 281 --NotYetResolvedCount; 282 } 283 284 void AsynchronousSymbolQuery::handleFullyResolved() { 285 assert(NotYetResolvedCount == 0 && "Not fully resolved?"); 286 287 if (!NotifySymbolsResolved) { 288 // handleFullyResolved may be called by handleFullyReady (see comments in 289 // that method), in which case this is a no-op, so bail out. 290 assert(!NotifySymbolsReady && 291 "NotifySymbolsResolved already called or an error occurred"); 292 return; 293 } 294 295 auto TmpNotifySymbolsResolved = std::move(NotifySymbolsResolved); 296 NotifySymbolsResolved = SymbolsResolvedCallback(); 297 TmpNotifySymbolsResolved(std::move(ResolvedSymbols)); 298 } 299 300 void AsynchronousSymbolQuery::notifySymbolReady() { 301 assert(NotYetReadyCount != 0 && "All symbols already emitted"); 302 --NotYetReadyCount; 303 } 304 305 void AsynchronousSymbolQuery::handleFullyReady() { 306 assert(NotifySymbolsReady && 307 "NotifySymbolsReady already called or an error occurred"); 308 309 auto TmpNotifySymbolsReady = std::move(NotifySymbolsReady); 310 NotifySymbolsReady = SymbolsReadyCallback(); 311 312 if (NotYetResolvedCount == 0 && NotifySymbolsResolved) { 313 // The NotifyResolved callback of one query must have caused this query to 314 // become ready (i.e. there is still a handleFullyResolved callback waiting 315 // to be made back up the stack). Fold the handleFullyResolved call into 316 // this one before proceeding. This will cause the call further up the 317 // stack to become a no-op. 318 handleFullyResolved(); 319 } 320 321 assert(QueryRegistrations.empty() && 322 "Query is still registered with some symbols"); 323 assert(!NotifySymbolsResolved && "Resolution not applied yet"); 324 TmpNotifySymbolsReady(Error::success()); 325 } 326 327 bool AsynchronousSymbolQuery::canStillFail() { 328 return (NotifySymbolsResolved || NotifySymbolsReady); 329 } 330 331 void AsynchronousSymbolQuery::handleFailed(Error Err) { 332 assert(QueryRegistrations.empty() && ResolvedSymbols.empty() && 333 NotYetResolvedCount == 0 && NotYetReadyCount == 0 && 334 "Query should already have been abandoned"); 335 if (NotifySymbolsResolved) { 336 NotifySymbolsResolved(std::move(Err)); 337 NotifySymbolsResolved = SymbolsResolvedCallback(); 338 } else { 339 assert(NotifySymbolsReady && "Failed after both callbacks issued?"); 340 NotifySymbolsReady(std::move(Err)); 341 } 342 NotifySymbolsReady = SymbolsReadyCallback(); 343 } 344 345 void AsynchronousSymbolQuery::addQueryDependence(JITDylib &JD, 346 SymbolStringPtr Name) { 347 bool Added = QueryRegistrations[&JD].insert(std::move(Name)).second; 348 (void)Added; 349 assert(Added && "Duplicate dependence notification?"); 350 } 351 352 void AsynchronousSymbolQuery::removeQueryDependence( 353 JITDylib &JD, const SymbolStringPtr &Name) { 354 auto QRI = QueryRegistrations.find(&JD); 355 assert(QRI != QueryRegistrations.end() && 356 "No dependencies registered for JD"); 357 assert(QRI->second.count(Name) && "No dependency on Name in JD"); 358 QRI->second.erase(Name); 359 if (QRI->second.empty()) 360 QueryRegistrations.erase(QRI); 361 } 362 363 void AsynchronousSymbolQuery::detach() { 364 ResolvedSymbols.clear(); 365 NotYetResolvedCount = 0; 366 NotYetReadyCount = 0; 367 for (auto &KV : QueryRegistrations) 368 KV.first->detachQueryHelper(*this, KV.second); 369 QueryRegistrations.clear(); 370 } 371 372 MaterializationResponsibility::MaterializationResponsibility( 373 JITDylib &JD, SymbolFlagsMap SymbolFlags, VModuleKey K) 374 : JD(JD), SymbolFlags(std::move(SymbolFlags)), K(std::move(K)) { 375 assert(!this->SymbolFlags.empty() && "Materializing nothing?"); 376 377 #ifndef NDEBUG 378 for (auto &KV : this->SymbolFlags) 379 KV.second |= JITSymbolFlags::Materializing; 380 #endif 381 } 382 383 MaterializationResponsibility::~MaterializationResponsibility() { 384 assert(SymbolFlags.empty() && 385 "All symbols should have been explicitly materialized or failed"); 386 } 387 388 SymbolNameSet MaterializationResponsibility::getRequestedSymbols() const { 389 return JD.getRequestedSymbols(SymbolFlags); 390 } 391 392 void MaterializationResponsibility::resolve(const SymbolMap &Symbols) { 393 LLVM_DEBUG(dbgs() << "In " << JD.getName() << " resolving " << Symbols 394 << "\n"); 395 #ifndef NDEBUG 396 for (auto &KV : Symbols) { 397 auto I = SymbolFlags.find(KV.first); 398 assert(I != SymbolFlags.end() && 399 "Resolving symbol outside this responsibility set"); 400 assert(I->second.isMaterializing() && "Duplicate resolution"); 401 I->second &= ~JITSymbolFlags::Materializing; 402 if (I->second.isWeak()) 403 assert(I->second == (KV.second.getFlags() | JITSymbolFlags::Weak) && 404 "Resolving symbol with incorrect flags"); 405 else 406 assert(I->second == KV.second.getFlags() && 407 "Resolving symbol with incorrect flags"); 408 } 409 #endif 410 411 JD.resolve(Symbols); 412 } 413 414 void MaterializationResponsibility::emit() { 415 #ifndef NDEBUG 416 for (auto &KV : SymbolFlags) 417 assert(!KV.second.isMaterializing() && 418 "Failed to resolve symbol before emission"); 419 #endif // NDEBUG 420 421 JD.emit(SymbolFlags); 422 SymbolFlags.clear(); 423 } 424 425 Error MaterializationResponsibility::defineMaterializing( 426 const SymbolFlagsMap &NewSymbolFlags) { 427 // Add the given symbols to this responsibility object. 428 // It's ok if we hit a duplicate here: In that case the new version will be 429 // discarded, and the JITDylib::defineMaterializing method will return a 430 // duplicate symbol error. 431 for (auto &KV : NewSymbolFlags) { 432 auto I = SymbolFlags.insert(KV).first; 433 (void)I; 434 #ifndef NDEBUG 435 I->second |= JITSymbolFlags::Materializing; 436 #endif 437 } 438 439 return JD.defineMaterializing(NewSymbolFlags); 440 } 441 442 void MaterializationResponsibility::failMaterialization() { 443 444 SymbolNameSet FailedSymbols; 445 for (auto &KV : SymbolFlags) 446 FailedSymbols.insert(KV.first); 447 448 JD.notifyFailed(FailedSymbols); 449 SymbolFlags.clear(); 450 } 451 452 void MaterializationResponsibility::replace( 453 std::unique_ptr<MaterializationUnit> MU) { 454 for (auto &KV : MU->getSymbols()) 455 SymbolFlags.erase(KV.first); 456 457 LLVM_DEBUG(JD.getExecutionSession().runSessionLocked([&]() { 458 dbgs() << "In " << JD.getName() << " replacing symbols with " << *MU 459 << "\n"; 460 });); 461 462 JD.replace(std::move(MU)); 463 } 464 465 MaterializationResponsibility 466 MaterializationResponsibility::delegate(const SymbolNameSet &Symbols, 467 VModuleKey NewKey) { 468 469 if (NewKey == VModuleKey()) 470 NewKey = K; 471 472 SymbolFlagsMap DelegatedFlags; 473 474 for (auto &Name : Symbols) { 475 auto I = SymbolFlags.find(Name); 476 assert(I != SymbolFlags.end() && 477 "Symbol is not tracked by this MaterializationResponsibility " 478 "instance"); 479 480 DelegatedFlags[Name] = std::move(I->second); 481 SymbolFlags.erase(I); 482 } 483 484 return MaterializationResponsibility(JD, std::move(DelegatedFlags), 485 std::move(NewKey)); 486 } 487 488 void MaterializationResponsibility::addDependencies( 489 const SymbolStringPtr &Name, const SymbolDependenceMap &Dependencies) { 490 assert(SymbolFlags.count(Name) && 491 "Symbol not covered by this MaterializationResponsibility instance"); 492 JD.addDependencies(Name, Dependencies); 493 } 494 495 void MaterializationResponsibility::addDependenciesForAll( 496 const SymbolDependenceMap &Dependencies) { 497 for (auto &KV : SymbolFlags) 498 JD.addDependencies(KV.first, Dependencies); 499 } 500 501 AbsoluteSymbolsMaterializationUnit::AbsoluteSymbolsMaterializationUnit( 502 SymbolMap Symbols, VModuleKey K) 503 : MaterializationUnit(extractFlags(Symbols), std::move(K)), 504 Symbols(std::move(Symbols)) {} 505 506 StringRef AbsoluteSymbolsMaterializationUnit::getName() const { 507 return "<Absolute Symbols>"; 508 } 509 510 void AbsoluteSymbolsMaterializationUnit::materialize( 511 MaterializationResponsibility R) { 512 R.resolve(Symbols); 513 R.emit(); 514 } 515 516 void AbsoluteSymbolsMaterializationUnit::discard(const JITDylib &JD, 517 const SymbolStringPtr &Name) { 518 assert(Symbols.count(Name) && "Symbol is not part of this MU"); 519 Symbols.erase(Name); 520 } 521 522 SymbolFlagsMap 523 AbsoluteSymbolsMaterializationUnit::extractFlags(const SymbolMap &Symbols) { 524 SymbolFlagsMap Flags; 525 for (const auto &KV : Symbols) 526 Flags[KV.first] = KV.second.getFlags(); 527 return Flags; 528 } 529 530 ReExportsMaterializationUnit::ReExportsMaterializationUnit( 531 JITDylib *SourceJD, bool MatchNonExported, SymbolAliasMap Aliases, 532 VModuleKey K) 533 : MaterializationUnit(extractFlags(Aliases), std::move(K)), 534 SourceJD(SourceJD), MatchNonExported(MatchNonExported), 535 Aliases(std::move(Aliases)) {} 536 537 StringRef ReExportsMaterializationUnit::getName() const { 538 return "<Reexports>"; 539 } 540 541 void ReExportsMaterializationUnit::materialize( 542 MaterializationResponsibility R) { 543 544 auto &ES = R.getTargetJITDylib().getExecutionSession(); 545 JITDylib &TgtJD = R.getTargetJITDylib(); 546 JITDylib &SrcJD = SourceJD ? *SourceJD : TgtJD; 547 548 // Find the set of requested aliases and aliasees. Return any unrequested 549 // aliases back to the JITDylib so as to not prematurely materialize any 550 // aliasees. 551 auto RequestedSymbols = R.getRequestedSymbols(); 552 SymbolAliasMap RequestedAliases; 553 554 for (auto &Name : RequestedSymbols) { 555 auto I = Aliases.find(Name); 556 assert(I != Aliases.end() && "Symbol not found in aliases map?"); 557 RequestedAliases[Name] = std::move(I->second); 558 Aliases.erase(I); 559 } 560 561 if (!Aliases.empty()) { 562 if (SourceJD) 563 R.replace(reexports(*SourceJD, std::move(Aliases), MatchNonExported)); 564 else 565 R.replace(symbolAliases(std::move(Aliases))); 566 } 567 568 // The OnResolveInfo struct will hold the aliases and responsibilty for each 569 // query in the list. 570 struct OnResolveInfo { 571 OnResolveInfo(MaterializationResponsibility R, SymbolAliasMap Aliases) 572 : R(std::move(R)), Aliases(std::move(Aliases)) {} 573 574 MaterializationResponsibility R; 575 SymbolAliasMap Aliases; 576 }; 577 578 // Build a list of queries to issue. In each round we build the largest set of 579 // aliases that we can resolve without encountering a chain definition of the 580 // form Foo -> Bar, Bar -> Baz. Such a form would deadlock as the query would 581 // be waitin on a symbol that it itself had to resolve. Usually this will just 582 // involve one round and a single query. 583 584 std::vector<std::pair<SymbolNameSet, std::shared_ptr<OnResolveInfo>>> 585 QueryInfos; 586 while (!RequestedAliases.empty()) { 587 SymbolNameSet ResponsibilitySymbols; 588 SymbolNameSet QuerySymbols; 589 SymbolAliasMap QueryAliases; 590 591 // Collect as many aliases as we can without including a chain. 592 for (auto &KV : RequestedAliases) { 593 // Chain detected. Skip this symbol for this round. 594 if (&SrcJD == &TgtJD && (QueryAliases.count(KV.second.Aliasee) || 595 RequestedAliases.count(KV.second.Aliasee))) 596 continue; 597 598 ResponsibilitySymbols.insert(KV.first); 599 QuerySymbols.insert(KV.second.Aliasee); 600 QueryAliases[KV.first] = std::move(KV.second); 601 } 602 603 // Remove the aliases collected this round from the RequestedAliases map. 604 for (auto &KV : QueryAliases) 605 RequestedAliases.erase(KV.first); 606 607 assert(!QuerySymbols.empty() && "Alias cycle detected!"); 608 609 auto QueryInfo = std::make_shared<OnResolveInfo>( 610 R.delegate(ResponsibilitySymbols), std::move(QueryAliases)); 611 QueryInfos.push_back( 612 make_pair(std::move(QuerySymbols), std::move(QueryInfo))); 613 } 614 615 // Issue the queries. 616 while (!QueryInfos.empty()) { 617 auto QuerySymbols = std::move(QueryInfos.back().first); 618 auto QueryInfo = std::move(QueryInfos.back().second); 619 620 QueryInfos.pop_back(); 621 622 auto RegisterDependencies = [QueryInfo, 623 &SrcJD](const SymbolDependenceMap &Deps) { 624 // If there were no materializing symbols, just bail out. 625 if (Deps.empty()) 626 return; 627 628 // Otherwise the only deps should be on SrcJD. 629 assert(Deps.size() == 1 && Deps.count(&SrcJD) && 630 "Unexpected dependencies for reexports"); 631 632 auto &SrcJDDeps = Deps.find(&SrcJD)->second; 633 SymbolDependenceMap PerAliasDepsMap; 634 auto &PerAliasDeps = PerAliasDepsMap[&SrcJD]; 635 636 for (auto &KV : QueryInfo->Aliases) 637 if (SrcJDDeps.count(KV.second.Aliasee)) { 638 PerAliasDeps = {KV.second.Aliasee}; 639 QueryInfo->R.addDependencies(KV.first, PerAliasDepsMap); 640 } 641 }; 642 643 auto OnResolve = [QueryInfo](Expected<SymbolMap> Result) { 644 if (Result) { 645 SymbolMap ResolutionMap; 646 for (auto &KV : QueryInfo->Aliases) { 647 assert(Result->count(KV.second.Aliasee) && 648 "Result map missing entry?"); 649 ResolutionMap[KV.first] = JITEvaluatedSymbol( 650 (*Result)[KV.second.Aliasee].getAddress(), KV.second.AliasFlags); 651 } 652 QueryInfo->R.resolve(ResolutionMap); 653 QueryInfo->R.emit(); 654 } else { 655 auto &ES = QueryInfo->R.getTargetJITDylib().getExecutionSession(); 656 ES.reportError(Result.takeError()); 657 QueryInfo->R.failMaterialization(); 658 } 659 }; 660 661 auto OnReady = [&ES](Error Err) { ES.reportError(std::move(Err)); }; 662 663 ES.lookup(JITDylibSearchList({{&SrcJD, MatchNonExported}}), QuerySymbols, 664 std::move(OnResolve), std::move(OnReady), 665 std::move(RegisterDependencies)); 666 } 667 } 668 669 void ReExportsMaterializationUnit::discard(const JITDylib &JD, 670 const SymbolStringPtr &Name) { 671 assert(Aliases.count(Name) && 672 "Symbol not covered by this MaterializationUnit"); 673 Aliases.erase(Name); 674 } 675 676 SymbolFlagsMap 677 ReExportsMaterializationUnit::extractFlags(const SymbolAliasMap &Aliases) { 678 SymbolFlagsMap SymbolFlags; 679 for (auto &KV : Aliases) 680 SymbolFlags[KV.first] = KV.second.AliasFlags; 681 682 return SymbolFlags; 683 } 684 685 Expected<SymbolAliasMap> 686 buildSimpleReexportsAliasMap(JITDylib &SourceJD, const SymbolNameSet &Symbols) { 687 auto Flags = SourceJD.lookupFlags(Symbols); 688 689 if (Flags.size() != Symbols.size()) { 690 SymbolNameSet Unresolved = Symbols; 691 for (auto &KV : Flags) 692 Unresolved.erase(KV.first); 693 return make_error<SymbolsNotFound>(std::move(Unresolved)); 694 } 695 696 SymbolAliasMap Result; 697 for (auto &Name : Symbols) { 698 assert(Flags.count(Name) && "Missing entry in flags map"); 699 Result[Name] = SymbolAliasMapEntry(Name, Flags[Name]); 700 } 701 702 return Result; 703 } 704 705 ReexportsGenerator::ReexportsGenerator(JITDylib &SourceJD, 706 bool MatchNonExported, 707 SymbolPredicate Allow) 708 : SourceJD(SourceJD), MatchNonExported(MatchNonExported), 709 Allow(std::move(Allow)) {} 710 711 SymbolNameSet ReexportsGenerator::operator()(JITDylib &JD, 712 const SymbolNameSet &Names) { 713 orc::SymbolNameSet Added; 714 orc::SymbolAliasMap AliasMap; 715 716 auto Flags = SourceJD.lookupFlags(Names); 717 718 for (auto &KV : Flags) { 719 if (Allow && !Allow(KV.first)) 720 continue; 721 AliasMap[KV.first] = SymbolAliasMapEntry(KV.first, KV.second); 722 Added.insert(KV.first); 723 } 724 725 if (!Added.empty()) 726 cantFail(JD.define(reexports(SourceJD, AliasMap, MatchNonExported))); 727 728 return Added; 729 } 730 731 Error JITDylib::defineMaterializing(const SymbolFlagsMap &SymbolFlags) { 732 return ES.runSessionLocked([&]() -> Error { 733 std::vector<SymbolMap::iterator> AddedSyms; 734 735 for (auto &KV : SymbolFlags) { 736 SymbolMap::iterator EntryItr; 737 bool Added; 738 739 auto NewFlags = KV.second; 740 NewFlags |= JITSymbolFlags::Materializing; 741 742 std::tie(EntryItr, Added) = Symbols.insert( 743 std::make_pair(KV.first, JITEvaluatedSymbol(0, NewFlags))); 744 745 if (Added) 746 AddedSyms.push_back(EntryItr); 747 else { 748 // Remove any symbols already added. 749 for (auto &SI : AddedSyms) 750 Symbols.erase(SI); 751 752 // FIXME: Return all duplicates. 753 return make_error<DuplicateDefinition>(*KV.first); 754 } 755 } 756 757 return Error::success(); 758 }); 759 } 760 761 void JITDylib::replace(std::unique_ptr<MaterializationUnit> MU) { 762 assert(MU != nullptr && "Can not replace with a null MaterializationUnit"); 763 764 auto MustRunMU = 765 ES.runSessionLocked([&, this]() -> std::unique_ptr<MaterializationUnit> { 766 767 #ifndef NDEBUG 768 for (auto &KV : MU->getSymbols()) { 769 auto SymI = Symbols.find(KV.first); 770 assert(SymI != Symbols.end() && "Replacing unknown symbol"); 771 assert(!SymI->second.getFlags().isLazy() && 772 SymI->second.getFlags().isMaterializing() && 773 "Can not replace symbol that is not materializing"); 774 assert(UnmaterializedInfos.count(KV.first) == 0 && 775 "Symbol being replaced should have no UnmaterializedInfo"); 776 } 777 #endif // NDEBUG 778 779 // If any symbol has pending queries against it then we need to 780 // materialize MU immediately. 781 for (auto &KV : MU->getSymbols()) { 782 auto MII = MaterializingInfos.find(KV.first); 783 if (MII != MaterializingInfos.end()) { 784 if (!MII->second.PendingQueries.empty()) 785 return std::move(MU); 786 } 787 } 788 789 // Otherwise, make MU responsible for all the symbols. 790 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU)); 791 for (auto &KV : UMI->MU->getSymbols()) { 792 assert(!KV.second.isLazy() && 793 "Lazy flag should be managed internally."); 794 assert(!KV.second.isMaterializing() && 795 "Materializing flags should be managed internally."); 796 797 auto SymI = Symbols.find(KV.first); 798 JITSymbolFlags ReplaceFlags = KV.second; 799 ReplaceFlags |= JITSymbolFlags::Lazy; 800 SymI->second = JITEvaluatedSymbol(SymI->second.getAddress(), 801 std::move(ReplaceFlags)); 802 UnmaterializedInfos[KV.first] = UMI; 803 } 804 805 return nullptr; 806 }); 807 808 if (MustRunMU) 809 ES.dispatchMaterialization(*this, std::move(MustRunMU)); 810 } 811 812 SymbolNameSet 813 JITDylib::getRequestedSymbols(const SymbolFlagsMap &SymbolFlags) const { 814 return ES.runSessionLocked([&]() { 815 SymbolNameSet RequestedSymbols; 816 817 for (auto &KV : SymbolFlags) { 818 assert(Symbols.count(KV.first) && "JITDylib does not cover this symbol?"); 819 assert(Symbols.find(KV.first)->second.getFlags().isMaterializing() && 820 "getRequestedSymbols can only be called for materializing " 821 "symbols"); 822 auto I = MaterializingInfos.find(KV.first); 823 if (I == MaterializingInfos.end()) 824 continue; 825 826 if (!I->second.PendingQueries.empty()) 827 RequestedSymbols.insert(KV.first); 828 } 829 830 return RequestedSymbols; 831 }); 832 } 833 834 void JITDylib::addDependencies(const SymbolStringPtr &Name, 835 const SymbolDependenceMap &Dependencies) { 836 assert(Symbols.count(Name) && "Name not in symbol table"); 837 assert((Symbols[Name].getFlags().isLazy() || 838 Symbols[Name].getFlags().isMaterializing()) && 839 "Symbol is not lazy or materializing"); 840 841 auto &MI = MaterializingInfos[Name]; 842 assert(!MI.IsEmitted && "Can not add dependencies to an emitted symbol"); 843 844 for (auto &KV : Dependencies) { 845 assert(KV.first && "Null JITDylib in dependency?"); 846 auto &OtherJITDylib = *KV.first; 847 auto &DepsOnOtherJITDylib = MI.UnemittedDependencies[&OtherJITDylib]; 848 849 for (auto &OtherSymbol : KV.second) { 850 #ifndef NDEBUG 851 // Assert that this symbol exists and has not been emitted already. 852 auto SymI = OtherJITDylib.Symbols.find(OtherSymbol); 853 assert(SymI != OtherJITDylib.Symbols.end() && 854 (SymI->second.getFlags().isLazy() || 855 SymI->second.getFlags().isMaterializing()) && 856 "Dependency on emitted symbol"); 857 #endif 858 859 auto &OtherMI = OtherJITDylib.MaterializingInfos[OtherSymbol]; 860 861 if (OtherMI.IsEmitted) 862 transferEmittedNodeDependencies(MI, Name, OtherMI); 863 else if (&OtherJITDylib != this || OtherSymbol != Name) { 864 OtherMI.Dependants[this].insert(Name); 865 DepsOnOtherJITDylib.insert(OtherSymbol); 866 } 867 } 868 869 if (DepsOnOtherJITDylib.empty()) 870 MI.UnemittedDependencies.erase(&OtherJITDylib); 871 } 872 } 873 874 void JITDylib::resolve(const SymbolMap &Resolved) { 875 auto FullyResolvedQueries = ES.runSessionLocked([&, this]() { 876 AsynchronousSymbolQuerySet FullyResolvedQueries; 877 for (const auto &KV : Resolved) { 878 auto &Name = KV.first; 879 auto Sym = KV.second; 880 881 assert(!Sym.getFlags().isLazy() && !Sym.getFlags().isMaterializing() && 882 "Materializing flags should be managed internally"); 883 884 auto I = Symbols.find(Name); 885 886 assert(I != Symbols.end() && "Symbol not found"); 887 assert(!I->second.getFlags().isLazy() && 888 I->second.getFlags().isMaterializing() && 889 "Symbol should be materializing"); 890 assert(I->second.getAddress() == 0 && "Symbol has already been resolved"); 891 892 assert((Sym.getFlags() & ~JITSymbolFlags::Weak) == 893 (JITSymbolFlags::stripTransientFlags(I->second.getFlags()) & 894 ~JITSymbolFlags::Weak) && 895 "Resolved flags should match the declared flags"); 896 897 // Once resolved, symbols can never be weak. 898 JITSymbolFlags ResolvedFlags = Sym.getFlags(); 899 ResolvedFlags &= ~JITSymbolFlags::Weak; 900 ResolvedFlags |= JITSymbolFlags::Materializing; 901 I->second = JITEvaluatedSymbol(Sym.getAddress(), ResolvedFlags); 902 903 auto &MI = MaterializingInfos[Name]; 904 for (auto &Q : MI.PendingQueries) { 905 Q->resolve(Name, Sym); 906 if (Q->isFullyResolved()) 907 FullyResolvedQueries.insert(Q); 908 } 909 } 910 911 return FullyResolvedQueries; 912 }); 913 914 for (auto &Q : FullyResolvedQueries) { 915 assert(Q->isFullyResolved() && "Q not fully resolved"); 916 Q->handleFullyResolved(); 917 } 918 } 919 920 void JITDylib::emit(const SymbolFlagsMap &Emitted) { 921 auto FullyReadyQueries = ES.runSessionLocked([&, this]() { 922 AsynchronousSymbolQuerySet ReadyQueries; 923 924 for (const auto &KV : Emitted) { 925 const auto &Name = KV.first; 926 927 auto MII = MaterializingInfos.find(Name); 928 assert(MII != MaterializingInfos.end() && 929 "Missing MaterializingInfo entry"); 930 931 auto &MI = MII->second; 932 933 // For each dependant, transfer this node's emitted dependencies to 934 // it. If the dependant node is ready (i.e. has no unemitted 935 // dependencies) then notify any pending queries. 936 for (auto &KV : MI.Dependants) { 937 auto &DependantJD = *KV.first; 938 for (auto &DependantName : KV.second) { 939 auto DependantMII = 940 DependantJD.MaterializingInfos.find(DependantName); 941 assert(DependantMII != DependantJD.MaterializingInfos.end() && 942 "Dependant should have MaterializingInfo"); 943 944 auto &DependantMI = DependantMII->second; 945 946 // Remove the dependant's dependency on this node. 947 assert(DependantMI.UnemittedDependencies[this].count(Name) && 948 "Dependant does not count this symbol as a dependency?"); 949 DependantMI.UnemittedDependencies[this].erase(Name); 950 if (DependantMI.UnemittedDependencies[this].empty()) 951 DependantMI.UnemittedDependencies.erase(this); 952 953 // Transfer unemitted dependencies from this node to the dependant. 954 DependantJD.transferEmittedNodeDependencies(DependantMI, 955 DependantName, MI); 956 957 // If the dependant is emitted and this node was the last of its 958 // unemitted dependencies then the dependant node is now ready, so 959 // notify any pending queries on the dependant node. 960 if (DependantMI.IsEmitted && 961 DependantMI.UnemittedDependencies.empty()) { 962 assert(DependantMI.Dependants.empty() && 963 "Dependants should be empty by now"); 964 for (auto &Q : DependantMI.PendingQueries) { 965 Q->notifySymbolReady(); 966 if (Q->isFullyReady()) 967 ReadyQueries.insert(Q); 968 Q->removeQueryDependence(DependantJD, DependantName); 969 } 970 971 // Since this dependant is now ready, we erase its MaterializingInfo 972 // and update its materializing state. 973 assert(DependantJD.Symbols.count(DependantName) && 974 "Dependant has no entry in the Symbols table"); 975 auto &DependantSym = DependantJD.Symbols[DependantName]; 976 DependantSym.setFlags(DependantSym.getFlags() & 977 ~JITSymbolFlags::Materializing); 978 DependantJD.MaterializingInfos.erase(DependantMII); 979 } 980 } 981 } 982 MI.Dependants.clear(); 983 MI.IsEmitted = true; 984 985 if (MI.UnemittedDependencies.empty()) { 986 for (auto &Q : MI.PendingQueries) { 987 Q->notifySymbolReady(); 988 if (Q->isFullyReady()) 989 ReadyQueries.insert(Q); 990 Q->removeQueryDependence(*this, Name); 991 } 992 assert(Symbols.count(Name) && 993 "Symbol has no entry in the Symbols table"); 994 auto &Sym = Symbols[Name]; 995 Sym.setFlags(Sym.getFlags() & ~JITSymbolFlags::Materializing); 996 MaterializingInfos.erase(MII); 997 } 998 } 999 1000 return ReadyQueries; 1001 }); 1002 1003 for (auto &Q : FullyReadyQueries) { 1004 assert(Q->isFullyReady() && "Q is not fully ready"); 1005 Q->handleFullyReady(); 1006 } 1007 } 1008 1009 void JITDylib::notifyFailed(const SymbolNameSet &FailedSymbols) { 1010 1011 // FIXME: This should fail any transitively dependant symbols too. 1012 1013 auto FailedQueriesToNotify = ES.runSessionLocked([&, this]() { 1014 AsynchronousSymbolQuerySet FailedQueries; 1015 1016 for (auto &Name : FailedSymbols) { 1017 auto I = Symbols.find(Name); 1018 assert(I != Symbols.end() && "Symbol not present in this JITDylib"); 1019 Symbols.erase(I); 1020 1021 auto MII = MaterializingInfos.find(Name); 1022 1023 // If we have not created a MaterializingInfo for this symbol yet then 1024 // there is nobody to notify. 1025 if (MII == MaterializingInfos.end()) 1026 continue; 1027 1028 // Copy all the queries to the FailedQueries list, then abandon them. 1029 // This has to be a copy, and the copy has to come before the abandon 1030 // operation: Each Q.detach() call will reach back into this 1031 // PendingQueries list to remove Q. 1032 for (auto &Q : MII->second.PendingQueries) 1033 FailedQueries.insert(Q); 1034 1035 for (auto &Q : FailedQueries) 1036 Q->detach(); 1037 1038 assert(MII->second.PendingQueries.empty() && 1039 "Queries remain after symbol was failed"); 1040 1041 MaterializingInfos.erase(MII); 1042 } 1043 1044 return FailedQueries; 1045 }); 1046 1047 for (auto &Q : FailedQueriesToNotify) 1048 Q->handleFailed(make_error<FailedToMaterialize>(FailedSymbols)); 1049 } 1050 1051 void JITDylib::setSearchOrder(JITDylibSearchList NewSearchOrder, 1052 bool SearchThisJITDylibFirst, 1053 bool MatchNonExportedInThisDylib) { 1054 if (SearchThisJITDylibFirst && NewSearchOrder.front().first != this) 1055 NewSearchOrder.insert(NewSearchOrder.begin(), 1056 {this, MatchNonExportedInThisDylib}); 1057 1058 ES.runSessionLocked([&]() { SearchOrder = std::move(NewSearchOrder); }); 1059 } 1060 1061 void JITDylib::addToSearchOrder(JITDylib &JD, bool MatchNonExported) { 1062 ES.runSessionLocked([&]() { 1063 SearchOrder.push_back({&JD, MatchNonExported}); 1064 }); 1065 } 1066 1067 void JITDylib::replaceInSearchOrder(JITDylib &OldJD, JITDylib &NewJD, 1068 bool MatchNonExported) { 1069 ES.runSessionLocked([&]() { 1070 auto I = std::find_if(SearchOrder.begin(), SearchOrder.end(), 1071 [&](const JITDylibSearchList::value_type &KV) { 1072 return KV.first == &OldJD; 1073 }); 1074 1075 if (I != SearchOrder.end()) 1076 *I = {&NewJD, MatchNonExported}; 1077 }); 1078 } 1079 1080 void JITDylib::removeFromSearchOrder(JITDylib &JD) { 1081 ES.runSessionLocked([&]() { 1082 auto I = std::find_if(SearchOrder.begin(), SearchOrder.end(), 1083 [&](const JITDylibSearchList::value_type &KV) { 1084 return KV.first == &JD; 1085 }); 1086 if (I != SearchOrder.end()) 1087 SearchOrder.erase(I); 1088 }); 1089 } 1090 1091 Error JITDylib::remove(const SymbolNameSet &Names) { 1092 return ES.runSessionLocked([&]() -> Error { 1093 using SymbolMaterializerItrPair = 1094 std::pair<SymbolMap::iterator, UnmaterializedInfosMap::iterator>; 1095 std::vector<SymbolMaterializerItrPair> SymbolsToRemove; 1096 SymbolNameSet Missing; 1097 SymbolNameSet Materializing; 1098 1099 for (auto &Name : Names) { 1100 auto I = Symbols.find(Name); 1101 1102 // Note symbol missing. 1103 if (I == Symbols.end()) { 1104 Missing.insert(Name); 1105 continue; 1106 } 1107 1108 // Note symbol materializing. 1109 if (I->second.getFlags().isMaterializing()) { 1110 Materializing.insert(Name); 1111 continue; 1112 } 1113 1114 auto UMII = I->second.getFlags().isLazy() ? UnmaterializedInfos.find(Name) 1115 : UnmaterializedInfos.end(); 1116 SymbolsToRemove.push_back(std::make_pair(I, UMII)); 1117 } 1118 1119 // If any of the symbols are not defined, return an error. 1120 if (!Missing.empty()) 1121 return make_error<SymbolsNotFound>(std::move(Missing)); 1122 1123 // If any of the symbols are currently materializing, return an error. 1124 if (!Materializing.empty()) 1125 return make_error<SymbolsCouldNotBeRemoved>(std::move(Materializing)); 1126 1127 // Remove the symbols. 1128 for (auto &SymbolMaterializerItrPair : SymbolsToRemove) { 1129 auto UMII = SymbolMaterializerItrPair.second; 1130 1131 // If there is a materializer attached, call discard. 1132 if (UMII != UnmaterializedInfos.end()) { 1133 UMII->second->MU->doDiscard(*this, UMII->first); 1134 UnmaterializedInfos.erase(UMII); 1135 } 1136 1137 auto SymI = SymbolMaterializerItrPair.first; 1138 Symbols.erase(SymI); 1139 } 1140 1141 return Error::success(); 1142 }); 1143 } 1144 1145 SymbolFlagsMap JITDylib::lookupFlags(const SymbolNameSet &Names) { 1146 return ES.runSessionLocked([&, this]() { 1147 SymbolFlagsMap Result; 1148 auto Unresolved = lookupFlagsImpl(Result, Names); 1149 if (DefGenerator && !Unresolved.empty()) { 1150 auto NewDefs = DefGenerator(*this, Unresolved); 1151 if (!NewDefs.empty()) { 1152 auto Unresolved2 = lookupFlagsImpl(Result, NewDefs); 1153 (void)Unresolved2; 1154 assert(Unresolved2.empty() && 1155 "All fallback defs should have been found by lookupFlagsImpl"); 1156 } 1157 }; 1158 return Result; 1159 }); 1160 } 1161 1162 SymbolNameSet JITDylib::lookupFlagsImpl(SymbolFlagsMap &Flags, 1163 const SymbolNameSet &Names) { 1164 SymbolNameSet Unresolved; 1165 1166 for (auto &Name : Names) { 1167 auto I = Symbols.find(Name); 1168 1169 if (I == Symbols.end()) { 1170 Unresolved.insert(Name); 1171 continue; 1172 } 1173 1174 assert(!Flags.count(Name) && "Symbol already present in Flags map"); 1175 Flags[Name] = JITSymbolFlags::stripTransientFlags(I->second.getFlags()); 1176 } 1177 1178 return Unresolved; 1179 } 1180 1181 void JITDylib::lodgeQuery(std::shared_ptr<AsynchronousSymbolQuery> &Q, 1182 SymbolNameSet &Unresolved, bool MatchNonExported, 1183 MaterializationUnitList &MUs) { 1184 assert(Q && "Query can not be null"); 1185 1186 lodgeQueryImpl(Q, Unresolved, MatchNonExported, MUs); 1187 if (DefGenerator && !Unresolved.empty()) { 1188 auto NewDefs = DefGenerator(*this, Unresolved); 1189 if (!NewDefs.empty()) { 1190 for (auto &D : NewDefs) 1191 Unresolved.erase(D); 1192 lodgeQueryImpl(Q, NewDefs, MatchNonExported, MUs); 1193 assert(NewDefs.empty() && 1194 "All fallback defs should have been found by lookupImpl"); 1195 } 1196 } 1197 } 1198 1199 void JITDylib::lodgeQueryImpl( 1200 std::shared_ptr<AsynchronousSymbolQuery> &Q, SymbolNameSet &Unresolved, 1201 bool MatchNonExported, 1202 std::vector<std::unique_ptr<MaterializationUnit>> &MUs) { 1203 1204 std::vector<SymbolStringPtr> ToRemove; 1205 for (auto Name : Unresolved) { 1206 // Search for the name in Symbols. Skip it if not found. 1207 auto SymI = Symbols.find(Name); 1208 if (SymI == Symbols.end()) 1209 continue; 1210 1211 // If this is a non exported symbol and we're skipping those then skip it. 1212 if (!SymI->second.getFlags().isExported() && !MatchNonExported) 1213 continue; 1214 1215 // If we matched against Name in JD, mark it to be removed from the Unresolved 1216 // set. 1217 ToRemove.push_back(Name); 1218 1219 // If the symbol has an address then resolve it. 1220 if (SymI->second.getAddress() != 0) 1221 Q->resolve(Name, SymI->second); 1222 1223 // If the symbol is lazy, get the MaterialiaztionUnit for it. 1224 if (SymI->second.getFlags().isLazy()) { 1225 assert(SymI->second.getAddress() == 0 && 1226 "Lazy symbol should not have a resolved address"); 1227 assert(!SymI->second.getFlags().isMaterializing() && 1228 "Materializing and lazy should not both be set"); 1229 auto UMII = UnmaterializedInfos.find(Name); 1230 assert(UMII != UnmaterializedInfos.end() && 1231 "Lazy symbol should have UnmaterializedInfo"); 1232 auto MU = std::move(UMII->second->MU); 1233 assert(MU != nullptr && "Materializer should not be null"); 1234 1235 // Move all symbols associated with this MaterializationUnit into 1236 // materializing state. 1237 for (auto &KV : MU->getSymbols()) { 1238 auto SymK = Symbols.find(KV.first); 1239 auto Flags = SymK->second.getFlags(); 1240 Flags &= ~JITSymbolFlags::Lazy; 1241 Flags |= JITSymbolFlags::Materializing; 1242 SymK->second.setFlags(Flags); 1243 UnmaterializedInfos.erase(KV.first); 1244 } 1245 1246 // Add MU to the list of MaterializationUnits to be materialized. 1247 MUs.push_back(std::move(MU)); 1248 } else if (!SymI->second.getFlags().isMaterializing()) { 1249 // The symbol is neither lazy nor materializing, so it must be 1250 // ready. Notify the query and continue. 1251 Q->notifySymbolReady(); 1252 continue; 1253 } 1254 1255 // Add the query to the PendingQueries list. 1256 assert(SymI->second.getFlags().isMaterializing() && 1257 "By this line the symbol should be materializing"); 1258 auto &MI = MaterializingInfos[Name]; 1259 MI.PendingQueries.push_back(Q); 1260 Q->addQueryDependence(*this, Name); 1261 } 1262 1263 // Remove any symbols that we found. 1264 for (auto &Name : ToRemove) 1265 Unresolved.erase(Name); 1266 } 1267 1268 SymbolNameSet JITDylib::legacyLookup(std::shared_ptr<AsynchronousSymbolQuery> Q, 1269 SymbolNameSet Names) { 1270 assert(Q && "Query can not be null"); 1271 1272 ES.runOutstandingMUs(); 1273 1274 LookupImplActionFlags ActionFlags = None; 1275 std::vector<std::unique_ptr<MaterializationUnit>> MUs; 1276 1277 SymbolNameSet Unresolved = std::move(Names); 1278 ES.runSessionLocked([&, this]() { 1279 ActionFlags = lookupImpl(Q, MUs, Unresolved); 1280 if (DefGenerator && !Unresolved.empty()) { 1281 assert(ActionFlags == None && 1282 "ActionFlags set but unresolved symbols remain?"); 1283 auto NewDefs = DefGenerator(*this, Unresolved); 1284 if (!NewDefs.empty()) { 1285 for (auto &D : NewDefs) 1286 Unresolved.erase(D); 1287 ActionFlags = lookupImpl(Q, MUs, NewDefs); 1288 assert(NewDefs.empty() && 1289 "All fallback defs should have been found by lookupImpl"); 1290 } 1291 } 1292 }); 1293 1294 assert((MUs.empty() || ActionFlags == None) && 1295 "If action flags are set, there should be no work to do (so no MUs)"); 1296 1297 if (ActionFlags & NotifyFullyResolved) 1298 Q->handleFullyResolved(); 1299 1300 if (ActionFlags & NotifyFullyReady) 1301 Q->handleFullyReady(); 1302 1303 // FIXME: Swap back to the old code below once RuntimeDyld works with 1304 // callbacks from asynchronous queries. 1305 // Add MUs to the OutstandingMUs list. 1306 { 1307 std::lock_guard<std::recursive_mutex> Lock(ES.OutstandingMUsMutex); 1308 for (auto &MU : MUs) 1309 ES.OutstandingMUs.push_back(make_pair(this, std::move(MU))); 1310 } 1311 ES.runOutstandingMUs(); 1312 1313 // Dispatch any required MaterializationUnits for materialization. 1314 // for (auto &MU : MUs) 1315 // ES.dispatchMaterialization(*this, std::move(MU)); 1316 1317 return Unresolved; 1318 } 1319 1320 JITDylib::LookupImplActionFlags 1321 JITDylib::lookupImpl(std::shared_ptr<AsynchronousSymbolQuery> &Q, 1322 std::vector<std::unique_ptr<MaterializationUnit>> &MUs, 1323 SymbolNameSet &Unresolved) { 1324 LookupImplActionFlags ActionFlags = None; 1325 std::vector<SymbolStringPtr> ToRemove; 1326 1327 for (auto Name : Unresolved) { 1328 1329 // Search for the name in Symbols. Skip it if not found. 1330 auto SymI = Symbols.find(Name); 1331 if (SymI == Symbols.end()) 1332 continue; 1333 1334 // If we found Name, mark it to be removed from the Unresolved set. 1335 ToRemove.push_back(Name); 1336 1337 // If the symbol has an address then resolve it. 1338 if (SymI->second.getAddress() != 0) { 1339 Q->resolve(Name, SymI->second); 1340 if (Q->isFullyResolved()) 1341 ActionFlags |= NotifyFullyResolved; 1342 } 1343 1344 // If the symbol is lazy, get the MaterialiaztionUnit for it. 1345 if (SymI->second.getFlags().isLazy()) { 1346 assert(SymI->second.getAddress() == 0 && 1347 "Lazy symbol should not have a resolved address"); 1348 assert(!SymI->second.getFlags().isMaterializing() && 1349 "Materializing and lazy should not both be set"); 1350 auto UMII = UnmaterializedInfos.find(Name); 1351 assert(UMII != UnmaterializedInfos.end() && 1352 "Lazy symbol should have UnmaterializedInfo"); 1353 auto MU = std::move(UMII->second->MU); 1354 assert(MU != nullptr && "Materializer should not be null"); 1355 1356 // Kick all symbols associated with this MaterializationUnit into 1357 // materializing state. 1358 for (auto &KV : MU->getSymbols()) { 1359 auto SymK = Symbols.find(KV.first); 1360 auto Flags = SymK->second.getFlags(); 1361 Flags &= ~JITSymbolFlags::Lazy; 1362 Flags |= JITSymbolFlags::Materializing; 1363 SymK->second.setFlags(Flags); 1364 UnmaterializedInfos.erase(KV.first); 1365 } 1366 1367 // Add MU to the list of MaterializationUnits to be materialized. 1368 MUs.push_back(std::move(MU)); 1369 } else if (!SymI->second.getFlags().isMaterializing()) { 1370 // The symbol is neither lazy nor materializing, so it must be ready. 1371 // Notify the query and continue. 1372 Q->notifySymbolReady(); 1373 if (Q->isFullyReady()) 1374 ActionFlags |= NotifyFullyReady; 1375 continue; 1376 } 1377 1378 // Add the query to the PendingQueries list. 1379 assert(SymI->second.getFlags().isMaterializing() && 1380 "By this line the symbol should be materializing"); 1381 auto &MI = MaterializingInfos[Name]; 1382 MI.PendingQueries.push_back(Q); 1383 Q->addQueryDependence(*this, Name); 1384 } 1385 1386 // Remove any marked symbols from the Unresolved set. 1387 for (auto &Name : ToRemove) 1388 Unresolved.erase(Name); 1389 1390 return ActionFlags; 1391 } 1392 1393 void JITDylib::dump(raw_ostream &OS) { 1394 ES.runSessionLocked([&, this]() { 1395 OS << "JITDylib \"" << JITDylibName 1396 << "\" (ES: " << format("0x%016x", reinterpret_cast<uintptr_t>(&ES)) 1397 << "):\n" 1398 << "Search order: ["; 1399 for (auto &KV : SearchOrder) 1400 OS << " (\"" << KV.first->getName() << "\", " 1401 << (KV.second ? "all" : "exported only") << ")"; 1402 OS << " ]\n" 1403 << "Symbol table:\n"; 1404 1405 for (auto &KV : Symbols) { 1406 OS << " \"" << *KV.first << "\": "; 1407 if (auto Addr = KV.second.getAddress()) 1408 OS << format("0x%016x", Addr) << ", " << KV.second.getFlags(); 1409 else 1410 OS << "<not resolved>"; 1411 if (KV.second.getFlags().isLazy() || 1412 KV.second.getFlags().isMaterializing()) { 1413 OS << " ("; 1414 if (KV.second.getFlags().isLazy()) { 1415 auto I = UnmaterializedInfos.find(KV.first); 1416 assert(I != UnmaterializedInfos.end() && 1417 "Lazy symbol should have UnmaterializedInfo"); 1418 OS << " Lazy (MU=" << I->second->MU.get() << ")"; 1419 } 1420 if (KV.second.getFlags().isMaterializing()) 1421 OS << " Materializing"; 1422 OS << ", " << KV.second.getFlags() << " )\n"; 1423 } else 1424 OS << "\n"; 1425 } 1426 1427 if (!MaterializingInfos.empty()) 1428 OS << " MaterializingInfos entries:\n"; 1429 for (auto &KV : MaterializingInfos) { 1430 OS << " \"" << *KV.first << "\":\n" 1431 << " IsEmitted = " << (KV.second.IsEmitted ? "true" : "false") 1432 << "\n" 1433 << " " << KV.second.PendingQueries.size() 1434 << " pending queries: { "; 1435 for (auto &Q : KV.second.PendingQueries) 1436 OS << Q.get() << " "; 1437 OS << "}\n Dependants:\n"; 1438 for (auto &KV2 : KV.second.Dependants) 1439 OS << " " << KV2.first->getName() << ": " << KV2.second << "\n"; 1440 OS << " Unemitted Dependencies:\n"; 1441 for (auto &KV2 : KV.second.UnemittedDependencies) 1442 OS << " " << KV2.first->getName() << ": " << KV2.second << "\n"; 1443 } 1444 }); 1445 } 1446 1447 JITDylib::JITDylib(ExecutionSession &ES, std::string Name) 1448 : ES(ES), JITDylibName(std::move(Name)) { 1449 SearchOrder.push_back({this, true}); 1450 } 1451 1452 Error JITDylib::defineImpl(MaterializationUnit &MU) { 1453 SymbolNameSet Duplicates; 1454 SymbolNameSet MUDefsOverridden; 1455 1456 struct ExistingDefOverriddenEntry { 1457 SymbolMap::iterator ExistingDefItr; 1458 JITSymbolFlags NewFlags; 1459 }; 1460 std::vector<ExistingDefOverriddenEntry> ExistingDefsOverridden; 1461 1462 for (auto &KV : MU.getSymbols()) { 1463 assert(!KV.second.isLazy() && "Lazy flag should be managed internally."); 1464 assert(!KV.second.isMaterializing() && 1465 "Materializing flags should be managed internally."); 1466 1467 SymbolMap::iterator EntryItr; 1468 bool Added; 1469 1470 auto NewFlags = KV.second; 1471 NewFlags |= JITSymbolFlags::Lazy; 1472 1473 std::tie(EntryItr, Added) = Symbols.insert( 1474 std::make_pair(KV.first, JITEvaluatedSymbol(0, NewFlags))); 1475 1476 if (!Added) { 1477 if (KV.second.isStrong()) { 1478 if (EntryItr->second.getFlags().isStrong() || 1479 (EntryItr->second.getFlags() & JITSymbolFlags::Materializing)) 1480 Duplicates.insert(KV.first); 1481 else 1482 ExistingDefsOverridden.push_back({EntryItr, NewFlags}); 1483 } else 1484 MUDefsOverridden.insert(KV.first); 1485 } 1486 } 1487 1488 if (!Duplicates.empty()) { 1489 // We need to remove the symbols we added. 1490 for (auto &KV : MU.getSymbols()) { 1491 if (Duplicates.count(KV.first)) 1492 continue; 1493 1494 bool Found = false; 1495 for (const auto &EDO : ExistingDefsOverridden) 1496 if (EDO.ExistingDefItr->first == KV.first) 1497 Found = true; 1498 1499 if (!Found) 1500 Symbols.erase(KV.first); 1501 } 1502 1503 // FIXME: Return all duplicates. 1504 return make_error<DuplicateDefinition>(**Duplicates.begin()); 1505 } 1506 1507 // Update flags on existing defs and call discard on their materializers. 1508 for (auto &EDO : ExistingDefsOverridden) { 1509 assert(EDO.ExistingDefItr->second.getFlags().isLazy() && 1510 !EDO.ExistingDefItr->second.getFlags().isMaterializing() && 1511 "Overridden existing def should be in the Lazy state"); 1512 1513 EDO.ExistingDefItr->second.setFlags(EDO.NewFlags); 1514 1515 auto UMII = UnmaterializedInfos.find(EDO.ExistingDefItr->first); 1516 assert(UMII != UnmaterializedInfos.end() && 1517 "Overridden existing def should have an UnmaterializedInfo"); 1518 1519 UMII->second->MU->doDiscard(*this, EDO.ExistingDefItr->first); 1520 } 1521 1522 // Discard overridden symbols povided by MU. 1523 for (auto &Sym : MUDefsOverridden) 1524 MU.doDiscard(*this, Sym); 1525 1526 return Error::success(); 1527 } 1528 1529 void JITDylib::detachQueryHelper(AsynchronousSymbolQuery &Q, 1530 const SymbolNameSet &QuerySymbols) { 1531 for (auto &QuerySymbol : QuerySymbols) { 1532 assert(MaterializingInfos.count(QuerySymbol) && 1533 "QuerySymbol does not have MaterializingInfo"); 1534 auto &MI = MaterializingInfos[QuerySymbol]; 1535 1536 auto IdenticalQuery = 1537 [&](const std::shared_ptr<AsynchronousSymbolQuery> &R) { 1538 return R.get() == &Q; 1539 }; 1540 1541 auto I = std::find_if(MI.PendingQueries.begin(), MI.PendingQueries.end(), 1542 IdenticalQuery); 1543 assert(I != MI.PendingQueries.end() && 1544 "Query Q should be in the PendingQueries list for QuerySymbol"); 1545 MI.PendingQueries.erase(I); 1546 } 1547 } 1548 1549 void JITDylib::transferEmittedNodeDependencies( 1550 MaterializingInfo &DependantMI, const SymbolStringPtr &DependantName, 1551 MaterializingInfo &EmittedMI) { 1552 for (auto &KV : EmittedMI.UnemittedDependencies) { 1553 auto &DependencyJD = *KV.first; 1554 SymbolNameSet *UnemittedDependenciesOnDependencyJD = nullptr; 1555 1556 for (auto &DependencyName : KV.second) { 1557 auto &DependencyMI = DependencyJD.MaterializingInfos[DependencyName]; 1558 1559 // Do not add self dependencies. 1560 if (&DependencyMI == &DependantMI) 1561 continue; 1562 1563 // If we haven't looked up the dependencies for DependencyJD yet, do it 1564 // now and cache the result. 1565 if (!UnemittedDependenciesOnDependencyJD) 1566 UnemittedDependenciesOnDependencyJD = 1567 &DependantMI.UnemittedDependencies[&DependencyJD]; 1568 1569 DependencyMI.Dependants[this].insert(DependantName); 1570 UnemittedDependenciesOnDependencyJD->insert(DependencyName); 1571 } 1572 } 1573 } 1574 1575 ExecutionSession::ExecutionSession(std::shared_ptr<SymbolStringPool> SSP) 1576 : SSP(SSP ? std::move(SSP) : std::make_shared<SymbolStringPool>()) { 1577 // Construct the main dylib. 1578 JDs.push_back(std::unique_ptr<JITDylib>(new JITDylib(*this, "<main>"))); 1579 } 1580 1581 JITDylib &ExecutionSession::getMainJITDylib() { 1582 return runSessionLocked([this]() -> JITDylib & { return *JDs.front(); }); 1583 } 1584 1585 JITDylib &ExecutionSession::createJITDylib(std::string Name, 1586 bool AddToMainDylibSearchOrder) { 1587 return runSessionLocked([&, this]() -> JITDylib & { 1588 JDs.push_back( 1589 std::unique_ptr<JITDylib>(new JITDylib(*this, std::move(Name)))); 1590 if (AddToMainDylibSearchOrder) 1591 JDs.front()->addToSearchOrder(*JDs.back()); 1592 return *JDs.back(); 1593 }); 1594 } 1595 1596 void ExecutionSession::legacyFailQuery(AsynchronousSymbolQuery &Q, Error Err) { 1597 assert(!!Err && "Error should be in failure state"); 1598 1599 bool SendErrorToQuery; 1600 runSessionLocked([&]() { 1601 Q.detach(); 1602 SendErrorToQuery = Q.canStillFail(); 1603 }); 1604 1605 if (SendErrorToQuery) 1606 Q.handleFailed(std::move(Err)); 1607 else 1608 reportError(std::move(Err)); 1609 } 1610 1611 Expected<SymbolMap> ExecutionSession::legacyLookup( 1612 LegacyAsyncLookupFunction AsyncLookup, SymbolNameSet Names, 1613 bool WaitUntilReady, RegisterDependenciesFunction RegisterDependencies) { 1614 #if LLVM_ENABLE_THREADS 1615 // In the threaded case we use promises to return the results. 1616 std::promise<SymbolMap> PromisedResult; 1617 std::mutex ErrMutex; 1618 Error ResolutionError = Error::success(); 1619 std::promise<void> PromisedReady; 1620 Error ReadyError = Error::success(); 1621 auto OnResolve = [&](Expected<SymbolMap> R) { 1622 if (R) 1623 PromisedResult.set_value(std::move(*R)); 1624 else { 1625 { 1626 ErrorAsOutParameter _(&ResolutionError); 1627 std::lock_guard<std::mutex> Lock(ErrMutex); 1628 ResolutionError = R.takeError(); 1629 } 1630 PromisedResult.set_value(SymbolMap()); 1631 } 1632 }; 1633 1634 std::function<void(Error)> OnReady; 1635 if (WaitUntilReady) { 1636 OnReady = [&](Error Err) { 1637 if (Err) { 1638 ErrorAsOutParameter _(&ReadyError); 1639 std::lock_guard<std::mutex> Lock(ErrMutex); 1640 ReadyError = std::move(Err); 1641 } 1642 PromisedReady.set_value(); 1643 }; 1644 } else { 1645 OnReady = [&](Error Err) { 1646 if (Err) 1647 reportError(std::move(Err)); 1648 }; 1649 } 1650 1651 #else 1652 SymbolMap Result; 1653 Error ResolutionError = Error::success(); 1654 Error ReadyError = Error::success(); 1655 1656 auto OnResolve = [&](Expected<SymbolMap> R) { 1657 ErrorAsOutParameter _(&ResolutionError); 1658 if (R) 1659 Result = std::move(*R); 1660 else 1661 ResolutionError = R.takeError(); 1662 }; 1663 1664 std::function<void(Error)> OnReady; 1665 if (WaitUntilReady) { 1666 OnReady = [&](Error Err) { 1667 ErrorAsOutParameter _(&ReadyError); 1668 if (Err) 1669 ReadyError = std::move(Err); 1670 }; 1671 } else { 1672 OnReady = [&](Error Err) { 1673 if (Err) 1674 reportError(std::move(Err)); 1675 }; 1676 } 1677 #endif 1678 1679 auto Query = std::make_shared<AsynchronousSymbolQuery>( 1680 Names, std::move(OnResolve), std::move(OnReady)); 1681 // FIXME: This should be run session locked along with the registration code 1682 // and error reporting below. 1683 SymbolNameSet UnresolvedSymbols = AsyncLookup(Query, std::move(Names)); 1684 1685 // If the query was lodged successfully then register the dependencies, 1686 // otherwise fail it with an error. 1687 if (UnresolvedSymbols.empty()) 1688 RegisterDependencies(Query->QueryRegistrations); 1689 else { 1690 bool DeliverError = runSessionLocked([&]() { 1691 Query->detach(); 1692 return Query->canStillFail(); 1693 }); 1694 auto Err = make_error<SymbolsNotFound>(std::move(UnresolvedSymbols)); 1695 if (DeliverError) 1696 Query->handleFailed(std::move(Err)); 1697 else 1698 reportError(std::move(Err)); 1699 } 1700 1701 #if LLVM_ENABLE_THREADS 1702 auto ResultFuture = PromisedResult.get_future(); 1703 auto Result = ResultFuture.get(); 1704 1705 { 1706 std::lock_guard<std::mutex> Lock(ErrMutex); 1707 if (ResolutionError) { 1708 // ReadyError will never be assigned. Consume the success value. 1709 cantFail(std::move(ReadyError)); 1710 return std::move(ResolutionError); 1711 } 1712 } 1713 1714 if (WaitUntilReady) { 1715 auto ReadyFuture = PromisedReady.get_future(); 1716 ReadyFuture.get(); 1717 1718 { 1719 std::lock_guard<std::mutex> Lock(ErrMutex); 1720 if (ReadyError) 1721 return std::move(ReadyError); 1722 } 1723 } else 1724 cantFail(std::move(ReadyError)); 1725 1726 return std::move(Result); 1727 1728 #else 1729 if (ResolutionError) { 1730 // ReadyError will never be assigned. Consume the success value. 1731 cantFail(std::move(ReadyError)); 1732 return std::move(ResolutionError); 1733 } 1734 1735 if (ReadyError) 1736 return std::move(ReadyError); 1737 1738 return Result; 1739 #endif 1740 } 1741 1742 void ExecutionSession::lookup( 1743 const JITDylibSearchList &SearchOrder, SymbolNameSet Symbols, 1744 SymbolsResolvedCallback OnResolve, SymbolsReadyCallback OnReady, 1745 RegisterDependenciesFunction RegisterDependencies) { 1746 1747 // lookup can be re-entered recursively if running on a single thread. Run any 1748 // outstanding MUs in case this query depends on them, otherwise this lookup 1749 // will starve waiting for a result from an MU that is stuck in the queue. 1750 runOutstandingMUs(); 1751 1752 auto Unresolved = std::move(Symbols); 1753 std::map<JITDylib *, MaterializationUnitList> CollectedMUsMap; 1754 auto Q = std::make_shared<AsynchronousSymbolQuery>( 1755 Unresolved, std::move(OnResolve), std::move(OnReady)); 1756 bool QueryIsFullyResolved = false; 1757 bool QueryIsFullyReady = false; 1758 bool QueryFailed = false; 1759 1760 runSessionLocked([&]() { 1761 for (auto &KV : SearchOrder) { 1762 assert(KV.first && "JITDylibList entries must not be null"); 1763 assert(!CollectedMUsMap.count(KV.first) && 1764 "JITDylibList should not contain duplicate entries"); 1765 1766 auto &JD = *KV.first; 1767 auto MatchNonExported = KV.second; 1768 JD.lodgeQuery(Q, Unresolved, MatchNonExported, CollectedMUsMap[&JD]); 1769 } 1770 1771 if (Unresolved.empty()) { 1772 // Query lodged successfully. 1773 1774 // Record whether this query is fully ready / resolved. We will use 1775 // this to call handleFullyResolved/handleFullyReady outside the session 1776 // lock. 1777 QueryIsFullyResolved = Q->isFullyResolved(); 1778 QueryIsFullyReady = Q->isFullyReady(); 1779 1780 // Call the register dependencies function. 1781 if (RegisterDependencies && !Q->QueryRegistrations.empty()) 1782 RegisterDependencies(Q->QueryRegistrations); 1783 } else { 1784 // Query failed due to unresolved symbols. 1785 QueryFailed = true; 1786 1787 // Disconnect the query from its dependencies. 1788 Q->detach(); 1789 1790 // Replace the MUs. 1791 for (auto &KV : CollectedMUsMap) 1792 for (auto &MU : KV.second) 1793 KV.first->replace(std::move(MU)); 1794 } 1795 }); 1796 1797 if (QueryFailed) { 1798 Q->handleFailed(make_error<SymbolsNotFound>(std::move(Unresolved))); 1799 return; 1800 } else { 1801 if (QueryIsFullyResolved) 1802 Q->handleFullyResolved(); 1803 if (QueryIsFullyReady) 1804 Q->handleFullyReady(); 1805 } 1806 1807 // Move the MUs to the OutstandingMUs list, then materialize. 1808 { 1809 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex); 1810 1811 for (auto &KV : CollectedMUsMap) 1812 for (auto &MU : KV.second) 1813 OutstandingMUs.push_back(std::make_pair(KV.first, std::move(MU))); 1814 } 1815 1816 runOutstandingMUs(); 1817 } 1818 1819 Expected<SymbolMap> ExecutionSession::lookup( 1820 const JITDylibSearchList &SearchOrder, const SymbolNameSet &Symbols, 1821 RegisterDependenciesFunction RegisterDependencies, bool WaitUntilReady) { 1822 #if LLVM_ENABLE_THREADS 1823 // In the threaded case we use promises to return the results. 1824 std::promise<SymbolMap> PromisedResult; 1825 std::mutex ErrMutex; 1826 Error ResolutionError = Error::success(); 1827 std::promise<void> PromisedReady; 1828 Error ReadyError = Error::success(); 1829 auto OnResolve = [&](Expected<SymbolMap> R) { 1830 if (R) 1831 PromisedResult.set_value(std::move(*R)); 1832 else { 1833 { 1834 ErrorAsOutParameter _(&ResolutionError); 1835 std::lock_guard<std::mutex> Lock(ErrMutex); 1836 ResolutionError = R.takeError(); 1837 } 1838 PromisedResult.set_value(SymbolMap()); 1839 } 1840 }; 1841 1842 std::function<void(Error)> OnReady; 1843 if (WaitUntilReady) { 1844 OnReady = [&](Error Err) { 1845 if (Err) { 1846 ErrorAsOutParameter _(&ReadyError); 1847 std::lock_guard<std::mutex> Lock(ErrMutex); 1848 ReadyError = std::move(Err); 1849 } 1850 PromisedReady.set_value(); 1851 }; 1852 } else { 1853 OnReady = [&](Error Err) { 1854 if (Err) 1855 reportError(std::move(Err)); 1856 }; 1857 } 1858 1859 #else 1860 SymbolMap Result; 1861 Error ResolutionError = Error::success(); 1862 Error ReadyError = Error::success(); 1863 1864 auto OnResolve = [&](Expected<SymbolMap> R) { 1865 ErrorAsOutParameter _(&ResolutionError); 1866 if (R) 1867 Result = std::move(*R); 1868 else 1869 ResolutionError = R.takeError(); 1870 }; 1871 1872 std::function<void(Error)> OnReady; 1873 if (WaitUntilReady) { 1874 OnReady = [&](Error Err) { 1875 ErrorAsOutParameter _(&ReadyError); 1876 if (Err) 1877 ReadyError = std::move(Err); 1878 }; 1879 } else { 1880 OnReady = [&](Error Err) { 1881 if (Err) 1882 reportError(std::move(Err)); 1883 }; 1884 } 1885 #endif 1886 1887 // Perform the asynchronous lookup. 1888 lookup(SearchOrder, Symbols, OnResolve, OnReady, RegisterDependencies); 1889 1890 #if LLVM_ENABLE_THREADS 1891 auto ResultFuture = PromisedResult.get_future(); 1892 auto Result = ResultFuture.get(); 1893 1894 { 1895 std::lock_guard<std::mutex> Lock(ErrMutex); 1896 if (ResolutionError) { 1897 // ReadyError will never be assigned. Consume the success value. 1898 cantFail(std::move(ReadyError)); 1899 return std::move(ResolutionError); 1900 } 1901 } 1902 1903 if (WaitUntilReady) { 1904 auto ReadyFuture = PromisedReady.get_future(); 1905 ReadyFuture.get(); 1906 1907 { 1908 std::lock_guard<std::mutex> Lock(ErrMutex); 1909 if (ReadyError) 1910 return std::move(ReadyError); 1911 } 1912 } else 1913 cantFail(std::move(ReadyError)); 1914 1915 return std::move(Result); 1916 1917 #else 1918 if (ResolutionError) { 1919 // ReadyError will never be assigned. Consume the success value. 1920 cantFail(std::move(ReadyError)); 1921 return std::move(ResolutionError); 1922 } 1923 1924 if (ReadyError) 1925 return std::move(ReadyError); 1926 1927 return Result; 1928 #endif 1929 } 1930 1931 Expected<JITEvaluatedSymbol> 1932 ExecutionSession::lookup(const JITDylibSearchList &SearchOrder, 1933 SymbolStringPtr Name) { 1934 SymbolNameSet Names({Name}); 1935 1936 if (auto ResultMap = lookup(SearchOrder, std::move(Names), 1937 NoDependenciesToRegister, true)) { 1938 assert(ResultMap->size() == 1 && "Unexpected number of results"); 1939 assert(ResultMap->count(Name) && "Missing result for symbol"); 1940 return std::move(ResultMap->begin()->second); 1941 } else 1942 return ResultMap.takeError(); 1943 } 1944 1945 Expected<JITEvaluatedSymbol> 1946 ExecutionSession::lookup(ArrayRef<JITDylib *> SearchOrder, 1947 SymbolStringPtr Name) { 1948 SymbolNameSet Names({Name}); 1949 1950 JITDylibSearchList FullSearchOrder(SearchOrder.size()); 1951 for (auto *JD : SearchOrder) 1952 FullSearchOrder.push_back({JD, false}); 1953 1954 return lookup(FullSearchOrder, Name); 1955 } 1956 1957 Expected<JITEvaluatedSymbol> 1958 ExecutionSession::lookup(ArrayRef<JITDylib *> SearchOrder, StringRef Name) { 1959 return lookup(SearchOrder, intern(Name)); 1960 } 1961 1962 void ExecutionSession::dump(raw_ostream &OS) { 1963 runSessionLocked([this, &OS]() { 1964 for (auto &JD : JDs) 1965 JD->dump(OS); 1966 }); 1967 } 1968 1969 void ExecutionSession::runOutstandingMUs() { 1970 while (1) { 1971 std::pair<JITDylib *, std::unique_ptr<MaterializationUnit>> JITDylibAndMU; 1972 1973 { 1974 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex); 1975 if (!OutstandingMUs.empty()) { 1976 JITDylibAndMU = std::move(OutstandingMUs.back()); 1977 OutstandingMUs.pop_back(); 1978 } 1979 } 1980 1981 if (JITDylibAndMU.first) { 1982 assert(JITDylibAndMU.second && "JITDylib, but no MU?"); 1983 dispatchMaterialization(*JITDylibAndMU.first, 1984 std::move(JITDylibAndMU.second)); 1985 } else 1986 break; 1987 } 1988 } 1989 1990 MangleAndInterner::MangleAndInterner(ExecutionSession &ES, const DataLayout &DL) 1991 : ES(ES), DL(DL) {} 1992 1993 SymbolStringPtr MangleAndInterner::operator()(StringRef Name) { 1994 std::string MangledName; 1995 { 1996 raw_string_ostream MangledNameStream(MangledName); 1997 Mangler::getNameWithPrefix(MangledNameStream, Name, DL); 1998 } 1999 return ES.intern(MangledName); 2000 } 2001 2002 } // End namespace orc. 2003 } // End namespace llvm. 2004