Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions NativeScript/napi/NapiEnv.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
#define NODE_API_EXPERIMENTAL_NO_WARNING
#endif

#include <CoreFoundation/CoreFoundation.h>
#include <pthread.h>

#include <atomic>
#include <memory>
Expand Down Expand Up @@ -58,9 +58,17 @@ class NapiEnv : public napi_env__ {

v8::Local<v8::Private> 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
Expand Down Expand Up @@ -88,7 +96,7 @@ class NapiEnv : public napi_env__ {

void DrainFinalizers();

CFRunLoopRef runtimeLoop_ = nullptr;
uint64_t threadId_ = 0;
std::weak_ptr<EventLoop> eventLoop_;
bool tearingDown_ = false;
v8::Eternal<v8::Private> privateKeys_[2];
Expand Down
2 changes: 1 addition & 1 deletion NativeScript/napi/NapiEnv.mm
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

NapiEnv::NapiEnv(Local<Context> context)
: napi_env__(context, NODE_API_DEFAULT_MODULE_API_VERSION),
runtimeLoop_(CFRunLoopGetCurrent()),
threadId_(CurrentThreadId()),
eventLoop_(Runtime::GetCurrentRuntime()->GetEventLoop()) {}

NapiEnv::~NapiEnv() = default;
Expand Down
26 changes: 7 additions & 19 deletions NativeScript/napi/NapiThreadSafeFunction.mm
Original file line number Diff line number Diff line change
Expand Up @@ -32,22 +32,14 @@

struct napi_threadsafe_function__
: public std::enable_shared_from_this<napi_threadsafe_function__> {
~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<tns::EventLoop> eventLoop;

// Touched on the env's thread only, which is where the abort path and every
Expand Down Expand Up @@ -344,14 +336,10 @@ void NapiAbortThreadSafeFunctions(NapiEnv* env) {
}

tns::NapiEnv* tnsEnv = static_cast<tns::NapiEnv*>(env);
RETURN_STATUS_IF_FALSE(env, tnsEnv->RuntimeLoop() != nullptr,
napi_generic_failure);

TsfnRef tsfn = std::make_shared<napi_threadsafe_function__>();
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;
Expand Down Expand Up @@ -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);
Expand Down
9 changes: 2 additions & 7 deletions NativeScript/napi/NodeApiEmbed.mm
Original file line number Diff line number Diff line change
Expand Up @@ -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<tns::NapiEnv*>(env)->RuntimeLoop(),
napi_generic_failure);
RETURN_STATUS_IF_FALSE(env, static_cast<tns::NapiEnv*>(env)->IsOnEnvThread(),
napi_generic_failure);

(void)async_context;

Expand Down Expand Up @@ -559,9 +557,6 @@ void CompleteAsyncWork(napi_async_work work, napi_status status) {
(void)async_resource;

tns::NapiEnv* tnsEnv = static_cast<tns::NapiEnv*>(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;
Expand Down
6 changes: 2 additions & 4 deletions NativeScript/runtime/ClassBuilder.mm
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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);
Expand Down Expand Up @@ -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);
Expand Down
87 changes: 61 additions & 26 deletions NativeScript/runtime/PromiseProxy.cpp
Original file line number Diff line number Diff line change
@@ -1,46 +1,81 @@
#include "PromiseProxy.h"

#include <CoreFoundation/CoreFoundation.h>

#include "BuiltinLoader.h"
#include "Caches.h"
#include "Checks.h"
#include "EventLoop.h"
#include "Helpers.h"
#include "Runtime.h"

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<Value>& args) {
namespace {

struct PromiseProxyState {
// promise-proxy.js's module.exports: runs the oldest queued settlement.
Global<v8::Function> runNext;
};

void RunNextSettlement(Isolate* isolate) {
PromiseProxyState* state = Caches::StateFor<PromiseProxyState>(isolate);
if (state == nullptr || state->runNext.IsEmpty()) {
return;
}
Local<Context> 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<Value>& 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<Value>& args) {
Isolate* isolate = args.GetIsolate();
Runtime* runtime = Runtime::GetRuntime(isolate);
std::shared_ptr<EventLoop> 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> context, Local<Object> binding,
const char* name, FunctionCallback callback) {
Local<v8::Function> 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<v8::Context> context) {
Isolate* isolate = v8::Isolate::GetCurrent();

Local<v8::Function> isRuntimeRunloop;
bool success = v8::Function::New(context, IsRuntimeRunloopCallback)
.ToLocal(&isRuntimeRunloop);
tns::Assert(success, isolate);

Local<Object> binding = Object::New(isolate);
success = binding
->Set(context, tns::ToV8String(isolate, "isRuntimeRunloop"),
isRuntimeRunloop)
.FromMaybe(false);
tns::Assert(success, isolate);

Local<Value> 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<Value> 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<PromiseProxyState>(isolate);
NS_CHECK(state != nullptr, "Promise proxy initialized on an isolate that is tearing down");
state->runNext.Reset(isolate, runNext.As<v8::Function>());
}

} // namespace tns
2 changes: 0 additions & 2 deletions NativeScript/runtime/Runtime.h
Original file line number Diff line number Diff line change
Expand Up @@ -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; }

/*
Expand Down
10 changes: 5 additions & 5 deletions NativeScript/runtime/Runtime.mm
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}
Expand Down
56 changes: 42 additions & 14 deletions NativeScript/runtime/js/promise-proxy.js
Original file line number Diff line number Diff line change
@@ -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() {
Expand All @@ -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);
}
});
});
Expand All @@ -55,3 +81,5 @@ global.Promise = new Proxy(global.Promise, {
return promise;
}
});

module.exports = runNext;
Loading
Loading