Skip to content
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 1 addition & 7 deletions src/jsc/JSValue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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(
Expand Down
14 changes: 6 additions & 8 deletions src/jsc/bindings/BunProcess.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down Expand Up @@ -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());
Expand Down
2 changes: 1 addition & 1 deletion src/jsc/bindings/bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
204 changes: 99 additions & 105 deletions src/jsc/bindings/napi.cpp

Large diffs are not rendered by default.

15 changes: 8 additions & 7 deletions src/jsc/bindings/v8/V8Isolate.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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::takePendingException.
Local<Value> Isolate::ThrowException(Local<Value> exception)
{
auto scope = DECLARE_THROW_SCOPE(vm());
JSC::throwException(m_globalObject, scope, exception->localToJSValue());
m_globalInternals->setPendingException(exception->localToJSValue());
return exception;
}

Local<Value> Isolate::ThrowError(Local<String> 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<Value> handle = currentHandleScope()->createLocal<Value>(vm, error);
JSC::throwException(m_globalObject, scope, error);
return handle;
m_globalInternals->setPendingException(error);
return currentHandleScope()->createLocal<Value>(vm, error);
}

Isolate::Isolate(shim::GlobalInternals* globalInternals)
Expand Down
5 changes: 5 additions & 0 deletions src/jsc/bindings/v8/node.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down
6 changes: 6 additions & 0 deletions src/jsc/bindings/v8/shim/FunctionTemplate.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/jsc/bindings/v8/shim/GlobalInternals.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
11 changes: 11 additions & 0 deletions src/jsc/bindings/v8/shim/GlobalInternals.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::pair<Isolate::GCCallbackWithData, void*>>& gcPrologueCallbacks() { return m_gcPrologueCallbacks; }
WTF::Vector<std::pair<Isolate::GCCallbackWithData, void*>>& gcEpilogueCallbacks() { return m_gcEpilogueCallbacks; }
WTF::Vector<std::pair<NearHeapLimitCallback, void*>>& nearHeapLimitCallbacks() { return m_nearHeapLimitCallbacks; }
Expand Down Expand Up @@ -135,6 +145,7 @@ class GlobalInternals : public JSC::JSCell {
// HandleScopeBuffer::m_rawGrants (cells are swept without destructors).
WTF::Vector<TaggedPointer*> m_activeReturnValueSlots;
JSC::LazyProperty<GlobalInternals, HandleScopeBuffer> m_globalHandles;
JSC::WriteBarrier<JSC::Unknown> m_pendingException;

WTF::Vector<std::pair<Isolate::GCCallbackWithData, void*>> m_gcPrologueCallbacks;
WTF::Vector<std::pair<Isolate::GCCallbackWithData, void*>> m_gcEpilogueCallbacks;
Expand Down
14 changes: 11 additions & 3 deletions src/jsc/bindings/v8/shim/TemplateProperty.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -104,11 +104,19 @@ static JSC::JSValue invokeAccessor(
frame[Info::kValueIndex] = valueLocal.tagged();
const auto& info = *reinterpret_cast<const PropertyCallbackInfo<void>*>(&frame[Info::kPropertyKeyIndex]);
setter(property, valueLocal, info);
return JSC::jsUndefined();
} else {
const auto& info = *reinterpret_cast<const Info*>(&frame[Info::kPropertyKeyIndex]);
getter(property, info);
}

const auto& info = *reinterpret_cast<const Info*>(&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()) {
Expand Down
38 changes: 24 additions & 14 deletions src/runtime/napi/napi_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`).
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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()
Expand All @@ -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);
Expand Down Expand Up @@ -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();
Expand All @@ -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()
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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();
Expand All @@ -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()
Expand Down Expand Up @@ -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.
Expand All @@ -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()
Expand Down Expand Up @@ -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()
}
Expand All @@ -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()
}
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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()
}
Expand All @@ -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()
}
Expand Down
4 changes: 4 additions & 0 deletions test/napi/napi-app/binding.gyp
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand Down
Loading
Loading