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