1 //===--- Core.cpp - Core ORC APIs (MaterializationUnit, JITDylib, etc.) ---===// 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 #include "llvm/ExecutionEngine/Orc/Core.h" 10 #include "llvm/Config/llvm-config.h" 11 #include "llvm/ExecutionEngine/Orc/OrcError.h" 12 #include "llvm/IR/Mangler.h" 13 #include "llvm/Support/CommandLine.h" 14 #include "llvm/Support/Debug.h" 15 #include "llvm/Support/Format.h" 16 17 #if LLVM_ENABLE_THREADS 18 #include <future> 19 #endif 20 21 #define DEBUG_TYPE "orc" 22 23 using namespace llvm; 24 25 namespace { 26 27 #ifndef NDEBUG 28 29 cl::opt<bool> PrintHidden("debug-orc-print-hidden", cl::init(true), 30 cl::desc("debug print hidden symbols defined by " 31 "materialization units"), 32 cl::Hidden); 33 34 cl::opt<bool> PrintCallable("debug-orc-print-callable", cl::init(true), 35 cl::desc("debug print callable symbols defined by " 36 "materialization units"), 37 cl::Hidden); 38 39 cl::opt<bool> PrintData("debug-orc-print-data", cl::init(true), 40 cl::desc("debug print data symbols defined by " 41 "materialization units"), 42 cl::Hidden); 43 44 #endif // NDEBUG 45 46 // SetPrinter predicate that prints every element. 47 template <typename T> struct PrintAll { 48 bool operator()(const T &E) { return true; } 49 }; 50 51 bool anyPrintSymbolOptionSet() { 52 #ifndef NDEBUG 53 return PrintHidden || PrintCallable || PrintData; 54 #else 55 return false; 56 #endif // NDEBUG 57 } 58 59 bool flagsMatchCLOpts(const JITSymbolFlags &Flags) { 60 #ifndef NDEBUG 61 // Bail out early if this is a hidden symbol and we're not printing hiddens. 62 if (!PrintHidden && !Flags.isExported()) 63 return false; 64 65 // Return true if this is callable and we're printing callables. 66 if (PrintCallable && Flags.isCallable()) 67 return true; 68 69 // Return true if this is data and we're printing data. 70 if (PrintData && !Flags.isCallable()) 71 return true; 72 73 // otherwise return false. 74 return false; 75 #else 76 return false; 77 #endif // NDEBUG 78 } 79 80 // Prints a set of items, filtered by an user-supplied predicate. 81 template <typename Set, typename Pred = PrintAll<typename Set::value_type>> 82 class SetPrinter { 83 public: 84 SetPrinter(const Set &S, Pred ShouldPrint = Pred()) 85 : S(S), ShouldPrint(std::move(ShouldPrint)) {} 86 87 void printTo(llvm::raw_ostream &OS) const { 88 bool PrintComma = false; 89 OS << "{"; 90 for (auto &E : S) { 91 if (ShouldPrint(E)) { 92 if (PrintComma) 93 OS << ','; 94 OS << ' ' << E; 95 PrintComma = true; 96 } 97 } 98 OS << " }"; 99 } 100 101 private: 102 const Set &S; 103 mutable Pred ShouldPrint; 104 }; 105 106 template <typename Set, typename Pred> 107 SetPrinter<Set, Pred> printSet(const Set &S, Pred P = Pred()) { 108 return SetPrinter<Set, Pred>(S, std::move(P)); 109 } 110 111 // Render a SetPrinter by delegating to its printTo method. 112 template <typename Set, typename Pred> 113 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, 114 const SetPrinter<Set, Pred> &Printer) { 115 Printer.printTo(OS); 116 return OS; 117 } 118 119 struct PrintSymbolFlagsMapElemsMatchingCLOpts { 120 bool operator()(const orc::SymbolFlagsMap::value_type &KV) { 121 return flagsMatchCLOpts(KV.second); 122 } 123 }; 124 125 struct PrintSymbolMapElemsMatchingCLOpts { 126 bool operator()(const orc::SymbolMap::value_type &KV) { 127 return flagsMatchCLOpts(KV.second.getFlags()); 128 } 129 }; 130 131 } // end anonymous namespace 132 133 namespace llvm { 134 namespace orc { 135 136 SymbolStringPool::PoolMapEntry SymbolStringPtr::Tombstone(0); 137 138 char FailedToMaterialize::ID = 0; 139 char SymbolsNotFound::ID = 0; 140 char SymbolsCouldNotBeRemoved::ID = 0; 141 142 RegisterDependenciesFunction NoDependenciesToRegister = 143 RegisterDependenciesFunction(); 144 145 void MaterializationUnit::anchor() {} 146 147 raw_ostream &operator<<(raw_ostream &OS, const SymbolStringPtr &Sym) { 148 return OS << *Sym; 149 } 150 151 raw_ostream &operator<<(raw_ostream &OS, const SymbolNameSet &Symbols) { 152 return OS << printSet(Symbols, PrintAll<SymbolStringPtr>()); 153 } 154 155 raw_ostream &operator<<(raw_ostream &OS, const JITSymbolFlags &Flags) { 156 if (Flags.isCallable()) 157 OS << "[Callable]"; 158 else 159 OS << "[Data]"; 160 if (Flags.isWeak()) 161 OS << "[Weak]"; 162 else if (Flags.isCommon()) 163 OS << "[Common]"; 164 165 if (!Flags.isExported()) 166 OS << "[Hidden]"; 167 168 return OS; 169 } 170 171 raw_ostream &operator<<(raw_ostream &OS, const JITEvaluatedSymbol &Sym) { 172 return OS << format("0x%016" PRIx64, Sym.getAddress()) << " " 173 << 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) { 1055 if (NewSearchOrder.empty() || NewSearchOrder.front().first != this) 1056 NewSearchOrder.insert(NewSearchOrder.begin(), 1057 {this, MatchNonExportedInThisDylib}); 1058 } 1059 1060 ES.runSessionLocked([&]() { SearchOrder = std::move(NewSearchOrder); }); 1061 } 1062 1063 void JITDylib::addToSearchOrder(JITDylib &JD, bool MatchNonExported) { 1064 ES.runSessionLocked([&]() { 1065 SearchOrder.push_back({&JD, MatchNonExported}); 1066 }); 1067 } 1068 1069 void JITDylib::replaceInSearchOrder(JITDylib &OldJD, JITDylib &NewJD, 1070 bool MatchNonExported) { 1071 ES.runSessionLocked([&]() { 1072 auto I = std::find_if(SearchOrder.begin(), SearchOrder.end(), 1073 [&](const JITDylibSearchList::value_type &KV) { 1074 return KV.first == &OldJD; 1075 }); 1076 1077 if (I != SearchOrder.end()) 1078 *I = {&NewJD, MatchNonExported}; 1079 }); 1080 } 1081 1082 void JITDylib::removeFromSearchOrder(JITDylib &JD) { 1083 ES.runSessionLocked([&]() { 1084 auto I = std::find_if(SearchOrder.begin(), SearchOrder.end(), 1085 [&](const JITDylibSearchList::value_type &KV) { 1086 return KV.first == &JD; 1087 }); 1088 if (I != SearchOrder.end()) 1089 SearchOrder.erase(I); 1090 }); 1091 } 1092 1093 Error JITDylib::remove(const SymbolNameSet &Names) { 1094 return ES.runSessionLocked([&]() -> Error { 1095 using SymbolMaterializerItrPair = 1096 std::pair<SymbolMap::iterator, UnmaterializedInfosMap::iterator>; 1097 std::vector<SymbolMaterializerItrPair> SymbolsToRemove; 1098 SymbolNameSet Missing; 1099 SymbolNameSet Materializing; 1100 1101 for (auto &Name : Names) { 1102 auto I = Symbols.find(Name); 1103 1104 // Note symbol missing. 1105 if (I == Symbols.end()) { 1106 Missing.insert(Name); 1107 continue; 1108 } 1109 1110 // Note symbol materializing. 1111 if (I->second.getFlags().isMaterializing()) { 1112 Materializing.insert(Name); 1113 continue; 1114 } 1115 1116 auto UMII = I->second.getFlags().isLazy() ? UnmaterializedInfos.find(Name) 1117 : UnmaterializedInfos.end(); 1118 SymbolsToRemove.push_back(std::make_pair(I, UMII)); 1119 } 1120 1121 // If any of the symbols are not defined, return an error. 1122 if (!Missing.empty()) 1123 return make_error<SymbolsNotFound>(std::move(Missing)); 1124 1125 // If any of the symbols are currently materializing, return an error. 1126 if (!Materializing.empty()) 1127 return make_error<SymbolsCouldNotBeRemoved>(std::move(Materializing)); 1128 1129 // Remove the symbols. 1130 for (auto &SymbolMaterializerItrPair : SymbolsToRemove) { 1131 auto UMII = SymbolMaterializerItrPair.second; 1132 1133 // If there is a materializer attached, call discard. 1134 if (UMII != UnmaterializedInfos.end()) { 1135 UMII->second->MU->doDiscard(*this, UMII->first); 1136 UnmaterializedInfos.erase(UMII); 1137 } 1138 1139 auto SymI = SymbolMaterializerItrPair.first; 1140 Symbols.erase(SymI); 1141 } 1142 1143 return Error::success(); 1144 }); 1145 } 1146 1147 SymbolFlagsMap JITDylib::lookupFlags(const SymbolNameSet &Names) { 1148 return ES.runSessionLocked([&, this]() { 1149 SymbolFlagsMap Result; 1150 auto Unresolved = lookupFlagsImpl(Result, Names); 1151 if (DefGenerator && !Unresolved.empty()) { 1152 auto NewDefs = DefGenerator(*this, Unresolved); 1153 if (!NewDefs.empty()) { 1154 auto Unresolved2 = lookupFlagsImpl(Result, NewDefs); 1155 (void)Unresolved2; 1156 assert(Unresolved2.empty() && 1157 "All fallback defs should have been found by lookupFlagsImpl"); 1158 } 1159 }; 1160 return Result; 1161 }); 1162 } 1163 1164 SymbolNameSet JITDylib::lookupFlagsImpl(SymbolFlagsMap &Flags, 1165 const SymbolNameSet &Names) { 1166 SymbolNameSet Unresolved; 1167 1168 for (auto &Name : Names) { 1169 auto I = Symbols.find(Name); 1170 1171 if (I == Symbols.end()) { 1172 Unresolved.insert(Name); 1173 continue; 1174 } 1175 1176 assert(!Flags.count(Name) && "Symbol already present in Flags map"); 1177 Flags[Name] = JITSymbolFlags::stripTransientFlags(I->second.getFlags()); 1178 } 1179 1180 return Unresolved; 1181 } 1182 1183 void JITDylib::lodgeQuery(std::shared_ptr<AsynchronousSymbolQuery> &Q, 1184 SymbolNameSet &Unresolved, bool MatchNonExported, 1185 MaterializationUnitList &MUs) { 1186 assert(Q && "Query can not be null"); 1187 1188 lodgeQueryImpl(Q, Unresolved, MatchNonExported, MUs); 1189 if (DefGenerator && !Unresolved.empty()) { 1190 auto NewDefs = DefGenerator(*this, Unresolved); 1191 if (!NewDefs.empty()) { 1192 for (auto &D : NewDefs) 1193 Unresolved.erase(D); 1194 lodgeQueryImpl(Q, NewDefs, MatchNonExported, MUs); 1195 assert(NewDefs.empty() && 1196 "All fallback defs should have been found by lookupImpl"); 1197 } 1198 } 1199 } 1200 1201 void JITDylib::lodgeQueryImpl( 1202 std::shared_ptr<AsynchronousSymbolQuery> &Q, SymbolNameSet &Unresolved, 1203 bool MatchNonExported, 1204 std::vector<std::unique_ptr<MaterializationUnit>> &MUs) { 1205 1206 std::vector<SymbolStringPtr> ToRemove; 1207 for (auto Name : Unresolved) { 1208 // Search for the name in Symbols. Skip it if not found. 1209 auto SymI = Symbols.find(Name); 1210 if (SymI == Symbols.end()) 1211 continue; 1212 1213 // If this is a non exported symbol and we're skipping those then skip it. 1214 if (!SymI->second.getFlags().isExported() && !MatchNonExported) 1215 continue; 1216 1217 // If we matched against Name in JD, mark it to be removed from the Unresolved 1218 // set. 1219 ToRemove.push_back(Name); 1220 1221 // If the symbol has an address then resolve it. 1222 if (SymI->second.getAddress() != 0) 1223 Q->resolve(Name, SymI->second); 1224 1225 // If the symbol is lazy, get the MaterialiaztionUnit for it. 1226 if (SymI->second.getFlags().isLazy()) { 1227 assert(SymI->second.getAddress() == 0 && 1228 "Lazy symbol should not have a resolved address"); 1229 assert(!SymI->second.getFlags().isMaterializing() && 1230 "Materializing and lazy should not both be set"); 1231 auto UMII = UnmaterializedInfos.find(Name); 1232 assert(UMII != UnmaterializedInfos.end() && 1233 "Lazy symbol should have UnmaterializedInfo"); 1234 auto MU = std::move(UMII->second->MU); 1235 assert(MU != nullptr && "Materializer should not be null"); 1236 1237 // Move all symbols associated with this MaterializationUnit into 1238 // materializing state. 1239 for (auto &KV : MU->getSymbols()) { 1240 auto SymK = Symbols.find(KV.first); 1241 auto Flags = SymK->second.getFlags(); 1242 Flags &= ~JITSymbolFlags::Lazy; 1243 Flags |= JITSymbolFlags::Materializing; 1244 SymK->second.setFlags(Flags); 1245 UnmaterializedInfos.erase(KV.first); 1246 } 1247 1248 // Add MU to the list of MaterializationUnits to be materialized. 1249 MUs.push_back(std::move(MU)); 1250 } else if (!SymI->second.getFlags().isMaterializing()) { 1251 // The symbol is neither lazy nor materializing, so it must be 1252 // ready. Notify the query and continue. 1253 Q->notifySymbolReady(); 1254 continue; 1255 } 1256 1257 // Add the query to the PendingQueries list. 1258 assert(SymI->second.getFlags().isMaterializing() && 1259 "By this line the symbol should be materializing"); 1260 auto &MI = MaterializingInfos[Name]; 1261 MI.PendingQueries.push_back(Q); 1262 Q->addQueryDependence(*this, Name); 1263 } 1264 1265 // Remove any symbols that we found. 1266 for (auto &Name : ToRemove) 1267 Unresolved.erase(Name); 1268 } 1269 1270 SymbolNameSet JITDylib::legacyLookup(std::shared_ptr<AsynchronousSymbolQuery> Q, 1271 SymbolNameSet Names) { 1272 assert(Q && "Query can not be null"); 1273 1274 ES.runOutstandingMUs(); 1275 1276 LookupImplActionFlags ActionFlags = None; 1277 std::vector<std::unique_ptr<MaterializationUnit>> MUs; 1278 1279 SymbolNameSet Unresolved = std::move(Names); 1280 ES.runSessionLocked([&, this]() { 1281 ActionFlags = lookupImpl(Q, MUs, Unresolved); 1282 if (DefGenerator && !Unresolved.empty()) { 1283 assert(ActionFlags == None && 1284 "ActionFlags set but unresolved symbols remain?"); 1285 auto NewDefs = DefGenerator(*this, Unresolved); 1286 if (!NewDefs.empty()) { 1287 for (auto &D : NewDefs) 1288 Unresolved.erase(D); 1289 ActionFlags = lookupImpl(Q, MUs, NewDefs); 1290 assert(NewDefs.empty() && 1291 "All fallback defs should have been found by lookupImpl"); 1292 } 1293 } 1294 }); 1295 1296 assert((MUs.empty() || ActionFlags == None) && 1297 "If action flags are set, there should be no work to do (so no MUs)"); 1298 1299 if (ActionFlags & NotifyFullyResolved) 1300 Q->handleFullyResolved(); 1301 1302 if (ActionFlags & NotifyFullyReady) 1303 Q->handleFullyReady(); 1304 1305 // FIXME: Swap back to the old code below once RuntimeDyld works with 1306 // callbacks from asynchronous queries. 1307 // Add MUs to the OutstandingMUs list. 1308 { 1309 std::lock_guard<std::recursive_mutex> Lock(ES.OutstandingMUsMutex); 1310 for (auto &MU : MUs) 1311 ES.OutstandingMUs.push_back(make_pair(this, std::move(MU))); 1312 } 1313 ES.runOutstandingMUs(); 1314 1315 // Dispatch any required MaterializationUnits for materialization. 1316 // for (auto &MU : MUs) 1317 // ES.dispatchMaterialization(*this, std::move(MU)); 1318 1319 return Unresolved; 1320 } 1321 1322 JITDylib::LookupImplActionFlags 1323 JITDylib::lookupImpl(std::shared_ptr<AsynchronousSymbolQuery> &Q, 1324 std::vector<std::unique_ptr<MaterializationUnit>> &MUs, 1325 SymbolNameSet &Unresolved) { 1326 LookupImplActionFlags ActionFlags = None; 1327 std::vector<SymbolStringPtr> ToRemove; 1328 1329 for (auto Name : Unresolved) { 1330 1331 // Search for the name in Symbols. Skip it if not found. 1332 auto SymI = Symbols.find(Name); 1333 if (SymI == Symbols.end()) 1334 continue; 1335 1336 // If we found Name, mark it to be removed from the Unresolved set. 1337 ToRemove.push_back(Name); 1338 1339 // If the symbol has an address then resolve it. 1340 if (SymI->second.getAddress() != 0) { 1341 Q->resolve(Name, SymI->second); 1342 if (Q->isFullyResolved()) 1343 ActionFlags |= NotifyFullyResolved; 1344 } 1345 1346 // If the symbol is lazy, get the MaterialiaztionUnit for it. 1347 if (SymI->second.getFlags().isLazy()) { 1348 assert(SymI->second.getAddress() == 0 && 1349 "Lazy symbol should not have a resolved address"); 1350 assert(!SymI->second.getFlags().isMaterializing() && 1351 "Materializing and lazy should not both be set"); 1352 auto UMII = UnmaterializedInfos.find(Name); 1353 assert(UMII != UnmaterializedInfos.end() && 1354 "Lazy symbol should have UnmaterializedInfo"); 1355 auto MU = std::move(UMII->second->MU); 1356 assert(MU != nullptr && "Materializer should not be null"); 1357 1358 // Kick all symbols associated with this MaterializationUnit into 1359 // materializing state. 1360 for (auto &KV : MU->getSymbols()) { 1361 auto SymK = Symbols.find(KV.first); 1362 auto Flags = SymK->second.getFlags(); 1363 Flags &= ~JITSymbolFlags::Lazy; 1364 Flags |= JITSymbolFlags::Materializing; 1365 SymK->second.setFlags(Flags); 1366 UnmaterializedInfos.erase(KV.first); 1367 } 1368 1369 // Add MU to the list of MaterializationUnits to be materialized. 1370 MUs.push_back(std::move(MU)); 1371 } else if (!SymI->second.getFlags().isMaterializing()) { 1372 // The symbol is neither lazy nor materializing, so it must be ready. 1373 // Notify the query and continue. 1374 Q->notifySymbolReady(); 1375 if (Q->isFullyReady()) 1376 ActionFlags |= NotifyFullyReady; 1377 continue; 1378 } 1379 1380 // Add the query to the PendingQueries list. 1381 assert(SymI->second.getFlags().isMaterializing() && 1382 "By this line the symbol should be materializing"); 1383 auto &MI = MaterializingInfos[Name]; 1384 MI.PendingQueries.push_back(Q); 1385 Q->addQueryDependence(*this, Name); 1386 } 1387 1388 // Remove any marked symbols from the Unresolved set. 1389 for (auto &Name : ToRemove) 1390 Unresolved.erase(Name); 1391 1392 return ActionFlags; 1393 } 1394 1395 void JITDylib::dump(raw_ostream &OS) { 1396 ES.runSessionLocked([&, this]() { 1397 OS << "JITDylib \"" << JITDylibName << "\" (ES: " 1398 << format("0x%016" PRIx64, reinterpret_cast<uintptr_t>(&ES)) << "):\n" 1399 << "Search order: ["; 1400 for (auto &KV : SearchOrder) 1401 OS << " (\"" << KV.first->getName() << "\", " 1402 << (KV.second ? "all" : "exported only") << ")"; 1403 OS << " ]\n" 1404 << "Symbol table:\n"; 1405 1406 for (auto &KV : Symbols) { 1407 OS << " \"" << *KV.first << "\": "; 1408 if (auto Addr = KV.second.getAddress()) 1409 OS << format("0x%016" PRIx64, Addr) << ", " << KV.second.getFlags(); 1410 else 1411 OS << "<not resolved>"; 1412 if (KV.second.getFlags().isLazy() || 1413 KV.second.getFlags().isMaterializing()) { 1414 OS << " ("; 1415 if (KV.second.getFlags().isLazy()) { 1416 auto I = UnmaterializedInfos.find(KV.first); 1417 assert(I != UnmaterializedInfos.end() && 1418 "Lazy symbol should have UnmaterializedInfo"); 1419 OS << " Lazy (MU=" << I->second->MU.get() << ")"; 1420 } 1421 if (KV.second.getFlags().isMaterializing()) 1422 OS << " Materializing"; 1423 OS << ", " << KV.second.getFlags() << " )\n"; 1424 } else 1425 OS << "\n"; 1426 } 1427 1428 if (!MaterializingInfos.empty()) 1429 OS << " MaterializingInfos entries:\n"; 1430 for (auto &KV : MaterializingInfos) { 1431 OS << " \"" << *KV.first << "\":\n" 1432 << " IsEmitted = " << (KV.second.IsEmitted ? "true" : "false") 1433 << "\n" 1434 << " " << KV.second.PendingQueries.size() 1435 << " pending queries: { "; 1436 for (auto &Q : KV.second.PendingQueries) 1437 OS << Q.get() << " "; 1438 OS << "}\n Dependants:\n"; 1439 for (auto &KV2 : KV.second.Dependants) 1440 OS << " " << KV2.first->getName() << ": " << KV2.second << "\n"; 1441 OS << " Unemitted Dependencies:\n"; 1442 for (auto &KV2 : KV.second.UnemittedDependencies) 1443 OS << " " << KV2.first->getName() << ": " << KV2.second << "\n"; 1444 } 1445 }); 1446 } 1447 1448 JITDylib::JITDylib(ExecutionSession &ES, std::string Name) 1449 : ES(ES), JITDylibName(std::move(Name)) { 1450 SearchOrder.push_back({this, true}); 1451 } 1452 1453 Error JITDylib::defineImpl(MaterializationUnit &MU) { 1454 SymbolNameSet Duplicates; 1455 std::vector<SymbolStringPtr> ExistingDefsOverridden; 1456 std::vector<SymbolStringPtr> MUDefsOverridden; 1457 1458 for (const auto &KV : MU.getSymbols()) { 1459 assert(!KV.second.isLazy() && "Lazy flag should be managed internally."); 1460 assert(!KV.second.isMaterializing() && 1461 "Materializing flags should be managed internally."); 1462 1463 auto I = Symbols.find(KV.first); 1464 1465 if (I != Symbols.end()) { 1466 if (KV.second.isStrong()) { 1467 if (I->second.getFlags().isStrong() || 1468 I->second.getFlags().isMaterializing()) 1469 Duplicates.insert(KV.first); 1470 else { 1471 assert(I->second.getFlags().isLazy() && 1472 !I->second.getFlags().isMaterializing() && 1473 "Overridden existing def should be in the Lazy state"); 1474 ExistingDefsOverridden.push_back(KV.first); 1475 } 1476 } else 1477 MUDefsOverridden.push_back(KV.first); 1478 } 1479 } 1480 1481 // If there were any duplicate definitions then bail out. 1482 if (!Duplicates.empty()) 1483 return make_error<DuplicateDefinition>(**Duplicates.begin()); 1484 1485 // Discard any overridden defs in this MU. 1486 for (auto &S : MUDefsOverridden) 1487 MU.doDiscard(*this, S); 1488 1489 // Discard existing overridden defs. 1490 for (auto &S : ExistingDefsOverridden) { 1491 1492 auto UMII = UnmaterializedInfos.find(S); 1493 assert(UMII != UnmaterializedInfos.end() && 1494 "Overridden existing def should have an UnmaterializedInfo"); 1495 UMII->second->MU->doDiscard(*this, S); 1496 } 1497 1498 // Finally, add the defs from this MU. 1499 for (auto &KV : MU.getSymbols()) { 1500 auto NewFlags = KV.second; 1501 NewFlags |= JITSymbolFlags::Lazy; 1502 Symbols[KV.first] = JITEvaluatedSymbol(0, NewFlags); 1503 } 1504 1505 return Error::success(); 1506 } 1507 1508 void JITDylib::detachQueryHelper(AsynchronousSymbolQuery &Q, 1509 const SymbolNameSet &QuerySymbols) { 1510 for (auto &QuerySymbol : QuerySymbols) { 1511 assert(MaterializingInfos.count(QuerySymbol) && 1512 "QuerySymbol does not have MaterializingInfo"); 1513 auto &MI = MaterializingInfos[QuerySymbol]; 1514 1515 auto IdenticalQuery = 1516 [&](const std::shared_ptr<AsynchronousSymbolQuery> &R) { 1517 return R.get() == &Q; 1518 }; 1519 1520 auto I = std::find_if(MI.PendingQueries.begin(), MI.PendingQueries.end(), 1521 IdenticalQuery); 1522 assert(I != MI.PendingQueries.end() && 1523 "Query Q should be in the PendingQueries list for QuerySymbol"); 1524 MI.PendingQueries.erase(I); 1525 } 1526 } 1527 1528 void JITDylib::transferEmittedNodeDependencies( 1529 MaterializingInfo &DependantMI, const SymbolStringPtr &DependantName, 1530 MaterializingInfo &EmittedMI) { 1531 for (auto &KV : EmittedMI.UnemittedDependencies) { 1532 auto &DependencyJD = *KV.first; 1533 SymbolNameSet *UnemittedDependenciesOnDependencyJD = nullptr; 1534 1535 for (auto &DependencyName : KV.second) { 1536 auto &DependencyMI = DependencyJD.MaterializingInfos[DependencyName]; 1537 1538 // Do not add self dependencies. 1539 if (&DependencyMI == &DependantMI) 1540 continue; 1541 1542 // If we haven't looked up the dependencies for DependencyJD yet, do it 1543 // now and cache the result. 1544 if (!UnemittedDependenciesOnDependencyJD) 1545 UnemittedDependenciesOnDependencyJD = 1546 &DependantMI.UnemittedDependencies[&DependencyJD]; 1547 1548 DependencyMI.Dependants[this].insert(DependantName); 1549 UnemittedDependenciesOnDependencyJD->insert(DependencyName); 1550 } 1551 } 1552 } 1553 1554 ExecutionSession::ExecutionSession(std::shared_ptr<SymbolStringPool> SSP) 1555 : SSP(SSP ? std::move(SSP) : std::make_shared<SymbolStringPool>()) { 1556 // Construct the main dylib. 1557 JDs.push_back(std::unique_ptr<JITDylib>(new JITDylib(*this, "<main>"))); 1558 } 1559 1560 JITDylib &ExecutionSession::getMainJITDylib() { 1561 return runSessionLocked([this]() -> JITDylib & { return *JDs.front(); }); 1562 } 1563 1564 JITDylib &ExecutionSession::createJITDylib(std::string Name, 1565 bool AddToMainDylibSearchOrder) { 1566 return runSessionLocked([&, this]() -> JITDylib & { 1567 JDs.push_back( 1568 std::unique_ptr<JITDylib>(new JITDylib(*this, std::move(Name)))); 1569 if (AddToMainDylibSearchOrder) 1570 JDs.front()->addToSearchOrder(*JDs.back()); 1571 return *JDs.back(); 1572 }); 1573 } 1574 1575 void ExecutionSession::legacyFailQuery(AsynchronousSymbolQuery &Q, Error Err) { 1576 assert(!!Err && "Error should be in failure state"); 1577 1578 bool SendErrorToQuery; 1579 runSessionLocked([&]() { 1580 Q.detach(); 1581 SendErrorToQuery = Q.canStillFail(); 1582 }); 1583 1584 if (SendErrorToQuery) 1585 Q.handleFailed(std::move(Err)); 1586 else 1587 reportError(std::move(Err)); 1588 } 1589 1590 Expected<SymbolMap> ExecutionSession::legacyLookup( 1591 LegacyAsyncLookupFunction AsyncLookup, SymbolNameSet Names, 1592 bool WaitUntilReady, RegisterDependenciesFunction RegisterDependencies) { 1593 #if LLVM_ENABLE_THREADS 1594 // In the threaded case we use promises to return the results. 1595 std::promise<SymbolMap> PromisedResult; 1596 std::mutex ErrMutex; 1597 Error ResolutionError = Error::success(); 1598 std::promise<void> PromisedReady; 1599 Error ReadyError = Error::success(); 1600 auto OnResolve = [&](Expected<SymbolMap> R) { 1601 if (R) 1602 PromisedResult.set_value(std::move(*R)); 1603 else { 1604 { 1605 ErrorAsOutParameter _(&ResolutionError); 1606 std::lock_guard<std::mutex> Lock(ErrMutex); 1607 ResolutionError = R.takeError(); 1608 } 1609 PromisedResult.set_value(SymbolMap()); 1610 } 1611 }; 1612 1613 std::function<void(Error)> OnReady; 1614 if (WaitUntilReady) { 1615 OnReady = [&](Error Err) { 1616 if (Err) { 1617 ErrorAsOutParameter _(&ReadyError); 1618 std::lock_guard<std::mutex> Lock(ErrMutex); 1619 ReadyError = std::move(Err); 1620 } 1621 PromisedReady.set_value(); 1622 }; 1623 } else { 1624 OnReady = [&](Error Err) { 1625 if (Err) 1626 reportError(std::move(Err)); 1627 }; 1628 } 1629 1630 #else 1631 SymbolMap Result; 1632 Error ResolutionError = Error::success(); 1633 Error ReadyError = Error::success(); 1634 1635 auto OnResolve = [&](Expected<SymbolMap> R) { 1636 ErrorAsOutParameter _(&ResolutionError); 1637 if (R) 1638 Result = std::move(*R); 1639 else 1640 ResolutionError = R.takeError(); 1641 }; 1642 1643 std::function<void(Error)> OnReady; 1644 if (WaitUntilReady) { 1645 OnReady = [&](Error Err) { 1646 ErrorAsOutParameter _(&ReadyError); 1647 if (Err) 1648 ReadyError = std::move(Err); 1649 }; 1650 } else { 1651 OnReady = [&](Error Err) { 1652 if (Err) 1653 reportError(std::move(Err)); 1654 }; 1655 } 1656 #endif 1657 1658 auto Query = std::make_shared<AsynchronousSymbolQuery>( 1659 Names, std::move(OnResolve), std::move(OnReady)); 1660 // FIXME: This should be run session locked along with the registration code 1661 // and error reporting below. 1662 SymbolNameSet UnresolvedSymbols = AsyncLookup(Query, std::move(Names)); 1663 1664 // If the query was lodged successfully then register the dependencies, 1665 // otherwise fail it with an error. 1666 if (UnresolvedSymbols.empty()) 1667 RegisterDependencies(Query->QueryRegistrations); 1668 else { 1669 bool DeliverError = runSessionLocked([&]() { 1670 Query->detach(); 1671 return Query->canStillFail(); 1672 }); 1673 auto Err = make_error<SymbolsNotFound>(std::move(UnresolvedSymbols)); 1674 if (DeliverError) 1675 Query->handleFailed(std::move(Err)); 1676 else 1677 reportError(std::move(Err)); 1678 } 1679 1680 #if LLVM_ENABLE_THREADS 1681 auto ResultFuture = PromisedResult.get_future(); 1682 auto Result = ResultFuture.get(); 1683 1684 { 1685 std::lock_guard<std::mutex> Lock(ErrMutex); 1686 if (ResolutionError) { 1687 // ReadyError will never be assigned. Consume the success value. 1688 cantFail(std::move(ReadyError)); 1689 return std::move(ResolutionError); 1690 } 1691 } 1692 1693 if (WaitUntilReady) { 1694 auto ReadyFuture = PromisedReady.get_future(); 1695 ReadyFuture.get(); 1696 1697 { 1698 std::lock_guard<std::mutex> Lock(ErrMutex); 1699 if (ReadyError) 1700 return std::move(ReadyError); 1701 } 1702 } else 1703 cantFail(std::move(ReadyError)); 1704 1705 return std::move(Result); 1706 1707 #else 1708 if (ResolutionError) { 1709 // ReadyError will never be assigned. Consume the success value. 1710 cantFail(std::move(ReadyError)); 1711 return std::move(ResolutionError); 1712 } 1713 1714 if (ReadyError) 1715 return std::move(ReadyError); 1716 1717 return Result; 1718 #endif 1719 } 1720 1721 void ExecutionSession::lookup( 1722 const JITDylibSearchList &SearchOrder, SymbolNameSet Symbols, 1723 SymbolsResolvedCallback OnResolve, SymbolsReadyCallback OnReady, 1724 RegisterDependenciesFunction RegisterDependencies) { 1725 1726 // lookup can be re-entered recursively if running on a single thread. Run any 1727 // outstanding MUs in case this query depends on them, otherwise this lookup 1728 // will starve waiting for a result from an MU that is stuck in the queue. 1729 runOutstandingMUs(); 1730 1731 auto Unresolved = std::move(Symbols); 1732 std::map<JITDylib *, MaterializationUnitList> CollectedMUsMap; 1733 auto Q = std::make_shared<AsynchronousSymbolQuery>( 1734 Unresolved, std::move(OnResolve), std::move(OnReady)); 1735 bool QueryIsFullyResolved = false; 1736 bool QueryIsFullyReady = false; 1737 bool QueryFailed = false; 1738 1739 runSessionLocked([&]() { 1740 for (auto &KV : SearchOrder) { 1741 assert(KV.first && "JITDylibList entries must not be null"); 1742 assert(!CollectedMUsMap.count(KV.first) && 1743 "JITDylibList should not contain duplicate entries"); 1744 1745 auto &JD = *KV.first; 1746 auto MatchNonExported = KV.second; 1747 JD.lodgeQuery(Q, Unresolved, MatchNonExported, CollectedMUsMap[&JD]); 1748 } 1749 1750 if (Unresolved.empty()) { 1751 // Query lodged successfully. 1752 1753 // Record whether this query is fully ready / resolved. We will use 1754 // this to call handleFullyResolved/handleFullyReady outside the session 1755 // lock. 1756 QueryIsFullyResolved = Q->isFullyResolved(); 1757 QueryIsFullyReady = Q->isFullyReady(); 1758 1759 // Call the register dependencies function. 1760 if (RegisterDependencies && !Q->QueryRegistrations.empty()) 1761 RegisterDependencies(Q->QueryRegistrations); 1762 } else { 1763 // Query failed due to unresolved symbols. 1764 QueryFailed = true; 1765 1766 // Disconnect the query from its dependencies. 1767 Q->detach(); 1768 1769 // Replace the MUs. 1770 for (auto &KV : CollectedMUsMap) 1771 for (auto &MU : KV.second) 1772 KV.first->replace(std::move(MU)); 1773 } 1774 }); 1775 1776 if (QueryFailed) { 1777 Q->handleFailed(make_error<SymbolsNotFound>(std::move(Unresolved))); 1778 return; 1779 } else { 1780 if (QueryIsFullyResolved) 1781 Q->handleFullyResolved(); 1782 if (QueryIsFullyReady) 1783 Q->handleFullyReady(); 1784 } 1785 1786 // Move the MUs to the OutstandingMUs list, then materialize. 1787 { 1788 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex); 1789 1790 for (auto &KV : CollectedMUsMap) 1791 for (auto &MU : KV.second) 1792 OutstandingMUs.push_back(std::make_pair(KV.first, std::move(MU))); 1793 } 1794 1795 runOutstandingMUs(); 1796 } 1797 1798 Expected<SymbolMap> ExecutionSession::lookup( 1799 const JITDylibSearchList &SearchOrder, const SymbolNameSet &Symbols, 1800 RegisterDependenciesFunction RegisterDependencies, bool WaitUntilReady) { 1801 #if LLVM_ENABLE_THREADS 1802 // In the threaded case we use promises to return the results. 1803 std::promise<SymbolMap> PromisedResult; 1804 std::mutex ErrMutex; 1805 Error ResolutionError = Error::success(); 1806 std::promise<void> PromisedReady; 1807 Error ReadyError = Error::success(); 1808 auto OnResolve = [&](Expected<SymbolMap> R) { 1809 if (R) 1810 PromisedResult.set_value(std::move(*R)); 1811 else { 1812 { 1813 ErrorAsOutParameter _(&ResolutionError); 1814 std::lock_guard<std::mutex> Lock(ErrMutex); 1815 ResolutionError = R.takeError(); 1816 } 1817 PromisedResult.set_value(SymbolMap()); 1818 } 1819 }; 1820 1821 std::function<void(Error)> OnReady; 1822 if (WaitUntilReady) { 1823 OnReady = [&](Error Err) { 1824 if (Err) { 1825 ErrorAsOutParameter _(&ReadyError); 1826 std::lock_guard<std::mutex> Lock(ErrMutex); 1827 ReadyError = std::move(Err); 1828 } 1829 PromisedReady.set_value(); 1830 }; 1831 } else { 1832 OnReady = [&](Error Err) { 1833 if (Err) 1834 reportError(std::move(Err)); 1835 }; 1836 } 1837 1838 #else 1839 SymbolMap Result; 1840 Error ResolutionError = Error::success(); 1841 Error ReadyError = Error::success(); 1842 1843 auto OnResolve = [&](Expected<SymbolMap> R) { 1844 ErrorAsOutParameter _(&ResolutionError); 1845 if (R) 1846 Result = std::move(*R); 1847 else 1848 ResolutionError = R.takeError(); 1849 }; 1850 1851 std::function<void(Error)> OnReady; 1852 if (WaitUntilReady) { 1853 OnReady = [&](Error Err) { 1854 ErrorAsOutParameter _(&ReadyError); 1855 if (Err) 1856 ReadyError = std::move(Err); 1857 }; 1858 } else { 1859 OnReady = [&](Error Err) { 1860 if (Err) 1861 reportError(std::move(Err)); 1862 }; 1863 } 1864 #endif 1865 1866 // Perform the asynchronous lookup. 1867 lookup(SearchOrder, Symbols, OnResolve, OnReady, RegisterDependencies); 1868 1869 #if LLVM_ENABLE_THREADS 1870 auto ResultFuture = PromisedResult.get_future(); 1871 auto Result = ResultFuture.get(); 1872 1873 { 1874 std::lock_guard<std::mutex> Lock(ErrMutex); 1875 if (ResolutionError) { 1876 // ReadyError will never be assigned. Consume the success value. 1877 cantFail(std::move(ReadyError)); 1878 return std::move(ResolutionError); 1879 } 1880 } 1881 1882 if (WaitUntilReady) { 1883 auto ReadyFuture = PromisedReady.get_future(); 1884 ReadyFuture.get(); 1885 1886 { 1887 std::lock_guard<std::mutex> Lock(ErrMutex); 1888 if (ReadyError) 1889 return std::move(ReadyError); 1890 } 1891 } else 1892 cantFail(std::move(ReadyError)); 1893 1894 return std::move(Result); 1895 1896 #else 1897 if (ResolutionError) { 1898 // ReadyError will never be assigned. Consume the success value. 1899 cantFail(std::move(ReadyError)); 1900 return std::move(ResolutionError); 1901 } 1902 1903 if (ReadyError) 1904 return std::move(ReadyError); 1905 1906 return Result; 1907 #endif 1908 } 1909 1910 Expected<JITEvaluatedSymbol> 1911 ExecutionSession::lookup(const JITDylibSearchList &SearchOrder, 1912 SymbolStringPtr Name) { 1913 SymbolNameSet Names({Name}); 1914 1915 if (auto ResultMap = lookup(SearchOrder, std::move(Names), 1916 NoDependenciesToRegister, true)) { 1917 assert(ResultMap->size() == 1 && "Unexpected number of results"); 1918 assert(ResultMap->count(Name) && "Missing result for symbol"); 1919 return std::move(ResultMap->begin()->second); 1920 } else 1921 return ResultMap.takeError(); 1922 } 1923 1924 Expected<JITEvaluatedSymbol> 1925 ExecutionSession::lookup(ArrayRef<JITDylib *> SearchOrder, 1926 SymbolStringPtr Name) { 1927 SymbolNameSet Names({Name}); 1928 1929 JITDylibSearchList FullSearchOrder; 1930 FullSearchOrder.reserve(SearchOrder.size()); 1931 for (auto *JD : SearchOrder) 1932 FullSearchOrder.push_back({JD, false}); 1933 1934 return lookup(FullSearchOrder, Name); 1935 } 1936 1937 Expected<JITEvaluatedSymbol> 1938 ExecutionSession::lookup(ArrayRef<JITDylib *> SearchOrder, StringRef Name) { 1939 return lookup(SearchOrder, intern(Name)); 1940 } 1941 1942 void ExecutionSession::dump(raw_ostream &OS) { 1943 runSessionLocked([this, &OS]() { 1944 for (auto &JD : JDs) 1945 JD->dump(OS); 1946 }); 1947 } 1948 1949 void ExecutionSession::runOutstandingMUs() { 1950 while (1) { 1951 std::pair<JITDylib *, std::unique_ptr<MaterializationUnit>> JITDylibAndMU; 1952 1953 { 1954 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex); 1955 if (!OutstandingMUs.empty()) { 1956 JITDylibAndMU = std::move(OutstandingMUs.back()); 1957 OutstandingMUs.pop_back(); 1958 } 1959 } 1960 1961 if (JITDylibAndMU.first) { 1962 assert(JITDylibAndMU.second && "JITDylib, but no MU?"); 1963 dispatchMaterialization(*JITDylibAndMU.first, 1964 std::move(JITDylibAndMU.second)); 1965 } else 1966 break; 1967 } 1968 } 1969 1970 MangleAndInterner::MangleAndInterner(ExecutionSession &ES, const DataLayout &DL) 1971 : ES(ES), DL(DL) {} 1972 1973 SymbolStringPtr MangleAndInterner::operator()(StringRef Name) { 1974 std::string MangledName; 1975 { 1976 raw_string_ostream MangledNameStream(MangledName); 1977 Mangler::getNameWithPrefix(MangledNameStream, Name, DL); 1978 } 1979 return ES.intern(MangledName); 1980 } 1981 1982 } // End namespace orc. 1983 } // End namespace llvm. 1984