From b3c6bd66e01667c46d490009cd6b276b3c90ae3b Mon Sep 17 00:00:00 2001 From: Nathan Walker Date: Thu, 29 Oct 2026 22:42:35 -0700 Subject: [PATCH 1/2] fix(ffi/objc): enter a Node callback scope for native callbacks from a host-owned run loop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In the Node-API build, Objective-C → JS callbacks (method overrides, target/action, delegates, blocks, C function pointers) assumed JS was already on the stack. That holds under Node, where the app pumps the Cocoa run loop from JS, but not in hosts that own the native run loop, such as Electron's main process: Cocoa re-enters JS with no V8 context entered and no HandleScope open, and the process aborts with "Cannot create a handle without a HandleScope". Route same-thread callbacks through a native trampoline invoked with napi_make_callback, which enters the env's context and opens a Node callback scope (draining nextTicks and microtasks when the outermost scope closes). The trampoline and async context are created at init, while JS is on the stack. Objective-C exceptions raised inside the callback are caught and rethrown after napi_make_callback returns, so they never unwind through V8 frames. ENABLE_JS_RUNTIME builds are unchanged. --- NativeScript/ffi/objc/napi/Closure.h | 6 + NativeScript/ffi/objc/napi/Closure.mm | 154 ++++++++++++++++++++++- NativeScript/ffi/objc/napi/ObjCBridge.mm | 3 + 3 files changed, 160 insertions(+), 3 deletions(-) diff --git a/NativeScript/ffi/objc/napi/Closure.h b/NativeScript/ffi/objc/napi/Closure.h index d81a43f4d..804ffcb4b 100644 --- a/NativeScript/ffi/objc/napi/Closure.h +++ b/NativeScript/ffi/objc/napi/Closure.h @@ -44,6 +44,12 @@ bool recordNapiNativeCallbackException(napi_env env, napi_value error); bool rethrowNapiNativeCallbackException( napi_env env, NapiNativeCallbackExceptionCapture& capture); +#ifndef ENABLE_JS_RUNTIME +// Must run while JS is on the stack (e.g. from module init): it allocates JS +// objects, which needs an entered V8 context. +void initHostCallbackScope(napi_env env); +#endif + class Closure { public: static void callBlockFromMainThread(napi_env env, napi_value js_cb, diff --git a/NativeScript/ffi/objc/napi/Closure.mm b/NativeScript/ffi/objc/napi/Closure.mm index a04380486..824ef0939 100644 --- a/NativeScript/ffi/objc/napi/Closure.mm +++ b/NativeScript/ffi/objc/napi/Closure.mm @@ -21,13 +21,113 @@ #include #include #include +#include #include +#include #include +#ifndef ENABLE_JS_RUNTIME +// Node-API entry points from node_api.h, which this tree does not vendor. +typedef struct napi_async_context__* napi_async_context; +typedef void(NAPI_CDECL* napi_cleanup_hook)(void* arg); +extern "C" { +NAPI_EXTERN napi_status NAPI_CDECL napi_async_init(napi_env env, napi_value async_resource, + napi_value async_resource_name, + napi_async_context* result); +NAPI_EXTERN napi_status NAPI_CDECL napi_async_destroy(napi_env env, + napi_async_context async_context); +NAPI_EXTERN napi_status NAPI_CDECL napi_make_callback(napi_env env, + napi_async_context async_context, + napi_value recv, napi_value func, size_t argc, + const napi_value* argv, napi_value* result); +NAPI_EXTERN napi_status NAPI_CDECL napi_add_env_cleanup_hook(node_api_basic_env env, + napi_cleanup_hook fun, void* arg); +} +#endif + namespace nativescript { namespace { +#ifndef ENABLE_JS_RUNTIME +// Hosts that own the native run loop (Electron's main process, for one) can +// make Objective-C call back into JS with no V8 context entered and no +// HandleScope open. napi_make_callback is the only Node-API call that enters +// the env's context itself, so callbacks are routed through a native +// trampoline invoked that way; Node also drains nextTicks and microtasks when +// the outermost callback scope closes, which keeps promises settled from +// native callbacks from stalling. +struct HostCallbackState { + napi_ref trampoline = nullptr; + napi_ref receiver = nullptr; + napi_async_context asyncContext = nullptr; +}; + +thread_local std::unordered_map gHostCallbackStates; +thread_local const std::function* gPendingHostCallback = nullptr; +thread_local NSException* gPendingHostCallbackException = nil; + +napi_value runPendingHostCallback(napi_env env, napi_callback_info info) { + const std::function* callback = gPendingHostCallback; + gPendingHostCallback = nullptr; + if (callback != nullptr) { + // An Objective-C exception must not unwind through V8 frames; it is + // rethrown once napi_make_callback has returned. + @try { + (*callback)(); + } @catch (NSException* exception) { + gPendingHostCallbackException = exception; + } + } + return nullptr; +} + +void destroyHostCallbackState(void* arg) { + napi_env env = (napi_env)arg; + auto it = gHostCallbackStates.find(env); + if (it == gHostCallbackStates.end()) { + return; + } + napi_async_destroy(env, it->second.asyncContext); + napi_delete_reference(env, it->second.trampoline); + napi_delete_reference(env, it->second.receiver); + gHostCallbackStates.erase(it); +} + +template +void runInHostCallbackScope(napi_env env, Fn&& fn) { + auto it = gHostCallbackStates.find(env); + if (it == gHostCallbackStates.end()) { + fn(); + return; + } + + const std::function callback = std::forward(fn); + napi_handle_scope handleScope = nullptr; + napi_open_handle_scope(env, &handleScope); + + const std::function* previous = gPendingHostCallback; + gPendingHostCallback = &callback; + napi_value result = nullptr; + napi_status status = + napi_make_callback(env, it->second.asyncContext, get_ref_value(env, it->second.receiver), + get_ref_value(env, it->second.trampoline), 0, nullptr, &result); + gPendingHostCallback = previous; + + if (status == napi_pending_exception) { + napi_value error = nullptr; + napi_get_and_clear_last_exception(env, &error); + } + napi_close_handle_scope(env, handleScope); + + if (gPendingHostCallbackException != nil) { + NSException* exception = gPendingHostCallbackException; + gPendingHostCallbackException = nil; + @throw exception; + } +} +#endif // ENABLE_JS_RUNTIME + thread_local std::vector gNativeCallbackExceptionCaptureStack; @@ -222,7 +322,7 @@ inline void JSCallbackInner(Closure* closure, napi_value func, napi_value thisAr // Bridge calls from Objective-C to JavaScript. // Opposite of what native_call.cc does - but a lot of type conversion logic // is reused, just in reverse. -void JSMethodCallback(ffi_cif* cif, void* ret, void* args[], void* data) { +void invokeJSMethodCallback(ffi_cif* cif, void* ret, void* args[], void* data) { Closure* closure = (Closure*)data; napi_env env = closure->env; @@ -338,7 +438,16 @@ void JSMethodCallback(ffi_cif* cif, void* ret, void* args[], void* data) { ConsumeNapiArgumentConversionFailure(env); } -void JSFunctionCallback(ffi_cif* cif, void* ret, void* args[], void* data) { +void JSMethodCallback(ffi_cif* cif, void* ret, void* args[], void* data) { +#ifdef ENABLE_JS_RUNTIME + invokeJSMethodCallback(cif, ret, args, data); +#else + runInHostCallbackScope(((Closure*)data)->env, + [&] { invokeJSMethodCallback(cif, ret, args, data); }); +#endif +} + +void invokeJSFunctionCallback(ffi_cif* cif, void* ret, void* args[], void* data) { Closure* closure = (Closure*)data; napi_env env = closure->env; @@ -366,6 +475,15 @@ void JSFunctionCallback(ffi_cif* cif, void* ret, void* args[], void* data) { JSCallbackInner(closure, func, thisArg, argv, cif->nargs, nullptr, ret); } +void JSFunctionCallback(ffi_cif* cif, void* ret, void* args[], void* data) { +#ifdef ENABLE_JS_RUNTIME + invokeJSFunctionCallback(cif, ret, args, data); +#else + runInHostCallbackScope(((Closure*)data)->env, + [&] { invokeJSFunctionCallback(cif, ret, args, data); }); +#endif +} + struct JSBlockCallContext { ffi_cif* cif; void* ret; @@ -433,8 +551,12 @@ void JSBlockCallback(ffi_cif* cif, void* ret, void* args[], void* data) { if (currentThreadId == closure->jsThreadId || shouldInvokeCallbackOnNativeCallerThread()) { #ifdef ENABLE_JS_RUNTIME NativeCallbackScope scope(env); -#endif Closure::callBlockFromMainThread(env, get_ref_value(env, closure->func), closure, &ctx); +#else + runInHostCallbackScope(env, [&] { + Closure::callBlockFromMainThread(env, get_ref_value(env, closure->func), closure, &ctx); + }); +#endif } else { #ifndef ENABLE_JS_RUNTIME if (!closure->tsfn) { @@ -608,4 +730,30 @@ void JSBlockCallback(ffi_cif* cif, void* ret, void* args[], void* data) { } } +#ifndef ENABLE_JS_RUNTIME +void initHostCallbackScope(napi_env env) { + if (gHostCallbackStates.count(env) != 0) { + return; + } + + napi_value trampoline = nullptr; + napi_value receiver = nullptr; + napi_value resourceName = nullptr; + HostCallbackState state; + if (napi_create_function(env, "nativeScriptHostCallback", NAPI_AUTO_LENGTH, + runPendingHostCallback, nullptr, &trampoline) != napi_ok || + napi_create_object(env, &receiver) != napi_ok || + napi_create_string_utf8(env, "NativeScriptHostCallback", NAPI_AUTO_LENGTH, &resourceName) != + napi_ok || + napi_async_init(env, receiver, resourceName, &state.asyncContext) != napi_ok) { + return; + } + + napi_create_reference(env, trampoline, 1, &state.trampoline); + napi_create_reference(env, receiver, 1, &state.receiver); + gHostCallbackStates[env] = state; + napi_add_env_cleanup_hook(env, destroyHostCallbackState, env); +} +#endif // ENABLE_JS_RUNTIME + } // namespace nativescript diff --git a/NativeScript/ffi/objc/napi/ObjCBridge.mm b/NativeScript/ffi/objc/napi/ObjCBridge.mm index fe330f374..b6c796e96 100644 --- a/NativeScript/ffi/objc/napi/ObjCBridge.mm +++ b/NativeScript/ffi/objc/napi/ObjCBridge.mm @@ -1238,6 +1238,9 @@ NAPI_EXPORT void nativescript_init(void* _env, const char* metadata_path, napi_env env = (napi_env)_env; ObjCBridgeState* bridgeState = new ObjCBridgeState(env, metadata_path, metadata_ptr); +#ifndef ENABLE_JS_RUNTIME + initHostCallbackScope(env); +#endif napi_value objc; napi_create_object(env, &objc); From e6ea813bc43cb671123e29966afe1fc7b45a3929 Mon Sep 17 00:00:00 2001 From: Nathan Walker Date: Sat, 7 Nov 2026 11:38:04 -0800 Subject: [PATCH 2/2] refactor(ffi/objc): move the host callback scope into NativeCallbackScope MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Same-thread callbacks call JS directly in a handle scope while a JS→native call is in progress on the thread (tracked by NativeCallRuntimeUnlockScope); only callbacks with no JS on the stack go through napi_make_callback. - Zero the native return value when the trampoline does not run. - Report a JS error left pending by a callback through the closure uncaught-error handling, inside the callback scope. - The helper is the Node-API branch of NativeCallbackScope and takes a function pointer plus data instead of a std::function. --- .../ffi/objc/napi/CallbackThreading.h | 189 ++++++++++++++++ NativeScript/ffi/objc/napi/Closure.h | 6 - NativeScript/ffi/objc/napi/Closure.mm | 211 +++++------------- NativeScript/ffi/objc/napi/ObjCBridge.mm | 5 +- 4 files changed, 254 insertions(+), 157 deletions(-) diff --git a/NativeScript/ffi/objc/napi/CallbackThreading.h b/NativeScript/ffi/objc/napi/CallbackThreading.h index d4f15a94a..945bbf537 100644 --- a/NativeScript/ffi/objc/napi/CallbackThreading.h +++ b/NativeScript/ffi/objc/napi/CallbackThreading.h @@ -8,16 +8,129 @@ #if defined(ENABLE_JS_RUNTIME) #include "jsr.h" +#else +#include + +#include + +// Node-API entry points from node_api.h, which this tree does not vendor. +typedef struct napi_async_context__* napi_async_context; +typedef void(NAPI_CDECL* napi_cleanup_hook)(void* arg); +extern "C" { +NAPI_EXTERN napi_status NAPI_CDECL +napi_async_init(napi_env env, napi_value async_resource, + napi_value async_resource_name, napi_async_context* result); +NAPI_EXTERN napi_status NAPI_CDECL +napi_async_destroy(napi_env env, napi_async_context async_context); +NAPI_EXTERN napi_status NAPI_CDECL napi_make_callback( + napi_env env, napi_async_context async_context, napi_value recv, + napi_value func, size_t argc, const napi_value* argv, napi_value* result); +NAPI_EXTERN napi_status NAPI_CDECL napi_add_env_cleanup_hook( + node_api_basic_env env, napi_cleanup_hook fun, void* arg); +} #endif namespace nativescript { +// Reports a JS error thrown by a JS implementation of a native callback: to +// the JS→native call that is waiting for it, if any, otherwise as uncaught. +void reportNativeCallbackError(napi_env env, napi_value error); + namespace detail { #if defined(ENABLE_JS_RUNTIME) && defined(TARGET_ENGINE_HERMES) inline thread_local int native_caller_thread_callback_depth = 0; #endif +#if !defined(ENABLE_JS_RUNTIME) +// Depth of JS→native calls in progress on this thread. While it is above 0, +// JS is on the stack, so a V8 context is entered and native callbacks can +// call into JS directly. +inline thread_local int napi_native_call_depth = 0; + +// Hosts that own the native run loop (Electron's main process, for one) can +// make Objective-C call back into JS with no V8 context entered and no +// HandleScope open. napi_make_callback is the only Node-API call that enters +// the env's context itself, so such callbacks run inside a native trampoline +// invoked that way. Node drains nextTicks and microtasks when the outermost +// callback scope closes. +// +// All callbacks share one async context created at init, so AsyncLocalStorage +// inside a callback sees the values from bridge initialization. +struct HostCallbackState { + napi_ref trampoline = nullptr; + napi_ref receiver = nullptr; + napi_async_context asyncContext = nullptr; +}; + +struct HostCallback { + void (*fn)(void*) = nullptr; + void* data = nullptr; + bool ran = false; + NSException* exception = nil; +}; + +inline thread_local std::unordered_map + host_callback_states; +inline thread_local HostCallback* pending_host_callback = nullptr; + +inline napi_value runPendingHostCallback(napi_env env, + napi_callback_info info) { + HostCallback* callback = pending_host_callback; + pending_host_callback = nullptr; + if (callback != nullptr) { + callback->ran = true; + // An Objective-C exception must not unwind through V8 frames; it is + // rethrown once napi_make_callback has returned. + @try { + callback->fn(callback->data); + // Reported here, while the context is still entered: reporting can + // call back into JS. + bool pending = false; + if (napi_is_exception_pending(env, &pending) == napi_ok && pending) { + napi_value error = nullptr; + napi_get_and_clear_last_exception(env, &error); + reportNativeCallbackError(env, error); + } + } @catch (NSException* exception) { + callback->exception = exception; + } + } + return nullptr; +} + +inline void destroyHostCallbackState(void* arg) { + napi_env env = (napi_env)arg; + auto it = host_callback_states.find(env); + if (it == host_callback_states.end()) { + return; + } + napi_async_destroy(env, it->second.asyncContext); + napi_delete_reference(env, it->second.trampoline); + napi_delete_reference(env, it->second.receiver); + host_callback_states.erase(it); +} + +class HandleScopeGuard final { + public: + explicit HandleScopeGuard(napi_env env) : env_(env) { + napi_open_handle_scope(env_, &scope_); + } + ~HandleScopeGuard() { + if (scope_ != nullptr) { + napi_close_handle_scope(env_, scope_); + } + } + + HandleScopeGuard(const HandleScopeGuard&) = delete; + HandleScopeGuard& operator=(const HandleScopeGuard&) = delete; + + private: + napi_env env_; + napi_handle_scope scope_ = nullptr; +}; +#endif // !ENABLE_JS_RUNTIME + } // namespace detail inline bool isNativeCallerThreadCallbackActive() { @@ -62,6 +175,9 @@ class NativeCallRuntimeUnlockScope final { } #else (void)env; +#if !defined(ENABLE_JS_RUNTIME) + detail::napi_native_call_depth += 1; +#endif #endif } @@ -75,6 +191,8 @@ class NativeCallRuntimeUnlockScope final { if (unlockedRuntime_ && relockRuntime_) { relockRuntime_(); } +#elif !defined(ENABLE_JS_RUNTIME) + detail::napi_native_call_depth -= 1; #endif } @@ -132,6 +250,77 @@ class NativeCallbackScope final { NativeCallbackScope(const NativeCallbackScope&) = delete; NativeCallbackScope& operator=(const NativeCallbackScope&) = delete; +#if !defined(ENABLE_JS_RUNTIME) + // Must run while JS is on the stack (e.g. from module init): it allocates + // JS objects, which needs an entered V8 context. + static void initialize(napi_env env) { + if (detail::host_callback_states.count(env) != 0) { + return; + } + + napi_value trampoline = nullptr; + napi_value receiver = nullptr; + napi_value resourceName = nullptr; + detail::HostCallbackState state; + if (napi_create_function(env, "nativeScriptHostCallback", NAPI_AUTO_LENGTH, + detail::runPendingHostCallback, nullptr, + &trampoline) != napi_ok || + napi_create_object(env, &receiver) != napi_ok || + napi_create_string_utf8(env, "NativeScriptHostCallback", + NAPI_AUTO_LENGTH, &resourceName) != napi_ok || + napi_async_init(env, receiver, resourceName, &state.asyncContext) != + napi_ok) { + return; + } + + napi_create_reference(env, trampoline, 1, &state.trampoline); + napi_create_reference(env, receiver, 1, &state.receiver); + detail::host_callback_states[env] = state; + napi_add_env_cleanup_hook(env, detail::destroyHostCallbackState, env); + } + + // Runs fn(data) on the JS thread as an entry from native code into JS. + // Returns false if fn did not run, in which case the caller must still + // produce a return value for its native caller. + static bool run(napi_env env, void (*fn)(void*), void* data) { + if (detail::napi_native_call_depth > 0) { + detail::HandleScopeGuard handleScope(env); + fn(data); + return true; + } + + auto it = detail::host_callback_states.find(env); + if (it == detail::host_callback_states.end()) { + detail::HandleScopeGuard handleScope(env); + fn(data); + return true; + } + + detail::HostCallback callback; + callback.fn = fn; + callback.data = data; + { + detail::HandleScopeGuard handleScope(env); + napi_value receiver = nullptr; + napi_value trampoline = nullptr; + napi_get_reference_value(env, it->second.receiver, &receiver); + napi_get_reference_value(env, it->second.trampoline, &trampoline); + + detail::HostCallback* previous = detail::pending_host_callback; + detail::pending_host_callback = &callback; + napi_value result = nullptr; + napi_make_callback(env, it->second.asyncContext, receiver, trampoline, 0, + nullptr, &result); + detail::pending_host_callback = previous; + } + + if (callback.exception != nil) { + @throw callback.exception; + } + return callback.ran; + } +#endif // !ENABLE_JS_RUNTIME + private: napi_env env_; #if defined(ENABLE_JS_RUNTIME) && defined(TARGET_ENGINE_HERMES) diff --git a/NativeScript/ffi/objc/napi/Closure.h b/NativeScript/ffi/objc/napi/Closure.h index 804ffcb4b..d81a43f4d 100644 --- a/NativeScript/ffi/objc/napi/Closure.h +++ b/NativeScript/ffi/objc/napi/Closure.h @@ -44,12 +44,6 @@ bool recordNapiNativeCallbackException(napi_env env, napi_value error); bool rethrowNapiNativeCallbackException( napi_env env, NapiNativeCallbackExceptionCapture& capture); -#ifndef ENABLE_JS_RUNTIME -// Must run while JS is on the stack (e.g. from module init): it allocates JS -// objects, which needs an entered V8 context. -void initHostCallbackScope(napi_env env); -#endif - class Closure { public: static void callBlockFromMainThread(napi_env env, napi_value js_cb, diff --git a/NativeScript/ffi/objc/napi/Closure.mm b/NativeScript/ffi/objc/napi/Closure.mm index 824ef0939..1f0125435 100644 --- a/NativeScript/ffi/objc/napi/Closure.mm +++ b/NativeScript/ffi/objc/napi/Closure.mm @@ -21,113 +21,13 @@ #include #include #include -#include #include -#include #include -#ifndef ENABLE_JS_RUNTIME -// Node-API entry points from node_api.h, which this tree does not vendor. -typedef struct napi_async_context__* napi_async_context; -typedef void(NAPI_CDECL* napi_cleanup_hook)(void* arg); -extern "C" { -NAPI_EXTERN napi_status NAPI_CDECL napi_async_init(napi_env env, napi_value async_resource, - napi_value async_resource_name, - napi_async_context* result); -NAPI_EXTERN napi_status NAPI_CDECL napi_async_destroy(napi_env env, - napi_async_context async_context); -NAPI_EXTERN napi_status NAPI_CDECL napi_make_callback(napi_env env, - napi_async_context async_context, - napi_value recv, napi_value func, size_t argc, - const napi_value* argv, napi_value* result); -NAPI_EXTERN napi_status NAPI_CDECL napi_add_env_cleanup_hook(node_api_basic_env env, - napi_cleanup_hook fun, void* arg); -} -#endif - namespace nativescript { namespace { -#ifndef ENABLE_JS_RUNTIME -// Hosts that own the native run loop (Electron's main process, for one) can -// make Objective-C call back into JS with no V8 context entered and no -// HandleScope open. napi_make_callback is the only Node-API call that enters -// the env's context itself, so callbacks are routed through a native -// trampoline invoked that way; Node also drains nextTicks and microtasks when -// the outermost callback scope closes, which keeps promises settled from -// native callbacks from stalling. -struct HostCallbackState { - napi_ref trampoline = nullptr; - napi_ref receiver = nullptr; - napi_async_context asyncContext = nullptr; -}; - -thread_local std::unordered_map gHostCallbackStates; -thread_local const std::function* gPendingHostCallback = nullptr; -thread_local NSException* gPendingHostCallbackException = nil; - -napi_value runPendingHostCallback(napi_env env, napi_callback_info info) { - const std::function* callback = gPendingHostCallback; - gPendingHostCallback = nullptr; - if (callback != nullptr) { - // An Objective-C exception must not unwind through V8 frames; it is - // rethrown once napi_make_callback has returned. - @try { - (*callback)(); - } @catch (NSException* exception) { - gPendingHostCallbackException = exception; - } - } - return nullptr; -} - -void destroyHostCallbackState(void* arg) { - napi_env env = (napi_env)arg; - auto it = gHostCallbackStates.find(env); - if (it == gHostCallbackStates.end()) { - return; - } - napi_async_destroy(env, it->second.asyncContext); - napi_delete_reference(env, it->second.trampoline); - napi_delete_reference(env, it->second.receiver); - gHostCallbackStates.erase(it); -} - -template -void runInHostCallbackScope(napi_env env, Fn&& fn) { - auto it = gHostCallbackStates.find(env); - if (it == gHostCallbackStates.end()) { - fn(); - return; - } - - const std::function callback = std::forward(fn); - napi_handle_scope handleScope = nullptr; - napi_open_handle_scope(env, &handleScope); - - const std::function* previous = gPendingHostCallback; - gPendingHostCallback = &callback; - napi_value result = nullptr; - napi_status status = - napi_make_callback(env, it->second.asyncContext, get_ref_value(env, it->second.receiver), - get_ref_value(env, it->second.trampoline), 0, nullptr, &result); - gPendingHostCallback = previous; - - if (status == napi_pending_exception) { - napi_value error = nullptr; - napi_get_and_clear_last_exception(env, &error); - } - napi_close_handle_scope(env, handleScope); - - if (gPendingHostCallbackException != nil) { - NSException* exception = gPendingHostCallbackException; - gPendingHostCallbackException = nil; - @throw exception; - } -} -#endif // ENABLE_JS_RUNTIME - thread_local std::vector gNativeCallbackExceptionCaptureStack; @@ -231,6 +131,12 @@ NativeScriptException nativeScriptException( return true; } +void reportNativeCallbackError(napi_env env, napi_value error) { + if (!recordNapiNativeCallbackException(env, error)) { + NativeScriptException::OnUncaughtError(env, error); + } +} + void Closure::destroyOnOwningThread(Closure* closure) { deleteClosureOnOwningThread(closure); } inline bool selectorEndsWithErrorParam(SEL selector) { @@ -305,11 +211,8 @@ inline void JSCallbackInner(Closure* closure, napi_value func, napi_value thisAr napi_create_error(env, code, msg, &result); } - if (recordNapiNativeCallbackException(env, result)) { - napi_get_undefined(env, &result); - } else { - NativeScriptException::OnUncaughtError(env, result); - } + reportNativeCallbackError(env, result); + napi_get_undefined(env, &result); } // Even if call was failed and result is just undefined, let's still try to @@ -426,11 +329,8 @@ void invokeJSMethodCallback(ffi_cif* cif, void* ret, void* args[], void* data) { napi_create_error(env, code, msg, &result); } - if (recordNapiNativeCallbackException(env, result)) { - napi_get_undefined(env, &result); - } else { - NativeScriptException::OnUncaughtError(env, result); - } + reportNativeCallbackError(env, result); + napi_get_undefined(env, &result); } bool shouldFree; @@ -438,15 +338,6 @@ void invokeJSMethodCallback(ffi_cif* cif, void* ret, void* args[], void* data) { ConsumeNapiArgumentConversionFailure(env); } -void JSMethodCallback(ffi_cif* cif, void* ret, void* args[], void* data) { -#ifdef ENABLE_JS_RUNTIME - invokeJSMethodCallback(cif, ret, args, data); -#else - runInHostCallbackScope(((Closure*)data)->env, - [&] { invokeJSMethodCallback(cif, ret, args, data); }); -#endif -} - void invokeJSFunctionCallback(ffi_cif* cif, void* ret, void* args[], void* data) { Closure* closure = (Closure*)data; napi_env env = closure->env; @@ -475,12 +366,46 @@ void invokeJSFunctionCallback(ffi_cif* cif, void* ret, void* args[], void* data) JSCallbackInner(closure, func, thisArg, argv, cif->nargs, nullptr, ret); } +#ifndef ENABLE_JS_RUNTIME +using ClosureInvoker = void (*)(ffi_cif* cif, void* ret, void* args[], void* data); + +struct ClosureInvocation { + ClosureInvoker invoke; + ffi_cif* cif; + void* ret; + void** args; + void* data; +}; + +void runClosureInvocation(void* data) { + auto invocation = static_cast(data); + invocation->invoke(invocation->cif, invocation->ret, invocation->args, invocation->data); +} + +void invokeInNativeCallbackScope(napi_env env, ClosureInvoker invoke, ffi_cif* cif, void* ret, + void* args[], void* data) { + ClosureInvocation invocation{invoke, cif, ret, args, data}; + if (!NativeCallbackScope::run(env, runClosureInvocation, &invocation) && + cif->rtype->type != FFI_TYPE_VOID) { + memset(ret, 0, cif->rtype->size); + } +} +#endif // ENABLE_JS_RUNTIME + +void JSMethodCallback(ffi_cif* cif, void* ret, void* args[], void* data) { +#ifdef ENABLE_JS_RUNTIME + invokeJSMethodCallback(cif, ret, args, data); +#else + invokeInNativeCallbackScope(((Closure*)data)->env, invokeJSMethodCallback, cif, ret, args, data); +#endif +} + void JSFunctionCallback(ffi_cif* cif, void* ret, void* args[], void* data) { #ifdef ENABLE_JS_RUNTIME invokeJSFunctionCallback(cif, ret, args, data); #else - runInHostCallbackScope(((Closure*)data)->env, - [&] { invokeJSFunctionCallback(cif, ret, args, data); }); + invokeInNativeCallbackScope(((Closure*)data)->env, invokeJSFunctionCallback, cif, ret, args, + data); #endif } @@ -526,6 +451,20 @@ void JSFunctionCallback(ffi_cif* cif, void* ret, void* args[], void* data) { } } +#ifndef ENABLE_JS_RUNTIME +void invokeJSBlockCallback(ffi_cif* cif, void* ret, void* args[], void* data) { + Closure* closure = (Closure*)data; + JSBlockCallContext ctx; + ctx.cif = cif; + ctx.ret = ret; + ctx.args = args; + ctx.done = false; + ctx.useCondvar = false; + Closure::callBlockFromMainThread(closure->env, get_ref_value(closure->env, closure->func), + closure, &ctx); +} +#endif // ENABLE_JS_RUNTIME + void JSBlockCallback(ffi_cif* cif, void* ret, void* args[], void* data) { Closure* closure = (Closure*)data; napi_env env = closure->env; @@ -553,9 +492,7 @@ void JSBlockCallback(ffi_cif* cif, void* ret, void* args[], void* data) { NativeCallbackScope scope(env); Closure::callBlockFromMainThread(env, get_ref_value(env, closure->func), closure, &ctx); #else - runInHostCallbackScope(env, [&] { - Closure::callBlockFromMainThread(env, get_ref_value(env, closure->func), closure, &ctx); - }); + invokeInNativeCallbackScope(env, invokeJSBlockCallback, cif, ret, args, closure); #endif } else { #ifndef ENABLE_JS_RUNTIME @@ -730,30 +667,4 @@ void JSBlockCallback(ffi_cif* cif, void* ret, void* args[], void* data) { } } -#ifndef ENABLE_JS_RUNTIME -void initHostCallbackScope(napi_env env) { - if (gHostCallbackStates.count(env) != 0) { - return; - } - - napi_value trampoline = nullptr; - napi_value receiver = nullptr; - napi_value resourceName = nullptr; - HostCallbackState state; - if (napi_create_function(env, "nativeScriptHostCallback", NAPI_AUTO_LENGTH, - runPendingHostCallback, nullptr, &trampoline) != napi_ok || - napi_create_object(env, &receiver) != napi_ok || - napi_create_string_utf8(env, "NativeScriptHostCallback", NAPI_AUTO_LENGTH, &resourceName) != - napi_ok || - napi_async_init(env, receiver, resourceName, &state.asyncContext) != napi_ok) { - return; - } - - napi_create_reference(env, trampoline, 1, &state.trampoline); - napi_create_reference(env, receiver, 1, &state.receiver); - gHostCallbackStates[env] = state; - napi_add_env_cleanup_hook(env, destroyHostCallbackState, env); -} -#endif // ENABLE_JS_RUNTIME - } // namespace nativescript diff --git a/NativeScript/ffi/objc/napi/ObjCBridge.mm b/NativeScript/ffi/objc/napi/ObjCBridge.mm index b6c796e96..514db9af9 100644 --- a/NativeScript/ffi/objc/napi/ObjCBridge.mm +++ b/NativeScript/ffi/objc/napi/ObjCBridge.mm @@ -18,6 +18,9 @@ #include "js_native_api.h" #include "js_native_api_types.h" #include "node_api_util.h" +#ifndef ENABLE_JS_RUNTIME +#include "CallbackThreading.h" +#endif #import @@ -1239,7 +1242,7 @@ NAPI_EXPORT void nativescript_init(void* _env, const char* metadata_path, ObjCBridgeState* bridgeState = new ObjCBridgeState(env, metadata_path, metadata_ptr); #ifndef ENABLE_JS_RUNTIME - initHostCallbackScope(env); + NativeCallbackScope::initialize(env); #endif napi_value objc;