Skip to content
Open
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
189 changes: 189 additions & 0 deletions NativeScript/ffi/objc/napi/CallbackThreading.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,129 @@

#if defined(ENABLE_JS_RUNTIME)
#include "jsr.h"
#else
#include <Foundation/Foundation.h>

#include <unordered_map>

// 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<napi_env, HostCallbackState>
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() {
Expand Down Expand Up @@ -62,6 +175,9 @@ class NativeCallRuntimeUnlockScope final {
}
#else
(void)env;
#if !defined(ENABLE_JS_RUNTIME)
detail::napi_native_call_depth += 1;
#endif
#endif
}

Expand All @@ -75,6 +191,8 @@ class NativeCallRuntimeUnlockScope final {
if (unlockedRuntime_ && relockRuntime_) {
relockRuntime_();
}
#elif !defined(ENABLE_JS_RUNTIME)
detail::napi_native_call_depth -= 1;
#endif
}

Expand Down Expand Up @@ -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)
Expand Down
85 changes: 72 additions & 13 deletions NativeScript/ffi/objc/napi/Closure.mm
Original file line number Diff line number Diff line change
Expand Up @@ -131,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) {
Expand Down Expand Up @@ -205,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
Expand All @@ -222,7 +225,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;

Expand Down Expand Up @@ -326,19 +329,16 @@ void JSMethodCallback(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;
closure->returnType->toNative(env, result, ret, &shouldFree, &shouldFree);
ConsumeNapiArgumentConversionFailure(env);
}

void JSFunctionCallback(ffi_cif* cif, void* ret, void* args[], void* data) {
void invokeJSFunctionCallback(ffi_cif* cif, void* ret, void* args[], void* data) {
Closure* closure = (Closure*)data;
napi_env env = closure->env;

Expand Down Expand Up @@ -366,6 +366,49 @@ void JSFunctionCallback(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<ClosureInvocation*>(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
invokeInNativeCallbackScope(((Closure*)data)->env, invokeJSFunctionCallback, cif, ret, args,
data);
#endif
}

struct JSBlockCallContext {
ffi_cif* cif;
void* ret;
Expand Down Expand Up @@ -408,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;
Expand All @@ -433,8 +490,10 @@ 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
invokeInNativeCallbackScope(env, invokeJSBlockCallback, cif, ret, args, closure);
#endif
} else {
#ifndef ENABLE_JS_RUNTIME
if (!closure->tsfn) {
Expand Down
6 changes: 6 additions & 0 deletions NativeScript/ffi/objc/napi/ObjCBridge.mm
Original file line number Diff line number Diff line change
Expand Up @@ -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 <Foundation/Foundation.h>

Expand Down Expand Up @@ -1238,6 +1241,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
NativeCallbackScope::initialize(env);
#endif

napi_value objc;
napi_create_object(env, &objc);
Expand Down
Loading