diff --git a/src/jsc/JSValue.rs b/src/jsc/JSValue.rs index 36e4f6d51aea..e737f122e20e 100644 --- a/src/jsc/JSValue.rs +++ b/src/jsc/JSValue.rs @@ -2295,12 +2295,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. @@ -2687,7 +2682,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/BunProcess.cpp b/src/jsc/bindings/BunProcess.cpp index 3704d48d687e..3fd9d0e4bbbb 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; @@ -590,8 +596,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) { @@ -607,9 +611,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; @@ -629,12 +637,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()); @@ -647,8 +654,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 @@ -657,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)); } @@ -678,12 +687,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()); @@ -767,8 +775,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/bindings.cpp b/src/jsc/bindings/bindings.cpp index 4f879199b898..fe1b42423213 100644 --- a/src/jsc/bindings/bindings.cpp +++ b/src/jsc/bindings/bindings.cpp @@ -4813,7 +4813,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 aaa41f6d2499..86fafb69c176 100644 --- a/src/jsc/bindings/napi.cpp +++ b/src/jsc/bindings/napi.cpp @@ -90,23 +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); \ - /* 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. */ \ - 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; \ @@ -114,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) @@ -169,32 +173,37 @@ 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. -#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); \ - } \ +// 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()); +} + +// 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) -#define NAPI_RETURN_IF_EXCEPTION(_env) NAPI_RETURN_IF_EXCEPTION_WITH_SCOPE((_env), napi_preamble_throw_scope__) +// 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) // Return indicating that no error occurred in a NAPI function, and an exception is not expected #define NAPI_RETURN_SUCCESS(_env) \ @@ -779,6 +788,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()) { @@ -1024,7 +1036,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__); @@ -1075,29 +1087,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); @@ -1107,20 +1104,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); } @@ -1348,21 +1337,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); - // First check if the environment has a pending exception + // 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(); - - // 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; - } - } - return napi_clear_last_error(env); } @@ -1377,16 +1354,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); } @@ -1446,9 +1420,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, @@ -1470,9 +1444,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. @@ -1585,11 +1559,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); @@ -1600,18 +1571,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, @@ -1787,9 +1757,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) @@ -1840,9 +1810,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, @@ -1868,10 +1838,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); @@ -1883,9 +1851,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) @@ -2077,14 +2047,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; @@ -2126,6 +2101,7 @@ extern "C" napi_status napi_get_all_property_names( if (include) { filteredKeys->push(globalObject, key); + NAPI_RETURN_IF_EXCEPTION(env); } } exportKeys = filteredKeys; @@ -2137,6 +2113,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); @@ -2287,10 +2264,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(); @@ -2302,12 +2277,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: @@ -2317,7 +2292,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, @@ -2325,10 +2300,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(); @@ -2337,22 +2310,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 @@ -2618,9 +2591,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 @@ -2930,7 +2903,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(); @@ -2963,7 +2936,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 @@ -3038,33 +3011,27 @@ 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()); - 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); - - return napi_set_last_error(env, napi_ok); + NAPI_RETURN_SUCCESS(env); } extern "C" napi_status napi_set_instance_data(napi_env env, @@ -3086,7 +3053,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); @@ -3098,7 +3065,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); @@ -3110,11 +3077,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); @@ -3123,21 +3087,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, @@ -3155,7 +3119,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); @@ -3188,8 +3152,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); } @@ -3238,11 +3201,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); - if (env->throwPendingException()) { - return 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); @@ -3290,7 +3248,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); @@ -3310,7 +3268,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)); @@ -3407,6 +3365,18 @@ 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()); + if (scope.exception()) + latchException(env, scope); +} + extern "C" bool NapiEnv__hasPendingException(napi_env env) { if (env->hasPendingException()) { 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 ecb145809496..293923e507a6 100644 --- a/src/jsc/bindings/v8/V8Isolate.cpp +++ b/src/jsc/bindings/v8/V8Isolate.cpp @@ -140,22 +140,23 @@ 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::throwPendingException. Local Isolate::ThrowException(Local exception) { - auto scope = DECLARE_THROW_SCOPE(vm()); - JSC::throwException(m_globalObject, scope, exception->localToJSValue()); + m_globalInternals->scheduleException(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); - return handle; + m_globalInternals->scheduleException(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..c2f3fc0540e0 100644 --- a/src/jsc/bindings/v8/node.cpp +++ b/src/jsc/bindings/v8/node.cpp @@ -179,7 +179,14 @@ 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()); + if (thrown) [[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..1c26bcbcb9c6 100644 --- a/src/jsc/bindings/v8/shim/FunctionTemplate.cpp +++ b/src/jsc/bindings/v8/shim/FunctionTemplate.cpp @@ -250,6 +250,9 @@ JSC::JSValue FunctionTemplate::invokeCallback(JSC::JSGlobalObject* globalObject, functionTemplate->m_callback(info); } + if (isolate->globalInternals()->throwPendingException(globalObject)) [[unlikely]] + 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..6eceadf0bd44 100644 --- a/src/jsc/bindings/v8/shim/GlobalInternals.cpp +++ b/src/jsc/bindings/v8/shim/GlobalInternals.cpp @@ -64,9 +64,22 @@ 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); +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 6ef2e1be5021..3e2480e7c757 100644 --- a/src/jsc/bindings/v8/shim/GlobalInternals.h +++ b/src/jsc/bindings/v8/shim/GlobalInternals.h @@ -107,6 +107,21 @@ 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 (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(); + 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; } WTF::Vector>& nearHeapLimitCallbacks() { return m_nearHeapLimitCallbacks; } @@ -135,6 +150,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..54b5904394b7 100644 --- a/src/jsc/bindings/v8/shim/TemplateProperty.cpp +++ b/src/jsc/bindings/v8/shim/TemplateProperty.cpp @@ -104,11 +104,15 @@ static JSC::JSValue invokeAccessor( frame[Info::kValueIndex] = valueLocal.tagged(); const auto& info = *reinterpret_cast*>(&frame[Info::kPropertyKeyIndex]); setter(property, valueLocal, info); + if (isolate->globalInternals()->throwPendingException(globalObject)) [[unlikely]] + return {}; return JSC::jsUndefined(); } const auto& info = *reinterpret_cast(&frame[Info::kPropertyKeyIndex]); getter(property, info); + if (isolate->globalInternals()->throwPendingException(globalObject)) [[unlikely]] + return {}; 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 6f3a8ea49e2c..10af8841a31f 100644 --- a/src/runtime/ffi/ffi_body.rs +++ b/src/runtime/ffi/ffi_body.rs @@ -2171,8 +2171,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", )?; } @@ -2526,6 +2528,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( @@ -2539,6 +2542,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 70a897756e67..647fbd15b35a 100644 --- a/src/runtime/napi/napi_body.rs +++ b/src/runtime/napi/napi_body.rs @@ -93,6 +93,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`). @@ -145,8 +146,17 @@ impl NapiEnv { Self::set_last_error(Some(self), NapiStatus::pending_exception) } - /// 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. + /// 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) + } + + /// 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()) } @@ -168,11 +178,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() { @@ -614,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() @@ -640,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); @@ -743,7 +752,7 @@ extern "C" fn napi_create_string_latin1( let js = match string.into_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() @@ -784,7 +793,7 @@ extern "C" fn napi_create_string_utf8( let global_object = env.to_js(); let string = match 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() @@ -840,7 +849,7 @@ extern "C" fn napi_create_string_utf16( let js = match string.into_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() @@ -966,7 +975,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. @@ -976,7 +985,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() @@ -1058,7 +1067,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() } @@ -1079,7 +1088,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() } @@ -1276,7 +1285,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. @@ -1644,7 +1653,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() } @@ -1662,7 +1671,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/js/bun/ffi/cc.test.ts b/test/js/bun/ffi/cc.test.ts index 0726df91e629..0fc9f39988b1 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"), stderr, exitCode }).toMatchObject({ + 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/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..2b0319a575a6 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); @@ -1766,6 +1784,33 @@ test_napi_dataview_bounds_errors(const Napi::CallbackInfo &info) { return ok(env); } +// 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, 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; + NODE_API_CALL(env, napi_is_exception_pending(env, &pending)); + char name[64] = ""; + if (pending) { + napi_value exc, ctor, name_val; + 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); + 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(); @@ -4473,6 +4518,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); @@ -4490,6 +4536,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); 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..de7401abef5b --- /dev/null +++ b/test/napi/napi-app/throwing_init_addon.c @@ -0,0 +1,32 @@ +#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, // 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) +#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..a61110224978 100644 --- a/test/napi/napi.test.ts +++ b/test/napi/napi.test.ts @@ -960,6 +960,15 @@ 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 () => { + // 9 = napi_generic_failure; 6 = napi_object, 3 = napi_number + let out = await checkSameOutput("test_napi_run_script_last_exception", [ + "(()=>{ throw new TypeError('oops'); })()", + ]); + 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 // this doesn't use await checkSameOutput because V8 and JSC use different error messages for a missing variable @@ -1393,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", []); }); @@ -1887,6 +1914,14 @@ describe.skipIf(!canBuildNodeAddons())("cleanup hooks", () => { }); 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", []); + // 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 () => { const output = await checkSameOutput("test_napi_dataview_bounds_errors", []); expect(output).toContain("napi_create_dataview"); diff --git a/test/v8/v8-module/main.cpp b/test/v8/v8-module/main.cpp index 5f658ad34d02..3a401564baa6 100644 --- a/test/v8/v8-module/main.cpp +++ b/test/v8/v8-module/main.cpp @@ -1808,6 +1808,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(); @@ -2144,6 +2157,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", () => {