From 006a2f37ddb133f61c6fa672652663204c2d2e54 Mon Sep 17 00:00:00 2001 From: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com> Date: Wed, 2 Nov 2022 13:30:40 -0700 Subject: [bun:ffi] Add `threadsafe` option to callbacks --- src/bun.js/bindings/JSFFIFunction.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) (limited to 'src/bun.js/bindings/JSFFIFunction.cpp') diff --git a/src/bun.js/bindings/JSFFIFunction.cpp b/src/bun.js/bindings/JSFFIFunction.cpp index 66fdc701d..c0fc34fc0 100644 --- a/src/bun.js/bindings/JSFFIFunction.cpp +++ b/src/bun.js/bindings/JSFFIFunction.cpp @@ -151,6 +151,32 @@ FFI_Callback_call(FFICallbackFunctionWrapper& wrapper, size_t argCount, JSC::Enc return JSC::JSValue::encode(result); } +extern "C" void +FFI_Callback_threadsafe_call(FFICallbackFunctionWrapper& wrapper, size_t argCount, JSC::EncodedJSValue* args) +{ + + auto* globalObject = wrapper.globalObject.get(); + WTF::Vector argsVec; + for (size_t i = 0; i < argCount; ++i) + argsVec.append(args[i]); + + WebCore::ScriptExecutionContext::postTaskTo(globalObject->scriptExecutionContext()->identifier(), [argsVec = WTFMove(argsVec), wrapper](WebCore::ScriptExecutionContext& ctx) mutable { + auto* globalObject = JSC::jsCast(ctx.jsGlobalObject()); + auto& vm = globalObject->vm(); + JSC::MarkedArgumentBuffer arguments; + auto* function = wrapper.m_function.get(); + for (size_t i = 0; i < argsVec.size(); ++i) + arguments.appendWithCrashOnOverflow(JSC::JSValue::decode(argsVec[i])); + WTF::NakedPtr exception; + JSC::call(globalObject, function, JSC::getCallData(function), JSC::jsUndefined(), arguments, exception); + if (UNLIKELY(exception)) { + auto scope = DECLARE_THROW_SCOPE(vm); + scope.throwException(globalObject, exception); + return; + } + }); +} + extern "C" JSC::EncodedJSValue FFI_Callback_call_0(FFICallbackFunctionWrapper& wrapper, size_t argCount, JSC::EncodedJSValue* args) { -- cgit v1.2.3