From 709601ca319c8be6664a6318252320cc2961f3b6 Mon Sep 17 00:00:00 2001 From: Dylan Conway Date: Sun, 23 Aug 2026 20:18:25 +0000 Subject: [PATCH 1/9] napi: use the addon-boundary scope in every entry point, surface an init-time napi_throw from napi_module_register, no crash for a DataView over a detached buffer - napi_create_dataview / napi_create_buffer / napi_create_buffer_copy / node_api_create_buffer_from_arraybuffer / napi_create_bigint_words / napi_run_script declared a plain ThrowScope and returned a status to the addon with the exception pending, which reads as an unchecked exception to the next napi call; they now use NAPI_PREAMBLE like the rest (and like Node). napi_new_instance's not-a-constructor path and v8::Isolate:: ThrowException/ThrowError throw the same way. - A module registered through napi_module_register() whose init threw with napi_throw_* lost that error ("Node-API module returned an error"); it is now the error require() throws, as on the napi_register_module_v1 path. - napi_create_dataview on a detached ArrayBuffer crashed; it now fails with the TypeError pending. - napi_get_all_property_names checked none of the gets/pushes in its filter loop; JSValue::to_object (Rust) inferred the throw from a null return without an exception check. --- src/jsc/JSValue.rs | 8 +- src/jsc/bindings/bindings.cpp | 2 +- src/jsc/bindings/napi.cpp | 118 +++--- src/jsc/bindings/v8/V8Isolate.cpp | 25 +- test/napi/napi-app/binding.gyp | 4 + test/napi/napi-app/standalone_tests.cpp | 451 ++++++++++++----------- test/napi/napi-app/throwing_init_addon.c | 26 ++ test/napi/napi.test.ts | 24 ++ 8 files changed, 374 insertions(+), 284 deletions(-) create mode 100644 test/napi/napi-app/throwing_init_addon.c diff --git a/src/jsc/JSValue.rs b/src/jsc/JSValue.rs index 791e86e4681c..0b81807204da 100644 --- a/src/jsc/JSValue.rs +++ b/src/jsc/JSValue.rs @@ -2337,12 +2337,7 @@ impl JSValue { } /// `JSValue.toObject` — ECMA `ToObject`; throws on null/undefined. pub fn to_object(self, global: &JSGlobalObject) -> JsResult<*mut JSObject> { - let p = JSC__JSValue__toObject(self, global); - if p.is_null() { - Err(JsError::Thrown) - } else { - Ok(p) - } + crate::cpp::JSC__JSValue__toObject(self, global).map(core::ptr::NonNull::as_ptr) } /// `JSValue.unwrapBoxedPrimitive` — unwraps Number, /// Boolean, String, and BigInt objects to their primitive forms. @@ -2742,7 +2737,6 @@ unsafe extern "C" { global: &JSGlobalObject, ) -> bool; safe fn Bun__JSValue__toNumber(this: JSValue, global: &JSGlobalObject) -> f64; - safe fn JSC__JSValue__toObject(this: JSValue, global: &JSGlobalObject) -> *mut JSObject; safe fn JSC__JSValue__unwrapBoxedPrimitive(global: &JSGlobalObject, this: JSValue) -> JSValue; safe fn JSC__JSValue__getPrototype(this: JSValue, global: &JSGlobalObject) -> JSValue; safe fn JSC__JSValue__getName( diff --git a/src/jsc/bindings/bindings.cpp b/src/jsc/bindings/bindings.cpp index dc02db769bbc..d887428c4e79 100644 --- a/src/jsc/bindings/bindings.cpp +++ b/src/jsc/bindings/bindings.cpp @@ -4956,7 +4956,7 @@ CPP_DECL double Bun__JSValue__toNumber(JSC::EncodedJSValue JSValue0, JSC::JSGlob return JSC::JSValue::encode(JSC::jsTDZValue()); }; -JSC::JSObject* JSC__JSValue__toObject(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1) +[[ZIG_EXPORT(null_is_throw)]] JSC::JSObject* JSC__JSValue__toObject(JSC::EncodedJSValue JSValue0, JSC::JSGlobalObject* arg1) { JSC::JSValue value = JSC::JSValue::decode(JSValue0); return value.toObject(arg1); diff --git a/src/jsc/bindings/napi.cpp b/src/jsc/bindings/napi.cpp index 2870f7a0d5bb..93d94eecc881 100644 --- a/src/jsc/bindings/napi.cpp +++ b/src/jsc/bindings/napi.cpp @@ -780,6 +780,9 @@ void Napi::executePendingNapiModule(Zig::GlobalObject* globalObject) return; } + // An exception the addon raised through napi_throw* during init is latched on the env; make it the + // pending JS exception, as the napi_register_module_v1 path in process.dlopen does. + env->throwPendingException(); RETURN_IF_EXCEPTION(scope, void()); if (resultValue.isEmpty()) { @@ -806,7 +809,7 @@ void Napi::executePendingNapiModule(Zig::GlobalObject* globalObject) // https://github.com/nodejs/node/blob/2eff28fb7a93d3f672f80b582f664a7c701569fb/src/node_api.cc#L734-L742 // https://github.com/oven-sh/bun/issues/1288 - if (!scope.exception() && strongExportsObject && strongExportsObject.get() != resultValue) { + if (strongExportsObject && strongExportsObject.get() != resultValue) { PutPropertySlot slot(strongObject.get(), false); strongObject->put(strongObject.get(), globalObject, WebCore::builtinNames(vm).exportsPublicName(), resultValue, slot); RETURN_IF_EXCEPTION(scope, void()); @@ -1586,11 +1589,8 @@ extern "C" JS_EXPORT napi_status node_api_create_buffer_from_arraybuffer(napi_en size_t byte_length, napi_value* result) { - NAPI_LOG_CURRENT_FUNCTION; - NAPI_PREAMBLE_NO_THROW_SCOPE(env); + NAPI_PREAMBLE(env); auto* globalObject = toJS(env); - auto scope = DECLARE_THROW_SCOPE(JSC::getVM(globalObject)); - NAPI_RETURN_IF_EXCEPTION_WITH_SCOPE(env, scope); NAPI_CHECK_ARG(env, arraybuffer); NAPI_CHECK_ARG(env, result); @@ -1601,18 +1601,17 @@ extern "C" JS_EXPORT napi_status node_api_create_buffer_from_arraybuffer(napi_en if (!impl || byte_offset + byte_length > impl->byteLength()) [[unlikely]] { auto* error = createErrorWithCode(JSC::getVM(globalObject), globalObject, "ERR_OUT_OF_RANGE"_s, "The byte offset + length is out of range"_s, JSC::ErrorType::RangeError); - RETURN_IF_EXCEPTION(scope, napi_set_last_error(env, napi_pending_exception)); + NAPI_RETURN_IF_EXCEPTION(env); env->scheduleException(error); return napi_set_last_error(env, napi_pending_exception); } auto* subclassStructure = globalObject->JSBufferSubclassStructure(); JSC::JSUint8Array* uint8Array = JSC::JSUint8Array::create(globalObject, subclassStructure, impl, byte_offset, byte_length); - RETURN_IF_EXCEPTION(scope, napi_set_last_error(env, napi_pending_exception)); + NAPI_RETURN_IF_EXCEPTION(env); *result = toNapi(uint8Array, globalObject); - - return napi_set_last_error(env, napi_ok); + NAPI_RETURN_SUCCESS(env); } extern "C" JS_EXPORT napi_status node_api_get_module_file_name(napi_env env, @@ -1870,10 +1869,8 @@ extern "C" napi_status napi_create_dataview(napi_env env, size_t length, size_t byte_offset, napi_value* result) { - NAPI_PREAMBLE_NO_THROW_SCOPE(env); + NAPI_PREAMBLE(env); Zig::GlobalObject* globalObject = toJS(env); - auto scope = DECLARE_THROW_SCOPE(JSC::getVM(globalObject)); - NAPI_RETURN_IF_EXCEPTION_WITH_SCOPE(env, scope); NAPI_CHECK_ARG(env, arraybuffer); NAPI_CHECK_ARG(env, result); JSValue arraybufferValue = toJS(arraybuffer); @@ -1885,9 +1882,11 @@ extern "C" napi_status napi_create_dataview(napi_env env, size_t length, return napi_set_last_error(env, napi_pending_exception); } - auto dataView = JSC::DataView::create(arraybufferPtr->impl(), byte_offset, length); - *result = toNapi(dataView->wrap(globalObject, globalObject), globalObject); - RELEASE_AND_RETURN(scope, napi_set_last_error(env, napi_ok)); + // JSDataView::create (rather than DataView::create + wrap) so a detached buffer is a TypeError, not a crash. + auto* dataView = JSC::JSDataView::create(globalObject, globalObject->typedArrayStructure(JSC::TypeDataView, arraybufferPtr->impl()->isResizableOrGrowableShared()), arraybufferPtr->impl(), byte_offset, length); + NAPI_RETURN_IF_EXCEPTION(env); + *result = toNapi(dataView, globalObject); + NAPI_RETURN_SUCCESS(env); } static JSC::TypedArrayType getTypedArrayTypeFromNAPI(napi_typedarray_type type) @@ -2079,14 +2078,19 @@ extern "C" napi_status napi_get_all_property_names( JSArray* filteredKeys = JSArray::create(JSC::getVM(globalObject), globalObject->originalArrayStructureForIndexingType(ArrayWithContiguous), 0); for (unsigned i = 0; i < exportKeys->getArrayLength(); i++) { JSValue key = exportKeys->get(globalObject, i); + NAPI_RETURN_IF_EXCEPTION(env); auto propKey = key.toPropertyKey(globalObject); + NAPI_RETURN_IF_EXCEPTION(env); PropertyDescriptor desc; JSObject* owner = object; if (key_mode == napi_key_include_prototypes) { // Climb up the prototype chain to find inherited properties - while (!owner->getOwnPropertyDescriptor(globalObject, propKey, desc)) { + for (;;) { + bool found = owner->getOwnPropertyDescriptor(globalObject, propKey, desc); NAPI_RETURN_IF_EXCEPTION(env); + if (found) + break; JSValue protoValue = owner->getPrototype(globalObject); NAPI_RETURN_IF_EXCEPTION(env); JSObject* proto = protoValue ? protoValue.getObject() : nullptr; @@ -2128,6 +2132,7 @@ extern "C" napi_status napi_get_all_property_names( if (include) { filteredKeys->push(globalObject, key); + NAPI_RETURN_IF_EXCEPTION(env); } } exportKeys = filteredKeys; @@ -2139,6 +2144,7 @@ extern "C" napi_status napi_get_all_property_names( unsigned length = exportKeys->getArrayLength(); for (unsigned i = 0; i < length; i++) { JSValue key = exportKeys->getDirectIndex(globalObject, i); + NAPI_RETURN_IF_EXCEPTION(env); if (!key.isString()) continue; auto keyStr = asString(key)->value(globalObject); @@ -2289,10 +2295,8 @@ extern "C" napi_status napi_create_buffer(napi_env env, size_t length, void** data, napi_value* result) { - NAPI_PREAMBLE_NO_THROW_SCOPE(env); + NAPI_PREAMBLE(env); Zig::GlobalObject* globalObject = toJS(env); - auto scope = DECLARE_THROW_SCOPE(env->vm()); - NAPI_RETURN_IF_EXCEPTION_WITH_SCOPE(env, scope); NAPI_CHECK_ARG(env, result); auto* subclassStructure = globalObject->JSBufferSubclassStructure(); @@ -2304,12 +2308,12 @@ extern "C" napi_status napi_create_buffer(napi_env env, size_t length, RefPtr arrayBuffer = ArrayBuffer::tryCreateUninitialized(length, 1); if (!arrayBuffer) { // Node leaves a pending exception for a failed allocation. - JSC::throwOutOfMemoryError(globalObject, scope); - RETURN_IF_EXCEPTION(scope, napi_set_last_error(env, napi_generic_failure)); + env->scheduleException(createOutOfMemoryError(globalObject)); + return napi_set_last_error(env, napi_generic_failure); } auto* uint8Array = JSC::JSUint8Array::create(globalObject, subclassStructure, WTF::move(arrayBuffer), 0, length); - RETURN_IF_EXCEPTION(scope, napi_set_last_error(env, napi_generic_failure)); + NAPI_RETURN_IF_EXCEPTION(env); if (data != nullptr) { // Node.js' code looks like this: @@ -2319,7 +2323,7 @@ extern "C" napi_status napi_create_buffer(napi_env env, size_t length, } *result = toNapi(uint8Array, globalObject); - return napi_set_last_error(env, napi_ok); + NAPI_RETURN_SUCCESS(env); } extern "C" napi_status napi_create_buffer_copy(napi_env env, size_t length, @@ -2327,10 +2331,8 @@ extern "C" napi_status napi_create_buffer_copy(napi_env env, size_t length, void** result_data, napi_value* result) { - NAPI_PREAMBLE_NO_THROW_SCOPE(env); + NAPI_PREAMBLE(env); Zig::GlobalObject* globalObject = toJS(env); - auto scope = DECLARE_THROW_SCOPE(env->vm()); - NAPI_RETURN_IF_EXCEPTION_WITH_SCOPE(env, scope); NAPI_CHECK_ARG(env, result); auto* subclassStructure = globalObject->JSBufferSubclassStructure(); @@ -2339,22 +2341,22 @@ extern "C" napi_status napi_create_buffer_copy(napi_env env, size_t length, RefPtr arrayBuffer = ArrayBuffer::tryCreateUninitialized(length, 1); if (!arrayBuffer) { // Node leaves a pending exception for a failed allocation. - JSC::throwOutOfMemoryError(globalObject, scope); - RETURN_IF_EXCEPTION(scope, napi_set_last_error(env, napi_generic_failure)); + env->scheduleException(createOutOfMemoryError(globalObject)); + return napi_set_last_error(env, napi_generic_failure); } if (length > 0) { memcpy(arrayBuffer->data(), data, length); } auto* uint8Array = JSC::JSUint8Array::create(globalObject, subclassStructure, WTF::move(arrayBuffer), 0, length); - RETURN_IF_EXCEPTION(scope, napi_set_last_error(env, napi_generic_failure)); + NAPI_RETURN_IF_EXCEPTION(env); if (result_data != nullptr) { *result_data = length > 0 ? uint8Array->typedVector() : nullptr; } *result = toNapi(uint8Array, globalObject); - return napi_set_last_error(env, napi_ok); + NAPI_RETURN_SUCCESS(env); } // SharedTask subclass with an armed flag so that the destructor can be @@ -3040,33 +3042,41 @@ extern "C" napi_status napi_get_instance_data(napi_env env, extern "C" napi_status napi_run_script(napi_env env, napi_value script, napi_value* result) { - NAPI_PREAMBLE_NO_THROW_SCOPE(env); + NAPI_PREAMBLE(env); Zig::GlobalObject* globalObject = toJS(env); auto& vm = JSC::getVM(globalObject); - auto throwScope = DECLARE_THROW_SCOPE(vm); - NAPI_RETURN_IF_EXCEPTION_WITH_SCOPE(env, throwScope); NAPI_CHECK_ARG(env, script); NAPI_CHECK_ARG(env, result); JSValue scriptValue = toJS(script); NAPI_RETURN_EARLY_IF_FALSE(env, scriptValue.isString(), napi_string_expected); WTF::String code = scriptValue.getString(globalObject); - RETURN_IF_EXCEPTION(throwScope, napi_set_last_error(env, napi_generic_failure)); + NAPI_RETURN_IF_EXCEPTION(env); JSC::SourceCode sourceCode = makeSource(code, SourceOrigin(), SourceTaintedOrigin::Untainted); - NakedPtr returnedException; - JSValue value = JSC::evaluate(globalObject, sourceCode, globalObject->globalThis(), returnedException); - - if (returnedException) { - env->scheduleException(returnedException.get()); + // JSC::evaluate catches what the script throws and hands it back here. + NakedPtr thrown; + JSValue value = JSC::evaluate(globalObject, sourceCode, globalObject->globalThis(), thrown); + if (thrown) { + if (vm.isTerminationException(thrown.get())) { + // Not the addon's to handle: put it straight back on the VM. + { + auto inner = DECLARE_THROW_SCOPE(vm); + JSC::throwException(globalObject, inner, thrown.get()); + inner.release(); + } + EXCEPTION_ASSERT(napi_preamble_throw_scope__.exception()); + return napi_set_last_error(env, napi_pending_exception); + } + // Latched on the env like napi_throw; Node returns napi_generic_failure (not napi_pending_exception) here. + env->scheduleException(thrown.get()); return napi_set_last_error(env, napi_generic_failure); } ASSERT(!value.isEmpty()); *result = toNapi(value, globalObject); - - return napi_set_last_error(env, napi_ok); + NAPI_RETURN_SUCCESS(env); } extern "C" napi_status napi_set_instance_data(napi_env env, @@ -3112,11 +3122,8 @@ extern "C" napi_status napi_create_bigint_words(napi_env env, const uint64_t* words, napi_value* result) { - NAPI_PREAMBLE_NO_THROW_SCOPE(env); + NAPI_PREAMBLE(env); Zig::GlobalObject* globalObject = toJS(env); - auto& vm = env->vm(); - auto scope = DECLARE_THROW_SCOPE(vm); - NAPI_RETURN_IF_EXCEPTION_WITH_SCOPE(env, scope); NAPI_CHECK_ARG(env, result); NAPI_CHECK_ARG(env, words); NAPI_RETURN_EARLY_IF_FALSE(env, word_count <= INT_MAX, napi_invalid_arg); @@ -3125,21 +3132,21 @@ extern "C" napi_status napi_create_bigint_words(napi_env env, // here first. Value mirrors JSBigInt::maxLength (maxLengthBits / digitBits). constexpr size_t jscBigIntMaxWords = (1 << 20) / (CHAR_BIT * sizeof(uint64_t)); if (word_count > jscBigIntMaxWords) { - JSC::throwOutOfMemoryError(globalObject, scope); - RETURN_IF_EXCEPTION(scope, napi_set_last_error(env, napi_pending_exception)); + env->scheduleException(createOutOfMemoryError(globalObject)); + return napi_set_last_error(env, napi_pending_exception); } std::span words_span(words, word_count); // throws RangeError if size is larger than JSC's limit auto* bigint = JSBigInt::createFromWords(globalObject, words_span, sign_bit != 0); - RETURN_IF_EXCEPTION(scope, napi_set_last_error(env, napi_pending_exception)); + NAPI_RETURN_IF_EXCEPTION(env); ASSERT(bigint); *result = toNapi(bigint, globalObject); ensureStillAliveHere(bigint); - return napi_set_last_error(env, napi_ok); + NAPI_RETURN_SUCCESS(env); } extern "C" napi_status napi_create_symbol(napi_env env, napi_value description, @@ -3190,8 +3197,7 @@ extern "C" napi_status napi_new_instance(napi_env env, napi_value constructor, if (constructData.type == JSC::CallData::Type::None) [[unlikely]] { // Callable but not constructible (e.g. arrow functions): Node.js lets V8 // throw "is not a constructor" and returns napi_pending_exception. - auto scope = DECLARE_THROW_SCOPE(vm); - JSC::throwException(globalObject, scope, JSC::createNotAConstructorError(globalObject, constructorValue)); + env->scheduleException(JSC::createNotAConstructorError(globalObject, constructorValue)); return napi_set_last_error(env, napi_pending_exception); } @@ -3241,10 +3247,14 @@ extern "C" napi_status napi_call_function(napi_env env, napi_value recv, napi_value* result) { NAPI_CHECK_ARG(env, env); - if (env->throwPendingException()) { - return napi_set_last_error(env, napi_pending_exception); + // An exception the addon raised through napi_throw* is latched on the env until control returns to JS; + // this is where the addon gets to observe it as the engine's pending exception (node-addon-api builds its + // Error object in that state) before the call is refused. + if (env->hasPendingException()) [[unlikely]] { + auto scope = DECLARE_TOP_EXCEPTION_SCOPE(env->vm()); + env->throwPendingException(); + RETURN_IF_EXCEPTION(scope, napi_set_last_error(env, napi_pending_exception)); } - NAPI_PREAMBLE(env); NAPI_CHECK_ARG(env, recv); NAPI_RETURN_EARLY_IF_FALSE(env, argc == 0 || argv, napi_invalid_arg); diff --git a/src/jsc/bindings/v8/V8Isolate.cpp b/src/jsc/bindings/v8/V8Isolate.cpp index ecb145809496..e86f1de2a2d4 100644 --- a/src/jsc/bindings/v8/V8Isolate.cpp +++ b/src/jsc/bindings/v8/V8Isolate.cpp @@ -140,21 +140,36 @@ void Isolate::RequestInterrupt(InterruptCallback callback, void* data) }); } +// v8::Isolate::ThrowException returns to addon code with the exception left pending on the VM; the frame that +// observes it is the FunctionTemplate trampoline (or whatever entered the addon), not a C++ caller of this +// function. So, as in the napi entry points, this is the top of its own scope: throw through a transient +// ThrowScope and acknowledge it here so the addon's next API call does not see an unchecked simulated throw. +static void throwIntoVM(JSC::JSGlobalObject* globalObject, JSC::JSValue value) +{ + JSC::VM& vm = JSC::getVM(globalObject); + auto scope = DECLARE_TOP_EXCEPTION_SCOPE(vm); + { + auto inner = DECLARE_THROW_SCOPE(vm); + JSC::throwException(globalObject, inner, value); + inner.release(); + } + EXCEPTION_ASSERT(scope.exception()); +} + Local Isolate::ThrowException(Local exception) { - auto scope = DECLARE_THROW_SCOPE(vm()); - JSC::throwException(m_globalObject, scope, exception->localToJSValue()); + throwIntoVM(m_globalObject, exception->localToJSValue()); return exception; } Local Isolate::ThrowError(Local message) { JSC::VM& vm = this->vm(); - auto scope = DECLARE_THROW_SCOPE(vm); - WTF::String wtfMessage = message->localToJSString()->value(m_globalObject); + // tryGetValue(): an unresolvable rope yields a null message here rather than a second exception. + WTF::String wtfMessage = message->localToJSString()->tryGetValue(); JSC::JSObject* error = JSC::createError(m_globalObject, wtfMessage); Local handle = currentHandleScope()->createLocal(vm, error); - JSC::throwException(m_globalObject, scope, error); + throwIntoVM(m_globalObject, error); return handle; } diff --git a/test/napi/napi-app/binding.gyp b/test/napi/napi-app/binding.gyp index bb38676c5d7d..6ac17aea0c02 100644 --- a/test/napi/napi-app/binding.gyp +++ b/test/napi/napi-app/binding.gyp @@ -121,6 +121,10 @@ "NAPI_DISABLE_CPP_EXCEPTIONS", ], }, + { + "target_name": "throwing_init_addon", + "sources": ["throwing_init_addon.c"], + }, { "target_name": "reentrant_register_addon", "sources": ["reentrant_register_addon.cpp"], diff --git a/test/napi/napi-app/standalone_tests.cpp b/test/napi/napi-app/standalone_tests.cpp index b9cfc51de1ea..faf48cd30cb6 100644 --- a/test/napi/napi-app/standalone_tests.cpp +++ b/test/napi/napi-app/standalone_tests.cpp @@ -169,14 +169,14 @@ static napi_value test_napi_threadsafe_function_abort_blocked_producers( napi_value resource_name = Napi::String::New(env, "abort_blocked_producers"); tsfn_abort_blocked_finalized = false; tsfn_abort_blocked_about_to_call.store(0); - NODE_API_CALL( - env, napi_create_threadsafe_function( - env, /* JavaScript function */ nullptr, - /* async resource */ nullptr, resource_name, - /* max queue size */ 1, - /* initial thread count */ 3, /* finalize data */ nullptr, - tsfn_abort_blocked_finalize, /* context */ nullptr, - &noop_callback, &tsfn_abort_blocked)); + NODE_API_CALL(env, + napi_create_threadsafe_function( + env, /* JavaScript function */ nullptr, + /* async resource */ nullptr, resource_name, + /* max queue size */ 1, + /* initial thread count */ 3, /* finalize data */ nullptr, + tsfn_abort_blocked_finalize, /* context */ nullptr, + &noop_callback, &tsfn_abort_blocked)); // Fill the queue so both producer threads block on the condvar. The JS // thread is parked in this function, so dispatch cannot drain it yet. NODE_API_CALL(env, napi_call_threadsafe_function(tsfn_abort_blocked, nullptr, @@ -216,20 +216,20 @@ test_napi_threadsafe_function_abort_full_queue(const Napi::CallbackInfo &info) { Napi::Env env = info.Env(); napi_value resource_name = Napi::String::New(env, "abort_full_queue"); tsfn_abort_full_finalized = false; - NODE_API_CALL(env, napi_create_threadsafe_function( - env, /* JavaScript function */ nullptr, - /* async resource */ nullptr, resource_name, - /* max queue size */ 1, - /* initial thread count */ 2, - /* finalize data */ nullptr, tsfn_abort_full_finalize, - /* context */ nullptr, &noop_callback, - &tsfn_abort_full)); + NODE_API_CALL(env, + napi_create_threadsafe_function( + env, /* JavaScript function */ nullptr, + /* async resource */ nullptr, resource_name, + /* max queue size */ 1, + /* initial thread count */ 2, + /* finalize data */ nullptr, tsfn_abort_full_finalize, + /* context */ nullptr, &noop_callback, &tsfn_abort_full)); // The JS thread is parked in here, so nothing drains the queue: it is still // full at the abort and at the call below. NODE_API_CALL(env, napi_call_threadsafe_function(tsfn_abort_full, nullptr, napi_tsfn_nonblocking)); - NODE_API_CALL(env, napi_release_threadsafe_function(tsfn_abort_full, - napi_tsfn_abort)); + NODE_API_CALL( + env, napi_release_threadsafe_function(tsfn_abort_full, napi_tsfn_abort)); napi_status status = napi_call_threadsafe_function(tsfn_abort_full, nullptr, napi_tsfn_nonblocking); tsfn_abort_full = nullptr; @@ -245,8 +245,8 @@ static napi_value test_napi_threadsafe_function_abort_full_queue_finalized( // one dispatch. Microtasks queued by one callback must be drained before the // next callback runs (https://github.com/nodejs/node/pull/38506), and must not // be drained before the first one. -static napi_value test_napi_threadsafe_function_microtask_order( - const Napi::CallbackInfo &info) { +static napi_value +test_napi_threadsafe_function_microtask_order(const Napi::CallbackInfo &info) { Napi::Env env = info.Env(); napi_value resource_name = Napi::String::New(env, "microtask_order"); napi_threadsafe_function tsfn; @@ -278,8 +278,8 @@ static void tsfn_throwing_call_js(napi_env env, napi_value js_callback, napi_throw_error(env, nullptr, message); } -static napi_value test_napi_threadsafe_function_call_js_throws( - const Napi::CallbackInfo &info) { +static napi_value +test_napi_threadsafe_function_call_js_throws(const Napi::CallbackInfo &info) { Napi::Env env = info.Env(); napi_value resource_name = Napi::String::New(env, "call_js_throws"); napi_threadsafe_function tsfn; @@ -292,9 +292,9 @@ static napi_value test_napi_threadsafe_function_call_js_throws( /* finalize callback */ nullptr, /* context */ nullptr, tsfn_throwing_call_js, &tsfn)); for (intptr_t i = 1; i <= 3; i++) { - NODE_API_CALL(env, napi_call_threadsafe_function( - tsfn, reinterpret_cast(i), - napi_tsfn_nonblocking)); + NODE_API_CALL( + env, napi_call_threadsafe_function(tsfn, reinterpret_cast(i), + napi_tsfn_nonblocking)); } NODE_API_CALL(env, napi_release_threadsafe_function(tsfn, napi_tsfn_release)); return env.Undefined(); @@ -770,8 +770,9 @@ static napi_value test_is_typedarray(const Napi::CallbackInfo &info) { // https://github.com/oven-sh/bun/issues/32624 // info[0] is the GC callback; the values to classify start at info[1]. For each -// one, print napi_is_arraybuffer and the raw napi_get_arraybuffer_info status so -// the output can be diffed against Node (napi_ok is 0, napi_invalid_arg is 1). +// one, print napi_is_arraybuffer and the raw napi_get_arraybuffer_info status +// so the output can be diffed against Node (napi_ok is 0, napi_invalid_arg is +// 1). static napi_value test_is_arraybuffer(const Napi::CallbackInfo &info) { napi_env env = info.Env(); for (size_t i = 1; i < info.Length(); i++) { @@ -1620,8 +1621,8 @@ test_napi_new_instance_status(const Napi::CallbackInfo &info) { NODE_API_CALL(env, napi_get_and_clear_last_exception(env, &exc)); napi_value global, type_error; NODE_API_CALL(env, napi_get_global(env, &global)); - NODE_API_CALL(env, napi_get_named_property(env, global, "TypeError", - &type_error)); + NODE_API_CALL( + env, napi_get_named_property(env, global, "TypeError", &type_error)); NODE_API_CALL(env, napi_instanceof(env, exc, type_error, &is_type_error)); } @@ -1767,6 +1768,28 @@ test_napi_dataview_bounds_errors(const Napi::CallbackInfo &info) { } // Test for napi_typeof with potentially empty/invalid values +// napi_create_dataview on a detached ArrayBuffer: must fail with the engine's +// TypeError pending, not return napi_ok with a NULL result. +static napi_value test_napi_dataview_detached(const Napi::CallbackInfo &info) { + napi_env env = info.Env(); + napi_value arraybuffer; + void *data = nullptr; + NODE_API_CALL(env, napi_create_arraybuffer(env, 16, &data, &arraybuffer)); + NODE_API_CALL(env, napi_detach_arraybuffer(env, arraybuffer)); + + napi_value dataview = nullptr; + napi_status status = napi_create_dataview(env, 0, arraybuffer, 0, &dataview); + bool pending = false; + napi_is_exception_pending(env, &pending); + printf("status_ok=%d result_null=%d pending=%d\n", status == napi_ok ? 1 : 0, + dataview == nullptr ? 1 : 0, pending ? 1 : 0); + if (pending) { + napi_value exc; + napi_get_and_clear_last_exception(env, &exc); + } + return ok(env); +} + static napi_value test_napi_typeof_empty_value(const Napi::CallbackInfo &info) { Napi::Env env = info.Env(); @@ -1837,25 +1860,22 @@ static napi_value test_napi_null_value_args(const Napi::CallbackInfo &info) { printf("napi_detach_arraybuffer(NULL) -> %d\n", (int)napi_detach_arraybuffer(env, nullptr)); - printf("node_api_create_buffer_from_arraybuffer(NULL) -> %d\n", - (int)node_api_create_buffer_from_arraybuffer(env, nullptr, 0, 0, - &out)); + printf( + "node_api_create_buffer_from_arraybuffer(NULL) -> %d\n", + (int)node_api_create_buffer_from_arraybuffer(env, nullptr, 0, 0, &out)); printf("napi_strict_equals(NULL, NULL) -> %d\n", (int)napi_strict_equals(env, nullptr, nullptr, &b)); printf("napi_instanceof(NULL, NULL) -> %d\n", (int)napi_instanceof(env, nullptr, nullptr, &b)); printf("napi_new_instance(NULL) -> %d\n", (int)napi_new_instance(env, nullptr, 0, nullptr, &out)); - printf("napi_is_array(NULL) -> %d\n", - (int)napi_is_array(env, nullptr, &b)); - printf("napi_is_error(NULL) -> %d\n", - (int)napi_is_error(env, nullptr, &b)); + printf("napi_is_array(NULL) -> %d\n", (int)napi_is_array(env, nullptr, &b)); + printf("napi_is_error(NULL) -> %d\n", (int)napi_is_error(env, nullptr, &b)); printf("napi_is_arraybuffer(NULL) -> %d\n", (int)napi_is_arraybuffer(env, nullptr, &b)); printf("napi_is_dataview(NULL) -> %d\n", (int)napi_is_dataview(env, nullptr, &b)); - printf("napi_is_date(NULL) -> %d\n", - (int)napi_is_date(env, nullptr, &b)); + printf("napi_is_date(NULL) -> %d\n", (int)napi_is_date(env, nullptr, &b)); printf("napi_get_array_length(NULL) -> %d\n", (int)napi_get_array_length(env, nullptr, &len)); printf("napi_get_dataview_info(NULL) -> %d\n", @@ -1865,13 +1885,15 @@ static napi_value test_napi_null_value_args(const Napi::CallbackInfo &info) { return ok(env); } -static napi_value test_napi_null_env_and_result(const Napi::CallbackInfo &info) { +static napi_value +test_napi_null_env_and_result(const Napi::CallbackInfo &info) { napi_env env = info.Env(); napi_value undef; NODE_API_CALL(env, napi_get_undefined(env, &undef)); napi_value name; - NODE_API_CALL(env, napi_create_string_utf8(env, "n", NAPI_AUTO_LENGTH, &name)); + NODE_API_CALL(env, + napi_create_string_utf8(env, "n", NAPI_AUTO_LENGTH, &name)); napi_valuetype ty; printf("napi_typeof(NULL env) -> %d\n", @@ -2158,19 +2180,18 @@ static napi_value test_napi_object_coercion(const Napi::CallbackInfo &info) { env, obj, static_cast(99), napi_key_all_properties, napi_key_numbers_to_strings, &out)); - report_status( - env, "get_all_property_names(key_conversion=99)", - napi_get_all_property_names(env, obj, napi_key_own_only, - napi_key_all_properties, - static_cast(99), &out)); - report_status(env, "get_all_property_names(string)", + report_status(env, "get_all_property_names(key_conversion=99)", napi_get_all_property_names( - env, v_str, napi_key_own_only, napi_key_all_properties, - napi_key_numbers_to_strings, &out)); + env, obj, napi_key_own_only, napi_key_all_properties, + static_cast(99), &out)); + report_status(env, "get_all_property_names(string)", + napi_get_all_property_names(env, v_str, napi_key_own_only, + napi_key_all_properties, + napi_key_numbers_to_strings, &out)); report_status(env, "get_all_property_names(null)", - napi_get_all_property_names( - env, v_null, napi_key_own_only, napi_key_all_properties, - napi_key_numbers_to_strings, &out)); + napi_get_all_property_names(env, v_null, napi_key_own_only, + napi_key_all_properties, + napi_key_numbers_to_strings, &out)); report_status(env, "get_all_property_names(null,key_mode=99)", napi_get_all_property_names( env, v_null, static_cast(99), @@ -2345,9 +2366,8 @@ static napi_value test_napi_v10_surface(const Napi::CallbackInfo &info) { bool copied = true; napi_value result = nullptr; - NODE_API_CALL(env, - node_api_create_external_string_utf16( - env, utf16_hi, 2, nullptr, nullptr, &result, &copied)); + NODE_API_CALL(env, node_api_create_external_string_utf16( + env, utf16_hi, 2, nullptr, nullptr, &result, &copied)); printf("external utf16 nonempty: copied=%d\n", (int)copied); return ok(env); @@ -2495,15 +2515,19 @@ static napi_value napi_get_typeof(const Napi::CallbackInfo &info) { // Regression test: napi_create_external_buffer must tie the finalize callback // to the ArrayBuffer's destructor, not addFinalizer on the JSUint8Array. // With addFinalizer, extracting .buffer (the ArrayBuffer) and then letting the -// Buffer get GC'd would call finalize_cb and free the data while the ArrayBuffer -// still references it. -static napi_value test_external_buffer_data_lifetime(const Napi::CallbackInfo &info) { +// Buffer get GC'd would call finalize_cb and free the data while the +// ArrayBuffer still references it. +static napi_value +test_external_buffer_data_lifetime(const Napi::CallbackInfo &info) { napi_env env = info.Env(); // Allocate data with a known pattern. const size_t data_size = 4; - uint8_t* ext_data = (uint8_t*)malloc(data_size); - ext_data[0] = 0xDE; ext_data[1] = 0xAD; ext_data[2] = 0xBE; ext_data[3] = 0xEF; + uint8_t *ext_data = (uint8_t *)malloc(data_size); + ext_data[0] = 0xDE; + ext_data[1] = 0xAD; + ext_data[2] = 0xBE; + ext_data[3] = 0xEF; napi_ref ab_ref = nullptr; @@ -2514,18 +2538,21 @@ static napi_value test_external_buffer_data_lifetime(const Napi::CallbackInfo &i // Allocate on the heap so conservative stack scanning can't find it. napi_value *buffer = new napi_value; - NODE_API_CALL(env, napi_create_external_buffer(env, data_size, ext_data, - +[](napi_env, void* data, void*) { - // Poison the data then free — detectable as use-after-free if - // the ArrayBuffer still tries to read through this pointer. - memset(data, 0x00, 4); - free(data); - }, nullptr, buffer)); + NODE_API_CALL(env, napi_create_external_buffer( + env, data_size, ext_data, + +[](napi_env, void *data, void *) { + // Poison the data then free — detectable as + // use-after-free if the ArrayBuffer still tries to + // read through this pointer. + memset(data, 0x00, 4); + free(data); + }, + nullptr, buffer)); // Extract the underlying ArrayBuffer and prevent it from being GC'd. napi_value *arraybuffer = new napi_value; NODE_API_CALL(env, napi_get_typedarray_info(env, *buffer, nullptr, nullptr, - nullptr, arraybuffer, nullptr)); + nullptr, arraybuffer, nullptr)); NODE_API_CALL(env, napi_create_reference(env, *arraybuffer, 1, &ab_ref)); // Drop heap pointers before closing the scope so the stack scanner @@ -2545,17 +2572,18 @@ static napi_value test_external_buffer_data_lifetime(const Napi::CallbackInfo &i napi_value ab_value; NODE_API_CALL(env, napi_get_reference_value(env, ab_ref, &ab_value)); - void* ab_data; + void *ab_data; size_t ab_len; - NODE_API_CALL(env, napi_get_arraybuffer_info(env, ab_value, &ab_data, &ab_len)); + NODE_API_CALL(env, + napi_get_arraybuffer_info(env, ab_value, &ab_data, &ab_len)); - uint8_t* bytes = (uint8_t*)ab_data; - if (ab_len >= data_size && - bytes[0] == 0xDE && bytes[1] == 0xAD && + uint8_t *bytes = (uint8_t *)ab_data; + if (ab_len >= data_size && bytes[0] == 0xDE && bytes[1] == 0xAD && bytes[2] == 0xBE && bytes[3] == 0xEF) { printf("PASS: external buffer data intact through ArrayBuffer after GC\n"); } else { - printf("FAIL: external buffer data was corrupted (finalize_cb ran too early)\n"); + printf("FAIL: external buffer data was corrupted (finalize_cb ran too " + "early)\n"); } NODE_API_CALL(env, napi_delete_reference(env, ab_ref)); @@ -2584,14 +2612,13 @@ test_external_arraybuffer_finalizer(const Napi::CallbackInfo &info) { ext_data[i] = (uint8_t)(0xA0 + i); napi_value arraybuffer; - NODE_API_CALL( - env, napi_create_external_arraybuffer( - env, ext_data, data_size, - +[](napi_env, void *data, void *) { - external_arraybuffer_finalize_count++; - free(data); - }, - nullptr, &arraybuffer)); + NODE_API_CALL(env, napi_create_external_arraybuffer( + env, ext_data, data_size, + +[](napi_env, void *data, void *) { + external_arraybuffer_finalize_count++; + free(data); + }, + nullptr, &arraybuffer)); // The finalizer must not have run yet: the ArrayBuffer is still live. if (external_arraybuffer_finalize_count != 0) { @@ -2603,8 +2630,8 @@ test_external_arraybuffer_finalizer(const Napi::CallbackInfo &info) { // Verify the backing store is the caller's pointer and the bytes match. void *ab_data; size_t ab_len; - NODE_API_CALL( - env, napi_get_arraybuffer_info(env, arraybuffer, &ab_data, &ab_len)); + NODE_API_CALL(env, + napi_get_arraybuffer_info(env, arraybuffer, &ab_data, &ab_len)); bool bytes_ok = ab_len == data_size; for (size_t i = 0; bytes_ok && i < data_size; i++) @@ -2675,8 +2702,7 @@ static napi_value test_external_arraybuffer_with_pending_exception( memset(ext_data, 0x5A, data_size); // Stash a napi-level pending exception (no VM exception is raised yet). - NODE_API_CALL(env, - napi_throw_error(env, nullptr, "stashed before create")); + NODE_API_CALL(env, napi_throw_error(env, nullptr, "stashed before create")); napi_value arraybuffer = nullptr; napi_status status = napi_create_external_arraybuffer( @@ -2704,8 +2730,8 @@ static napi_value test_external_arraybuffer_with_pending_exception( } void *ab_data; size_t ab_len; - NODE_API_CALL(env, napi_get_arraybuffer_info(env, arraybuffer, &ab_data, - &ab_len)); + NODE_API_CALL( + env, napi_get_arraybuffer_info(env, arraybuffer, &ab_data, &ab_len)); if (ab_data == ext_data && ab_len == data_size) { printf("PASS: ownership transferred on napi_ok with pending " "exception\n"); @@ -2736,8 +2762,8 @@ static napi_value test_external_arraybuffer_with_pending_exception( // rejected up front rather than after createFromBytes has adopted data. static int external_buffer_finalize_count = 0; -static napi_value test_external_buffer_with_pending_exception( - const Napi::CallbackInfo &info) { +static napi_value +test_external_buffer_with_pending_exception(const Napi::CallbackInfo &info) { napi_env env = info.Env(); external_buffer_finalize_count = 0; @@ -2746,8 +2772,7 @@ static napi_value test_external_buffer_with_pending_exception( uint8_t *ext_data = (uint8_t *)malloc(data_size); memset(ext_data, 0x5A, data_size); - NODE_API_CALL(env, - napi_throw_error(env, nullptr, "stashed before create")); + NODE_API_CALL(env, napi_throw_error(env, nullptr, "stashed before create")); napi_value buffer = nullptr; napi_status status = napi_create_external_buffer( @@ -2771,8 +2796,7 @@ static napi_value test_external_buffer_with_pending_exception( } void *buf_data; size_t buf_len; - NODE_API_CALL(env, - napi_get_buffer_info(env, buffer, &buf_data, &buf_len)); + NODE_API_CALL(env, napi_get_buffer_info(env, buffer, &buf_data, &buf_len)); if (buf_data == ext_data && buf_len == data_size) { printf("PASS: ownership transferred on napi_ok with pending " "exception\n"); @@ -2889,31 +2913,27 @@ static napi_value test_pending_exception_gate(const Napi::CallbackInfo &info) { NODE_API_CALL(env, napi_create_object(env, &obj)); NODE_API_CALL(env, napi_create_array_with_length(env, 3, &arr)); NODE_API_CALL(env, napi_create_int32(env, 5, &five)); - NODE_API_CALL(env, napi_create_string_utf8( - env, "globalThis.__napiGateMark()", NAPI_AUTO_LENGTH, - &script)); + NODE_API_CALL(env, napi_create_string_utf8(env, "globalThis.__napiGateMark()", + NAPI_AUTO_LENGTH, &script)); NODE_API_CALL(env, napi_get_global(env, &global)); NODE_API_CALL(env, napi_get_named_property(env, global, "Function", &fn_ctor)); - NODE_API_CALL(env, - napi_create_arraybuffer(env, 16, &ab_data, &arraybuffer)); + NODE_API_CALL(env, napi_create_arraybuffer(env, 16, &ab_data, &arraybuffer)); NODE_API_CALL(env, napi_create_date(env, 1234.0, &date_in)); // Install a global the script would call so we can observe it running. napi_value mark_fn; NODE_API_CALL(env, napi_create_function(env, "mark", NAPI_AUTO_LENGTH, - pending_gate_mark_script_ran, - nullptr, &mark_fn)); - NODE_API_CALL(env, - napi_set_named_property(env, global, "__napiGateMark", - mark_fn)); + pending_gate_mark_script_ran, nullptr, + &mark_fn)); + NODE_API_CALL( + env, napi_set_named_property(env, global, "__napiGateMark", mark_fn)); // Create a real deferred/promise BEFORE throwing so resolve_deferred has // a valid handle to refuse. napi_deferred deferred_pre; napi_value promise_pre; - NODE_API_CALL(env, - napi_create_promise(env, &deferred_pre, &promise_pre)); + NODE_API_CALL(env, napi_create_promise(env, &deferred_pre, &promise_pre)); // Arm: exception now pending on the env (not the VM). NODE_API_CALL(env, napi_throw_error(env, "EGATE", "armed")); @@ -2998,10 +3018,10 @@ static napi_value test_pending_exception_gate(const Napi::CallbackInfo &info) { napi_value frozen_obj, is_frozen; NODE_API_CALL(env, napi_get_named_property(env, global, "Object", &frozen_obj)); - NODE_API_CALL(env, napi_get_named_property(env, frozen_obj, "isFrozen", - &frozen_obj)); - NODE_API_CALL(env, napi_call_function(env, global, frozen_obj, 1, &obj, - &is_frozen)); + NODE_API_CALL( + env, napi_get_named_property(env, frozen_obj, "isFrozen", &frozen_obj)); + NODE_API_CALL( + env, napi_call_function(env, global, frozen_obj, 1, &obj, &is_frozen)); bool frozen; NODE_API_CALL(env, napi_get_value_bool(env, is_frozen, &frozen)); printf("side_effect frozen=%s\n", frozen ? "true" : "false"); @@ -3237,7 +3257,8 @@ ungated_calls_through_timeout(const Napi::CallbackInfo &info) { // With createWithoutCopying, the atom table retains a reference to the // freed CString memory. On the next lookup of the same property name, // Identifier::fromString compares against the stale atom -> use-after-free. -static napi_value test_napi_get_named_property_copied_string(const Napi::CallbackInfo &info) { +static napi_value +test_napi_get_named_property_copied_string(const Napi::CallbackInfo &info) { napi_env env = info.Env(); napi_value global; @@ -3247,8 +3268,8 @@ static napi_value test_napi_get_named_property_copied_string(const Napi::Callbac // heap-allocated keys (like napi-rs CString), then free them. // The property names here match what impit uses in its response handling. const char *property_names[] = { - "ReadableStream", "Response", "arrayBuffer", "then", "eval", - "enqueue", "bind", "close", + "ReadableStream", "Response", "arrayBuffer", "then", + "eval", "enqueue", "bind", "close", }; const int num_names = sizeof(property_names) / sizeof(property_names[0]); @@ -3313,8 +3334,8 @@ static void test_issue_25933_callback(napi_env env, napi_value js_callback, } else if (type == napi_function) { printf("PASS: napi_typeof returned napi_function\n"); } else { - printf("FAIL: napi_typeof returned %d, expected napi_function (%d)\n", - type, napi_function); + printf("FAIL: napi_typeof returned %d, expected napi_function (%d)\n", type, + napi_function); } napi_release_threadsafe_function(tsfn_25933, napi_tsfn_release); tsfn_25933 = nullptr; @@ -3330,10 +3351,9 @@ static napi_value test_issue_25933(const Napi::CallbackInfo &info) { napi_value js_cb = info[0]; napi_value name = Napi::String::New(env, "tsfn_typeof_test"); - NODE_API_CALL(env, - napi_create_threadsafe_function( - env, js_cb, nullptr, name, 0, 1, nullptr, nullptr, - nullptr, &test_issue_25933_callback, &tsfn_25933)); + NODE_API_CALL(env, napi_create_threadsafe_function( + env, js_cb, nullptr, name, 0, 1, nullptr, nullptr, + nullptr, &test_issue_25933_callback, &tsfn_25933)); NODE_API_CALL(env, napi_call_threadsafe_function(tsfn_25933, nullptr, napi_tsfn_nonblocking)); return env.Undefined(); @@ -3350,7 +3370,8 @@ static void test_make_callback_tsfn_cb(napi_env env, napi_value js_callback, napi_get_global(env, &recv); napi_value result; - napi_status status = napi_make_callback(env, nullptr, recv, js_callback, 0, nullptr, &result); + napi_status status = + napi_make_callback(env, nullptr, recv, js_callback, 0, nullptr, &result); if (status == napi_ok) { printf("PASS: napi_make_callback succeeded\n"); } else { @@ -3404,7 +3425,8 @@ test_napi_make_callback_status(const Napi::CallbackInfo &info) { return ok(env); } -static napi_value test_napi_make_callback_async_context_frame(const Napi::CallbackInfo &info) { +static napi_value +test_napi_make_callback_async_context_frame(const Napi::CallbackInfo &info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); @@ -3413,8 +3435,8 @@ static napi_value test_napi_make_callback_async_context_frame(const Napi::Callba NODE_API_CALL(env, napi_create_threadsafe_function( - env, js_cb, nullptr, name, 0, 1, nullptr, nullptr, - nullptr, &test_make_callback_tsfn_cb, &tsfn_make_callback)); + env, js_cb, nullptr, name, 0, 1, nullptr, nullptr, nullptr, + &test_make_callback_tsfn_cb, &tsfn_make_callback)); NODE_API_CALL(env, napi_call_threadsafe_function(tsfn_make_callback, nullptr, napi_tsfn_nonblocking)); return env.Undefined(); @@ -3434,12 +3456,14 @@ static void test_create_tsfn_outer_cb(napi_env env, napi_value js_callback, napi_threadsafe_function inner_tsfn = nullptr; napi_status status = napi_create_threadsafe_function( - env, js_callback, nullptr, name, 0, 1, nullptr, nullptr, - nullptr, /* call_js_cb */ nullptr, &inner_tsfn); + env, js_callback, nullptr, name, 0, 1, nullptr, nullptr, nullptr, + /* call_js_cb */ nullptr, &inner_tsfn); if (status != napi_ok) { - printf("FAIL: napi_create_threadsafe_function returned status %d\n", status); + printf("FAIL: napi_create_threadsafe_function returned status %d\n", + status); } else { - printf("PASS: napi_create_threadsafe_function accepted AsyncContextFrame\n"); + printf( + "PASS: napi_create_threadsafe_function accepted AsyncContextFrame\n"); // Release immediately — we only needed to verify creation succeeds. napi_release_threadsafe_function(inner_tsfn, napi_tsfn_release); } @@ -3447,7 +3471,8 @@ static void test_create_tsfn_outer_cb(napi_env env, napi_value js_callback, tsfn_create_outer = nullptr; } -static napi_value test_napi_create_tsfn_async_context_frame(const Napi::CallbackInfo &info) { +static napi_value +test_napi_create_tsfn_async_context_frame(const Napi::CallbackInfo &info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); @@ -3456,8 +3481,8 @@ static napi_value test_napi_create_tsfn_async_context_frame(const Napi::Callback NODE_API_CALL(env, napi_create_threadsafe_function( - env, js_cb, nullptr, name, 0, 1, nullptr, nullptr, - nullptr, &test_create_tsfn_outer_cb, &tsfn_create_outer)); + env, js_cb, nullptr, name, 0, 1, nullptr, nullptr, nullptr, + &test_create_tsfn_outer_cb, &tsfn_create_outer)); NODE_API_CALL(env, napi_call_threadsafe_function(tsfn_create_outer, nullptr, napi_tsfn_nonblocking)); return env.Undefined(); @@ -3548,9 +3573,9 @@ test_typedarray_info_write_visibility(const Napi::CallbackInfo &info) { if (length > 0) { NODE_API_CALL(env, napi_get_element(env, typedarray, 0, &element)); NODE_API_CALL(env, napi_get_value_uint32(env, element, &first)); - NODE_API_CALL(env, - napi_get_element(env, typedarray, - static_cast(length) - 1, &element)); + NODE_API_CALL(env, napi_get_element(env, typedarray, + static_cast(length) - 1, + &element)); NODE_API_CALL(env, napi_get_value_uint32(env, element, &last)); } printf("length=%zu first=%u last=%u\n", length, first, last); @@ -3579,9 +3604,9 @@ test_buffer_info_pointer_stability(const Napi::CallbackInfo &info) { memset(data, 0x2b, length); NODE_API_CALL(env, napi_get_element(env, buffer, 0, &element)); NODE_API_CALL(env, napi_get_value_uint32(env, element, &first)); - NODE_API_CALL(env, - napi_get_element(env, buffer, - static_cast(length) - 1, &element)); + NODE_API_CALL(env, napi_get_element(env, buffer, + static_cast(length) - 1, + &element)); NODE_API_CALL(env, napi_get_value_uint32(env, element, &last)); } printf("length=%zu first=%u last=%u\n", length, first, last); @@ -3613,9 +3638,9 @@ test_create_buffer_pointer_stability(const Napi::CallbackInfo &info) { NODE_API_CALL( env, napi_create_buffer_copy(env, sizeof src, src, ©_data, ©)); napi_value copy_arraybuffer = nullptr; - NODE_API_CALL(env, napi_get_typedarray_info(env, copy, nullptr, nullptr, - nullptr, ©_arraybuffer, - nullptr)); + NODE_API_CALL(env, + napi_get_typedarray_info(env, copy, nullptr, nullptr, nullptr, + ©_arraybuffer, nullptr)); memset(copy_data, 0x2d, sizeof src); uint32_t copy_last = 0; NODE_API_CALL(env, napi_get_element(env, copy, 15, &element)); @@ -3650,8 +3675,8 @@ static napi_value test_napi_float16_array(const Napi::CallbackInfo &info) { void *ab_data = nullptr; size_t ab_len = 0; - NODE_API_CALL( - env, napi_get_arraybuffer_info(env, arraybuffer, &ab_data, &ab_len)); + NODE_API_CALL(env, + napi_get_arraybuffer_info(env, arraybuffer, &ab_data, &ab_len)); printf("arraybuffer_byte_length=%zu data_is_ab_plus_offset=%d\n", ab_len, static_cast(ab_data) + byte_offset == static_cast(data) @@ -3666,10 +3691,9 @@ static napi_value test_napi_float16_array(const Napi::CallbackInfo &info) { size_t created_len = 0; if (sc == napi_ok) { NODE_API_CALL(env, napi_is_typedarray(env, created, &created_is)); - NODE_API_CALL(env, - napi_get_typedarray_info(env, created, &created_type, - &created_len, nullptr, nullptr, - nullptr)); + NODE_API_CALL(env, napi_get_typedarray_info(env, created, &created_type, + &created_len, nullptr, nullptr, + nullptr)); } printf("create_status=%d created_is_typedarray=%d created_type=%d " "created_length=%zu\n", @@ -3788,7 +3812,8 @@ static napi_value test_node_api_set_prototype(const Napi::CallbackInfo &info) { bool same = false; NODE_API_CALL(env, napi_strict_equals(env, got_proto, proto, &same)); napi_value inherited; - NODE_API_CALL(env, napi_get_named_property(env, obj, "inherited", &inherited)); + NODE_API_CALL(env, + napi_get_named_property(env, obj, "inherited", &inherited)); int32_t inherited_i = 0; NODE_API_CALL(env, napi_get_value_int32(env, inherited, &inherited_i)); printf("set_prototype: proto_matches=%s inherited=%d\n", @@ -3823,8 +3848,8 @@ test_node_api_create_object_with_properties(const Napi::CallbackInfo &info) { NODE_API_CALL(env, napi_create_int32(env, 4, &values[3])); napi_value obj; - NODE_API_CALL(env, node_api_create_object_with_properties( - env, nullptr, names, values, 4, &obj)); + NODE_API_CALL(env, node_api_create_object_with_properties(env, nullptr, names, + values, 4, &obj)); napi_value proto; NODE_API_CALL(env, napi_get_prototype(env, obj, &proto)); @@ -3875,8 +3900,7 @@ test_node_api_sharedarraybuffer(const Napi::CallbackInfo &info) { void *data = nullptr; napi_value sab; - NODE_API_CALL(env, - node_api_create_sharedarraybuffer(env, 16, &data, &sab)); + NODE_API_CALL(env, node_api_create_sharedarraybuffer(env, 16, &data, &sab)); bool is_sab = false; NODE_API_CALL(env, node_api_is_sharedarraybuffer(env, sab, &is_sab)); bool is_ab = true; @@ -3938,7 +3962,8 @@ static void noop_tsfn_cb(napi_env, napi_value, void *, void *) {} // prior to the fix; see the PR body for the per-function Node.js references. // This test prints status codes and pending-exception state so checkSameOutput // can diff Bun against Node byte-for-byte. -static napi_value test_napi_status_codes_node26(const Napi::CallbackInfo &info) { +static napi_value +test_napi_status_codes_node26(const Napi::CallbackInfo &info) { napi_env env = info.Env(); #ifndef _WIN32 @@ -3981,18 +4006,17 @@ static napi_value test_napi_status_codes_node26(const Napi::CallbackInfo &info) { void *out; napi_ref ref_out; - print_status( - "napi_wrap(number)", - napi_wrap(env, number, nullptr, nullptr, nullptr, nullptr), true); + print_status("napi_wrap(number)", + napi_wrap(env, number, nullptr, nullptr, nullptr, nullptr), + true); print_status("napi_unwrap(number)", napi_unwrap(env, number, &out), true); print_status("napi_remove_wrap(number)", napi_remove_wrap(env, number, &out), true); - print_status( - "napi_add_finalizer(number)", - napi_add_finalizer( - env, number, nullptr, - [](napi_env, void *, void *) {}, nullptr, &ref_out), - true); + print_status("napi_add_finalizer(number)", + napi_add_finalizer( + env, number, nullptr, [](napi_env, void *, void *) {}, + nullptr, &ref_out), + true); } // napi_coerce_to_*: when coercion throws, Node returns napi__expected @@ -4011,9 +4035,9 @@ static napi_value test_napi_status_codes_node26(const Napi::CallbackInfo &info) // napi_generic_failure, not napi_pending_exception. { napi_value script_throw, script_syntax, out; - NODE_API_CALL(env, napi_create_string_utf8(env, "throw new Error('E')", - NAPI_AUTO_LENGTH, - &script_throw)); + NODE_API_CALL(env, + napi_create_string_utf8(env, "throw new Error('E')", + NAPI_AUTO_LENGTH, &script_throw)); NODE_API_CALL(env, napi_create_string_utf8(env, "?!?", NAPI_AUTO_LENGTH, &script_syntax)); print_status("napi_run_script(throw)", @@ -4044,8 +4068,7 @@ static napi_value test_napi_status_codes_node26(const Napi::CallbackInfo &info) static const char one_byte = 0; print_status( "napi_create_buffer_copy(SIZE_MAX)", - napi_create_buffer_copy(env, SIZE_MAX, &one_byte, nullptr, &out), - true); + napi_create_buffer_copy(env, SIZE_MAX, &one_byte, nullptr, &out), true); } // napi_throw_error while an exception is already pending: Node returns @@ -4057,8 +4080,8 @@ static napi_value test_napi_status_codes_node26(const Napi::CallbackInfo &info) napi_value exc; NODE_API_CALL(env, napi_get_and_clear_last_exception(env, &exc)); napi_value msg_key, msg; - NODE_API_CALL(env, napi_create_string_utf8(env, "message", - NAPI_AUTO_LENGTH, &msg_key)); + NODE_API_CALL(env, napi_create_string_utf8(env, "message", NAPI_AUTO_LENGTH, + &msg_key)); NODE_API_CALL(env, napi_get_property(env, exc, msg_key, &msg)); char buf[64] = {0}; size_t len = 0; @@ -4070,8 +4093,7 @@ static napi_value test_napi_status_codes_node26(const Napi::CallbackInfo &info) // node_api_post_finalizer: Node accepts a NULL finalize_cb. { print_status("node_api_post_finalizer(NULL)", - node_api_post_finalizer(env, nullptr, nullptr, nullptr), - true); + node_api_post_finalizer(env, nullptr, nullptr, nullptr), true); } // napi_make_callback argument validation: Node returns napi_invalid_arg for @@ -4081,13 +4103,12 @@ static napi_value test_napi_status_codes_node26(const Napi::CallbackInfo &info) print_status( "napi_make_callback(recv=NULL)", napi_make_callback(env, nullptr, nullptr, fn, 0, nullptr, &out), true); - print_status( - "napi_make_callback(argc>0,argv=NULL)", - napi_make_callback(env, nullptr, obj, fn, 1, nullptr, &out), true); + print_status("napi_make_callback(argc>0,argv=NULL)", + napi_make_callback(env, nullptr, obj, fn, 1, nullptr, &out), + true); print_status( "napi_make_callback(func=number)", - napi_make_callback(env, nullptr, obj, number, 0, nullptr, &out), - true); + napi_make_callback(env, nullptr, obj, number, 0, nullptr, &out), true); } // napi_ref/unref_threadsafe_function: Node ignores env (basic-env function) @@ -4098,8 +4119,8 @@ static napi_value test_napi_status_codes_node26(const Napi::CallbackInfo &info) NAPI_AUTO_LENGTH, &name)); napi_threadsafe_function tsfn = nullptr; NODE_API_CALL(env, napi_create_threadsafe_function( - env, nullptr, nullptr, name, 0, 1, nullptr, - nullptr, nullptr, noop_tsfn_cb, &tsfn)); + env, nullptr, nullptr, name, 0, 1, nullptr, nullptr, + nullptr, noop_tsfn_cb, &tsfn)); printf("napi_ref_threadsafe_function(env=NULL): status=%d\n", (int)napi_ref_threadsafe_function(nullptr, tsfn)); printf("napi_unref_threadsafe_function(env=NULL): status=%d\n", @@ -4129,22 +4150,20 @@ static void tsfn_nullcb_call_js(napi_env env, napi_value js_callback, static void tsfn_nullcb_finalize(napi_env env, void *data, void *hint) {} -static napi_value -test_tsfn_null_js_callback(const Napi::CallbackInfo &info) { +static napi_value test_tsfn_null_js_callback(const Napi::CallbackInfo &info) { napi_env env = info.Env(); tsfn_nullcb_was_null.store(-1); napi_value name; NODE_API_CALL(env, napi_create_string_utf8(env, "tsfn-nullcb", NAPI_AUTO_LENGTH, &name)); napi_threadsafe_function tsfn; - NODE_API_CALL(env, napi_create_threadsafe_function( - env, NULL, NULL, name, 0, 1, NULL, - tsfn_nullcb_finalize, NULL, tsfn_nullcb_call_js, - &tsfn)); + NODE_API_CALL( + env, napi_create_threadsafe_function(env, NULL, NULL, name, 0, 1, NULL, + tsfn_nullcb_finalize, NULL, + tsfn_nullcb_call_js, &tsfn)); NODE_API_CALL( env, napi_call_threadsafe_function(tsfn, NULL, napi_tsfn_nonblocking)); - NODE_API_CALL(env, - napi_release_threadsafe_function(tsfn, napi_tsfn_release)); + NODE_API_CALL(env, napi_release_threadsafe_function(tsfn, napi_tsfn_release)); return ok(env); } @@ -4268,14 +4287,13 @@ test_napi_symbol_key_result_ordering(const Napi::CallbackInfo &info) { { napi_value thrower; - NODE_API_CALL( - env, napi_create_function( - env, "Throws", NAPI_AUTO_LENGTH, - [](napi_env e, napi_callback_info) -> napi_value { - napi_throw_error(e, NULL, "ctor"); - return NULL; - }, - NULL, &thrower)); + NODE_API_CALL(env, napi_create_function( + env, "Throws", NAPI_AUTO_LENGTH, + [](napi_env e, napi_callback_info) -> napi_value { + napi_throw_error(e, NULL, "ctor"); + return NULL; + }, + NULL, &thrower)); napi_value sentinel = reinterpret_cast(0xdeadbeef); napi_value r = sentinel; napi_status s = napi_new_instance(env, thrower, 0, NULL, &r); @@ -4289,12 +4307,12 @@ test_napi_symbol_key_result_ordering(const Napi::CallbackInfo &info) { r != sentinel); napi_value script, proxy; - NODE_API_CALL( - env, napi_create_string_utf8( - env, - "new Proxy({}, {has: () => { throw new Error('h'); }, " - "get: () => { throw new Error('g'); }})", - NAPI_AUTO_LENGTH, &script)); + NODE_API_CALL(env, + napi_create_string_utf8( + env, + "new Proxy({}, {has: () => { throw new Error('h'); }, " + "get: () => { throw new Error('g'); }})", + NAPI_AUTO_LENGTH, &script)); NODE_API_CALL(env, napi_run_script(env, script, &proxy)); r = sentinel; s = napi_get_named_property(env, proxy, "k", &r); @@ -4341,13 +4359,13 @@ test_napi_external_string_args(const Napi::CallbackInfo &info) { static char sbuf[1] = {0}; report_status( env, "ext_string_latin1(ptr,INT_MAX+1)", - node_api_create_external_string_latin1( - env, sbuf, ((size_t)INT_MAX) + 1u, NULL, NULL, &out, &copied)); + node_api_create_external_string_latin1(env, sbuf, ((size_t)INT_MAX) + 1u, + NULL, NULL, &out, &copied)); static char16_t sbuf16[1] = {0}; report_status( env, "ext_string_utf16(ptr,INT_MAX+1)", - node_api_create_external_string_utf16( - env, sbuf16, ((size_t)INT_MAX) + 1u, NULL, NULL, &out, &copied)); + node_api_create_external_string_utf16(env, sbuf16, ((size_t)INT_MAX) + 1u, + NULL, NULL, &out, &copied)); return ok(env); } @@ -4379,23 +4397,20 @@ test_napi_get_buffer_info_gate(const Napi::CallbackInfo &info) { // Returns a weak napi_ref to a fresh object so the JS side can GC and then // inspect napi_reference_ref behaviour after the referent is collected. -static napi_value -test_create_weak_ref_for_gc(const Napi::CallbackInfo &info) { +static napi_value test_create_weak_ref_for_gc(const Napi::CallbackInfo &info) { napi_env env = info.Env(); napi_value obj; NODE_API_CALL(env, napi_create_object(env, &obj)); napi_ref ref; NODE_API_CALL(env, napi_create_reference(env, obj, 0, &ref)); napi_value ext; - NODE_API_CALL(env, - napi_create_external(env, reinterpret_cast(ref), NULL, - NULL, &ext)); + NODE_API_CALL(env, napi_create_external(env, reinterpret_cast(ref), + NULL, NULL, &ext)); return ext; } // Predicate for gcUntil: true once the weak ref's value is undefined. -static napi_value -test_weak_ref_is_collected(const Napi::CallbackInfo &info) { +static napi_value test_weak_ref_is_collected(const Napi::CallbackInfo &info) { napi_env env = info.Env(); void *p; NODE_API_CALL(env, napi_get_value_external(env, info[1], &p)); @@ -4403,7 +4418,8 @@ test_weak_ref_is_collected(const Napi::CallbackInfo &info) { napi_value v = NULL; NODE_API_CALL(env, napi_get_reference_value(env, ref, &v)); napi_valuetype t = napi_undefined; - if (v) napi_typeof(env, v, &t); + if (v) + napi_typeof(env, v, &t); napi_value r; NODE_API_CALL(env, napi_get_boolean(env, v == NULL || t == napi_undefined, &r)); @@ -4420,7 +4436,8 @@ test_reference_ref_after_collect(const Napi::CallbackInfo &info) { napi_value v = NULL; NODE_API_CALL(env, napi_get_reference_value(env, ref, &v)); napi_valuetype t = napi_undefined; - if (v) napi_typeof(env, v, &t); + if (v) + napi_typeof(env, v, &t); uint32_t count = 999; NODE_API_CALL(env, napi_reference_ref(env, ref, &count)); printf("get_reference_value is undefined=%d reference_ref count=%u\n", @@ -4458,13 +4475,13 @@ void register_standalone_tests(Napi::Env env, Napi::Object exports) { REGISTER_FUNCTION( env, exports, test_napi_threadsafe_function_abort_blocked_producers_finalized); - REGISTER_FUNCTION(env, exports, test_napi_threadsafe_function_abort_full_queue); - REGISTER_FUNCTION( - env, exports, test_napi_threadsafe_function_abort_full_queue_finalized); REGISTER_FUNCTION(env, exports, - test_napi_threadsafe_function_microtask_order); + test_napi_threadsafe_function_abort_full_queue); REGISTER_FUNCTION(env, exports, - test_napi_threadsafe_function_call_js_throws); + test_napi_threadsafe_function_abort_full_queue_finalized); + REGISTER_FUNCTION(env, exports, + test_napi_threadsafe_function_microtask_order); + REGISTER_FUNCTION(env, exports, test_napi_threadsafe_function_call_js_throws); REGISTER_FUNCTION(env, exports, test_napi_handle_scope_string); REGISTER_FUNCTION(env, exports, test_napi_handle_scope_bigint); REGISTER_FUNCTION(env, exports, test_napi_delete_property); @@ -4490,6 +4507,7 @@ void register_standalone_tests(Napi::Env env, Napi::Object exports) { REGISTER_FUNCTION(env, exports, test_napi_new_instance_status); REGISTER_FUNCTION(env, exports, test_napi_create_array_boundary); REGISTER_FUNCTION(env, exports, test_napi_dataview_bounds_errors); + REGISTER_FUNCTION(env, exports, test_napi_dataview_detached); REGISTER_FUNCTION(env, exports, test_napi_typeof_empty_value); REGISTER_FUNCTION(env, exports, test_napi_null_value_args); REGISTER_FUNCTION(env, exports, test_napi_null_env_and_result); @@ -4503,8 +4521,7 @@ void register_standalone_tests(Napi::Env env, Napi::Object exports) { REGISTER_FUNCTION(env, exports, test_external_arraybuffer_finalizer); REGISTER_FUNCTION(env, exports, test_external_arraybuffer_with_pending_exception); - REGISTER_FUNCTION(env, exports, - test_external_buffer_with_pending_exception); + REGISTER_FUNCTION(env, exports, test_external_buffer_with_pending_exception); REGISTER_FUNCTION(env, exports, create_external_arraybuffer_for_transfer); REGISTER_FUNCTION(env, exports, create_external_buffer_for_transfer); REGISTER_FUNCTION(env, exports, external_for_transfer_stats); diff --git a/test/napi/napi-app/throwing_init_addon.c b/test/napi/napi-app/throwing_init_addon.c new file mode 100644 index 000000000000..92c1f7125e61 --- /dev/null +++ b/test/napi/napi-app/throwing_init_addon.c @@ -0,0 +1,26 @@ +#include +#include + +// Registered through napi_module_register() from a static constructor (the +// pre-NAPI_MODULE_INIT registration path). Its init throws with +// napi_throw_error; requiring the addon must throw that error. + +static napi_value init(napi_env env, napi_value exports) { + napi_throw_error(env, "ERR_THROWING_INIT", "init threw on purpose"); + return NULL; +} + +static napi_module mod = { + 1, 0, "throwing_init_addon.c", init, "throwing_init_addon", NULL, {NULL}, +}; + +#if defined(_MSC_VER) +#pragma section(".CRT$XCU", read) +static void __cdecl do_register(void); +__declspec(allocate(".CRT$XCU")) void(__cdecl *do_register_)(void) = + do_register; +static void __cdecl do_register(void) { napi_module_register(&mod); } +#else +static void do_register(void) __attribute__((constructor)); +static void do_register(void) { napi_module_register(&mod); } +#endif diff --git a/test/napi/napi.test.ts b/test/napi/napi.test.ts index 7434fe512a00..0bdb08de032f 100644 --- a/test/napi/napi.test.ts +++ b/test/napi/napi.test.ts @@ -1886,7 +1886,31 @@ describe.skipIf(!canBuildNodeAddons())("cleanup hooks", () => { }); }); + it("an addon registered with napi_module_register whose init throws makes require() throw that error", async () => { + const addonPath = join(__dirname, "napi-app", "build", "Debug", "throwing_init_addon.node"); + await using proc = spawn({ + cmd: [ + bunExe(), + "-e", + `try { require(${JSON.stringify(addonPath)}); console.log("no throw"); } catch (e) { console.log(e.code, e.message); }`, + ], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stdout.trim()).toBe("ERR_THROWING_INIT init threw on purpose"); + expect(exitCode).toBe(0); + }); + describe("napi_create_dataview", () => { + // Node hands back a zero-length DataView here; JSC has no DataView over a detached buffer, so Bun reports + // the TypeError instead (it used to crash). + it("on a detached ArrayBuffer fails with a pending TypeError", async () => { + const output = await runOn(bunExe(), "test_napi_dataview_detached", []); + expect(output).toContain("status_ok=0 result_null=1 pending=1"); + }); + it("should validate bounds and provide consistent error messages", async () => { const output = await checkSameOutput("test_napi_dataview_bounds_errors", []); expect(output).toContain("napi_create_dataview"); From 5ae094b50a9827b70bc9dff9cc9e779dd0f0368a Mon Sep 17 00:00:00 2001 From: Dylan Conway Date: Sun, 23 Aug 2026 20:49:24 +0000 Subject: [PATCH 2/9] test: keep the napi_typeof comment attached to its function --- test/napi/napi-app/standalone_tests.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/napi/napi-app/standalone_tests.cpp b/test/napi/napi-app/standalone_tests.cpp index faf48cd30cb6..63e594ccd09d 100644 --- a/test/napi/napi-app/standalone_tests.cpp +++ b/test/napi/napi-app/standalone_tests.cpp @@ -1767,7 +1767,6 @@ test_napi_dataview_bounds_errors(const Napi::CallbackInfo &info) { return ok(env); } -// Test for napi_typeof with potentially empty/invalid values // napi_create_dataview on a detached ArrayBuffer: must fail with the engine's // TypeError pending, not return napi_ok with a NULL result. static napi_value test_napi_dataview_detached(const Napi::CallbackInfo &info) { @@ -1790,6 +1789,7 @@ static napi_value test_napi_dataview_detached(const Napi::CallbackInfo &info) { return ok(env); } +// Test for napi_typeof with potentially empty/invalid values static napi_value test_napi_typeof_empty_value(const Napi::CallbackInfo &info) { Napi::Env env = info.Env(); From f2f95b54466486c60d011c4cc3ad7ffaf65a7a2e Mon Sep 17 00:00:00 2001 From: Dylan Conway Date: Sun, 23 Aug 2026 20:57:54 +0000 Subject: [PATCH 3/9] test: assert napi_pending_exception + TypeError for the detached DataView case; check stderr in the throwing-init test --- test/napi/napi-app/standalone_tests.cpp | 10 +++++++--- test/napi/napi.test.ts | 4 +++- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/test/napi/napi-app/standalone_tests.cpp b/test/napi/napi-app/standalone_tests.cpp index 63e594ccd09d..35e0de3c7743 100644 --- a/test/napi/napi-app/standalone_tests.cpp +++ b/test/napi/napi-app/standalone_tests.cpp @@ -1780,12 +1780,16 @@ static napi_value test_napi_dataview_detached(const Napi::CallbackInfo &info) { napi_status status = napi_create_dataview(env, 0, arraybuffer, 0, &dataview); bool pending = false; napi_is_exception_pending(env, &pending); - printf("status_ok=%d result_null=%d pending=%d\n", status == napi_ok ? 1 : 0, - dataview == nullptr ? 1 : 0, pending ? 1 : 0); + char name[64] = ""; if (pending) { - napi_value exc; + napi_value exc, ctor, name_val; napi_get_and_clear_last_exception(env, &exc); + napi_get_named_property(env, exc, "constructor", &ctor); + napi_get_named_property(env, ctor, "name", &name_val); + napi_get_value_string_utf8(env, name_val, name, sizeof(name), NULL); } + printf("status=%d result_null=%d pending=%d error=%s\n", (int)status, + dataview == nullptr ? 1 : 0, pending ? 1 : 0, name); return ok(env); } diff --git a/test/napi/napi.test.ts b/test/napi/napi.test.ts index 0bdb08de032f..38e2c17b337e 100644 --- a/test/napi/napi.test.ts +++ b/test/napi/napi.test.ts @@ -1900,6 +1900,7 @@ describe.skipIf(!canBuildNodeAddons())("cleanup hooks", () => { }); const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); expect(stdout.trim()).toBe("ERR_THROWING_INIT init threw on purpose"); + expect(stderr).toBe(""); expect(exitCode).toBe(0); }); @@ -1908,7 +1909,8 @@ describe.skipIf(!canBuildNodeAddons())("cleanup hooks", () => { // the TypeError instead (it used to crash). it("on a detached ArrayBuffer fails with a pending TypeError", async () => { const output = await runOn(bunExe(), "test_napi_dataview_detached", []); - expect(output).toContain("status_ok=0 result_null=1 pending=1"); + // 10 = napi_pending_exception + expect(output).toContain("status=10 result_null=1 pending=1 error=TypeError"); }); it("should validate bounds and provide consistent error messages", async () => { From 88cef0059a005bc595c41462043ff26fbe5dc6f4 Mon Sep 17 00:00:00 2001 From: Dylan Conway Date: Sun, 23 Aug 2026 21:37:07 +0000 Subject: [PATCH 4/9] napi_run_script: hand the addon the thrown value, not the engine's Exception wrapper, as the last exception --- src/jsc/bindings/napi.cpp | 2 +- test/napi/napi-app/standalone_tests.cpp | 19 +++++++++++++++++++ test/napi/napi.test.ts | 7 +++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/jsc/bindings/napi.cpp b/src/jsc/bindings/napi.cpp index 93d94eecc881..11bcdd8b38e8 100644 --- a/src/jsc/bindings/napi.cpp +++ b/src/jsc/bindings/napi.cpp @@ -3070,7 +3070,7 @@ extern "C" napi_status napi_run_script(napi_env env, napi_value script, return napi_set_last_error(env, napi_pending_exception); } // Latched on the env like napi_throw; Node returns napi_generic_failure (not napi_pending_exception) here. - env->scheduleException(thrown.get()); + env->scheduleException(thrown->value()); return napi_set_last_error(env, napi_generic_failure); } diff --git a/test/napi/napi-app/standalone_tests.cpp b/test/napi/napi-app/standalone_tests.cpp index 35e0de3c7743..421d522bb4f1 100644 --- a/test/napi/napi-app/standalone_tests.cpp +++ b/test/napi/napi-app/standalone_tests.cpp @@ -589,6 +589,24 @@ static napi_value test_napi_run_script(const Napi::CallbackInfo &info) { return ret; } +// After a throwing napi_run_script, napi_get_and_clear_last_exception hands +// the addon the value the script threw (not an engine wrapper around it). +static napi_value +test_napi_run_script_last_exception(const Napi::CallbackInfo &info) { + napi_env env = info.Env(); + napi_value ret = nullptr; + napi_status status = napi_run_script(env, info[1], &ret); + napi_value exc = nullptr; + NODE_API_CALL(env, napi_get_and_clear_last_exception(env, &exc)); + napi_valuetype type; + NODE_API_CALL(env, napi_typeof(env, exc, &type)); + bool is_error = false; + NODE_API_CALL(env, napi_is_error(env, exc, &is_error)); + printf("status=%d typeof=%d is_error=%d\n", (int)status, (int)type, + is_error ? 1 : 0); + return exc; +} + static napi_value test_napi_throw_with_nullptr(const Napi::CallbackInfo &info) { napi_env env = info.Env(); const napi_status status = napi_throw(env, nullptr); @@ -4494,6 +4512,7 @@ void register_standalone_tests(Napi::Env env, Napi::Object exports) { REGISTER_FUNCTION(env, exports, test_napi_handle_scope_many_args); REGISTER_FUNCTION(env, exports, test_napi_ref); REGISTER_FUNCTION(env, exports, test_napi_run_script); + REGISTER_FUNCTION(env, exports, test_napi_run_script_last_exception); REGISTER_FUNCTION(env, exports, test_napi_throw_with_nullptr); REGISTER_FUNCTION(env, exports, test_extended_error_messages); REGISTER_FUNCTION(env, exports, bigint_to_i64); diff --git a/test/napi/napi.test.ts b/test/napi/napi.test.ts index 38e2c17b337e..ea9ffa42dfa0 100644 --- a/test/napi/napi.test.ts +++ b/test/napi/napi.test.ts @@ -960,6 +960,13 @@ describe.concurrent.skipIf(!canBuildNodeAddons())("napi", () => { it("propagates exceptions", async () => { await checkSameOutput("test_napi_run_script", ["(()=>{ throw new TypeError('oops'); })()"]); }); + it("hands the addon the thrown value via napi_get_and_clear_last_exception", async () => { + const out = await checkSameOutput("test_napi_run_script_last_exception", [ + "(()=>{ throw new TypeError('oops'); })()", + ]); + // 9 = napi_generic_failure, 6 = napi_object + expect(out).toContain("status=9 typeof=6 is_error=1"); + }); it("cannot see locals from around its invocation", async () => { // variable should_not_exist is declared on main.js:18, but it should not be in scope for the eval'd code // this doesn't use await checkSameOutput because V8 and JSC use different error messages for a missing variable From 222aee47acd85049e80fe9f10bfb49747bbb04d8 Mon Sep 17 00:00:00 2001 From: Dylan Conway Date: Sun, 23 Aug 2026 22:12:58 +0000 Subject: [PATCH 5/9] napi/v8: never leave a JS exception on the VM while addon code runs A Node-API or V8 API call returns to the addon's C/C++ code, which cannot check a JS exception; the first frame that can is the trampoline the addon returns to. So, as JSC's own C API does (APIUtils.h handleExceptionIfNeeded), an exception raised inside an API call is taken off the VM and latched on the env / isolate, and the trampoline (NapiClass call/construct, module registration, finalizers, FunctionTemplate call/construct, accessors) throws it once the addon returns. napi_throw* already worked this way; this makes every NAPI_RETURN_IF_EXCEPTION / CHECK_TO_OBJECT path, the Rust napi functions, napi_run_script, and v8::Isolate::ThrowException/ThrowError do the same, and removes the places that threw into the VM from inside an API call (napi_call_function's pre-throw, the nested throw scopes). A termination is the one thing left on the VM. napi_is_exception_pending / napi_get_and_clear_last_exception read the latch; process.dlopen throws whatever registration left in its result slot, error object or not. --- src/jsc/bindings/BunProcess.cpp | 14 +- src/jsc/bindings/napi.cpp | 132 ++++++++---------- src/jsc/bindings/v8/V8Isolate.cpp | 26 +--- src/jsc/bindings/v8/node.cpp | 5 + src/jsc/bindings/v8/shim/FunctionTemplate.cpp | 6 + src/jsc/bindings/v8/shim/GlobalInternals.cpp | 1 + src/jsc/bindings/v8/shim/GlobalInternals.h | 11 ++ src/jsc/bindings/v8/shim/TemplateProperty.cpp | 14 +- src/runtime/napi/napi_body.rs | 38 +++-- test/v8/v8-module/main.cpp | 60 +++++--- test/v8/v8-module/module.js | 21 ++- test/v8/v8.test.ts | 3 + 12 files changed, 189 insertions(+), 142 deletions(-) diff --git a/src/jsc/bindings/BunProcess.cpp b/src/jsc/bindings/BunProcess.cpp index aa38a9c863be..b9d81778c76f 100644 --- a/src/jsc/bindings/BunProcess.cpp +++ b/src/jsc/bindings/BunProcess.cpp @@ -628,12 +628,11 @@ JSC_DEFINE_HOST_FUNCTION_WITH_ATTRIBUTES(Process_functionDlopen, __attribute__(( pendingNapiModules = std::exchange(globalObject->m_pendingNapiModules, {}); } + // Slot 0 holds either the module object or what registration threw. JSValue resultValue = globalObject->m_pendingNapiModuleAndExports[0].get(); if (resultValue && resultValue != strongModule.get()) { - if (resultValue.isCell() && resultValue.getObject()->isErrorInstance()) { - JSC::throwException(globalObject, scope, resultValue); - return {}; - } + JSC::throwException(globalObject, scope, resultValue); + return {}; } return JSValue::encode(jsUndefined()); @@ -677,12 +676,11 @@ JSC_DEFINE_HOST_FUNCTION_WITH_ATTRIBUTES(Process_functionDlopen, __attribute__(( } } + // Slot 0 holds either the module object or what registration threw. JSValue resultValue = globalObject->m_pendingNapiModuleAndExports[0].get(); if (resultValue && resultValue != strongModule.get()) { - if (resultValue.isCell() && resultValue.getObject()->isErrorInstance()) { - JSC::throwException(globalObject, scope, resultValue); - return {}; - } + JSC::throwException(globalObject, scope, resultValue); + return {}; } return JSValue::encode(jsUndefined()); diff --git a/src/jsc/bindings/napi.cpp b/src/jsc/bindings/napi.cpp index 11bcdd8b38e8..0f4f4997a295 100644 --- a/src/jsc/bindings/napi.cpp +++ b/src/jsc/bindings/napi.cpp @@ -93,11 +93,10 @@ using namespace Zig; #define NAPI_PREAMBLE(_env) \ NAPI_LOG_CURRENT_FUNCTION; \ NAPI_CHECK_ARG(_env, _env); \ - /* TopExceptionScope (not ThrowScope) because NAPI functions return to */ \ - /* C addon code, not to JS: a ThrowScope's destructor simulates a throw */ \ - /* to the caller under validateExceptionChecks, which the next NAPI_ */ \ - /* PREAMBLE then sees as an unchecked exception. If you need to throw */ \ - /* or clear exceptions, make your own scope. */ \ + /* The top of its own scope: the caller is addon C code, which learns */ \ + /* of an exception from the returned status, not from a scope. Nothing */ \ + /* is thrown into the VM from here (see latchException); to raise an */ \ + /* error use env->scheduleException(). */ \ auto napi_preamble_throw_scope__ = DECLARE_TOP_EXCEPTION_SCOPE(_env->vm()); \ NAPI_RETURN_IF_EXCEPTION(_env); \ /* Node: RETURN_STATUS_IF_FALSE(env, env->can_call_into_js(), ...) */ \ @@ -169,29 +168,46 @@ extern "C" void NapiUngatedScope__destruct(void* storage) } \ } while (0) -// Node's CHECK_TO_OBJECT: ToObject coerces primitives and throws on -// null/undefined; on failure the TypeError is left pending and the call -// returns napi_object_expected. Callers must have run NAPI_PREAMBLE first -// (which already bailed for an env-stashed napi_throw* exception). Declares -// `_result` in the enclosing scope. +// A JS exception raised inside a Node-API call is not left on the VM for the addon to keep running under. Like one +// raised through napi_throw, it is latched on the env — napi_is_exception_pending / napi_get_and_clear_last_exception +// read it there — and thrown into JS by whichever trampoline the addon returns to (NapiClass_ConstructorFunction, +// executePendingNapiModule, finalizers, async completions). This is what JSC's own C API does at its boundary +// (APIUtils.h handleExceptionIfNeeded). A pending termination is the one thing left on the VM: it is not the addon's +// to catch, every further call must keep failing, and it unwinds as soon as the addon returns. +static void latchException(napi_env env, JSC::TopExceptionScope& scope) +{ + JSC::Exception* exception = scope.exception(); + if (env->vm().isTerminationException(exception)) [[unlikely]] + return; + scope.clearException(); + env->scheduleException(exception->value()); +} + +// Node's CHECK_TO_OBJECT: ToObject coerces primitives and throws on null/undefined, in which case the call returns +// napi_object_expected with the TypeError pending. Declares `_result` in the enclosing scope. #define NAPI_CHECK_TO_OBJECT(_env, _globalObject, _result, _src) \ JSObject* _result = (_src).toObject((_globalObject)); \ - RETURN_IF_EXCEPTION(napi_preamble_throw_scope__, \ - napi_set_last_error((_env), napi_object_expected)) - -// Return an error code if an exception was thrown after NAPI_PREAMBLE -#define NAPI_RETURN_IF_VM_EXCEPTION(_env) RETURN_IF_EXCEPTION(napi_preamble_throw_scope__, napi_set_last_error((_env), napi_pending_exception)) - -// Like NAPI_RETURN_IF_VM_EXCEPTION but returns a caller-chosen status while leaving the exception pending. -#define NAPI_RETURN_STATUS_IF_EXCEPTION(_env, _status) \ - RETURN_IF_EXCEPTION(napi_preamble_throw_scope__, napi_set_last_error((_env), (_status))) - -#define NAPI_RETURN_IF_EXCEPTION_WITH_SCOPE(_env, _scope) \ - do { \ - RETURN_IF_EXCEPTION((_scope), napi_set_last_error((_env), napi_pending_exception)); \ - if ((_env)->hasPendingException()) { \ - return napi_set_last_error((_env), napi_pending_exception); \ - } \ + NAPI_RETURN_STATUS_IF_EXCEPTION((_env), napi_object_expected) + +#define NAPI_RETURN_IF_VM_EXCEPTION(_env) NAPI_RETURN_STATUS_IF_EXCEPTION((_env), napi_pending_exception) + +#define NAPI_RETURN_STATUS_IF_EXCEPTION(_env, _status) \ + do { \ + if (napi_preamble_throw_scope__.exception()) [[unlikely]] { \ + latchException((_env), napi_preamble_throw_scope__); \ + return napi_set_last_error((_env), (_status)); \ + } \ + } while (0) + +#define NAPI_RETURN_IF_EXCEPTION_WITH_SCOPE(_env, _scope) \ + do { \ + if ((_scope).exception()) [[unlikely]] { \ + latchException((_env), (_scope)); \ + return napi_set_last_error((_env), napi_pending_exception); \ + } \ + if ((_env)->hasPendingException()) [[unlikely]] { \ + return napi_set_last_error((_env), napi_pending_exception); \ + } \ } while (0) #define NAPI_RETURN_IF_EXCEPTION(_env) NAPI_RETURN_IF_EXCEPTION_WITH_SCOPE((_env), napi_preamble_throw_scope__) @@ -1028,7 +1044,7 @@ napi_define_properties(napi_env env, napi_value object, size_t property_count, JSValue objectValue = toJS(object); JSC::JSObject* objectObject = objectValue.toObject(globalObject); - RETURN_IF_EXCEPTION(napi_preamble_throw_scope__, napi_set_last_error(env, napi_object_expected)); + NAPI_RETURN_STATUS_IF_EXCEPTION(env, napi_object_expected); for (size_t i = 0; i < property_count; i++) { napi_status status = Napi::defineProperty(env, objectObject, properties[i], napi_preamble_throw_scope__); @@ -1352,21 +1368,8 @@ extern "C" napi_status napi_is_exception_pending(napi_env env, bool* result) NAPI_CHECK_ENV_NOT_IN_GC(env); NAPI_CHECK_ARG(env, result); - // First check if the environment has a pending exception - *result = env->hasPendingException(); - - // If no exception is pending in the environment, check the VM's exception state - // but only if it's safe to access the VM (not during cleanup) - if (!*result && !env->isFinishingFinalizers()) { - auto globalObject = toJS(env); - if (globalObject) { - auto& vm = JSC::getVM(globalObject); - // Use a catch scope instead of throw scope for safety during cleanup - auto scope = DECLARE_TOP_EXCEPTION_SCOPE(vm); - *result = scope.exception() != nullptr; - } - } - + // What a Node-API call or napi_throw latched, or a termination still on the VM. + *result = env->hasPendingException() || (!env->isFinishingFinalizers() && env->vm().exceptionForInspection()); return napi_clear_last_error(env); } @@ -1381,16 +1384,13 @@ extern "C" napi_status napi_get_and_clear_last_exception(napi_env env, } auto globalObject = toJS(env); - auto scope = DECLARE_TOP_EXCEPTION_SCOPE(JSC::getVM(globalObject)); - if (scope.exception()) [[unlikely]] { - *result = toNapi(JSValue(scope.exception()->value()), globalObject); - } else if (std::optional pending = env->pendingException()) { + // A termination left on the VM is not the addon's to take. + if (std::optional pending = env->pendingException()) { *result = toNapi(pending.value(), globalObject); env->clearPendingException(); } else { *result = toNapi(JSC::jsUndefined(), globalObject); } - (void)scope.tryClearException(); return napi_set_last_error(env, napi_ok); } @@ -3055,24 +3055,10 @@ extern "C" napi_status napi_run_script(napi_env env, napi_value script, JSC::SourceCode sourceCode = makeSource(code, SourceOrigin(), SourceTaintedOrigin::Untainted); - // JSC::evaluate catches what the script throws and hands it back here. - NakedPtr thrown; - JSValue value = JSC::evaluate(globalObject, sourceCode, globalObject->globalThis(), thrown); - if (thrown) { - if (vm.isTerminationException(thrown.get())) { - // Not the addon's to handle: put it straight back on the VM. - { - auto inner = DECLARE_THROW_SCOPE(vm); - JSC::throwException(globalObject, inner, thrown.get()); - inner.release(); - } - EXCEPTION_ASSERT(napi_preamble_throw_scope__.exception()); - return napi_set_last_error(env, napi_pending_exception); - } - // Latched on the env like napi_throw; Node returns napi_generic_failure (not napi_pending_exception) here. - env->scheduleException(thrown->value()); - return napi_set_last_error(env, napi_generic_failure); - } + // Not JSC::evaluate(): that takes the exception off the VM and hands it back, and a termination has to stay there. + JSValue value = vm.interpreter.executeProgram(sourceCode, globalObject, globalObject->globalThis()); + // Node reports a script that threw as napi_generic_failure, not napi_pending_exception. + NAPI_RETURN_STATUS_IF_EXCEPTION(env, napi_generic_failure); ASSERT(!value.isEmpty()); *result = toNapi(value, globalObject); @@ -3246,15 +3232,6 @@ extern "C" napi_status napi_call_function(napi_env env, napi_value recv, const napi_value* argv, napi_value* result) { - NAPI_CHECK_ARG(env, env); - // An exception the addon raised through napi_throw* is latched on the env until control returns to JS; - // this is where the addon gets to observe it as the engine's pending exception (node-addon-api builds its - // Error object in that state) before the call is refused. - if (env->hasPendingException()) [[unlikely]] { - auto scope = DECLARE_TOP_EXCEPTION_SCOPE(env->vm()); - env->throwPendingException(); - RETURN_IF_EXCEPTION(scope, napi_set_last_error(env, napi_pending_exception)); - } NAPI_PREAMBLE(env); NAPI_CHECK_ARG(env, recv); NAPI_RETURN_EARLY_IF_FALSE(env, argc == 0 || argv, napi_invalid_arg); @@ -3419,6 +3396,13 @@ extern "C" void napi_internal_check_gc(napi_env env) env->checkGC(); } +extern "C" void NapiEnv__latchException(napi_env env) +{ + auto scope = DECLARE_TOP_EXCEPTION_SCOPE(env->vm()); + if (scope.exception()) + latchException(env, scope); +} + extern "C" bool NapiEnv__hasPendingException(napi_env env) { if (env->hasPendingException()) { diff --git a/src/jsc/bindings/v8/V8Isolate.cpp b/src/jsc/bindings/v8/V8Isolate.cpp index e86f1de2a2d4..2a0256261512 100644 --- a/src/jsc/bindings/v8/V8Isolate.cpp +++ b/src/jsc/bindings/v8/V8Isolate.cpp @@ -140,25 +140,12 @@ void Isolate::RequestInterrupt(InterruptCallback callback, void* data) }); } -// v8::Isolate::ThrowException returns to addon code with the exception left pending on the VM; the frame that -// observes it is the FunctionTemplate trampoline (or whatever entered the addon), not a C++ caller of this -// function. So, as in the napi entry points, this is the top of its own scope: throw through a transient -// ThrowScope and acknowledge it here so the addon's next API call does not see an unchecked simulated throw. -static void throwIntoVM(JSC::JSGlobalObject* globalObject, JSC::JSValue value) -{ - JSC::VM& vm = JSC::getVM(globalObject); - auto scope = DECLARE_TOP_EXCEPTION_SCOPE(vm); - { - auto inner = DECLARE_THROW_SCOPE(vm); - JSC::throwException(globalObject, inner, value); - inner.release(); - } - EXCEPTION_ASSERT(scope.exception()); -} - +// The value is not thrown into the VM here: addon code keeps running after ThrowException() and cannot check a JS +// exception. The trampoline that called into the addon (FunctionTemplate call/construct, accessor callbacks, module +// registration) throws it when the addon returns — see GlobalInternals::takePendingException. Local Isolate::ThrowException(Local exception) { - throwIntoVM(m_globalObject, exception->localToJSValue()); + m_globalInternals->setPendingException(exception->localToJSValue()); return exception; } @@ -168,9 +155,8 @@ Local Isolate::ThrowError(Local message) // tryGetValue(): an unresolvable rope yields a null message here rather than a second exception. WTF::String wtfMessage = message->localToJSString()->tryGetValue(); JSC::JSObject* error = JSC::createError(m_globalObject, wtfMessage); - Local handle = currentHandleScope()->createLocal(vm, error); - throwIntoVM(m_globalObject, error); - return handle; + m_globalInternals->setPendingException(error); + return currentHandleScope()->createLocal(vm, error); } Isolate::Isolate(shim::GlobalInternals* globalInternals) diff --git a/src/jsc/bindings/v8/node.cpp b/src/jsc/bindings/v8/node.cpp index 7389e978c201..e51919553957 100644 --- a/src/jsc/bindings/v8/node.cpp +++ b/src/jsc/bindings/v8/node.cpp @@ -180,6 +180,11 @@ void node_module_register(void* opaque_mod) } RETURN_IF_EXCEPTION(scope, void()); + // This runs under dlopen(); process.dlopen throws slot 0 once dlopen() returns. + if (JSC::JSValue thrown = isolate->globalInternals()->takePendingException()) [[unlikely]] { + globalObject->m_pendingNapiModuleAndExports[0].set(vm, globalObject, thrown); + return; + } globalObject->m_pendingNapiModuleAndExports[1].set(vm, globalObject, object); } diff --git a/src/jsc/bindings/v8/shim/FunctionTemplate.cpp b/src/jsc/bindings/v8/shim/FunctionTemplate.cpp index 04d46fdac133..efe070c26a25 100644 --- a/src/jsc/bindings/v8/shim/FunctionTemplate.cpp +++ b/src/jsc/bindings/v8/shim/FunctionTemplate.cpp @@ -250,6 +250,12 @@ JSC::JSValue FunctionTemplate::invokeCallback(JSC::JSGlobalObject* globalObject, functionTemplate->m_callback(info); } + if (JSC::JSValue thrown = isolate->globalInternals()->takePendingException()) [[unlikely]] { + auto scope = DECLARE_THROW_SCOPE(vm); + JSC::throwException(globalObject, scope, thrown); + return {}; + } + TaggedPointer& return_value = slot(Info::kReturnValueIndex); if (return_value.isEmpty()) { // callback forgot to set a return value, so return undefined diff --git a/src/jsc/bindings/v8/shim/GlobalInternals.cpp b/src/jsc/bindings/v8/shim/GlobalInternals.cpp index 7145ecf8ce45..4e38d78c07bd 100644 --- a/src/jsc/bindings/v8/shim/GlobalInternals.cpp +++ b/src/jsc/bindings/v8/shim/GlobalInternals.cpp @@ -64,6 +64,7 @@ void GlobalInternals::visitChildrenImpl(JSCell* cell, Visitor& visitor) thisObject->m_functionTemplateStructure.visit(visitor); thisObject->m_v8FunctionStructure.visit(visitor); thisObject->m_globalHandles.visit(visitor); + visitor.append(thisObject->m_pendingException); } DEFINE_VISIT_CHILDREN_WITH_MODIFIER(JS_EXPORT_PRIVATE, GlobalInternals); diff --git a/src/jsc/bindings/v8/shim/GlobalInternals.h b/src/jsc/bindings/v8/shim/GlobalInternals.h index 6ef2e1be5021..2a6d9f0ec450 100644 --- a/src/jsc/bindings/v8/shim/GlobalInternals.h +++ b/src/jsc/bindings/v8/shim/GlobalInternals.h @@ -107,6 +107,16 @@ class GlobalInternals : public JSC::JSCell { void setCurrentHandleScope(HandleScope* handleScope) { m_currentHandleScope = handleScope; } + // What the addon threw through the API (Isolate::ThrowException). It is not thrown into the VM while addon code is + // still running; the trampoline that called into the addon throws it when the addon returns. + void setPendingException(JSC::JSValue value) { m_pendingException.set(JSC::JSCell::vm(), this, value); } + JSC::JSValue takePendingException() + { + JSC::JSValue value = m_pendingException.get(); + m_pendingException.clear(); + return value; + } + WTF::Vector>& gcPrologueCallbacks() { return m_gcPrologueCallbacks; } WTF::Vector>& gcEpilogueCallbacks() { return m_gcEpilogueCallbacks; } WTF::Vector>& nearHeapLimitCallbacks() { return m_nearHeapLimitCallbacks; } @@ -135,6 +145,7 @@ class GlobalInternals : public JSC::JSCell { // HandleScopeBuffer::m_rawGrants (cells are swept without destructors). WTF::Vector m_activeReturnValueSlots; JSC::LazyProperty m_globalHandles; + JSC::WriteBarrier m_pendingException; WTF::Vector> m_gcPrologueCallbacks; WTF::Vector> m_gcEpilogueCallbacks; diff --git a/src/jsc/bindings/v8/shim/TemplateProperty.cpp b/src/jsc/bindings/v8/shim/TemplateProperty.cpp index 41507567876c..2f81a450e4d6 100644 --- a/src/jsc/bindings/v8/shim/TemplateProperty.cpp +++ b/src/jsc/bindings/v8/shim/TemplateProperty.cpp @@ -104,11 +104,19 @@ static JSC::JSValue invokeAccessor( frame[Info::kValueIndex] = valueLocal.tagged(); const auto& info = *reinterpret_cast*>(&frame[Info::kPropertyKeyIndex]); setter(property, valueLocal, info); - return JSC::jsUndefined(); + } else { + const auto& info = *reinterpret_cast(&frame[Info::kPropertyKeyIndex]); + getter(property, info); } - const auto& info = *reinterpret_cast(&frame[Info::kPropertyKeyIndex]); - getter(property, info); + if (JSC::JSValue thrown = isolate->globalInternals()->takePendingException()) [[unlikely]] { + auto scope = DECLARE_THROW_SCOPE(vm); + JSC::throwException(globalObject, scope, thrown); + return {}; + } + if (setter) { + return JSC::jsUndefined(); + } TaggedPointer& returnValue = frame[Info::kReturnValueIndex]; if (returnValue.isEmpty()) { diff --git a/src/runtime/napi/napi_body.rs b/src/runtime/napi/napi_body.rs index d3d28da3e700..aea3a5a22ad5 100644 --- a/src/runtime/napi/napi_body.rs +++ b/src/runtime/napi/napi_body.rs @@ -92,6 +92,7 @@ unsafe extern "C" { fn NapiEnv__globalObject(env: *mut NapiEnv) -> *mut JSGlobalObject; fn NapiEnv__getAndClearPendingException(env: *mut NapiEnv, out: *mut JSValue) -> bool; fn NapiEnv__hasPendingException(env: *mut NapiEnv) -> bool; + fn NapiEnv__latchException(env: *mut NapiEnv); fn NapiEnv__deref(env: *mut NapiEnv); fn NapiEnv__ref(env: *mut NapiEnv); /// The reference to its VM's handle the env holds (`BunVmHandleRef`). @@ -144,6 +145,15 @@ impl NapiEnv { Self::set_last_error(Some(self), NapiStatus::pending_exception) } + /// A JS exception was raised inside this call (`JsError` from a JSC operation): hand it to the addon the way + /// napi.cpp's `NAPI_RETURN_IF_EXCEPTION` does — off the VM, latched on the env, thrown into JS when the addon + /// returns — and report `status`. + pub(crate) fn threw(&self, status: NapiStatus) -> napi_status { + // SAFETY: env is non-null and live for the call. + unsafe { NapiEnv__latchException(self.as_mut_ptr()) }; + Self::set_last_error(Some(self), status) + } + /// Checks both `env->m_pendingException` (set by `napi_throw*`) and the JSC /// VM exception slot. This is the gate Node.js's `NAPI_PREAMBLE` enforces. pub(crate) fn has_pending_exception(&self) -> bool { @@ -613,7 +623,7 @@ extern "C" fn napi_create_array(env_: napi_env, result_: *mut napi_value) -> nap let result = get_out!(env, result_); let arr = match JSValue::create_empty_array(env.to_js(), 0) { Ok(v) => v, - Err(_) => return NapiEnv::set_last_error(Some(env), NapiStatus::pending_exception), + Err(_) => return env.threw(NapiStatus::pending_exception), }; result.set(env, arr); env.ok() @@ -639,7 +649,7 @@ extern "C" fn napi_create_array_with_length( let array = match JSValue::create_empty_array(env.to_js(), len as usize) { Ok(v) => v, - Err(_) => return NapiEnv::set_last_error(Some(env), NapiStatus::pending_exception), + Err(_) => return env.threw(NapiStatus::pending_exception), }; array.ensure_still_alive(); result.set(env, array); @@ -735,7 +745,7 @@ extern "C" fn napi_create_string_latin1( if slice.is_empty() { let js = match bun_core::String::empty().to_js(env.to_js()) { Ok(v) => v, - Err(_) => return NapiEnv::set_last_error(Some(env), NapiStatus::generic_failure), + Err(_) => return env.threw(NapiStatus::generic_failure), }; result.set(env, js); return env.ok(); @@ -746,7 +756,7 @@ extern "C" fn napi_create_string_latin1( let js = match string.transfer_to_js(env.to_js()) { Ok(v) => v, - Err(_) => return NapiEnv::set_last_error(Some(env), NapiStatus::generic_failure), + Err(_) => return env.threw(NapiStatus::generic_failure), }; result.set(env, js); env.ok() @@ -787,7 +797,7 @@ extern "C" fn napi_create_string_utf8( let global_object = env.to_js(); let string = match jsc::bun_string_jsc::create_utf8_for_js(global_object, slice) { Ok(v) => v, - Err(_) => return env.generic_failure(), + Err(_) => return env.threw(NapiStatus::generic_failure), }; result.set(env, string); env.ok() @@ -836,7 +846,7 @@ extern "C" fn napi_create_string_utf16( if slice.is_empty() { let js = match bun_core::String::empty().to_js(env.to_js()) { Ok(v) => v, - Err(_) => return NapiEnv::set_last_error(Some(env), NapiStatus::generic_failure), + Err(_) => return env.threw(NapiStatus::generic_failure), }; result.set(env, js); return env.ok(); @@ -847,7 +857,7 @@ extern "C" fn napi_create_string_utf16( let js = match string.transfer_to_js(env.to_js()) { Ok(v) => v, - Err(_) => return NapiEnv::set_last_error(Some(env), NapiStatus::generic_failure), + Err(_) => return env.threw(NapiStatus::generic_failure), }; result.set(env, js); env.ok() @@ -973,7 +983,7 @@ extern "C" fn napi_get_prototype( // non-object values) handles them without an allocation. if object.is_undefined_or_null() { let _ = object.to_object(env.to_js()); - return NapiEnv::set_last_error(Some(env), NapiStatus::object_expected); + return env.threw(NapiStatus::object_expected); } // Like V8's Object::GetPrototype: a Proxy yields null and its trap never runs. @@ -983,7 +993,7 @@ extern "C" fn napi_get_prototype( } let prototype = match object.get_prototype(env.to_js()) { Ok(prototype) => prototype, - Err(_) => return env.pending_exception(), + Err(_) => return env.threw(NapiStatus::pending_exception), }; result.set(env, prototype); env.ok() @@ -1065,7 +1075,7 @@ extern "C" fn napi_get_array_length( *result = match value.get_length(env.to_js()) { Ok(len) => len as u32, // intentional truncation - Err(_) => return NapiEnv::set_last_error(Some(env), NapiStatus::pending_exception), + Err(_) => return env.threw(NapiStatus::pending_exception), }; env.ok() } @@ -1086,7 +1096,7 @@ extern "C" fn napi_strict_equals( } *result = match lhs.is_strict_equal(rhs, env.to_js()) { Ok(b) => b, - Err(_) => return NapiEnv::set_last_error(Some(env), NapiStatus::pending_exception), + Err(_) => return env.threw(NapiStatus::pending_exception), }; env.ok() } @@ -1283,7 +1293,7 @@ extern "C" fn napi_make_callback( // without throwing is napi_ok. let res = match func.call(env.to_js(), this_value, args_slice) { Ok(v) => v, - Err(_) => return env.pending_exception(), + Err(_) => return env.threw(NapiStatus::pending_exception), }; // SAFETY: `maybe_result` is null or a valid exclusive out-param per N-API contract. @@ -1651,7 +1661,7 @@ extern "C" fn napi_resolve_deferred( let resolution = resolution_.get(); let prom = deferred_box.get(); if prom.resolve(env.to_js(), resolution).is_err() { - return env.generic_failure(); + return env.threw(NapiStatus::generic_failure); } env.ok() } @@ -1669,7 +1679,7 @@ extern "C" fn napi_reject_deferred( let rejection = rejection_.get(); let prom = deferred_box.get(); if prom.reject(env.to_js(), Ok(rejection)).is_err() { - return env.generic_failure(); + return env.threw(NapiStatus::generic_failure); } env.ok() } diff --git a/test/v8/v8-module/main.cpp b/test/v8/v8-module/main.cpp index 5f658ad34d02..52954bbe8af5 100644 --- a/test/v8/v8-module/main.cpp +++ b/test/v8/v8-module/main.cpp @@ -54,8 +54,8 @@ static std::string describe(Isolate *isolate, Local value) { return result; } else if (value->IsFunction()) { char buf[1024] = {0}; - value.As()->GetName().As()->WriteUtf8V2( - isolate, buf, sizeof(buf) - 1); + value.As()->GetName().As()->WriteUtf8V2(isolate, buf, + sizeof(buf) - 1); std::string result = "function "; result += buf; result += "()"; @@ -268,7 +268,8 @@ void test_v8_string_write_utf8(const FunctionCallbackInfo &info) { // in that case; WriteUtf8V2 instead refuses to write partial sequences and // stops before the astral character. The encoder that backs this on Bun // previously wrote U+FFFD (0xEF 0xBF 0xBD) here, diverging from V8. -void test_v8_string_write_utf8_surrogate(const FunctionCallbackInfo &info) { +void test_v8_string_write_utf8_surrogate( + const FunctionCallbackInfo &info) { Isolate *isolate = info.GetIsolate(); struct { @@ -1650,16 +1651,14 @@ void test_v8_function_call(const FunctionCallbackInfo &info) { String::NewFromUtf8(isolate, "hello").ToLocalChecked(), Boolean::New(isolate, true), }; - MaybeLocal result = - f->Call(context, Undefined(isolate), 3, argv); + MaybeLocal result = f->Call(context, Undefined(isolate), 3, argv); LOG_EXPR(result.IsEmpty()); if (!result.IsEmpty()) { LOG_EXPR(describe(isolate, result.ToLocalChecked())); } Local recv = Object::New(isolate); - (void)recv->Set(context, - String::NewFromUtf8(isolate, "tag").ToLocalChecked(), + (void)recv->Set(context, String::NewFromUtf8(isolate, "tag").ToLocalChecked(), Number::New(isolate, 99.0)); MaybeLocal result2 = f->Call(context, recv, 0, nullptr); LOG_EXPR(result2.IsEmpty()); @@ -1706,8 +1705,7 @@ void test_v8_function_new_instance(const FunctionCallbackInfo &info) { .ToLocalChecked(); LOG_EXPR(describe(isolate, constructed)); Local arg0 = - inst->Get(context, - String::NewFromUtf8(isolate, "arg0").ToLocalChecked()) + inst->Get(context, String::NewFromUtf8(isolate, "arg0").ToLocalChecked()) .ToLocalChecked(); LOG_EXPR(describe(isolate, arg0)); @@ -1793,12 +1791,12 @@ void test_v8_exception(const FunctionCallbackInfo &info) { Local err = Exception::Error(msg); LOG_EXPR(err->IsObject()); - LOG_EXPR( - describe(isolate, - err.As() - ->Get(isolate->GetCurrentContext(), - String::NewFromUtf8(isolate, "message").ToLocalChecked()) - .ToLocalChecked())); + LOG_EXPR(describe( + isolate, + err.As() + ->Get(isolate->GetCurrentContext(), + String::NewFromUtf8(isolate, "message").ToLocalChecked()) + .ToLocalChecked())); Local type_err = Exception::TypeError( String::NewFromUtf8(isolate, "wrong type").ToLocalChecked()); @@ -1808,6 +1806,19 @@ void test_v8_exception(const FunctionCallbackInfo &info) { isolate->ThrowException(err); } +// ThrowException() with the addon still running afterwards: it keeps allocating +// through the API before it returns, and what it threw — a non-Error here — is +// what the JS caller catches. +void test_v8_throw_then_continue(const FunctionCallbackInfo &info) { + Isolate *isolate = info.GetIsolate(); + isolate->ThrowException(Number::New(isolate, 42)); + Local s = + String::NewFromUtf8(isolate, "still running").ToLocalChecked(); + LOG_EXPR(describe(isolate, s)); + Local o = Object::New(isolate); + LOG_EXPR(o->IsObject()); +} + void test_v8_aligned_pointer_in_internal_field( const FunctionCallbackInfo &info) { Isolate *isolate = info.GetIsolate(); @@ -1869,7 +1880,8 @@ void test_v8_cpu_profiler(const FunctionCallbackInfo &info) { // Do a little work so at least the root node exists; do NOT assert on sample // counts because those are timing-dependent and differ across engines. volatile double sink = 0; - for (int i = 0; i < 100000; i++) sink += i * 0.5; + for (int i = 0; i < 100000; i++) + sink += i * 0.5; (void)sink; CpuProfile *profile = profiler->Stop(start_result.id); @@ -1906,7 +1918,8 @@ void test_v8_cpu_profiler_overlapping_sessions( auto busy = [] { volatile double sink = 0; - for (int i = 0; i < 100000; i++) sink += i * 0.5; + for (int i = 0; i < 100000; i++) + sink += i * 0.5; (void)sink; }; @@ -1915,14 +1928,14 @@ void test_v8_cpu_profiler_overlapping_sessions( Local title_b = String::NewFromUtf8(isolate, "bun-v8-test-b").ToLocalChecked(); - CpuProfilingResult a = profiler->Start( - title_a, kLeafNodeLineNumbers, true, CpuProfilingOptions::kNoSampleLimit); + CpuProfilingResult a = profiler->Start(title_a, kLeafNodeLineNumbers, true, + CpuProfilingOptions::kNoSampleLimit); LOG_EXPR((int)a.status); busy(); // Second session while the first is still running. - CpuProfilingResult b = profiler->Start( - title_b, kLeafNodeLineNumbers, true, CpuProfilingOptions::kNoSampleLimit); + CpuProfilingResult b = profiler->Start(title_b, kLeafNodeLineNumbers, true, + CpuProfilingOptions::kNoSampleLimit); LOG_EXPR((int)b.status); LOG_EXPR(a.id != b.id); @@ -1983,7 +1996,8 @@ void test_v8_cpu_profiler_title_api(const FunctionCallbackInfo &info) { auto busy = [] { volatile double sink = 0; - for (int i = 0; i < 100000; i++) sink += i * 0.5; + for (int i = 0; i < 100000; i++) + sink += i * 0.5; (void)sink; }; @@ -2144,6 +2158,8 @@ void initialize(Local exports, Local module, test_v8_getfunction_memoized); NODE_SET_METHOD(exports, "test_v8_map", test_v8_map); NODE_SET_METHOD(exports, "test_v8_exception", test_v8_exception); + NODE_SET_METHOD(exports, "test_v8_throw_then_continue", + test_v8_throw_then_continue); NODE_SET_METHOD(exports, "test_v8_aligned_pointer_in_internal_field", test_v8_aligned_pointer_in_internal_field); NODE_SET_METHOD(exports, "test_v8_cpu_profiler", test_v8_cpu_profiler); diff --git a/test/v8/v8-module/module.js b/test/v8/v8-module/module.js index 2d2df400313d..acb4fa48ef90 100644 --- a/test/v8/v8-module/module.js +++ b/test/v8/v8-module/module.js @@ -36,7 +36,17 @@ module.exports = debugMode => { const obj = nativeModule.test_v8_define_own_property(); for (const key of ["writable", "readonly", "hidden"]) { const d = Object.getOwnPropertyDescriptor(obj, key); - console.log(key, "=", d.value, "writable =", d.writable, "enumerable =", d.enumerable, "configurable =", d.configurable); + console.log( + key, + "=", + d.value, + "writable =", + d.writable, + "enumerable =", + d.enumerable, + "configurable =", + d.configurable, + ); } console.log("enumerable keys =", JSON.stringify(Object.keys(obj).sort())); }, @@ -99,6 +109,15 @@ module.exports = debugMode => { } }, + test_v8_throw_then_continue() { + try { + const r = nativeModule.test_v8_throw_then_continue(); + console.log("did not throw, returned", r); + } catch (e) { + console.log("caught", typeof e, e); + } + }, + print_native_function() { nativeModule.print_values_from_js(nativeModule.create_function_with_data()); }, diff --git a/test/v8/v8.test.ts b/test/v8/v8.test.ts index eb9cc906a6a0..adbf09ee847d 100644 --- a/test/v8/v8.test.ts +++ b/test/v8/v8.test.ts @@ -453,6 +453,9 @@ describe.skipIf(!canBuildNodeAddons()).todoIf(isBroken && isMusl)("node:v8", () it("Exception::Error/TypeError create throwable Error objects", async () => { await checkSameOutput("test_v8_exception"); }); + it("ThrowException() takes effect when the callback returns; the addon can keep using the API until then", async () => { + await checkSameOutput("test_v8_throw_then_continue"); + }); }); describe("Aligned internal fields", () => { From a52dfee233989c66f5afd086bad7b656072ffe2d Mon Sep 17 00:00:00 2001 From: Dylan Conway Date: Sun, 23 Aug 2026 22:18:35 +0000 Subject: [PATCH 6/9] test: also check a primitive thrown from napi_run_script comes back unchanged --- test/napi/napi.test.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/test/napi/napi.test.ts b/test/napi/napi.test.ts index ea9ffa42dfa0..a49cf11490a2 100644 --- a/test/napi/napi.test.ts +++ b/test/napi/napi.test.ts @@ -961,11 +961,13 @@ describe.concurrent.skipIf(!canBuildNodeAddons())("napi", () => { await checkSameOutput("test_napi_run_script", ["(()=>{ throw new TypeError('oops'); })()"]); }); it("hands the addon the thrown value via napi_get_and_clear_last_exception", async () => { - const out = await checkSameOutput("test_napi_run_script_last_exception", [ + // 9 = napi_generic_failure; 6 = napi_object, 3 = napi_number + let out = await checkSameOutput("test_napi_run_script_last_exception", [ "(()=>{ throw new TypeError('oops'); })()", ]); - // 9 = napi_generic_failure, 6 = napi_object expect(out).toContain("status=9 typeof=6 is_error=1"); + out = await checkSameOutput("test_napi_run_script_last_exception", ["(()=>{ throw 42; })()"]); + expect(out).toContain("status=9 typeof=3 is_error=0"); }); it("cannot see locals from around its invocation", async () => { // variable should_not_exist is declared on main.js:18, but it should not be in scope for the eval'd code From 7d383bd40055471b6edf0dcdbdd63794697aa1be Mon Sep 17 00:00:00 2001 From: Dylan Conway Date: Mon, 24 Aug 2026 20:24:02 +0000 Subject: [PATCH 7/9] review: deliver the latch from every trampoline, one macro set, Node-parity reads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - bun:ffi cc(): the generated trampoline for napi_env/napi_value symbols now throws what the C code latched on the env (napi_throw, or an API call that threw) when it returns; previously napi_throw_error there crashed and an API-raised exception was lost. - v8 node_module_register: take the isolate latch before returning on a VM exception so it cannot fire from a later callback; the FunctionTemplate / accessor trampolines use GlobalInternals::throwPendingException (an exception already on the VM wins), mirroring NapiEnv. - process.dlopen: the module/exports slots are cleared on every exit, so a nested failed load cannot leave a value for the outer one to misread; a V8 init error reported through slot 0 is thrown before pending napi modules run. - napi_is_exception_pending reads only the latch (Node: !last_exception.IsEmpty()); createErrorWithNapiValues latches like everything else; NAPI_PREAMBLE's entry gate reports (latch or a VM termination) without moving anything, as the Rust preamble does. - One macro family: NAPI_RETURN_IF_EXCEPTION_WITH_SCOPE(env, scope, status) → NAPI_RETURN_STATUS_IF_EXCEPTION → NAPI_RETURN_IF_EXCEPTION; the _VM_ variant is gone. Comments updated for the latch model. - Tests: cc() + Node-API exceptions; test files rebuilt without unrelated reformatting; the napi_module_register test sits with the reentrant one. --- src/jsc/bindings/BunProcess.cpp | 20 +- src/jsc/bindings/napi.cpp | 156 +++---- src/jsc/bindings/napi.h | 31 +- src/jsc/bindings/v8/V8Isolate.cpp | 6 +- src/jsc/bindings/v8/node.cpp | 6 +- src/jsc/bindings/v8/shim/FunctionTemplate.cpp | 5 +- src/jsc/bindings/v8/shim/GlobalInternals.cpp | 12 + src/jsc/bindings/v8/shim/GlobalInternals.h | 11 +- src/jsc/bindings/v8/shim/TemplateProperty.cpp | 16 +- src/runtime/ffi/FFI.h | 2 + src/runtime/ffi/ffi_body.rs | 11 +- src/runtime/napi/napi_body.rs | 13 +- test/js/bun/ffi/cc.test.ts | 59 +++ test/napi/napi-app/standalone_tests.cpp | 441 +++++++++--------- test/napi/napi-app/throwing_init_addon.c | 8 +- test/napi/napi.test.ts | 36 +- test/v8/v8-module/main.cpp | 51 +- 17 files changed, 472 insertions(+), 412 deletions(-) diff --git a/src/jsc/bindings/BunProcess.cpp b/src/jsc/bindings/BunProcess.cpp index b9d81778c76f..65c04e44751a 100644 --- a/src/jsc/bindings/BunProcess.cpp +++ b/src/jsc/bindings/BunProcess.cpp @@ -440,6 +440,12 @@ JSC_DEFINE_HOST_FUNCTION_WITH_ATTRIBUTES(Process_functionDlopen, __attribute__(( globalObject->m_pendingNapiModuleAndExports[0].set(vm, globalObject, moduleObject); globalObject->m_pendingNapiModuleAndExports[1].set(vm, globalObject, exports); + // The slots are how registration (which may run under dlopen()) talks to this call; nothing may be left in them + // for the next — possibly nested — process.dlopen to misread. + auto clearModuleSlots = WTF::makeScopeExit([&] { + globalObject->m_pendingNapiModuleAndExports[0].clear(); + globalObject->m_pendingNapiModuleAndExports[1].clear(); + }); Strong strongExports; @@ -589,8 +595,6 @@ JSC_DEFINE_HOST_FUNCTION_WITH_ATTRIBUTES(Process_functionDlopen, __attribute__(( globalObject->m_pendingV8Modules.clear(); globalObject->m_pendingNapiModules.clear(); globalObject->napiModuleRegisterCallCount = 0; - globalObject->m_pendingNapiModuleAndExports[0].clear(); - globalObject->m_pendingNapiModuleAndExports[1].clear(); }); if (handle) { @@ -606,9 +610,13 @@ JSC_DEFINE_HOST_FUNCTION_WITH_ATTRIBUTES(Process_functionDlopen, __attribute__(( } } - // A V8-style module's nm_register_func already ran inside dlopen() (node_module_register) - // and may have thrown. + // A V8-style module's nm_register_func already ran inside dlopen() (node_module_register) and may have + // thrown, or reported its failure through slot 0. RETURN_IF_EXCEPTION(scope, {}); + if (JSValue thrown = globalObject->m_pendingNapiModuleAndExports[0].get(); thrown && thrown != strongModule.get()) { + JSC::throwException(globalObject, scope, thrown); + return {}; + } // Execute all NAPI modules. If an nm_register_func registers more // modules re-entrantly, they accumulate back in m_pendingNapiModules; @@ -645,8 +653,6 @@ JSC_DEFINE_HOST_FUNCTION_WITH_ATTRIBUTES(Process_functionDlopen, __attribute__(( globalObject->m_pendingV8Modules.clear(); globalObject->m_pendingNapiModules.clear(); globalObject->napiModuleRegisterCallCount = 0; - globalObject->m_pendingNapiModuleAndExports[0].clear(); - globalObject->m_pendingNapiModuleAndExports[1].clear(); }); // Replay all registrations from this handle. napi ones only queue into @@ -764,8 +770,6 @@ JSC_DEFINE_HOST_FUNCTION_WITH_ATTRIBUTES(Process_functionDlopen, __attribute__(( } } - globalObject->m_pendingNapiModuleAndExports[0].clear(); - globalObject->m_pendingNapiModuleAndExports[1].clear(); globalObject->m_pendingNapiModuleDlopenHandle = nullptr; // https://github.com/nodejs/node/blob/2eff28fb7a93d3f672f80b582f664a7c701569fb/src/node_api.cc#L734-L742 diff --git a/src/jsc/bindings/napi.cpp b/src/jsc/bindings/napi.cpp index 0f4f4997a295..a6650edbe38e 100644 --- a/src/jsc/bindings/napi.cpp +++ b/src/jsc/bindings/napi.cpp @@ -90,22 +90,26 @@ using namespace Zig; // - if env is nullptr, return napi_invalid_arg // - if there is a pending exception, return napi_pending_exception // No do..while is used as this declares a variable that other macros need to use -#define NAPI_PREAMBLE(_env) \ - NAPI_LOG_CURRENT_FUNCTION; \ - NAPI_CHECK_ARG(_env, _env); \ - /* The top of its own scope: the caller is addon C code, which learns */ \ - /* of an exception from the returned status, not from a scope. Nothing */ \ - /* is thrown into the VM from here (see latchException); to raise an */ \ - /* error use env->scheduleException(). */ \ - auto napi_preamble_throw_scope__ = DECLARE_TOP_EXCEPTION_SCOPE(_env->vm()); \ - NAPI_RETURN_IF_EXCEPTION(_env); \ - /* Node: RETURN_STATUS_IF_FALSE(env, env->can_call_into_js(), ...) */ \ - if (WebCore::clientData(_env->vm())->isStoppingOrStopped(_env->vm())) \ - [[unlikely]] \ +#define NAPI_PREAMBLE(_env) \ + NAPI_LOG_CURRENT_FUNCTION; \ + NAPI_CHECK_ARG(_env, _env); \ + /* The top of its own scope: the caller is addon C code, which learns */ \ + /* of an exception from the returned status, not from a scope. Nothing */ \ + /* is thrown into the VM from here (see latchException); to raise an */ \ + /* error use env->scheduleException(). */ \ + auto napi_preamble_throw_scope__ = DECLARE_TOP_EXCEPTION_SCOPE(_env->vm()); \ + /* Node: if (!env->last_exception.IsEmpty()) return napi_pending_exception; */ \ + /* a termination already on the VM refuses the call the same way. */ \ + if (_env->hasPendingException() || napi_preamble_throw_scope__.exception()) \ + [[unlikely]] \ + return napi_set_last_error(_env, napi_pending_exception); \ + /* Node: RETURN_STATUS_IF_FALSE(env, env->can_call_into_js(), ...) */ \ + if (WebCore::clientData(_env->vm())->isStoppingOrStopped(_env->vm())) \ + [[unlikely]] \ return napi_set_last_error(_env, _env->napiModule().nm_version >= 10 ? napi_cannot_run_js : napi_pending_exception); -// Only use this for functions that need their own throw or catch scope. Functions that call into -// JS code that might throw should use NAPI_RETURN_IF_EXCEPTION. +// For entry points that neither enter the VM nor consult the pending exception (pure argument checks, or ones +// that delegate to a helper that sets up its own scope). #define NAPI_PREAMBLE_NO_THROW_SCOPE(_env) \ do { \ NAPI_LOG_CURRENT_FUNCTION; \ @@ -113,9 +117,10 @@ using namespace Zig; } while (0) // What the value constructors/accessors Node gates with CHECK_ENV only run under (NAPI_PREAMBLE_NO_PENDING_CHECK -// here, `ungated!` in napi_body.rs): callable with an exception pending (stashed for the call; only then, since the -// restore is unconditional) and never where a worker.terminate() / node:vm timeout is delivered (DeferTraps: the -// next exception check after the call delivers it, as in Node). No JS or addon code may run under it. +// here, `ungated!` in napi_body.rs): callable with an exception latched on the env or a termination pending on the +// VM (the latter is stashed for the call; only then, since the restore is unconditional), and never where a +// worker.terminate() / node:vm timeout is delivered (DeferTraps: the next exception check after the call delivers +// it, as in Node). No JS or addon code may run under it. struct NapiUngatedScope { explicit NapiUngatedScope(JSC::VM& vm) : deferTraps(vm) @@ -183,35 +188,23 @@ static void latchException(napi_env env, JSC::TopExceptionScope& scope) env->scheduleException(exception->value()); } +// After a step that may have thrown: latch what it threw (see latchException) and return `_status` to the addon. +#define NAPI_RETURN_IF_EXCEPTION_WITH_SCOPE(_env, _scope, _status) \ + do { \ + if ((_scope).exception()) [[unlikely]] { \ + latchException((_env), (_scope)); \ + return napi_set_last_error((_env), (_status)); \ + } \ + } while (0) +#define NAPI_RETURN_STATUS_IF_EXCEPTION(_env, _status) NAPI_RETURN_IF_EXCEPTION_WITH_SCOPE((_env), napi_preamble_throw_scope__, (_status)) +#define NAPI_RETURN_IF_EXCEPTION(_env) NAPI_RETURN_STATUS_IF_EXCEPTION((_env), napi_pending_exception) + // Node's CHECK_TO_OBJECT: ToObject coerces primitives and throws on null/undefined, in which case the call returns // napi_object_expected with the TypeError pending. Declares `_result` in the enclosing scope. #define NAPI_CHECK_TO_OBJECT(_env, _globalObject, _result, _src) \ JSObject* _result = (_src).toObject((_globalObject)); \ NAPI_RETURN_STATUS_IF_EXCEPTION((_env), napi_object_expected) -#define NAPI_RETURN_IF_VM_EXCEPTION(_env) NAPI_RETURN_STATUS_IF_EXCEPTION((_env), napi_pending_exception) - -#define NAPI_RETURN_STATUS_IF_EXCEPTION(_env, _status) \ - do { \ - if (napi_preamble_throw_scope__.exception()) [[unlikely]] { \ - latchException((_env), napi_preamble_throw_scope__); \ - return napi_set_last_error((_env), (_status)); \ - } \ - } while (0) - -#define NAPI_RETURN_IF_EXCEPTION_WITH_SCOPE(_env, _scope) \ - do { \ - if ((_scope).exception()) [[unlikely]] { \ - latchException((_env), (_scope)); \ - return napi_set_last_error((_env), napi_pending_exception); \ - } \ - if ((_env)->hasPendingException()) [[unlikely]] { \ - return napi_set_last_error((_env), napi_pending_exception); \ - } \ - } while (0) - -#define NAPI_RETURN_IF_EXCEPTION(_env) NAPI_RETURN_IF_EXCEPTION_WITH_SCOPE((_env), napi_preamble_throw_scope__) - // Return indicating that no error occurred in a NAPI function, and an exception is not expected #define NAPI_RETURN_SUCCESS(_env) \ do { \ @@ -1095,29 +1088,14 @@ static napi_status throwErrorWithCStrings(napi_env env, const char* code_utf8, c return napi_set_last_error(env, napi_ok); } -// code must be a string or nullptr (no code) -// msg must be a string -// -// Matches Node.js, where napi_create_error is a pure value producer that -// does not check the VM exception state on entry. Bun previously used a -// throw scope + RETURN_IF_EXCEPTION here, so a *pre-existing* VM exception -// made napi_create_error return napi_pending_exception. That broke -// node-addon-api's `Error::New(env)` during env cleanup: the helper calls -// napi_is_exception_pending (which Bun deliberately skips the VM check for -// during cleanup, so it reports "no pending exception"), then falls through -// to napi_create_error; when a prior finalizer left a VM exception on the -// scope, the mismatch tripped NAPI_FATAL_IF_FAILED -> napi_fatal_error -> -// panic. See #30286 and #22259. -// -// We use a TopExceptionScope (not a throw scope) so a pre-existing exception -// does not force an early return. A *new* exception (getString() resolving a -// rope can throw OutOfMemoryError) is left pending and reported as -// napi_pending_exception, like any other napi call that threw. -static napi_status createErrorWithNapiValues(napi_env env, napi_value code, napi_value message, JSC::ErrorType type, napi_value* result) +// code must be a string or nullptr (no code); msg must be a string. +// As in Node, the napi_create_*error functions are value producers callable with an exception pending (node-addon-api's +// Error::New(env) relies on that during env cleanup, #30286 / #22259), hence NAPI_PREAMBLE_NO_PENDING_CHECK in the +// callers. Resolving a rope for the message can still throw (out of memory); that is latched like any other throw. +static napi_status createErrorWithNapiValues(napi_env env, JSC::TopExceptionScope& scope, napi_value code, napi_value message, JSC::ErrorType type, napi_value* result) { auto* globalObject = toJS(env); auto& vm = JSC::getVM(globalObject); - auto scope = DECLARE_TOP_EXCEPTION_SCOPE(vm); NAPI_CHECK_ARG(env, result); NAPI_CHECK_ARG(env, message); @@ -1127,20 +1105,12 @@ static napi_status createErrorWithNapiValues(napi_env env, napi_value code, napi js_message.isString() && (js_code.isEmpty() || js_code.isString()), napi_string_expected); - JSC::Exception* preExisting = scope.exception(); auto wtf_code = js_code.isEmpty() ? WTF::String() : js_code.getString(globalObject); - if (scope.exception() != preExisting) [[unlikely]] - return napi_set_last_error(env, napi_pending_exception); + NAPI_RETURN_IF_EXCEPTION_WITH_SCOPE(env, scope, napi_pending_exception); auto wtf_message = js_message.getString(globalObject); - if (scope.exception() != preExisting) [[unlikely]] - return napi_set_last_error(env, napi_pending_exception); - - *result = toNapi( - createErrorWithCode(vm, globalObject, wtf_code, wtf_message, type), - globalObject); + NAPI_RETURN_IF_EXCEPTION_WITH_SCOPE(env, scope, napi_pending_exception); - if (scope.exception() != preExisting) [[unlikely]] - return napi_set_last_error(env, napi_pending_exception); + *result = toNapi(createErrorWithCode(vm, globalObject, wtf_code, wtf_message, type), globalObject); return napi_set_last_error(env, napi_ok); } @@ -1368,8 +1338,9 @@ extern "C" napi_status napi_is_exception_pending(napi_env env, bool* result) NAPI_CHECK_ENV_NOT_IN_GC(env); NAPI_CHECK_ARG(env, result); - // What a Node-API call or napi_throw latched, or a termination still on the VM. - *result = env->hasPendingException() || (!env->isFinishingFinalizers() && env->vm().exceptionForInspection()); + // Node: `*result = !env->last_exception.IsEmpty()`. A termination on the VM is not the addon's and is not + // reported here (napi_get_and_clear_last_exception could never hand it out). + *result = env->hasPendingException(); return napi_clear_last_error(env); } @@ -1450,9 +1421,9 @@ extern "C" napi_status node_api_create_syntax_error(napi_env env, napi_value msg, napi_value* result) { - NAPI_PREAMBLE_NO_THROW_SCOPE(env); + NAPI_PREAMBLE_NO_PENDING_CHECK(env); NAPI_CHECK_ENV_NOT_IN_GC(env); - return createErrorWithNapiValues(env, code, msg, JSC::ErrorType::SyntaxError, result); + return createErrorWithNapiValues(env, napi_preamble_throw_scope__, code, msg, JSC::ErrorType::SyntaxError, result); } extern "C" napi_status node_api_throw_syntax_error(napi_env env, @@ -1474,9 +1445,9 @@ extern "C" napi_status napi_create_type_error(napi_env env, napi_value code, napi_value msg, napi_value* result) { - NAPI_PREAMBLE_NO_THROW_SCOPE(env); + NAPI_PREAMBLE_NO_PENDING_CHECK(env); NAPI_CHECK_ENV_NOT_IN_GC(env); - return createErrorWithNapiValues(env, code, msg, JSC::ErrorType::TypeError, result); + return createErrorWithNapiValues(env, napi_preamble_throw_scope__, code, msg, JSC::ErrorType::TypeError, result); } // On `disposeNow` the caller runs the addon's finalizer, which must not run under this function's preamble. @@ -1788,9 +1759,9 @@ extern "C" napi_status napi_create_error(napi_env env, napi_value code, napi_value msg, napi_value* result) { - NAPI_PREAMBLE_NO_THROW_SCOPE(env); + NAPI_PREAMBLE_NO_PENDING_CHECK(env); NAPI_CHECK_ENV_NOT_IN_GC(env); - return createErrorWithNapiValues(env, code, msg, JSC::ErrorType::Error, result); + return createErrorWithNapiValues(env, napi_preamble_throw_scope__, code, msg, JSC::ErrorType::Error, result); } extern "C" napi_status napi_throw_range_error(napi_env env, const char* code, const char* msg) @@ -1841,9 +1812,9 @@ extern "C" napi_status napi_create_range_error(napi_env env, napi_value code, napi_value msg, napi_value* result) { - NAPI_PREAMBLE_NO_THROW_SCOPE(env); + NAPI_PREAMBLE_NO_PENDING_CHECK(env); NAPI_CHECK_ENV_NOT_IN_GC(env); - return createErrorWithNapiValues(env, code, msg, JSC::ErrorType::RangeError, result); + return createErrorWithNapiValues(env, napi_preamble_throw_scope__, code, msg, JSC::ErrorType::RangeError, result); } extern "C" napi_status napi_get_new_target(napi_env env, @@ -2622,9 +2593,9 @@ napi_status napi_get_value_string_any_encoding(napi_env env, napi_value napiValu Zig::GlobalObject* globalObject = toJS(env); JSString* jsString = jsValue.toString(globalObject); - NAPI_RETURN_IF_VM_EXCEPTION(env); + NAPI_RETURN_IF_EXCEPTION(env); const auto view = jsString->view(globalObject); - NAPI_RETURN_IF_VM_EXCEPTION(env); + NAPI_RETURN_IF_EXCEPTION(env); if (buf == nullptr) { // they just want to know the length @@ -2934,7 +2905,7 @@ extern "C" napi_status napi_get_value_bigint_int64(napi_env env, napi_value valu NAPI_RETURN_EARLY_IF_FALSE(env, jsValue.isHeapBigInt(), napi_bigint_expected); *result = jsValue.toBigInt64(toJS(env)); - NAPI_RETURN_IF_VM_EXCEPTION(env); + NAPI_RETURN_IF_EXCEPTION(env); JSBigInt* bigint = jsValue.asHeapBigInt(); auto length = bigint->length(); @@ -2967,7 +2938,7 @@ extern "C" napi_status napi_get_value_bigint_uint64(napi_env env, napi_value val NAPI_RETURN_EARLY_IF_FALSE(env, jsValue.isHeapBigInt(), napi_bigint_expected); *result = jsValue.toBigUInt64(toJS(env)); - NAPI_RETURN_IF_VM_EXCEPTION(env); + NAPI_RETURN_IF_EXCEPTION(env); // bigint to uint64 conversion is lossless if and only if there aren't multiple digits and the // value is positive @@ -3084,7 +3055,7 @@ extern "C" napi_status napi_create_bigint_uint64(napi_env env, uint64_t value, n NAPI_CHECK_ARG(env, result); auto* globalObject = toJS(env); auto* bigint = JSBigInt::createFrom(globalObject, value); - NAPI_RETURN_IF_VM_EXCEPTION(env); + NAPI_RETURN_IF_EXCEPTION(env); *result = toNapi(bigint, globalObject); ensureStillAliveHere(bigint); NAPI_RETURN_SUCCESS(env); @@ -3096,7 +3067,7 @@ extern "C" napi_status napi_create_bigint_int64(napi_env env, int64_t value, nap NAPI_CHECK_ARG(env, result); auto* globalObject = toJS(env); auto* bigint = JSBigInt::createFrom(globalObject, value); - NAPI_RETURN_IF_VM_EXCEPTION(env); + NAPI_RETURN_IF_EXCEPTION(env); *result = toNapi(bigint, globalObject); ensureStillAliveHere(bigint); NAPI_RETURN_SUCCESS(env); @@ -3150,7 +3121,7 @@ extern "C" napi_status napi_create_symbol(napi_env env, napi_value description, NAPI_RETURN_EARLY_IF_FALSE(env, descriptionValue.isString(), napi_string_expected); WTF::String descriptionString = descriptionValue.getString(globalObject); - NAPI_RETURN_IF_VM_EXCEPTION(env); + NAPI_RETURN_IF_EXCEPTION(env); *result = toNapi(JSC::Symbol::createWithDescription(vm, descriptionString), globalObject); NAPI_RETURN_SUCCESS(env); @@ -3279,7 +3250,7 @@ extern "C" napi_status napi_type_tag_object(napi_env env, napi_value value, cons NAPI_CHECK_ARG(env, type_tag); Zig::GlobalObject* globalObject = toJS(env); JSObject* js_object = toJS(value).toObject(globalObject); - NAPI_RETURN_IF_VM_EXCEPTION(env); + NAPI_RETURN_IF_EXCEPTION(env); JSValue napiTypeTagValue = globalObject->napiTypeTags()->get(js_object); auto* existing_tag = dynamicDowncast(napiTypeTagValue); @@ -3299,7 +3270,7 @@ extern "C" napi_status napi_check_object_type_tag(napi_env env, napi_value value NAPI_CHECK_ARG(env, type_tag); Zig::GlobalObject* globalObject = toJS(env); JSObject* js_object = toJS(value).toObject(globalObject); - NAPI_RETURN_IF_VM_EXCEPTION(env); + NAPI_RETURN_IF_EXCEPTION(env); bool match = false; auto* found_tag = dynamicDowncast(globalObject->napiTypeTags()->get(js_object)); @@ -3396,6 +3367,11 @@ extern "C" void napi_internal_check_gc(napi_env env) env->checkGC(); } +extern "C" bool NapiEnv__throwPendingException(napi_env env) +{ + return env->throwPendingException(); +} + extern "C" void NapiEnv__latchException(napi_env env) { auto scope = DECLARE_TOP_EXCEPTION_SCOPE(env->vm()); diff --git a/src/jsc/bindings/napi.h b/src/jsc/bindings/napi.h index 2ac1eda89f78..dacfb7bb277b 100644 --- a/src/jsc/bindings/napi.h +++ b/src/jsc/bindings/napi.h @@ -178,17 +178,12 @@ struct NapiEnv : public WTF::RefCounted { void cleanup() { - // The VM can already have a pending exception when cleanup starts: - // a Worker torn down via terminate() has JSC's TerminationException - // set (termination is trap-based, so clearing the exception object - // does not cancel the termination request -- re-entering JS - // re-throws it). Cleanup hooks and finalizers are native callbacks - // with no JS frame above them to catch anything, so, matching - // Node.js, each starts from a clean exception state. Without this, - // the first napi call in the first callback that checks the VM - // (e.g. napi_create_string_utf8 in a node-addon-api ObjectWrap - // finalizer) fails with napi_pending_exception and the addon's - // error path escalates to napi_fatal_error. See #30286. + // The VM can already have a termination pending when cleanup starts (a Worker torn down via terminate(); + // termination is trap-based, so clearing the exception object does not cancel the request -- re-entering + // JS re-throws it), and the env can hold a latched exception nothing will ever throw. Cleanup hooks and + // finalizers are native callbacks with no JS frame above them to catch anything, so, matching Node.js, each + // starts from a clean exception state; otherwise the first gated napi call in a node-addon-api ObjectWrap + // finalizer fails with napi_pending_exception and its error path escalates to napi_fatal_error. See #30286. clearExceptionsBetweenFinalizers(); while (!m_cleanupHooks.empty()) { @@ -237,13 +232,8 @@ struct NapiEnv : public WTF::RefCounted { // Whatever the call appended sits after `current`; remove `current` itself by value // (still a live node: deactivate() only marks the running entry). m_finalizers.remove(*current); - // Each finalizer starts from a clean exception state: Node.js - // never propagates one finalizer's throw into the next (there - // is no JS frame to catch in between). Leaving a pending - // exception also breaks later finalizers in subtle ways -- - // napi_is_exception_pending skips the VM check during cleanup - // for safety, so user code thinks there is no exception, but - // the next napi call with a throw scope sees it. See #30286. + // Each finalizer starts from a clean exception state: Node.js never propagates one finalizer's throw + // (latched on the env) into the next -- there is no JS frame to catch in between. See #30286. clearExceptionsBetweenFinalizers(); } m_isFinishingFinalizers = false; @@ -412,10 +402,7 @@ struct NapiEnv : public WTF::RefCounted { void scheduleException(JSC::JSValue exception) { - if (exception.isEmpty()) { - m_pendingException.clear(); - } - + ASSERT(!exception.isEmpty()); m_pendingException.set(m_vm, exception); } diff --git a/src/jsc/bindings/v8/V8Isolate.cpp b/src/jsc/bindings/v8/V8Isolate.cpp index 2a0256261512..293923e507a6 100644 --- a/src/jsc/bindings/v8/V8Isolate.cpp +++ b/src/jsc/bindings/v8/V8Isolate.cpp @@ -142,10 +142,10 @@ void Isolate::RequestInterrupt(InterruptCallback callback, void* data) // The value is not thrown into the VM here: addon code keeps running after ThrowException() and cannot check a JS // exception. The trampoline that called into the addon (FunctionTemplate call/construct, accessor callbacks, module -// registration) throws it when the addon returns — see GlobalInternals::takePendingException. +// registration) throws it when the addon returns — see GlobalInternals::throwPendingException. Local Isolate::ThrowException(Local exception) { - m_globalInternals->setPendingException(exception->localToJSValue()); + m_globalInternals->scheduleException(exception->localToJSValue()); return exception; } @@ -155,7 +155,7 @@ Local Isolate::ThrowError(Local message) // tryGetValue(): an unresolvable rope yields a null message here rather than a second exception. WTF::String wtfMessage = message->localToJSString()->tryGetValue(); JSC::JSObject* error = JSC::createError(m_globalObject, wtfMessage); - m_globalInternals->setPendingException(error); + m_globalInternals->scheduleException(error); return currentHandleScope()->createLocal(vm, error); } diff --git a/src/jsc/bindings/v8/node.cpp b/src/jsc/bindings/v8/node.cpp index e51919553957..c2f3fc0540e0 100644 --- a/src/jsc/bindings/v8/node.cpp +++ b/src/jsc/bindings/v8/node.cpp @@ -179,9 +179,11 @@ void node_module_register(void* opaque_mod) return; } + // This runs under dlopen(); process.dlopen throws slot 0 once dlopen() returns. Take the latch even when a VM + // exception is also pending (that one wins), so it cannot fire from a later, unrelated callback. + JSC::JSValue thrown = isolate->globalInternals()->takePendingException(); RETURN_IF_EXCEPTION(scope, void()); - // This runs under dlopen(); process.dlopen throws slot 0 once dlopen() returns. - if (JSC::JSValue thrown = isolate->globalInternals()->takePendingException()) [[unlikely]] { + if (thrown) [[unlikely]] { globalObject->m_pendingNapiModuleAndExports[0].set(vm, globalObject, thrown); return; } diff --git a/src/jsc/bindings/v8/shim/FunctionTemplate.cpp b/src/jsc/bindings/v8/shim/FunctionTemplate.cpp index efe070c26a25..1c26bcbcb9c6 100644 --- a/src/jsc/bindings/v8/shim/FunctionTemplate.cpp +++ b/src/jsc/bindings/v8/shim/FunctionTemplate.cpp @@ -250,11 +250,8 @@ JSC::JSValue FunctionTemplate::invokeCallback(JSC::JSGlobalObject* globalObject, functionTemplate->m_callback(info); } - if (JSC::JSValue thrown = isolate->globalInternals()->takePendingException()) [[unlikely]] { - auto scope = DECLARE_THROW_SCOPE(vm); - JSC::throwException(globalObject, scope, thrown); + if (isolate->globalInternals()->throwPendingException(globalObject)) [[unlikely]] return {}; - } TaggedPointer& return_value = slot(Info::kReturnValueIndex); if (return_value.isEmpty()) { diff --git a/src/jsc/bindings/v8/shim/GlobalInternals.cpp b/src/jsc/bindings/v8/shim/GlobalInternals.cpp index 4e38d78c07bd..6eceadf0bd44 100644 --- a/src/jsc/bindings/v8/shim/GlobalInternals.cpp +++ b/src/jsc/bindings/v8/shim/GlobalInternals.cpp @@ -69,5 +69,17 @@ void GlobalInternals::visitChildrenImpl(JSCell* cell, Visitor& visitor) DEFINE_VISIT_CHILDREN_WITH_MODIFIER(JS_EXPORT_PRIVATE, GlobalInternals); +bool GlobalInternals::throwPendingException(JSC::JSGlobalObject* globalObject) +{ + JSC::VM& vm = this->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + JSC::JSValue thrown = takePendingException(); + RETURN_IF_EXCEPTION(scope, true); + if (!thrown) [[likely]] + return false; + JSC::throwException(globalObject, scope, thrown); + return true; +} + } // namespace shim } // namespace v8 diff --git a/src/jsc/bindings/v8/shim/GlobalInternals.h b/src/jsc/bindings/v8/shim/GlobalInternals.h index 2a6d9f0ec450..3e2480e7c757 100644 --- a/src/jsc/bindings/v8/shim/GlobalInternals.h +++ b/src/jsc/bindings/v8/shim/GlobalInternals.h @@ -108,14 +108,19 @@ class GlobalInternals : public JSC::JSCell { void setCurrentHandleScope(HandleScope* handleScope) { m_currentHandleScope = handleScope; } // What the addon threw through the API (Isolate::ThrowException). It is not thrown into the VM while addon code is - // still running; the trampoline that called into the addon throws it when the addon returns. - void setPendingException(JSC::JSValue value) { m_pendingException.set(JSC::JSCell::vm(), this, value); } + // still running; the trampoline that called into the addon throws it when the addon returns (throwPendingException), + // as NapiEnv does for Node-API. + void scheduleException(JSC::JSValue value) { m_pendingException.set(vm(), this, value); } JSC::JSValue takePendingException() { JSC::JSValue value = m_pendingException.get(); - m_pendingException.clear(); + if (value) [[unlikely]] + m_pendingException.clear(); return value; } + // True when an exception is pending on the VM afterwards — the latched one, or one that was already there (which + // wins; the latched value is dropped, as it would be by any catch of the first). + bool throwPendingException(JSC::JSGlobalObject*); WTF::Vector>& gcPrologueCallbacks() { return m_gcPrologueCallbacks; } WTF::Vector>& gcEpilogueCallbacks() { return m_gcEpilogueCallbacks; } diff --git a/src/jsc/bindings/v8/shim/TemplateProperty.cpp b/src/jsc/bindings/v8/shim/TemplateProperty.cpp index 2f81a450e4d6..54b5904394b7 100644 --- a/src/jsc/bindings/v8/shim/TemplateProperty.cpp +++ b/src/jsc/bindings/v8/shim/TemplateProperty.cpp @@ -104,19 +104,15 @@ static JSC::JSValue invokeAccessor( frame[Info::kValueIndex] = valueLocal.tagged(); const auto& info = *reinterpret_cast*>(&frame[Info::kPropertyKeyIndex]); setter(property, valueLocal, info); - } else { - const auto& info = *reinterpret_cast(&frame[Info::kPropertyKeyIndex]); - getter(property, info); + if (isolate->globalInternals()->throwPendingException(globalObject)) [[unlikely]] + return {}; + return JSC::jsUndefined(); } - if (JSC::JSValue thrown = isolate->globalInternals()->takePendingException()) [[unlikely]] { - auto scope = DECLARE_THROW_SCOPE(vm); - JSC::throwException(globalObject, scope, thrown); + const auto& info = *reinterpret_cast(&frame[Info::kPropertyKeyIndex]); + getter(property, info); + if (isolate->globalInternals()->throwPendingException(globalObject)) [[unlikely]] return {}; - } - if (setter) { - return JSC::jsUndefined(); - } TaggedPointer& returnValue = frame[Info::kReturnValueIndex]; if (returnValue.isEmpty()) { diff --git a/src/runtime/ffi/FFI.h b/src/runtime/ffi/FFI.h index 6a4f733c3e17..9ba7f85e96fe 100644 --- a/src/runtime/ffi/FFI.h +++ b/src/runtime/ffi/FFI.h @@ -64,6 +64,7 @@ typedef enum { } napi_status; BUN_FFI_IMPORT void* NapiHandleScope__open(void* napi_env, bool detached); BUN_FFI_IMPORT void NapiHandleScope__close(void* napi_env, void* handleScope); +BUN_FFI_IMPORT bool NapiEnv__throwPendingException(void* napi_env); BUN_FFI_IMPORT extern struct NapiEnv Bun__thisFFIModuleNapiEnv; #endif @@ -123,6 +124,7 @@ napi_value asNapiValue; ZIG_REPR_TYPE asZigRepr; } EncodedJSValue; +EncodedJSValue ValueEmpty = { 0 }; EncodedJSValue ValueUndefined = { TagValueUndefined }; EncodedJSValue ValueTrue = { TagValueTrue }; diff --git a/src/runtime/ffi/ffi_body.rs b/src/runtime/ffi/ffi_body.rs index 1a1ec085173e..6298a812c3a8 100644 --- a/src/runtime/ffi/ffi_body.rs +++ b/src/runtime/ffi/ffi_body.rs @@ -2226,8 +2226,10 @@ impl Function { writer.write_all(b" ")?; if self.needs_handle_scope() { + // What the C code raised through Node-API (napi_throw, or an API call that threw) is latched on the + // env; this is the trampoline that throws it. writer.write_all( - b" NapiHandleScope__close(&Bun__thisFFIModuleNapiEnv, handleScope);\n", + b" NapiHandleScope__close(&Bun__thisFFIModuleNapiEnv, handleScope);\n if (NapiEnv__throwPendingException(&Bun__thisFFIModuleNapiEnv)) return ValueEmpty.asZigRepr;\n", )?; } @@ -2581,6 +2583,7 @@ impl CompilerRT { unsafe extern "C" { fn NapiHandleScope__open(env: *mut napi::NapiEnv, escapable: bool) -> *mut c_void; fn NapiHandleScope__close(env: *mut napi::NapiEnv, current: *mut c_void); + fn NapiEnv__throwPendingException(env: *mut napi::NapiEnv) -> bool; } state .add_symbol( @@ -2594,6 +2597,12 @@ impl CompilerRT { NapiHandleScope__close as *const c_void, ) .expect("unreachable"); + state + .add_symbol( + zstr!("NapiEnv__throwPendingException"), + NapiEnv__throwPendingException as *const c_void, + ) + .expect("unreachable"); state .add_symbol( diff --git a/src/runtime/napi/napi_body.rs b/src/runtime/napi/napi_body.rs index aea3a5a22ad5..9a274f8dfb44 100644 --- a/src/runtime/napi/napi_body.rs +++ b/src/runtime/napi/napi_body.rs @@ -154,8 +154,8 @@ impl NapiEnv { Self::set_last_error(Some(self), status) } - /// Checks both `env->m_pendingException` (set by `napi_throw*`) and the JSC - /// VM exception slot. This is the gate Node.js's `NAPI_PREAMBLE` enforces. + /// The gate Node's `NAPI_PREAMBLE` enforces: an exception latched on the env (by `napi_throw*` or by an earlier + /// call that threw), or a termination pending on the VM. pub(crate) fn has_pending_exception(&self) -> bool { // SAFETY: env is non-null; C++ side is read-only here. unsafe { NapiEnv__hasPendingException(self.as_mut_ptr()) } @@ -177,11 +177,10 @@ impl NapiEnv { None } - /// After a native addon callback (a `complete`, a finalizer, a `call_js`): - /// what it raised through Node-API — latched on the env — or left on the VM - /// is that call's exception, surfaced as `Err` with it pending on the VM. - /// If both exist the VM's own wins and the latched one is discarded (it - /// cannot be reported without running JS over the pending one). + /// After a native addon callback (a `complete`, a finalizer, a `call_js`): what it raised through Node-API — + /// latched on the env — is that call's exception, surfaced as `Err` with it pending on the VM. If the VM + /// already has one (a termination; or a nested trampoline already threw), that wins and the latched one is + /// discarded, as it would be by any catch of the first. pub(crate) fn surface_exception(&self, global: &JSGlobalObject) -> JsResult<()> { let latched = self.get_and_clear_pending_exception(); if global.has_exception() { diff --git a/test/js/bun/ffi/cc.test.ts b/test/js/bun/ffi/cc.test.ts index 0726df91e629..c53294ed2742 100644 --- a/test/js/bun/ffi/cc.test.ts +++ b/test/js/bun/ffi/cc.test.ts @@ -1017,6 +1017,65 @@ describe("double <-> JSValue conversions", () => { }); }); + it.skipIf(isWindows)( + "a JS exception raised through Node-API inside cc() code is thrown when it returns", + async () => { + using dir = tempDir("bun-ffi-napi-throws", { + "throws.c": /* c */ ` + typedef struct napi_env_fake* napi_env_t; + typedef struct napi_value_fake* napi_value_t; + extern int napi_get_global(napi_env_t env, napi_value_t* result); + extern int napi_get_named_property(napi_env_t env, napi_value_t object, const char* name, napi_value_t* result); + extern int napi_call_function(napi_env_t env, napi_value_t recv, napi_value_t fn, unsigned long argc, const napi_value_t* argv, napi_value_t* result); + extern int napi_throw_error(napi_env_t env, const char* code, const char* msg); + napi_value_t call_cb(napi_env_t env) { + napi_value_t global, fn, result = 0; + napi_get_global(env, &global); + napi_get_named_property(env, global, "__cb", &fn); + napi_call_function(env, global, fn, 0, 0, &result); + return result; + } + napi_value_t throw_it(napi_env_t env) { + napi_throw_error(env, "ERR_FROM_CC", "thrown from cc"); + return 0; + } + `, + "fixture.js": /* js */ ` + import { cc } from "bun:ffi"; + import path from "path"; + const { symbols } = cc({ + source: path.join(import.meta.dir, "throws.c"), + symbols: { + call_cb: { args: ["napi_env"], returns: "napi_value" }, + throw_it: { args: ["napi_env"], returns: "napi_value" }, + }, + }); + const err = new Error("from the callback"); + const out = {}; + globalThis.__cb = () => { throw err; }; + try { symbols.call_cb(); out.callCb = "returned"; } catch (e) { out.callCb = e === err; } + try { symbols.throw_it(); out.throwIt = "returned"; } catch (e) { out.throwIt = e.code + ": " + e.message; } + // and the env is usable afterwards + globalThis.__cb = () => 7; + out.after = symbols.call_cb(); + console.log(JSON.stringify(out)); + `, + }); + + await using proc = Bun.spawn({ + cmd: [bunExe(), "fixture.js"], + env: bunEnv, + cwd: String(dir), + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect({ out: JSON.parse(stdout.trim().split("\n").at(-1) || "null"), exitCode }).toEqual({ + out: { callCb: true, throwIt: "ERR_FROM_CC: thrown from cc", after: 7 }, + exitCode: 0, + }); + }, + ); + // napi_create_double and napi_create_date take the double from the addon // verbatim, so they are the same boundary. cc()-compiled C resolves napi_* // from the host process; that lookup is only exercised on POSIX today (see diff --git a/test/napi/napi-app/standalone_tests.cpp b/test/napi/napi-app/standalone_tests.cpp index 421d522bb4f1..2b0319a575a6 100644 --- a/test/napi/napi-app/standalone_tests.cpp +++ b/test/napi/napi-app/standalone_tests.cpp @@ -169,14 +169,14 @@ static napi_value test_napi_threadsafe_function_abort_blocked_producers( napi_value resource_name = Napi::String::New(env, "abort_blocked_producers"); tsfn_abort_blocked_finalized = false; tsfn_abort_blocked_about_to_call.store(0); - NODE_API_CALL(env, - napi_create_threadsafe_function( - env, /* JavaScript function */ nullptr, - /* async resource */ nullptr, resource_name, - /* max queue size */ 1, - /* initial thread count */ 3, /* finalize data */ nullptr, - tsfn_abort_blocked_finalize, /* context */ nullptr, - &noop_callback, &tsfn_abort_blocked)); + NODE_API_CALL( + env, napi_create_threadsafe_function( + env, /* JavaScript function */ nullptr, + /* async resource */ nullptr, resource_name, + /* max queue size */ 1, + /* initial thread count */ 3, /* finalize data */ nullptr, + tsfn_abort_blocked_finalize, /* context */ nullptr, + &noop_callback, &tsfn_abort_blocked)); // Fill the queue so both producer threads block on the condvar. The JS // thread is parked in this function, so dispatch cannot drain it yet. NODE_API_CALL(env, napi_call_threadsafe_function(tsfn_abort_blocked, nullptr, @@ -216,20 +216,20 @@ test_napi_threadsafe_function_abort_full_queue(const Napi::CallbackInfo &info) { Napi::Env env = info.Env(); napi_value resource_name = Napi::String::New(env, "abort_full_queue"); tsfn_abort_full_finalized = false; - NODE_API_CALL(env, - napi_create_threadsafe_function( - env, /* JavaScript function */ nullptr, - /* async resource */ nullptr, resource_name, - /* max queue size */ 1, - /* initial thread count */ 2, - /* finalize data */ nullptr, tsfn_abort_full_finalize, - /* context */ nullptr, &noop_callback, &tsfn_abort_full)); + NODE_API_CALL(env, napi_create_threadsafe_function( + env, /* JavaScript function */ nullptr, + /* async resource */ nullptr, resource_name, + /* max queue size */ 1, + /* initial thread count */ 2, + /* finalize data */ nullptr, tsfn_abort_full_finalize, + /* context */ nullptr, &noop_callback, + &tsfn_abort_full)); // The JS thread is parked in here, so nothing drains the queue: it is still // full at the abort and at the call below. NODE_API_CALL(env, napi_call_threadsafe_function(tsfn_abort_full, nullptr, napi_tsfn_nonblocking)); - NODE_API_CALL( - env, napi_release_threadsafe_function(tsfn_abort_full, napi_tsfn_abort)); + NODE_API_CALL(env, napi_release_threadsafe_function(tsfn_abort_full, + napi_tsfn_abort)); napi_status status = napi_call_threadsafe_function(tsfn_abort_full, nullptr, napi_tsfn_nonblocking); tsfn_abort_full = nullptr; @@ -245,8 +245,8 @@ static napi_value test_napi_threadsafe_function_abort_full_queue_finalized( // one dispatch. Microtasks queued by one callback must be drained before the // next callback runs (https://github.com/nodejs/node/pull/38506), and must not // be drained before the first one. -static napi_value -test_napi_threadsafe_function_microtask_order(const Napi::CallbackInfo &info) { +static napi_value test_napi_threadsafe_function_microtask_order( + const Napi::CallbackInfo &info) { Napi::Env env = info.Env(); napi_value resource_name = Napi::String::New(env, "microtask_order"); napi_threadsafe_function tsfn; @@ -278,8 +278,8 @@ static void tsfn_throwing_call_js(napi_env env, napi_value js_callback, napi_throw_error(env, nullptr, message); } -static napi_value -test_napi_threadsafe_function_call_js_throws(const Napi::CallbackInfo &info) { +static napi_value test_napi_threadsafe_function_call_js_throws( + const Napi::CallbackInfo &info) { Napi::Env env = info.Env(); napi_value resource_name = Napi::String::New(env, "call_js_throws"); napi_threadsafe_function tsfn; @@ -292,9 +292,9 @@ test_napi_threadsafe_function_call_js_throws(const Napi::CallbackInfo &info) { /* finalize callback */ nullptr, /* context */ nullptr, tsfn_throwing_call_js, &tsfn)); for (intptr_t i = 1; i <= 3; i++) { - NODE_API_CALL( - env, napi_call_threadsafe_function(tsfn, reinterpret_cast(i), - napi_tsfn_nonblocking)); + NODE_API_CALL(env, napi_call_threadsafe_function( + tsfn, reinterpret_cast(i), + napi_tsfn_nonblocking)); } NODE_API_CALL(env, napi_release_threadsafe_function(tsfn, napi_tsfn_release)); return env.Undefined(); @@ -788,9 +788,8 @@ static napi_value test_is_typedarray(const Napi::CallbackInfo &info) { // https://github.com/oven-sh/bun/issues/32624 // info[0] is the GC callback; the values to classify start at info[1]. For each -// one, print napi_is_arraybuffer and the raw napi_get_arraybuffer_info status -// so the output can be diffed against Node (napi_ok is 0, napi_invalid_arg is -// 1). +// one, print napi_is_arraybuffer and the raw napi_get_arraybuffer_info status so +// the output can be diffed against Node (napi_ok is 0, napi_invalid_arg is 1). static napi_value test_is_arraybuffer(const Napi::CallbackInfo &info) { napi_env env = info.Env(); for (size_t i = 1; i < info.Length(); i++) { @@ -1639,8 +1638,8 @@ test_napi_new_instance_status(const Napi::CallbackInfo &info) { NODE_API_CALL(env, napi_get_and_clear_last_exception(env, &exc)); napi_value global, type_error; NODE_API_CALL(env, napi_get_global(env, &global)); - NODE_API_CALL( - env, napi_get_named_property(env, global, "TypeError", &type_error)); + NODE_API_CALL(env, napi_get_named_property(env, global, "TypeError", + &type_error)); NODE_API_CALL(env, napi_instanceof(env, exc, type_error, &is_type_error)); } @@ -1791,20 +1790,21 @@ static napi_value test_napi_dataview_detached(const Napi::CallbackInfo &info) { napi_env env = info.Env(); napi_value arraybuffer; void *data = nullptr; - NODE_API_CALL(env, napi_create_arraybuffer(env, 16, &data, &arraybuffer)); + NODE_API_CALL(env, napi_create_arraybuffer(env, 8, &data, &arraybuffer)); NODE_API_CALL(env, napi_detach_arraybuffer(env, arraybuffer)); napi_value dataview = nullptr; napi_status status = napi_create_dataview(env, 0, arraybuffer, 0, &dataview); bool pending = false; - napi_is_exception_pending(env, &pending); + NODE_API_CALL(env, napi_is_exception_pending(env, &pending)); char name[64] = ""; if (pending) { napi_value exc, ctor, name_val; - napi_get_and_clear_last_exception(env, &exc); - napi_get_named_property(env, exc, "constructor", &ctor); - napi_get_named_property(env, ctor, "name", &name_val); - napi_get_value_string_utf8(env, name_val, name, sizeof(name), NULL); + NODE_API_CALL(env, napi_get_and_clear_last_exception(env, &exc)); + NODE_API_CALL(env, napi_get_named_property(env, exc, "constructor", &ctor)); + NODE_API_CALL(env, napi_get_named_property(env, ctor, "name", &name_val)); + NODE_API_CALL(env, napi_get_value_string_utf8(env, name_val, name, + sizeof(name), nullptr)); } printf("status=%d result_null=%d pending=%d error=%s\n", (int)status, dataview == nullptr ? 1 : 0, pending ? 1 : 0, name); @@ -1882,22 +1882,25 @@ static napi_value test_napi_null_value_args(const Napi::CallbackInfo &info) { printf("napi_detach_arraybuffer(NULL) -> %d\n", (int)napi_detach_arraybuffer(env, nullptr)); - printf( - "node_api_create_buffer_from_arraybuffer(NULL) -> %d\n", - (int)node_api_create_buffer_from_arraybuffer(env, nullptr, 0, 0, &out)); + printf("node_api_create_buffer_from_arraybuffer(NULL) -> %d\n", + (int)node_api_create_buffer_from_arraybuffer(env, nullptr, 0, 0, + &out)); printf("napi_strict_equals(NULL, NULL) -> %d\n", (int)napi_strict_equals(env, nullptr, nullptr, &b)); printf("napi_instanceof(NULL, NULL) -> %d\n", (int)napi_instanceof(env, nullptr, nullptr, &b)); printf("napi_new_instance(NULL) -> %d\n", (int)napi_new_instance(env, nullptr, 0, nullptr, &out)); - printf("napi_is_array(NULL) -> %d\n", (int)napi_is_array(env, nullptr, &b)); - printf("napi_is_error(NULL) -> %d\n", (int)napi_is_error(env, nullptr, &b)); + printf("napi_is_array(NULL) -> %d\n", + (int)napi_is_array(env, nullptr, &b)); + printf("napi_is_error(NULL) -> %d\n", + (int)napi_is_error(env, nullptr, &b)); printf("napi_is_arraybuffer(NULL) -> %d\n", (int)napi_is_arraybuffer(env, nullptr, &b)); printf("napi_is_dataview(NULL) -> %d\n", (int)napi_is_dataview(env, nullptr, &b)); - printf("napi_is_date(NULL) -> %d\n", (int)napi_is_date(env, nullptr, &b)); + printf("napi_is_date(NULL) -> %d\n", + (int)napi_is_date(env, nullptr, &b)); printf("napi_get_array_length(NULL) -> %d\n", (int)napi_get_array_length(env, nullptr, &len)); printf("napi_get_dataview_info(NULL) -> %d\n", @@ -1907,15 +1910,13 @@ static napi_value test_napi_null_value_args(const Napi::CallbackInfo &info) { return ok(env); } -static napi_value -test_napi_null_env_and_result(const Napi::CallbackInfo &info) { +static napi_value test_napi_null_env_and_result(const Napi::CallbackInfo &info) { napi_env env = info.Env(); napi_value undef; NODE_API_CALL(env, napi_get_undefined(env, &undef)); napi_value name; - NODE_API_CALL(env, - napi_create_string_utf8(env, "n", NAPI_AUTO_LENGTH, &name)); + NODE_API_CALL(env, napi_create_string_utf8(env, "n", NAPI_AUTO_LENGTH, &name)); napi_valuetype ty; printf("napi_typeof(NULL env) -> %d\n", @@ -2202,18 +2203,19 @@ static napi_value test_napi_object_coercion(const Napi::CallbackInfo &info) { env, obj, static_cast(99), napi_key_all_properties, napi_key_numbers_to_strings, &out)); - report_status(env, "get_all_property_names(key_conversion=99)", - napi_get_all_property_names( - env, obj, napi_key_own_only, napi_key_all_properties, - static_cast(99), &out)); + report_status( + env, "get_all_property_names(key_conversion=99)", + napi_get_all_property_names(env, obj, napi_key_own_only, + napi_key_all_properties, + static_cast(99), &out)); report_status(env, "get_all_property_names(string)", - napi_get_all_property_names(env, v_str, napi_key_own_only, - napi_key_all_properties, - napi_key_numbers_to_strings, &out)); + napi_get_all_property_names( + env, v_str, napi_key_own_only, napi_key_all_properties, + napi_key_numbers_to_strings, &out)); report_status(env, "get_all_property_names(null)", - napi_get_all_property_names(env, v_null, napi_key_own_only, - napi_key_all_properties, - napi_key_numbers_to_strings, &out)); + napi_get_all_property_names( + env, v_null, napi_key_own_only, napi_key_all_properties, + napi_key_numbers_to_strings, &out)); report_status(env, "get_all_property_names(null,key_mode=99)", napi_get_all_property_names( env, v_null, static_cast(99), @@ -2388,8 +2390,9 @@ static napi_value test_napi_v10_surface(const Napi::CallbackInfo &info) { bool copied = true; napi_value result = nullptr; - NODE_API_CALL(env, node_api_create_external_string_utf16( - env, utf16_hi, 2, nullptr, nullptr, &result, &copied)); + NODE_API_CALL(env, + node_api_create_external_string_utf16( + env, utf16_hi, 2, nullptr, nullptr, &result, &copied)); printf("external utf16 nonempty: copied=%d\n", (int)copied); return ok(env); @@ -2537,19 +2540,15 @@ static napi_value napi_get_typeof(const Napi::CallbackInfo &info) { // Regression test: napi_create_external_buffer must tie the finalize callback // to the ArrayBuffer's destructor, not addFinalizer on the JSUint8Array. // With addFinalizer, extracting .buffer (the ArrayBuffer) and then letting the -// Buffer get GC'd would call finalize_cb and free the data while the -// ArrayBuffer still references it. -static napi_value -test_external_buffer_data_lifetime(const Napi::CallbackInfo &info) { +// Buffer get GC'd would call finalize_cb and free the data while the ArrayBuffer +// still references it. +static napi_value test_external_buffer_data_lifetime(const Napi::CallbackInfo &info) { napi_env env = info.Env(); // Allocate data with a known pattern. const size_t data_size = 4; - uint8_t *ext_data = (uint8_t *)malloc(data_size); - ext_data[0] = 0xDE; - ext_data[1] = 0xAD; - ext_data[2] = 0xBE; - ext_data[3] = 0xEF; + uint8_t* ext_data = (uint8_t*)malloc(data_size); + ext_data[0] = 0xDE; ext_data[1] = 0xAD; ext_data[2] = 0xBE; ext_data[3] = 0xEF; napi_ref ab_ref = nullptr; @@ -2560,21 +2559,18 @@ test_external_buffer_data_lifetime(const Napi::CallbackInfo &info) { // Allocate on the heap so conservative stack scanning can't find it. napi_value *buffer = new napi_value; - NODE_API_CALL(env, napi_create_external_buffer( - env, data_size, ext_data, - +[](napi_env, void *data, void *) { - // Poison the data then free — detectable as - // use-after-free if the ArrayBuffer still tries to - // read through this pointer. - memset(data, 0x00, 4); - free(data); - }, - nullptr, buffer)); + NODE_API_CALL(env, napi_create_external_buffer(env, data_size, ext_data, + +[](napi_env, void* data, void*) { + // Poison the data then free — detectable as use-after-free if + // the ArrayBuffer still tries to read through this pointer. + memset(data, 0x00, 4); + free(data); + }, nullptr, buffer)); // Extract the underlying ArrayBuffer and prevent it from being GC'd. napi_value *arraybuffer = new napi_value; NODE_API_CALL(env, napi_get_typedarray_info(env, *buffer, nullptr, nullptr, - nullptr, arraybuffer, nullptr)); + nullptr, arraybuffer, nullptr)); NODE_API_CALL(env, napi_create_reference(env, *arraybuffer, 1, &ab_ref)); // Drop heap pointers before closing the scope so the stack scanner @@ -2594,18 +2590,17 @@ test_external_buffer_data_lifetime(const Napi::CallbackInfo &info) { napi_value ab_value; NODE_API_CALL(env, napi_get_reference_value(env, ab_ref, &ab_value)); - void *ab_data; + void* ab_data; size_t ab_len; - NODE_API_CALL(env, - napi_get_arraybuffer_info(env, ab_value, &ab_data, &ab_len)); + NODE_API_CALL(env, napi_get_arraybuffer_info(env, ab_value, &ab_data, &ab_len)); - uint8_t *bytes = (uint8_t *)ab_data; - if (ab_len >= data_size && bytes[0] == 0xDE && bytes[1] == 0xAD && + uint8_t* bytes = (uint8_t*)ab_data; + if (ab_len >= data_size && + bytes[0] == 0xDE && bytes[1] == 0xAD && bytes[2] == 0xBE && bytes[3] == 0xEF) { printf("PASS: external buffer data intact through ArrayBuffer after GC\n"); } else { - printf("FAIL: external buffer data was corrupted (finalize_cb ran too " - "early)\n"); + printf("FAIL: external buffer data was corrupted (finalize_cb ran too early)\n"); } NODE_API_CALL(env, napi_delete_reference(env, ab_ref)); @@ -2634,13 +2629,14 @@ test_external_arraybuffer_finalizer(const Napi::CallbackInfo &info) { ext_data[i] = (uint8_t)(0xA0 + i); napi_value arraybuffer; - NODE_API_CALL(env, napi_create_external_arraybuffer( - env, ext_data, data_size, - +[](napi_env, void *data, void *) { - external_arraybuffer_finalize_count++; - free(data); - }, - nullptr, &arraybuffer)); + NODE_API_CALL( + env, napi_create_external_arraybuffer( + env, ext_data, data_size, + +[](napi_env, void *data, void *) { + external_arraybuffer_finalize_count++; + free(data); + }, + nullptr, &arraybuffer)); // The finalizer must not have run yet: the ArrayBuffer is still live. if (external_arraybuffer_finalize_count != 0) { @@ -2652,8 +2648,8 @@ test_external_arraybuffer_finalizer(const Napi::CallbackInfo &info) { // Verify the backing store is the caller's pointer and the bytes match. void *ab_data; size_t ab_len; - NODE_API_CALL(env, - napi_get_arraybuffer_info(env, arraybuffer, &ab_data, &ab_len)); + NODE_API_CALL( + env, napi_get_arraybuffer_info(env, arraybuffer, &ab_data, &ab_len)); bool bytes_ok = ab_len == data_size; for (size_t i = 0; bytes_ok && i < data_size; i++) @@ -2724,7 +2720,8 @@ static napi_value test_external_arraybuffer_with_pending_exception( memset(ext_data, 0x5A, data_size); // Stash a napi-level pending exception (no VM exception is raised yet). - NODE_API_CALL(env, napi_throw_error(env, nullptr, "stashed before create")); + NODE_API_CALL(env, + napi_throw_error(env, nullptr, "stashed before create")); napi_value arraybuffer = nullptr; napi_status status = napi_create_external_arraybuffer( @@ -2752,8 +2749,8 @@ static napi_value test_external_arraybuffer_with_pending_exception( } void *ab_data; size_t ab_len; - NODE_API_CALL( - env, napi_get_arraybuffer_info(env, arraybuffer, &ab_data, &ab_len)); + NODE_API_CALL(env, napi_get_arraybuffer_info(env, arraybuffer, &ab_data, + &ab_len)); if (ab_data == ext_data && ab_len == data_size) { printf("PASS: ownership transferred on napi_ok with pending " "exception\n"); @@ -2784,8 +2781,8 @@ static napi_value test_external_arraybuffer_with_pending_exception( // rejected up front rather than after createFromBytes has adopted data. static int external_buffer_finalize_count = 0; -static napi_value -test_external_buffer_with_pending_exception(const Napi::CallbackInfo &info) { +static napi_value test_external_buffer_with_pending_exception( + const Napi::CallbackInfo &info) { napi_env env = info.Env(); external_buffer_finalize_count = 0; @@ -2794,7 +2791,8 @@ test_external_buffer_with_pending_exception(const Napi::CallbackInfo &info) { uint8_t *ext_data = (uint8_t *)malloc(data_size); memset(ext_data, 0x5A, data_size); - NODE_API_CALL(env, napi_throw_error(env, nullptr, "stashed before create")); + NODE_API_CALL(env, + napi_throw_error(env, nullptr, "stashed before create")); napi_value buffer = nullptr; napi_status status = napi_create_external_buffer( @@ -2818,7 +2816,8 @@ test_external_buffer_with_pending_exception(const Napi::CallbackInfo &info) { } void *buf_data; size_t buf_len; - NODE_API_CALL(env, napi_get_buffer_info(env, buffer, &buf_data, &buf_len)); + NODE_API_CALL(env, + napi_get_buffer_info(env, buffer, &buf_data, &buf_len)); if (buf_data == ext_data && buf_len == data_size) { printf("PASS: ownership transferred on napi_ok with pending " "exception\n"); @@ -2935,27 +2934,31 @@ static napi_value test_pending_exception_gate(const Napi::CallbackInfo &info) { NODE_API_CALL(env, napi_create_object(env, &obj)); NODE_API_CALL(env, napi_create_array_with_length(env, 3, &arr)); NODE_API_CALL(env, napi_create_int32(env, 5, &five)); - NODE_API_CALL(env, napi_create_string_utf8(env, "globalThis.__napiGateMark()", - NAPI_AUTO_LENGTH, &script)); + NODE_API_CALL(env, napi_create_string_utf8( + env, "globalThis.__napiGateMark()", NAPI_AUTO_LENGTH, + &script)); NODE_API_CALL(env, napi_get_global(env, &global)); NODE_API_CALL(env, napi_get_named_property(env, global, "Function", &fn_ctor)); - NODE_API_CALL(env, napi_create_arraybuffer(env, 16, &ab_data, &arraybuffer)); + NODE_API_CALL(env, + napi_create_arraybuffer(env, 16, &ab_data, &arraybuffer)); NODE_API_CALL(env, napi_create_date(env, 1234.0, &date_in)); // Install a global the script would call so we can observe it running. napi_value mark_fn; NODE_API_CALL(env, napi_create_function(env, "mark", NAPI_AUTO_LENGTH, - pending_gate_mark_script_ran, nullptr, - &mark_fn)); - NODE_API_CALL( - env, napi_set_named_property(env, global, "__napiGateMark", mark_fn)); + pending_gate_mark_script_ran, + nullptr, &mark_fn)); + NODE_API_CALL(env, + napi_set_named_property(env, global, "__napiGateMark", + mark_fn)); // Create a real deferred/promise BEFORE throwing so resolve_deferred has // a valid handle to refuse. napi_deferred deferred_pre; napi_value promise_pre; - NODE_API_CALL(env, napi_create_promise(env, &deferred_pre, &promise_pre)); + NODE_API_CALL(env, + napi_create_promise(env, &deferred_pre, &promise_pre)); // Arm: exception now pending on the env (not the VM). NODE_API_CALL(env, napi_throw_error(env, "EGATE", "armed")); @@ -3040,10 +3043,10 @@ static napi_value test_pending_exception_gate(const Napi::CallbackInfo &info) { napi_value frozen_obj, is_frozen; NODE_API_CALL(env, napi_get_named_property(env, global, "Object", &frozen_obj)); - NODE_API_CALL( - env, napi_get_named_property(env, frozen_obj, "isFrozen", &frozen_obj)); - NODE_API_CALL( - env, napi_call_function(env, global, frozen_obj, 1, &obj, &is_frozen)); + NODE_API_CALL(env, napi_get_named_property(env, frozen_obj, "isFrozen", + &frozen_obj)); + NODE_API_CALL(env, napi_call_function(env, global, frozen_obj, 1, &obj, + &is_frozen)); bool frozen; NODE_API_CALL(env, napi_get_value_bool(env, is_frozen, &frozen)); printf("side_effect frozen=%s\n", frozen ? "true" : "false"); @@ -3279,8 +3282,7 @@ ungated_calls_through_timeout(const Napi::CallbackInfo &info) { // With createWithoutCopying, the atom table retains a reference to the // freed CString memory. On the next lookup of the same property name, // Identifier::fromString compares against the stale atom -> use-after-free. -static napi_value -test_napi_get_named_property_copied_string(const Napi::CallbackInfo &info) { +static napi_value test_napi_get_named_property_copied_string(const Napi::CallbackInfo &info) { napi_env env = info.Env(); napi_value global; @@ -3290,8 +3292,8 @@ test_napi_get_named_property_copied_string(const Napi::CallbackInfo &info) { // heap-allocated keys (like napi-rs CString), then free them. // The property names here match what impit uses in its response handling. const char *property_names[] = { - "ReadableStream", "Response", "arrayBuffer", "then", - "eval", "enqueue", "bind", "close", + "ReadableStream", "Response", "arrayBuffer", "then", "eval", + "enqueue", "bind", "close", }; const int num_names = sizeof(property_names) / sizeof(property_names[0]); @@ -3356,8 +3358,8 @@ static void test_issue_25933_callback(napi_env env, napi_value js_callback, } else if (type == napi_function) { printf("PASS: napi_typeof returned napi_function\n"); } else { - printf("FAIL: napi_typeof returned %d, expected napi_function (%d)\n", type, - napi_function); + printf("FAIL: napi_typeof returned %d, expected napi_function (%d)\n", + type, napi_function); } napi_release_threadsafe_function(tsfn_25933, napi_tsfn_release); tsfn_25933 = nullptr; @@ -3373,9 +3375,10 @@ static napi_value test_issue_25933(const Napi::CallbackInfo &info) { napi_value js_cb = info[0]; napi_value name = Napi::String::New(env, "tsfn_typeof_test"); - NODE_API_CALL(env, napi_create_threadsafe_function( - env, js_cb, nullptr, name, 0, 1, nullptr, nullptr, - nullptr, &test_issue_25933_callback, &tsfn_25933)); + NODE_API_CALL(env, + napi_create_threadsafe_function( + env, js_cb, nullptr, name, 0, 1, nullptr, nullptr, + nullptr, &test_issue_25933_callback, &tsfn_25933)); NODE_API_CALL(env, napi_call_threadsafe_function(tsfn_25933, nullptr, napi_tsfn_nonblocking)); return env.Undefined(); @@ -3392,8 +3395,7 @@ static void test_make_callback_tsfn_cb(napi_env env, napi_value js_callback, napi_get_global(env, &recv); napi_value result; - napi_status status = - napi_make_callback(env, nullptr, recv, js_callback, 0, nullptr, &result); + napi_status status = napi_make_callback(env, nullptr, recv, js_callback, 0, nullptr, &result); if (status == napi_ok) { printf("PASS: napi_make_callback succeeded\n"); } else { @@ -3447,8 +3449,7 @@ test_napi_make_callback_status(const Napi::CallbackInfo &info) { return ok(env); } -static napi_value -test_napi_make_callback_async_context_frame(const Napi::CallbackInfo &info) { +static napi_value test_napi_make_callback_async_context_frame(const Napi::CallbackInfo &info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); @@ -3457,8 +3458,8 @@ test_napi_make_callback_async_context_frame(const Napi::CallbackInfo &info) { NODE_API_CALL(env, napi_create_threadsafe_function( - env, js_cb, nullptr, name, 0, 1, nullptr, nullptr, nullptr, - &test_make_callback_tsfn_cb, &tsfn_make_callback)); + env, js_cb, nullptr, name, 0, 1, nullptr, nullptr, + nullptr, &test_make_callback_tsfn_cb, &tsfn_make_callback)); NODE_API_CALL(env, napi_call_threadsafe_function(tsfn_make_callback, nullptr, napi_tsfn_nonblocking)); return env.Undefined(); @@ -3478,14 +3479,12 @@ static void test_create_tsfn_outer_cb(napi_env env, napi_value js_callback, napi_threadsafe_function inner_tsfn = nullptr; napi_status status = napi_create_threadsafe_function( - env, js_callback, nullptr, name, 0, 1, nullptr, nullptr, nullptr, - /* call_js_cb */ nullptr, &inner_tsfn); + env, js_callback, nullptr, name, 0, 1, nullptr, nullptr, + nullptr, /* call_js_cb */ nullptr, &inner_tsfn); if (status != napi_ok) { - printf("FAIL: napi_create_threadsafe_function returned status %d\n", - status); + printf("FAIL: napi_create_threadsafe_function returned status %d\n", status); } else { - printf( - "PASS: napi_create_threadsafe_function accepted AsyncContextFrame\n"); + printf("PASS: napi_create_threadsafe_function accepted AsyncContextFrame\n"); // Release immediately — we only needed to verify creation succeeds. napi_release_threadsafe_function(inner_tsfn, napi_tsfn_release); } @@ -3493,8 +3492,7 @@ static void test_create_tsfn_outer_cb(napi_env env, napi_value js_callback, tsfn_create_outer = nullptr; } -static napi_value -test_napi_create_tsfn_async_context_frame(const Napi::CallbackInfo &info) { +static napi_value test_napi_create_tsfn_async_context_frame(const Napi::CallbackInfo &info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); @@ -3503,8 +3501,8 @@ test_napi_create_tsfn_async_context_frame(const Napi::CallbackInfo &info) { NODE_API_CALL(env, napi_create_threadsafe_function( - env, js_cb, nullptr, name, 0, 1, nullptr, nullptr, nullptr, - &test_create_tsfn_outer_cb, &tsfn_create_outer)); + env, js_cb, nullptr, name, 0, 1, nullptr, nullptr, + nullptr, &test_create_tsfn_outer_cb, &tsfn_create_outer)); NODE_API_CALL(env, napi_call_threadsafe_function(tsfn_create_outer, nullptr, napi_tsfn_nonblocking)); return env.Undefined(); @@ -3595,9 +3593,9 @@ test_typedarray_info_write_visibility(const Napi::CallbackInfo &info) { if (length > 0) { NODE_API_CALL(env, napi_get_element(env, typedarray, 0, &element)); NODE_API_CALL(env, napi_get_value_uint32(env, element, &first)); - NODE_API_CALL(env, napi_get_element(env, typedarray, - static_cast(length) - 1, - &element)); + NODE_API_CALL(env, + napi_get_element(env, typedarray, + static_cast(length) - 1, &element)); NODE_API_CALL(env, napi_get_value_uint32(env, element, &last)); } printf("length=%zu first=%u last=%u\n", length, first, last); @@ -3626,9 +3624,9 @@ test_buffer_info_pointer_stability(const Napi::CallbackInfo &info) { memset(data, 0x2b, length); NODE_API_CALL(env, napi_get_element(env, buffer, 0, &element)); NODE_API_CALL(env, napi_get_value_uint32(env, element, &first)); - NODE_API_CALL(env, napi_get_element(env, buffer, - static_cast(length) - 1, - &element)); + NODE_API_CALL(env, + napi_get_element(env, buffer, + static_cast(length) - 1, &element)); NODE_API_CALL(env, napi_get_value_uint32(env, element, &last)); } printf("length=%zu first=%u last=%u\n", length, first, last); @@ -3660,9 +3658,9 @@ test_create_buffer_pointer_stability(const Napi::CallbackInfo &info) { NODE_API_CALL( env, napi_create_buffer_copy(env, sizeof src, src, ©_data, ©)); napi_value copy_arraybuffer = nullptr; - NODE_API_CALL(env, - napi_get_typedarray_info(env, copy, nullptr, nullptr, nullptr, - ©_arraybuffer, nullptr)); + NODE_API_CALL(env, napi_get_typedarray_info(env, copy, nullptr, nullptr, + nullptr, ©_arraybuffer, + nullptr)); memset(copy_data, 0x2d, sizeof src); uint32_t copy_last = 0; NODE_API_CALL(env, napi_get_element(env, copy, 15, &element)); @@ -3697,8 +3695,8 @@ static napi_value test_napi_float16_array(const Napi::CallbackInfo &info) { void *ab_data = nullptr; size_t ab_len = 0; - NODE_API_CALL(env, - napi_get_arraybuffer_info(env, arraybuffer, &ab_data, &ab_len)); + NODE_API_CALL( + env, napi_get_arraybuffer_info(env, arraybuffer, &ab_data, &ab_len)); printf("arraybuffer_byte_length=%zu data_is_ab_plus_offset=%d\n", ab_len, static_cast(ab_data) + byte_offset == static_cast(data) @@ -3713,9 +3711,10 @@ static napi_value test_napi_float16_array(const Napi::CallbackInfo &info) { size_t created_len = 0; if (sc == napi_ok) { NODE_API_CALL(env, napi_is_typedarray(env, created, &created_is)); - NODE_API_CALL(env, napi_get_typedarray_info(env, created, &created_type, - &created_len, nullptr, nullptr, - nullptr)); + NODE_API_CALL(env, + napi_get_typedarray_info(env, created, &created_type, + &created_len, nullptr, nullptr, + nullptr)); } printf("create_status=%d created_is_typedarray=%d created_type=%d " "created_length=%zu\n", @@ -3834,8 +3833,7 @@ static napi_value test_node_api_set_prototype(const Napi::CallbackInfo &info) { bool same = false; NODE_API_CALL(env, napi_strict_equals(env, got_proto, proto, &same)); napi_value inherited; - NODE_API_CALL(env, - napi_get_named_property(env, obj, "inherited", &inherited)); + NODE_API_CALL(env, napi_get_named_property(env, obj, "inherited", &inherited)); int32_t inherited_i = 0; NODE_API_CALL(env, napi_get_value_int32(env, inherited, &inherited_i)); printf("set_prototype: proto_matches=%s inherited=%d\n", @@ -3870,8 +3868,8 @@ test_node_api_create_object_with_properties(const Napi::CallbackInfo &info) { NODE_API_CALL(env, napi_create_int32(env, 4, &values[3])); napi_value obj; - NODE_API_CALL(env, node_api_create_object_with_properties(env, nullptr, names, - values, 4, &obj)); + NODE_API_CALL(env, node_api_create_object_with_properties( + env, nullptr, names, values, 4, &obj)); napi_value proto; NODE_API_CALL(env, napi_get_prototype(env, obj, &proto)); @@ -3922,7 +3920,8 @@ test_node_api_sharedarraybuffer(const Napi::CallbackInfo &info) { void *data = nullptr; napi_value sab; - NODE_API_CALL(env, node_api_create_sharedarraybuffer(env, 16, &data, &sab)); + NODE_API_CALL(env, + node_api_create_sharedarraybuffer(env, 16, &data, &sab)); bool is_sab = false; NODE_API_CALL(env, node_api_is_sharedarraybuffer(env, sab, &is_sab)); bool is_ab = true; @@ -3984,8 +3983,7 @@ static void noop_tsfn_cb(napi_env, napi_value, void *, void *) {} // prior to the fix; see the PR body for the per-function Node.js references. // This test prints status codes and pending-exception state so checkSameOutput // can diff Bun against Node byte-for-byte. -static napi_value -test_napi_status_codes_node26(const Napi::CallbackInfo &info) { +static napi_value test_napi_status_codes_node26(const Napi::CallbackInfo &info) { napi_env env = info.Env(); #ifndef _WIN32 @@ -4028,17 +4026,18 @@ test_napi_status_codes_node26(const Napi::CallbackInfo &info) { { void *out; napi_ref ref_out; - print_status("napi_wrap(number)", - napi_wrap(env, number, nullptr, nullptr, nullptr, nullptr), - true); + print_status( + "napi_wrap(number)", + napi_wrap(env, number, nullptr, nullptr, nullptr, nullptr), true); print_status("napi_unwrap(number)", napi_unwrap(env, number, &out), true); print_status("napi_remove_wrap(number)", napi_remove_wrap(env, number, &out), true); - print_status("napi_add_finalizer(number)", - napi_add_finalizer( - env, number, nullptr, [](napi_env, void *, void *) {}, - nullptr, &ref_out), - true); + print_status( + "napi_add_finalizer(number)", + napi_add_finalizer( + env, number, nullptr, + [](napi_env, void *, void *) {}, nullptr, &ref_out), + true); } // napi_coerce_to_*: when coercion throws, Node returns napi__expected @@ -4057,9 +4056,9 @@ test_napi_status_codes_node26(const Napi::CallbackInfo &info) { // napi_generic_failure, not napi_pending_exception. { napi_value script_throw, script_syntax, out; - NODE_API_CALL(env, - napi_create_string_utf8(env, "throw new Error('E')", - NAPI_AUTO_LENGTH, &script_throw)); + NODE_API_CALL(env, napi_create_string_utf8(env, "throw new Error('E')", + NAPI_AUTO_LENGTH, + &script_throw)); NODE_API_CALL(env, napi_create_string_utf8(env, "?!?", NAPI_AUTO_LENGTH, &script_syntax)); print_status("napi_run_script(throw)", @@ -4090,7 +4089,8 @@ test_napi_status_codes_node26(const Napi::CallbackInfo &info) { static const char one_byte = 0; print_status( "napi_create_buffer_copy(SIZE_MAX)", - napi_create_buffer_copy(env, SIZE_MAX, &one_byte, nullptr, &out), true); + napi_create_buffer_copy(env, SIZE_MAX, &one_byte, nullptr, &out), + true); } // napi_throw_error while an exception is already pending: Node returns @@ -4102,8 +4102,8 @@ test_napi_status_codes_node26(const Napi::CallbackInfo &info) { napi_value exc; NODE_API_CALL(env, napi_get_and_clear_last_exception(env, &exc)); napi_value msg_key, msg; - NODE_API_CALL(env, napi_create_string_utf8(env, "message", NAPI_AUTO_LENGTH, - &msg_key)); + NODE_API_CALL(env, napi_create_string_utf8(env, "message", + NAPI_AUTO_LENGTH, &msg_key)); NODE_API_CALL(env, napi_get_property(env, exc, msg_key, &msg)); char buf[64] = {0}; size_t len = 0; @@ -4115,7 +4115,8 @@ test_napi_status_codes_node26(const Napi::CallbackInfo &info) { // node_api_post_finalizer: Node accepts a NULL finalize_cb. { print_status("node_api_post_finalizer(NULL)", - node_api_post_finalizer(env, nullptr, nullptr, nullptr), true); + node_api_post_finalizer(env, nullptr, nullptr, nullptr), + true); } // napi_make_callback argument validation: Node returns napi_invalid_arg for @@ -4125,12 +4126,13 @@ test_napi_status_codes_node26(const Napi::CallbackInfo &info) { print_status( "napi_make_callback(recv=NULL)", napi_make_callback(env, nullptr, nullptr, fn, 0, nullptr, &out), true); - print_status("napi_make_callback(argc>0,argv=NULL)", - napi_make_callback(env, nullptr, obj, fn, 1, nullptr, &out), - true); + print_status( + "napi_make_callback(argc>0,argv=NULL)", + napi_make_callback(env, nullptr, obj, fn, 1, nullptr, &out), true); print_status( "napi_make_callback(func=number)", - napi_make_callback(env, nullptr, obj, number, 0, nullptr, &out), true); + napi_make_callback(env, nullptr, obj, number, 0, nullptr, &out), + true); } // napi_ref/unref_threadsafe_function: Node ignores env (basic-env function) @@ -4141,8 +4143,8 @@ test_napi_status_codes_node26(const Napi::CallbackInfo &info) { NAPI_AUTO_LENGTH, &name)); napi_threadsafe_function tsfn = nullptr; NODE_API_CALL(env, napi_create_threadsafe_function( - env, nullptr, nullptr, name, 0, 1, nullptr, nullptr, - nullptr, noop_tsfn_cb, &tsfn)); + env, nullptr, nullptr, name, 0, 1, nullptr, + nullptr, nullptr, noop_tsfn_cb, &tsfn)); printf("napi_ref_threadsafe_function(env=NULL): status=%d\n", (int)napi_ref_threadsafe_function(nullptr, tsfn)); printf("napi_unref_threadsafe_function(env=NULL): status=%d\n", @@ -4172,20 +4174,22 @@ static void tsfn_nullcb_call_js(napi_env env, napi_value js_callback, static void tsfn_nullcb_finalize(napi_env env, void *data, void *hint) {} -static napi_value test_tsfn_null_js_callback(const Napi::CallbackInfo &info) { +static napi_value +test_tsfn_null_js_callback(const Napi::CallbackInfo &info) { napi_env env = info.Env(); tsfn_nullcb_was_null.store(-1); napi_value name; NODE_API_CALL(env, napi_create_string_utf8(env, "tsfn-nullcb", NAPI_AUTO_LENGTH, &name)); napi_threadsafe_function tsfn; - NODE_API_CALL( - env, napi_create_threadsafe_function(env, NULL, NULL, name, 0, 1, NULL, - tsfn_nullcb_finalize, NULL, - tsfn_nullcb_call_js, &tsfn)); + NODE_API_CALL(env, napi_create_threadsafe_function( + env, NULL, NULL, name, 0, 1, NULL, + tsfn_nullcb_finalize, NULL, tsfn_nullcb_call_js, + &tsfn)); NODE_API_CALL( env, napi_call_threadsafe_function(tsfn, NULL, napi_tsfn_nonblocking)); - NODE_API_CALL(env, napi_release_threadsafe_function(tsfn, napi_tsfn_release)); + NODE_API_CALL(env, + napi_release_threadsafe_function(tsfn, napi_tsfn_release)); return ok(env); } @@ -4309,13 +4313,14 @@ test_napi_symbol_key_result_ordering(const Napi::CallbackInfo &info) { { napi_value thrower; - NODE_API_CALL(env, napi_create_function( - env, "Throws", NAPI_AUTO_LENGTH, - [](napi_env e, napi_callback_info) -> napi_value { - napi_throw_error(e, NULL, "ctor"); - return NULL; - }, - NULL, &thrower)); + NODE_API_CALL( + env, napi_create_function( + env, "Throws", NAPI_AUTO_LENGTH, + [](napi_env e, napi_callback_info) -> napi_value { + napi_throw_error(e, NULL, "ctor"); + return NULL; + }, + NULL, &thrower)); napi_value sentinel = reinterpret_cast(0xdeadbeef); napi_value r = sentinel; napi_status s = napi_new_instance(env, thrower, 0, NULL, &r); @@ -4329,12 +4334,12 @@ test_napi_symbol_key_result_ordering(const Napi::CallbackInfo &info) { r != sentinel); napi_value script, proxy; - NODE_API_CALL(env, - napi_create_string_utf8( - env, - "new Proxy({}, {has: () => { throw new Error('h'); }, " - "get: () => { throw new Error('g'); }})", - NAPI_AUTO_LENGTH, &script)); + NODE_API_CALL( + env, napi_create_string_utf8( + env, + "new Proxy({}, {has: () => { throw new Error('h'); }, " + "get: () => { throw new Error('g'); }})", + NAPI_AUTO_LENGTH, &script)); NODE_API_CALL(env, napi_run_script(env, script, &proxy)); r = sentinel; s = napi_get_named_property(env, proxy, "k", &r); @@ -4381,13 +4386,13 @@ test_napi_external_string_args(const Napi::CallbackInfo &info) { static char sbuf[1] = {0}; report_status( env, "ext_string_latin1(ptr,INT_MAX+1)", - node_api_create_external_string_latin1(env, sbuf, ((size_t)INT_MAX) + 1u, - NULL, NULL, &out, &copied)); + node_api_create_external_string_latin1( + env, sbuf, ((size_t)INT_MAX) + 1u, NULL, NULL, &out, &copied)); static char16_t sbuf16[1] = {0}; report_status( env, "ext_string_utf16(ptr,INT_MAX+1)", - node_api_create_external_string_utf16(env, sbuf16, ((size_t)INT_MAX) + 1u, - NULL, NULL, &out, &copied)); + node_api_create_external_string_utf16( + env, sbuf16, ((size_t)INT_MAX) + 1u, NULL, NULL, &out, &copied)); return ok(env); } @@ -4419,20 +4424,23 @@ test_napi_get_buffer_info_gate(const Napi::CallbackInfo &info) { // Returns a weak napi_ref to a fresh object so the JS side can GC and then // inspect napi_reference_ref behaviour after the referent is collected. -static napi_value test_create_weak_ref_for_gc(const Napi::CallbackInfo &info) { +static napi_value +test_create_weak_ref_for_gc(const Napi::CallbackInfo &info) { napi_env env = info.Env(); napi_value obj; NODE_API_CALL(env, napi_create_object(env, &obj)); napi_ref ref; NODE_API_CALL(env, napi_create_reference(env, obj, 0, &ref)); napi_value ext; - NODE_API_CALL(env, napi_create_external(env, reinterpret_cast(ref), - NULL, NULL, &ext)); + NODE_API_CALL(env, + napi_create_external(env, reinterpret_cast(ref), NULL, + NULL, &ext)); return ext; } // Predicate for gcUntil: true once the weak ref's value is undefined. -static napi_value test_weak_ref_is_collected(const Napi::CallbackInfo &info) { +static napi_value +test_weak_ref_is_collected(const Napi::CallbackInfo &info) { napi_env env = info.Env(); void *p; NODE_API_CALL(env, napi_get_value_external(env, info[1], &p)); @@ -4440,8 +4448,7 @@ static napi_value test_weak_ref_is_collected(const Napi::CallbackInfo &info) { napi_value v = NULL; NODE_API_CALL(env, napi_get_reference_value(env, ref, &v)); napi_valuetype t = napi_undefined; - if (v) - napi_typeof(env, v, &t); + if (v) napi_typeof(env, v, &t); napi_value r; NODE_API_CALL(env, napi_get_boolean(env, v == NULL || t == napi_undefined, &r)); @@ -4458,8 +4465,7 @@ test_reference_ref_after_collect(const Napi::CallbackInfo &info) { napi_value v = NULL; NODE_API_CALL(env, napi_get_reference_value(env, ref, &v)); napi_valuetype t = napi_undefined; - if (v) - napi_typeof(env, v, &t); + if (v) napi_typeof(env, v, &t); uint32_t count = 999; NODE_API_CALL(env, napi_reference_ref(env, ref, &count)); printf("get_reference_value is undefined=%d reference_ref count=%u\n", @@ -4497,13 +4503,13 @@ void register_standalone_tests(Napi::Env env, Napi::Object exports) { REGISTER_FUNCTION( env, exports, test_napi_threadsafe_function_abort_blocked_producers_finalized); - REGISTER_FUNCTION(env, exports, - test_napi_threadsafe_function_abort_full_queue); - REGISTER_FUNCTION(env, exports, - test_napi_threadsafe_function_abort_full_queue_finalized); + REGISTER_FUNCTION(env, exports, test_napi_threadsafe_function_abort_full_queue); + REGISTER_FUNCTION( + env, exports, test_napi_threadsafe_function_abort_full_queue_finalized); REGISTER_FUNCTION(env, exports, test_napi_threadsafe_function_microtask_order); - REGISTER_FUNCTION(env, exports, test_napi_threadsafe_function_call_js_throws); + REGISTER_FUNCTION(env, exports, + test_napi_threadsafe_function_call_js_throws); REGISTER_FUNCTION(env, exports, test_napi_handle_scope_string); REGISTER_FUNCTION(env, exports, test_napi_handle_scope_bigint); REGISTER_FUNCTION(env, exports, test_napi_delete_property); @@ -4544,7 +4550,8 @@ void register_standalone_tests(Napi::Env env, Napi::Object exports) { REGISTER_FUNCTION(env, exports, test_external_arraybuffer_finalizer); REGISTER_FUNCTION(env, exports, test_external_arraybuffer_with_pending_exception); - REGISTER_FUNCTION(env, exports, test_external_buffer_with_pending_exception); + REGISTER_FUNCTION(env, exports, + test_external_buffer_with_pending_exception); REGISTER_FUNCTION(env, exports, create_external_arraybuffer_for_transfer); REGISTER_FUNCTION(env, exports, create_external_buffer_for_transfer); REGISTER_FUNCTION(env, exports, external_for_transfer_stats); diff --git a/test/napi/napi-app/throwing_init_addon.c b/test/napi/napi-app/throwing_init_addon.c index 92c1f7125e61..de7401abef5b 100644 --- a/test/napi/napi-app/throwing_init_addon.c +++ b/test/napi/napi-app/throwing_init_addon.c @@ -11,7 +11,13 @@ static napi_value init(napi_env env, napi_value exports) { } static napi_module mod = { - 1, 0, "throwing_init_addon.c", init, "throwing_init_addon", NULL, {NULL}, + 1, // nm_version + 0, // nm_flags + "throwing_init_addon.c", // nm_filename + init, // nm_register_func + "throwing_init_addon", // nm_modname + NULL, // nm_priv + {NULL} // reserved }; #if defined(_MSC_VER) diff --git a/test/napi/napi.test.ts b/test/napi/napi.test.ts index a49cf11490a2..a61110224978 100644 --- a/test/napi/napi.test.ts +++ b/test/napi/napi.test.ts @@ -1402,6 +1402,24 @@ describe.concurrent.skipIf(!canBuildNodeAddons())("napi", () => { expect(exitCode).toBe(0); }); + it("an addon registered with napi_module_register whose init throws makes require() throw that error", async () => { + const addonPath = join(__dirname, "napi-app", "build", "Debug", "throwing_init_addon.node"); + await using proc = spawn({ + cmd: [ + bunExe(), + "-e", + `try { require(${JSON.stringify(addonPath)}); console.log("no throw"); } catch (e) { console.log(e.code, e.message); }`, + ], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stdout.trim()).toBe("ERR_THROWING_INIT init threw on purpose"); + expect(stderr).toBe(""); + expect(exitCode).toBe(0); + }); + it("behaves as expected when performing operations with an exception pending", async () => { await checkSameOutput("test_deferred_exceptions", []); }); @@ -1895,24 +1913,6 @@ describe.skipIf(!canBuildNodeAddons())("cleanup hooks", () => { }); }); - it("an addon registered with napi_module_register whose init throws makes require() throw that error", async () => { - const addonPath = join(__dirname, "napi-app", "build", "Debug", "throwing_init_addon.node"); - await using proc = spawn({ - cmd: [ - bunExe(), - "-e", - `try { require(${JSON.stringify(addonPath)}); console.log("no throw"); } catch (e) { console.log(e.code, e.message); }`, - ], - env: bunEnv, - stdout: "pipe", - stderr: "pipe", - }); - const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - expect(stdout.trim()).toBe("ERR_THROWING_INIT init threw on purpose"); - expect(stderr).toBe(""); - expect(exitCode).toBe(0); - }); - describe("napi_create_dataview", () => { // Node hands back a zero-length DataView here; JSC has no DataView over a detached buffer, so Bun reports // the TypeError instead (it used to crash). diff --git a/test/v8/v8-module/main.cpp b/test/v8/v8-module/main.cpp index 52954bbe8af5..3a401564baa6 100644 --- a/test/v8/v8-module/main.cpp +++ b/test/v8/v8-module/main.cpp @@ -54,8 +54,8 @@ static std::string describe(Isolate *isolate, Local value) { return result; } else if (value->IsFunction()) { char buf[1024] = {0}; - value.As()->GetName().As()->WriteUtf8V2(isolate, buf, - sizeof(buf) - 1); + value.As()->GetName().As()->WriteUtf8V2( + isolate, buf, sizeof(buf) - 1); std::string result = "function "; result += buf; result += "()"; @@ -268,8 +268,7 @@ void test_v8_string_write_utf8(const FunctionCallbackInfo &info) { // in that case; WriteUtf8V2 instead refuses to write partial sequences and // stops before the astral character. The encoder that backs this on Bun // previously wrote U+FFFD (0xEF 0xBF 0xBD) here, diverging from V8. -void test_v8_string_write_utf8_surrogate( - const FunctionCallbackInfo &info) { +void test_v8_string_write_utf8_surrogate(const FunctionCallbackInfo &info) { Isolate *isolate = info.GetIsolate(); struct { @@ -1651,14 +1650,16 @@ void test_v8_function_call(const FunctionCallbackInfo &info) { String::NewFromUtf8(isolate, "hello").ToLocalChecked(), Boolean::New(isolate, true), }; - MaybeLocal result = f->Call(context, Undefined(isolate), 3, argv); + MaybeLocal result = + f->Call(context, Undefined(isolate), 3, argv); LOG_EXPR(result.IsEmpty()); if (!result.IsEmpty()) { LOG_EXPR(describe(isolate, result.ToLocalChecked())); } Local recv = Object::New(isolate); - (void)recv->Set(context, String::NewFromUtf8(isolate, "tag").ToLocalChecked(), + (void)recv->Set(context, + String::NewFromUtf8(isolate, "tag").ToLocalChecked(), Number::New(isolate, 99.0)); MaybeLocal result2 = f->Call(context, recv, 0, nullptr); LOG_EXPR(result2.IsEmpty()); @@ -1705,7 +1706,8 @@ void test_v8_function_new_instance(const FunctionCallbackInfo &info) { .ToLocalChecked(); LOG_EXPR(describe(isolate, constructed)); Local arg0 = - inst->Get(context, String::NewFromUtf8(isolate, "arg0").ToLocalChecked()) + inst->Get(context, + String::NewFromUtf8(isolate, "arg0").ToLocalChecked()) .ToLocalChecked(); LOG_EXPR(describe(isolate, arg0)); @@ -1791,12 +1793,12 @@ void test_v8_exception(const FunctionCallbackInfo &info) { Local err = Exception::Error(msg); LOG_EXPR(err->IsObject()); - LOG_EXPR(describe( - isolate, - err.As() - ->Get(isolate->GetCurrentContext(), - String::NewFromUtf8(isolate, "message").ToLocalChecked()) - .ToLocalChecked())); + LOG_EXPR( + describe(isolate, + err.As() + ->Get(isolate->GetCurrentContext(), + String::NewFromUtf8(isolate, "message").ToLocalChecked()) + .ToLocalChecked())); Local type_err = Exception::TypeError( String::NewFromUtf8(isolate, "wrong type").ToLocalChecked()); @@ -1806,9 +1808,9 @@ void test_v8_exception(const FunctionCallbackInfo &info) { isolate->ThrowException(err); } -// ThrowException() with the addon still running afterwards: it keeps allocating -// through the API before it returns, and what it threw — a non-Error here — is -// what the JS caller catches. +// ThrowException() with the addon still running afterwards: it keeps +// allocating through the API before it returns, and what it threw — a +// non-Error here — is what the JS caller catches. void test_v8_throw_then_continue(const FunctionCallbackInfo &info) { Isolate *isolate = info.GetIsolate(); isolate->ThrowException(Number::New(isolate, 42)); @@ -1880,8 +1882,7 @@ void test_v8_cpu_profiler(const FunctionCallbackInfo &info) { // Do a little work so at least the root node exists; do NOT assert on sample // counts because those are timing-dependent and differ across engines. volatile double sink = 0; - for (int i = 0; i < 100000; i++) - sink += i * 0.5; + for (int i = 0; i < 100000; i++) sink += i * 0.5; (void)sink; CpuProfile *profile = profiler->Stop(start_result.id); @@ -1918,8 +1919,7 @@ void test_v8_cpu_profiler_overlapping_sessions( auto busy = [] { volatile double sink = 0; - for (int i = 0; i < 100000; i++) - sink += i * 0.5; + for (int i = 0; i < 100000; i++) sink += i * 0.5; (void)sink; }; @@ -1928,14 +1928,14 @@ void test_v8_cpu_profiler_overlapping_sessions( Local title_b = String::NewFromUtf8(isolate, "bun-v8-test-b").ToLocalChecked(); - CpuProfilingResult a = profiler->Start(title_a, kLeafNodeLineNumbers, true, - CpuProfilingOptions::kNoSampleLimit); + CpuProfilingResult a = profiler->Start( + title_a, kLeafNodeLineNumbers, true, CpuProfilingOptions::kNoSampleLimit); LOG_EXPR((int)a.status); busy(); // Second session while the first is still running. - CpuProfilingResult b = profiler->Start(title_b, kLeafNodeLineNumbers, true, - CpuProfilingOptions::kNoSampleLimit); + CpuProfilingResult b = profiler->Start( + title_b, kLeafNodeLineNumbers, true, CpuProfilingOptions::kNoSampleLimit); LOG_EXPR((int)b.status); LOG_EXPR(a.id != b.id); @@ -1996,8 +1996,7 @@ void test_v8_cpu_profiler_title_api(const FunctionCallbackInfo &info) { auto busy = [] { volatile double sink = 0; - for (int i = 0; i < 100000; i++) - sink += i * 0.5; + for (int i = 0; i < 100000; i++) sink += i * 0.5; (void)sink; }; From 41625c7043764945c527fdd1ce8685a9969fd8c3 Mon Sep 17 00:00:00 2001 From: Dylan Conway Date: Mon, 24 Aug 2026 20:39:51 +0000 Subject: [PATCH 8/9] test: include stderr in the cc() Node-API assertion --- test/js/bun/ffi/cc.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/js/bun/ffi/cc.test.ts b/test/js/bun/ffi/cc.test.ts index c53294ed2742..0fc9f39988b1 100644 --- a/test/js/bun/ffi/cc.test.ts +++ b/test/js/bun/ffi/cc.test.ts @@ -1069,7 +1069,7 @@ describe("double <-> JSValue conversions", () => { stderr: "pipe", }); const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - expect({ out: JSON.parse(stdout.trim().split("\n").at(-1) || "null"), exitCode }).toEqual({ + expect({ out: JSON.parse(stdout.trim().split("\n").at(-1) || "null"), stderr, exitCode }).toMatchObject({ out: { callCb: true, throwIt: "ERR_FROM_CC: thrown from cc", after: 7 }, exitCode: 0, }); From 8681870190a091df04efae9d1faaaf7b28e37f8e Mon Sep 17 00:00:00 2001 From: Dylan Conway Date: Tue, 25 Aug 2026 02:45:44 +0000 Subject: [PATCH 9/9] process.dlopen: the cached-replay path checks slot 0 after a V8 register func too --- src/jsc/bindings/BunProcess.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/jsc/bindings/BunProcess.cpp b/src/jsc/bindings/BunProcess.cpp index b3f8b66f1a26..3fd9d0e4bbbb 100644 --- a/src/jsc/bindings/BunProcess.cpp +++ b/src/jsc/bindings/BunProcess.cpp @@ -662,6 +662,10 @@ JSC_DEFINE_HOST_FUNCTION_WITH_ATTRIBUTES(Process_functionDlopen, __attribute__(( if (auto* const* nodeModule = std::get_if(®istration)) { node::node_module_register(*nodeModule); RETURN_IF_EXCEPTION(scope, {}); + if (JSValue thrown = globalObject->m_pendingNapiModuleAndExports[0].get(); thrown && thrown != strongModule.get()) { + JSC::throwException(globalObject, scope, thrown); + return {}; + } } else { napi_module_register(std::get(registration)); }