diff --git a/NativeScript/napi/NapiEnv.h b/NativeScript/napi/NapiEnv.h index 855ceeb6..c7bcfa07 100644 --- a/NativeScript/napi/NapiEnv.h +++ b/NativeScript/napi/NapiEnv.h @@ -10,7 +10,7 @@ #define NODE_API_EXPERIMENTAL_NO_WARNING #endif -#include +#include #include #include @@ -58,9 +58,17 @@ class NapiEnv : public napi_env__ { v8::Local PrivateKey(NapiPrivateKeySlot slot); - // The runloop of the thread that owns this env — identity checks only - // (is-this-the-env's-thread); work is posted through GetEventLoop(). - CFRunLoopRef RuntimeLoop() const { return runtimeLoop_; } + // System-wide id of the thread that owns this env (pthread_threadid_np). + // Unlike a pthread_t it is never reused after the thread exits, so it stays + // safe to compare against from a producer that outlives the env's thread. + // Work is posted through GetEventLoop(). + uint64_t ThreadId() const { return threadId_; } + bool IsOnEnvThread() const { return CurrentThreadId() == threadId_; } + static uint64_t CurrentThreadId() { + uint64_t id = 0; + pthread_threadid_np(nullptr, &id); + return id; + } // The runtime's event loop, or null once ~Runtime released it. Between // Shutdown and that release it is still returned, and posts to it are @@ -88,7 +96,7 @@ class NapiEnv : public napi_env__ { void DrainFinalizers(); - CFRunLoopRef runtimeLoop_ = nullptr; + uint64_t threadId_ = 0; std::weak_ptr eventLoop_; bool tearingDown_ = false; v8::Eternal privateKeys_[2]; diff --git a/NativeScript/napi/NapiEnv.mm b/NativeScript/napi/NapiEnv.mm index d04a6596..29890fdd 100644 --- a/NativeScript/napi/NapiEnv.mm +++ b/NativeScript/napi/NapiEnv.mm @@ -15,7 +15,7 @@ NapiEnv::NapiEnv(Local context) : napi_env__(context, NODE_API_DEFAULT_MODULE_API_VERSION), - runtimeLoop_(CFRunLoopGetCurrent()), + threadId_(CurrentThreadId()), eventLoop_(Runtime::GetCurrentRuntime()->GetEventLoop()) {} NapiEnv::~NapiEnv() = default; diff --git a/NativeScript/napi/NapiThreadSafeFunction.mm b/NativeScript/napi/NapiThreadSafeFunction.mm index 6e6e2532..6482c800 100644 --- a/NativeScript/napi/NapiThreadSafeFunction.mm +++ b/NativeScript/napi/NapiThreadSafeFunction.mm @@ -32,22 +32,14 @@ struct napi_threadsafe_function__ : public std::enable_shared_from_this { - ~napi_threadsafe_function__() { - if (loop != nullptr) { - CFRelease(loop); - } - } - // Read from producer threads, so they are fixed at construction and only - // cleared once the function is closed for good. The runloop is retained for - // the object's lifetime and used for thread-identity checks only: a producer - // may compare against it after the owning thread exits, and comparing a - // deallocated pointer is fine where calling into it would not be. Work is - // posted through the event loop, whose weak_ptr goes null once the runtime - // shuts it down. + // cleared once the function is closed for good. envThreadId is for + // thread-identity checks only (see NapiEnv::ThreadId); work is posted + // through the event loop, whose weak_ptr goes null once the runtime shuts + // it down. tns::NapiEnv* env = nullptr; v8::Isolate* isolate = nullptr; - CFRunLoopRef loop = nullptr; + uint64_t envThreadId = 0; std::weak_ptr eventLoop; // Touched on the env's thread only, which is where the abort path and every @@ -344,14 +336,10 @@ void NapiAbortThreadSafeFunctions(NapiEnv* env) { } tns::NapiEnv* tnsEnv = static_cast(env); - RETURN_STATUS_IF_FALSE(env, tnsEnv->RuntimeLoop() != nullptr, - napi_generic_failure); - TsfnRef tsfn = std::make_shared(); tsfn->env = tnsEnv; tsfn->isolate = env->isolate; - tsfn->loop = tnsEnv->RuntimeLoop(); - CFRetain(tsfn->loop); + tsfn->envThreadId = tnsEnv->ThreadId(); tsfn->eventLoop = tnsEnv->GetEventLoop(); tsfn->callJs = call_js_cb; tsfn->finalizeCb = thread_finalize_cb; @@ -407,7 +395,7 @@ napi_status NAPI_CDECL napi_get_threadsafe_function_context( // this wait, so blocking on it there can only stall forever. Node blocks // regardless and leaves this status unused; wedging the runloop is worse // than a status an addon may not expect. - if (CFRunLoopGetCurrent() == func->loop) { + if (tns::NapiEnv::CurrentThreadId() == func->envThreadId) { return napi_would_deadlock; } func->spaceAvailable.wait(lock); diff --git a/NativeScript/napi/NodeApiEmbed.mm b/NativeScript/napi/NodeApiEmbed.mm index 4609c2ae..40a56701 100644 --- a/NativeScript/napi/NodeApiEmbed.mm +++ b/NativeScript/napi/NodeApiEmbed.mm @@ -448,10 +448,8 @@ napi_status NAPI_CDECL napi_make_callback(napi_env env, // Entering the isolate is only ever legal from the thread that owns it; // reaching JS from anywhere else is what threadsafe functions are for. - RETURN_STATUS_IF_FALSE( - env, - CFRunLoopGetCurrent() == static_cast(env)->RuntimeLoop(), - napi_generic_failure); + RETURN_STATUS_IF_FALSE(env, static_cast(env)->IsOnEnvThread(), + napi_generic_failure); (void)async_context; @@ -559,9 +557,6 @@ void CompleteAsyncWork(napi_async_work work, napi_status status) { (void)async_resource; tns::NapiEnv* tnsEnv = static_cast(env); - RETURN_STATUS_IF_FALSE(env, tnsEnv->RuntimeLoop() != nullptr, - napi_generic_failure); - napi_async_work__* work = new napi_async_work__(); work->env = tnsEnv; work->isolate = env->isolate; diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index 91c066b0..d4c18f24 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -380,7 +380,6 @@ void ThrowTypeError(Isolate* isolate, const std::string& message) { } if ([self retainCount] == 1) { auto runtime = Runtime::GetRuntime(isolate); - auto runtimeLoop = runtime->RuntimeLoop(); void* weakSelf = (__bridge void*)self; auto gcProtect = [isolateWrapper, weakSelf, isolate]() { auto innerCache = isolateWrapper.GetCache(); @@ -403,7 +402,7 @@ void ThrowTypeError(Isolate* isolate, const std::string& message) { }; // After the retain: reconciling reads the new retain count. id result = retain(self, @selector(retain)); - if (CFRunLoopGetCurrent() != runtimeLoop) { + if (!runtime->IsOnRuntimeThread()) { // bare entry: the closure does its own Locker ceremony, exactly // like the performed block it replaces runtime->GetEventLoop()->PostInternalBare(gcProtect); @@ -449,11 +448,10 @@ void ThrowTypeError(Isolate* isolate, const std::string& message) { } }; auto runtime = Runtime::GetRuntime(isolate); - auto runtimeLoop = runtime->RuntimeLoop(); // After the release: reconciling reads the new retain count, and // the Instances entry still holds the object. release(self, @selector(release)); - if (CFRunLoopGetCurrent() != runtimeLoop) { + if (!runtime->IsOnRuntimeThread()) { // bare entry: the closure does its own Locker ceremony, exactly // like the performed block it replaces runtime->GetEventLoop()->PostInternalBare(gcUnprotect); diff --git a/NativeScript/runtime/PromiseProxy.cpp b/NativeScript/runtime/PromiseProxy.cpp index b918245b..60ecad82 100644 --- a/NativeScript/runtime/PromiseProxy.cpp +++ b/NativeScript/runtime/PromiseProxy.cpp @@ -1,8 +1,9 @@ #include "PromiseProxy.h" -#include - #include "BuiltinLoader.h" +#include "Caches.h" +#include "Checks.h" +#include "EventLoop.h" #include "Helpers.h" #include "Runtime.h" @@ -10,37 +11,71 @@ using namespace v8; namespace tns { -// Reports whether the calling thread runs the isolate's runtime loop. That loop -// is where timers fire and is always being pumped, so a promise resolution is -// marshaled back to its creating thread only when that thread is the runtime -// loop; a promise created elsewhere settles on whichever thread resolves it. -static void IsRuntimeRunloopCallback(const FunctionCallbackInfo& args) { +namespace { + +struct PromiseProxyState { + // promise-proxy.js's module.exports: runs the oldest queued settlement. + Global runNext; +}; + +void RunNextSettlement(Isolate* isolate) { + PromiseProxyState* state = Caches::StateFor(isolate); + if (state == nullptr || state->runNext.IsEmpty()) { + return; + } + Local context = isolate->GetCurrentContext(); + if (context.IsEmpty()) { + return; + } + (void)state->runNext.Get(isolate)->Call(context, v8::Undefined(isolate), 0, nullptr); +} + +// Whether the calling thread is the isolate's runtime thread. Its run loop is +// always being pumped, so a promise resolution is marshaled back to its +// creating thread only when that thread is the runtime thread; a promise +// created elsewhere settles on whichever thread resolves it. +void IsRuntimeThreadCallback(const FunctionCallbackInfo& args) { Runtime* runtime = Runtime::GetRuntime(args.GetIsolate()); - bool isRuntimeLoop = - runtime != nullptr && CFRunLoopGetCurrent() == runtime->RuntimeLoop(); - args.GetReturnValue().Set(isRuntimeLoop); + args.GetReturnValue().Set(runtime != nullptr && runtime->IsOnRuntimeThread()); +} + +// Called from a foreign thread holding the isolate's Locker. Each successful +// post runs runNext exactly once on the runtime thread; false means the +// runtime is shutting down and the settlement can never run. +void PostToRuntimeThreadCallback(const FunctionCallbackInfo& args) { + Isolate* isolate = args.GetIsolate(); + Runtime* runtime = Runtime::GetRuntime(isolate); + std::shared_ptr loop = runtime != nullptr ? runtime->GetEventLoop() : nullptr; + bool posted = + loop != nullptr && loop->PostInternal([isolate]() { RunNextSettlement(isolate); }); + args.GetReturnValue().Set(posted); } +void SetFunction(Isolate* isolate, Local context, Local binding, + const char* name, FunctionCallback callback) { + Local fn; + bool success = v8::Function::New(context, callback).ToLocal(&fn) && + binding->Set(context, tns::ToV8String(isolate, name), fn).FromMaybe(false); + NS_CHECK(success, std::string("cannot install the Promise proxy binding ") + name); +} + +} // namespace + void PromiseProxy::Init(v8::Local context) { Isolate* isolate = v8::Isolate::GetCurrent(); - Local isRuntimeRunloop; - bool success = v8::Function::New(context, IsRuntimeRunloopCallback) - .ToLocal(&isRuntimeRunloop); - tns::Assert(success, isolate); - Local binding = Object::New(isolate); - success = binding - ->Set(context, tns::ToV8String(isolate, "isRuntimeRunloop"), - isRuntimeRunloop) - .FromMaybe(false); - tns::Assert(success, isolate); - - Local result; - success = - BuiltinLoader::RunBuiltin(context, BuiltinId::kPromiseProxy, binding) - .ToLocal(&result); - tns::Assert(success, isolate); + SetFunction(isolate, context, binding, "isRuntimeThread", IsRuntimeThreadCallback); + SetFunction(isolate, context, binding, "postToRuntimeThread", PostToRuntimeThreadCallback); + + Local runNext; + NS_CHECK(BuiltinLoader::RunBuiltin(context, BuiltinId::kPromiseProxy, binding).ToLocal(&runNext), + "the promise-proxy builtin threw"); + NS_CHECK(runNext->IsFunction(), "the promise-proxy builtin must export a function"); + + PromiseProxyState* state = Caches::StateFor(isolate); + NS_CHECK(state != nullptr, "Promise proxy initialized on an isolate that is tearing down"); + state->runNext.Reset(isolate, runNext.As()); } } // namespace tns diff --git a/NativeScript/runtime/Runtime.h b/NativeScript/runtime/Runtime.h index 714e44ae..cb2fe7dc 100644 --- a/NativeScript/runtime/Runtime.h +++ b/NativeScript/runtime/Runtime.h @@ -50,8 +50,6 @@ class Runtime { inline bool IsRuntimeWorker() { return workerId_ > 0; } - inline CFRunLoopRef RuntimeLoop() { return runtimeLoop_; } - inline bool IsOnRuntimeThread() const { return pthread_equal(runtimeThread_, pthread_self()) != 0; } /* diff --git a/NativeScript/runtime/Runtime.mm b/NativeScript/runtime/Runtime.mm index e60a35ab..1dd423f0 100644 --- a/NativeScript/runtime/Runtime.mm +++ b/NativeScript/runtime/Runtime.mm @@ -854,12 +854,12 @@ bool OnRuntimeThreadOf(v8::Isolate* isolate) { SpinLock lock(isolatesMutex_); for (Isolate* isolate : Runtime::isolates_) { Runtime* candidate = GetRuntime(isolate); - // The home-loop comparison closes the allocator-reuse (ABA) hole: a stale - // thread-local can only exist on the dead runtime's home thread, and a - // recycled same-address Runtime homed on this thread would have + // The home-thread comparison closes the allocator-reuse (ABA) hole: a + // stale thread-local can only exist on the dead runtime's home thread, and + // a recycled same-address Runtime homed on this thread would have // overwritten that thread-local — so an address match with a foreign home - // loop can only be a recycled pointer. - if (candidate == runtime && candidate->RuntimeLoop() == CFRunLoopGetCurrent()) { + // thread can only be a recycled pointer. + if (candidate == runtime && candidate->IsOnRuntimeThread()) { return candidate->GetNapiEnv(); } } diff --git a/NativeScript/runtime/js/promise-proxy.js b/NativeScript/runtime/js/promise-proxy.js index 40612727..719a147a 100644 --- a/NativeScript/runtime/js/promise-proxy.js +++ b/NativeScript/runtime/js/promise-proxy.js @@ -1,15 +1,45 @@ // Run a Promise's callbacks on the thread that created it, but only when -// that thread is the runtime loop. A Promise created on a background +// that thread is the runtime thread. A Promise created on a background // thread settles on whichever thread resolves it, because the background // run loop may be dormant and marshaling a resolution to it would hang. -const { isRuntimeRunloop } = binding; +const { isRuntimeThread, postToRuntimeThread } = binding; const { FunctionPrototypeBind, Proxy } = primordials; +// Settlements waiting for the runtime thread, oldest first. Every successful +// postToRuntimeThread() makes the runtime thread call runNext() exactly once, +// so queued nodes and posts pair 1:1. +let head = null; +let tail = null; + +function enqueue(settle) { + if (!postToRuntimeThread()) { + return; + } + const node = { settle, next: null }; + if (tail === null) { + head = node; + } else { + tail.next = node; + } + tail = node; +} + +function runNext() { + const node = head; + if (node === null) { + return; + } + head = node.next; + if (head === null) { + tail = null; + } + node.settle(); +} + global.Promise = new Proxy(global.Promise, { construct: function(target, args) { let origFunc = args[0]; - let runloop = CFRunLoopGetCurrent(); - let originIsRuntimeLoop = isRuntimeRunloop(); + const originIsRuntimeThread = isRuntimeThread(); let promise = new target(function(resolve, reject) { function isFulfilled() { @@ -25,26 +55,22 @@ global.Promise = new Proxy(global.Promise, { return; } const resolveCall = FunctionPrototypeBind(resolve, this, value); - if (!originIsRuntimeLoop || runloop === CFRunLoopGetCurrent()) { - markFulfilled(); + markFulfilled(); + if (!originIsRuntimeThread || isRuntimeThread()) { resolveCall(); } else { - CFRunLoopPerformBlock(runloop, kCFRunLoopDefaultMode, resolveCall); - CFRunLoopWakeUp(runloop); - markFulfilled(); + enqueue(resolveCall); } }, reason => { if (isFulfilled()) { return; } const rejectCall = FunctionPrototypeBind(reject, this, reason); - if (!originIsRuntimeLoop || runloop === CFRunLoopGetCurrent()) { - markFulfilled(); + markFulfilled(); + if (!originIsRuntimeThread || isRuntimeThread()) { rejectCall(); } else { - CFRunLoopPerformBlock(runloop, kCFRunLoopDefaultMode, rejectCall); - CFRunLoopWakeUp(runloop); - markFulfilled(); + enqueue(rejectCall); } }); }); @@ -55,3 +81,5 @@ global.Promise = new Proxy(global.Promise, { return promise; } }); + +module.exports = runNext; diff --git a/TestRunner/app/tests/Promises.js b/TestRunner/app/tests/Promises.js index 8a01ff90..99693895 100644 --- a/TestRunner/app/tests/Promises.js +++ b/TestRunner/app/tests/Promises.js @@ -133,6 +133,37 @@ describe("Promise scheduling", function () { }); }); + it("settles promises resolved back-to-back on a background thread in resolution order", done => { + const expectedHash = NSThread.currentThread.hash; + const count = 5; + const resolvers = []; + const order = []; + const settled = []; + for (let i = 0; i < count; i++) { + settled.push(new Promise((resolve, reject) => { + resolvers.push(i % 2 === 0 ? () => resolve(i) : () => reject(i)); + }).then(value => { + expect(NSThread.currentThread.hash).toBe(expectedHash); + order.push(value); + }, reason => { + expect(NSThread.currentThread.hash).toBe(expectedHash); + order.push(reason); + })); + } + + const queue = NSOperationQueue.alloc().init(); + queue.addOperationWithBlock(() => { + for (let i = count - 1; i >= 0; i--) { + resolvers[i](); + } + }); + + Promise.all(settled).then(() => { + expect(order).toEqual([4, 3, 2, 1, 0]); + done(); + }); + }); + it("the 'then' callback runs for a Promise created on a background thread and resolved on the runtime loop", done => { // https://github.com/NativeScript/ios/issues/330 // The promise is constructed on a background dispatch queue whose run