From 5d3cd0de73c9dbdbfd43ab253d93130bb50335fc Mon Sep 17 00:00:00 2001 From: ldm0 Date: Fri, 23 Oct 2026 09:53:33 +0800 Subject: [PATCH] fix(webidl): classify DOMException through V8 native error hooks Register V8's API-wrapper error classifier for Window and worker isolates, using the existing native DOMException interface brand and inheritance. Keep Error.isError itself unchanged, including ordinary Error and Proxy classification and author getter avoidance. Allocate native exception data/failures through cached interface instance templates. Preserve sparse facade/host contexts with a cached API wrapper allocator and their existing declaration/prototype policy. Keep the data versus failure-stack boundary, native constructor path and wire format. Cover script/subclass/native/cloned exceptions, genuine and forged receivers, worker kinds, bare and retired cold contexts, and cross-realm behavior. Validation: cargo fmt --all; cargo clippy --workspace --all-targets --all-features -- -D warnings; cargo nextest run --no-fail-fast (23219 passed, 17 existing skips, 32 threads, no automatic retries). --- moli-renderer-v8/src/context_bootstrap.rs | 6 +- .../src/context_bootstrap/constructors.rs | 18 ++-- .../exposed_interfaces/install.rs | 1 + .../src/script_vm/document_isolate.rs | 1 + .../tests/extracted/child_documents.rs | 5 +- .../tests/native_exception_stack_capture.rs | 84 +++++++++++++++ moli-renderer-v8/src/worker/thread/isolate.rs | 1 + .../thread/tests/dom_exception_stacks.rs | 62 +++++++++++ .../tests/fixtures/native-error-brand.js | 78 ++++++++++++++ moli-webapi/src/dom_exception.rs | 101 ++++++++++++++---- .../dom_exception/overconstrained_error.rs | 5 +- moli-webapi/src/dom_exception/rtc_error.rs | 7 +- .../src/dom_exception/web_transport_error.rs | 7 +- moli-webapi/src/embedding.rs | 1 + moli-webapi/tests/value_objects.rs | 1 + vendor/v8-152.2.0/src/isolate.rs | 24 +++++ vendor/v8-152.2.0/src/isolate_ext.cc | 13 +++ vendor/v8-152.2.0/src/lib.rs | 1 + 18 files changed, 376 insertions(+), 40 deletions(-) create mode 100644 moli-renderer-v8/tests/fixtures/native-error-brand.js create mode 100644 vendor/v8-152.2.0/src/isolate_ext.cc diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs index e303394ac2c..739482e9962 100644 --- a/moli-renderer-v8/src/context_bootstrap.rs +++ b/moli-renderer-v8/src/context_bootstrap.rs @@ -351,9 +351,9 @@ pub(crate) use self::constructors::{ WebTransportErrorClonePayload, WebTransportErrorSource, build_dom_exception_object, build_quota_exceeded_error_object, build_rtc_sdp_error, build_web_transport_error, build_web_transport_error_from_clone_payload, dom_exception_clone_fields, - ensure_dom_implementation_singleton, new_dom_error_value, new_dom_exception_value, - new_most_derived_dom_exception_value, new_quota_exceeded_error_value, - quota_exceeded_error_clone_fields, throw_dom_exception_value, + ensure_dom_implementation_singleton, install_dom_exception_error_classifier, + new_dom_error_value, new_dom_exception_value, new_most_derived_dom_exception_value, + new_quota_exceeded_error_value, quota_exceeded_error_clone_fields, throw_dom_exception_value, web_transport_error_clone_payload_from_object, }; pub(crate) use self::css_stylesheet_runtime::{ diff --git a/moli-renderer-v8/src/context_bootstrap/constructors.rs b/moli-renderer-v8/src/context_bootstrap/constructors.rs index dcd7c21525c..7d75f7bf0e5 100644 --- a/moli-renderer-v8/src/context_bootstrap/constructors.rs +++ b/moli-renderer-v8/src/context_bootstrap/constructors.rs @@ -33,15 +33,15 @@ pub(super) use document_nodes::{ }; pub(crate) use dom_exception::{ WebTransportErrorClonePayload, WebTransportErrorSource, build_dom_exception_object, - build_overconstrained_error, build_quota_exceeded_error_object, - dom_error_constructor_callback, dom_exception_clone_fields, dom_exception_constructor_callback, - install_dom_exception_template_bindings, new_dom_error_value, - new_dom_exception_value, new_most_derived_dom_exception_value, new_quota_exceeded_error_value, - new_websocket_error_value, overconstrained_error_constructor_callback, - quota_exceeded_error_clone_fields, quota_exceeded_error_constructor_callback, - rtc_error_constructor_callback, throw_dom_exception_value, - web_transport_error_clone_payload_from_object, web_transport_error_constructor_callback, - websocket_error_close_info, + build_overconstrained_error, build_quota_exceeded_error_object, dom_error_constructor_callback, + dom_exception_clone_fields, dom_exception_constructor_callback, + install_dom_exception_error_classifier, install_dom_exception_template_bindings, + new_dom_error_value, new_dom_exception_value, new_most_derived_dom_exception_value, + new_quota_exceeded_error_value, new_websocket_error_value, + overconstrained_error_constructor_callback, quota_exceeded_error_clone_fields, + quota_exceeded_error_constructor_callback, rtc_error_constructor_callback, + throw_dom_exception_value, web_transport_error_clone_payload_from_object, + web_transport_error_constructor_callback, websocket_error_close_info, }; pub(crate) use dom_implementation::ensure_dom_implementation_singleton; pub(super) use dom_implementation::install_dom_implementation_template_bindings; diff --git a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/install.rs b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/install.rs index e3cd2ab6d2e..cbf0751efbc 100644 --- a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/install.rs +++ b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/install.rs @@ -295,6 +295,7 @@ pub(crate) fn capture_eager_intrinsic_interfaces<'s>( moli_webapi::install_realm_callbacks( scope, moli_webapi::RealmCallbacks { + new_interface_instance: Some(|scope, name| super::build_intrinsic_interface_instance(scope, name).ok()), call_function: Some(crate::util::call_script_visible_function), is_window_named_properties_object: Some(crate::context_bootstrap::window_template::is_window_named_properties_object), point_accessed: crate::context_bootstrap::svg_runtime::sync_svg_point_from_owner, diff --git a/moli-renderer-v8/src/script_vm/document_isolate.rs b/moli-renderer-v8/src/script_vm/document_isolate.rs index 78bfc57165e..31d787c67bd 100644 --- a/moli-renderer-v8/src/script_vm/document_isolate.rs +++ b/moli-renderer-v8/src/script_vm/document_isolate.rs @@ -926,6 +926,7 @@ impl RendererIsolateHolder { // Blink configures its main-thread isolates the same way; dedicated // workers keep V8's default and may use the blocking operation. let mut isolate = v8::Isolate::new(v8::CreateParams::default().allow_atomics_wait(false)); + crate::context_bootstrap::install_dom_exception_error_classifier(&mut isolate); if timing_enabled { tracing::info!( target: "moli_cdp_nav_timing", diff --git a/moli-renderer-v8/src/script_vm/tests/extracted/child_documents.rs b/moli-renderer-v8/src/script_vm/tests/extracted/child_documents.rs index ec940b36317..9a077b4390f 100644 --- a/moli-renderer-v8/src/script_vm/tests/extracted/child_documents.rs +++ b/moli-renderer-v8/src/script_vm/tests/extracted/child_documents.rs @@ -469,14 +469,15 @@ async fn child_navigation_retires_local_window_owned_xhr() { error.code, Object.getPrototypeOf(error) === __getRetiredChildXhrExceptionPrototype(), Object.getPrototypeOf(Object.getPrototypeOf(error)) === __retiredChildErrorPrototype, - !(error instanceof DOMException) + !(error instanceof DOMException), + Error.isError(error) ].join("|"); } })() "#, ) .expect("calling open on a retained old-child XHR wrapper should fail closed"); - assert_eq!(stale_open, "InvalidStateError|11|true|true|true"); + assert_eq!(stale_open, "InvalidStateError|11|true|true|true|true"); assert!( vm._context_host .borrow() diff --git a/moli-renderer-v8/src/script_vm/tests/native_exception_stack_capture.rs b/moli-renderer-v8/src/script_vm/tests/native_exception_stack_capture.rs index f9d9e045920..b9fc7d4ba04 100644 --- a/moli-renderer-v8/src/script_vm/tests/native_exception_stack_capture.rs +++ b/moli-renderer-v8/src/script_vm/tests/native_exception_stack_capture.rs @@ -1,5 +1,89 @@ use super::*; +#[test] +fn native_exception_constructors_and_factories_use_v8_api_wrappers() { + let mut vm = new_storage_test_vm("https://native-error-wrapper.test/"); + vm.eval( + r#"(() => { + let failure; + try { structuredClone(Symbol()); } catch(error) { failure = error; } + globalThis.nativeErrorWrappers = [ + new DOMException('message'), new QuotaExceededError('full'), + new WebSocketError('closed'), new RTCError({errorDetail:'dtls-failure'}), + new OverconstrainedError('width'), new WebTransportError(), failure, + structuredClone(new DOMException('copy')), structuredClone(new QuotaExceededError('copy')) + ]; + })()"#, + ) + .unwrap(); + let context_ptr = &vm.current_main_world().unwrap().context as *const _; + vm.with_context_scope_by_ptr_and_checkpoint_for_test(context_ptr, |scope, _| { + let global = scope.get_current_context().global(scope); + let key = crate::util::v8str(scope, "nativeErrorWrappers"); + let values = + v8::Local::::try_from(global.get(scope, key.into()).unwrap()).unwrap(); + let mut wrappers = Vec::new(); + for index in 0..values.length() { + let object = + v8::Local::::try_from(values.get_index(scope, index).unwrap()).unwrap(); + wrappers.push(object.is_api_wrapper()); + } + assert_eq!(wrappers, vec![true; 9]); + + // Native facade/host contexts can throw without a full interface registry. + let bare = v8::Context::new(scope, Default::default()); + let scope = &mut v8::ContextScope::new(scope, bare); + let fallback = crate::context_bootstrap::build_dom_exception_object( + scope, + "standalone host failure", + "DataCloneError", + ); + assert!(fallback.is_api_wrapper()); + let key = crate::util::v8str(scope, "nativeFallbackException"); + let global = bare.global(scope); + assert_eq!( + global.create_data_property(scope, key.into(), fallback.into()), + Some(true) + ); + let source = crate::util::v8str(scope, "Error.isError(nativeFallbackException)"); + let script = v8::Script::compile(scope, source, None).unwrap(); + assert!( + crate::script_execution::execute_compiled_script(scope, script) + .unwrap() + .is_true() + ); + Ok(()) + }) + .unwrap(); +} + +#[test] +fn native_error_brand_uses_v8_classification_across_window_realms() { + let mut vm = new_parsed_test_vm( + "https://native-error-brand.test/", + "", + ); + let result = vm + .eval(&format!( + r#"(() => {{ + {fixture} + const child = document.body.appendChild(document.createElement('iframe')).contentWindow; + return JSON.stringify({{main:nativeErrorBrandProbe(window),child:nativeErrorBrandProbe(child)}}); + }})()"#, + fixture = include_str!("../../../tests/fixtures/native-error-brand.js"), + )) + .expect("native Error.isError probe should complete"); + let result: serde_json::Value = serde_json::from_str(&result).unwrap(); + for realm in ["main", "child"] { + assert_eq!(result[realm]["failures"], serde_json::json!([]), "{result}"); + assert_eq!( + result[realm]["rows"].as_array().unwrap().len(), + 84, + "{result}" + ); + } +} + #[test] fn native_exception_stacks_ignore_mutated_javascript_capture_helpers() { let mut vm = new_parsed_test_vm( diff --git a/moli-renderer-v8/src/worker/thread/isolate.rs b/moli-renderer-v8/src/worker/thread/isolate.rs index 72d0e8e765a..dc7e70e4a11 100644 --- a/moli-renderer-v8/src/worker/thread/isolate.rs +++ b/moli-renderer-v8/src/worker/thread/isolate.rs @@ -33,6 +33,7 @@ impl WorkerIsolateState { debugger_enabled: bool, ) -> Self { let mut isolate = v8::Isolate::new(Default::default()); + crate::context_bootstrap::install_dom_exception_error_classifier(&mut isolate); crate::context_bootstrap::install_agent_microtask_checkpoint_tasks(&mut isolate); isolate.set_microtasks_policy(v8::MicrotasksPolicy::Explicit); isolate.set_capture_stack_trace_for_uncaught_exceptions(true, 32); diff --git a/moli-renderer-v8/src/worker/thread/tests/dom_exception_stacks.rs b/moli-renderer-v8/src/worker/thread/tests/dom_exception_stacks.rs index 72eb4c35365..17dd45c321a 100644 --- a/moli-renderer-v8/src/worker/thread/tests/dom_exception_stacks.rs +++ b/moli-renderer-v8/src/worker/thread/tests/dom_exception_stacks.rs @@ -1,5 +1,67 @@ use super::*; +#[tokio::test] +async fn native_error_brand_uses_v8_classification_across_worker_kinds() { + ensure_v8(); + let storage_key = moli_storage_key::MoliStorageKey::new( + "https://native-error-brand.test".to_owned(), + "https://native-error-brand.test".to_owned(), + None, + moli_storage_key::StoragePartitionRelation::FirstParty, + ); + for (kind, script_kind) in [ + ( + super::super::WorkerGlobalKind::Dedicated { + name: String::new(), + }, + WorkerScriptKind::Classic, + ), + ( + super::super::WorkerGlobalKind::Dedicated { + name: String::new(), + }, + WorkerScriptKind::Module, + ), + ( + super::super::WorkerGlobalKind::Shared { + name: "errors".to_owned(), + storage_key, + }, + WorkerScriptKind::Classic, + ), + ( + super::super::WorkerGlobalKind::Service { + registration_id: ServiceWorkerRegistrationId::from_u64_for_test(1), + version_id: ServiceWorkerVersionId::from_u64_for_test(1), + scope_url: url::Url::parse("https://native-error-brand.test/").unwrap(), + }, + WorkerScriptKind::Classic, + ), + ] { + let source = format!( + "{}\nconsole.log(JSON.stringify(nativeErrorBrandProbe(globalThis)));", + include_str!("../../../../tests/fixtures/native-error-brand.js"), + ); + let mut handle = spawn_test_worker_with_options( + WorkerSpawnOptions::new( + source, + "https://native-error-brand.test/worker.js".to_owned(), + ) + .with_global_kind(kind) + .with_script_kind(script_kind), + ); + let message = timeout(TIMEOUT, handle.recv()).await.unwrap().unwrap(); + handle.terminate_and_join(); + let WorkerToParentMessage::Console(console) = message else { + panic!("expected completed native error brand checks, got {message:?}"); + }; + let result: serde_json::Value = + serde_json::from_str(console.message.strip_prefix("log: ").unwrap()).unwrap(); + assert_eq!(result["failures"], serde_json::json!([]), "{result}"); + assert_eq!(result["rows"].as_array().unwrap().len(), 64, "{result}"); + } +} + #[tokio::test] async fn worker_dom_exception_data_and_native_failures_have_distinct_stack_boundaries() { ensure_v8(); diff --git a/moli-renderer-v8/tests/fixtures/native-error-brand.js b/moli-renderer-v8/tests/fixtures/native-error-brand.js new file mode 100644 index 00000000000..96cad5c5ec7 --- /dev/null +++ b/moli-renderer-v8/tests/fixtures/native-error-brand.js @@ -0,0 +1,78 @@ +function nativeErrorBrandProbe(realm) { + const rows = [], failures = []; + const check = (name, actual, expected = true) => { + rows.push({name, actual}); + if (actual !== expected) failures.push({name, actual, expected}); + }; + const isError = realm.Error.isError, DOM = realm.DOMException; + check('intrinsic metadata', isError.name === 'isError' && isError.length === 1 && /\[native code\]/.test(realm.Function.prototype.toString.call(isError))); + const entries = [ + ['DOMException', ['message','AbortError']], + ['QuotaExceededError', ['full',{quota:0,requested:12.5}]], + ['WebSocketError', ['closed']], + ['WebTransportError', []], + ]; + if (realm.document) entries.push(['RTCError',[{errorDetail:'dtls-failure'}]],['OverconstrainedError',['width']]); + let authorReads = 0; + const poison = () => { ++authorReads; throw new Error('author lookup'); }; + for (const [name,args] of entries) { + const Constructor = realm[name]; + check(name+': exposed constructor',typeof Constructor === 'function'); + if (typeof Constructor !== 'function') continue; + const value = Reflect.construct(Constructor,args); + check(name+': script-created native brand',isError(value)); + const Derived = class extends Constructor {}; + check(name+': genuine subclass',isError(Reflect.construct(Constructor,args,Derived))); + check(name+': forged prototype rejected',isError(Object.create(Constructor.prototype)),false); + check(name+': inherited native identity rejected',isError(Object.create(value)),false); + const proxy = new Proxy(value,{get:poison,getPrototypeOf:poison}); + check(name+': author Proxy rejected without traps',isError(proxy),false); + const revoked = Proxy.revocable(value,{}); revoked.revoke(); + check(name+': revoked Proxy rejected',isError(revoked.proxy),false); + Object.setPrototypeOf(value,null); + for (const property of ['name','message','stack','constructor']) Object.defineProperty(value,property,{get:poison}); + Object.defineProperty(value,Symbol.toStringTag,{get:poison}); + check(name+': classification uses only native identity',isError(value)); + check(name+': this value is irrelevant',isError.call(null,value)); + } + for (const [name,make] of [ + ['Error',()=>new realm.Error('ordinary')], + ['TypeError',()=>new realm.TypeError('ordinary')], + ['AggregateError',()=>new realm.AggregateError([])], + ['WebAssembly.CompileError',()=>new realm.WebAssembly.CompileError('ordinary')], + ]) { + const value=make(); + check(name+': V8 ordinary Error brand retained',isError(value)); + check(name+': Proxy does not acquire ErrorData',isError(new Proxy(value,{})),false); + } + for (const [name,value] of [ + ['global',realm], + ['null',null],['undefined',undefined],['number',1],['string','error'], + ['Object',{}],['Error.prototype',realm.Error.prototype], + ['DOMException.prototype',DOM.prototype],['Event',new realm.Event('test')], + ['URL',new realm.URL('https://native-error.test/')],['Blob',new realm.Blob([])], + ]) check(name+': not a native error',isError(value),false); + if (realm.document) { + check('Document is not an error',isError(realm.document),false); + check('Element is not an error',isError(realm.document.createElement('div')),false); + } + let native; + try {realm.structuredClone(Symbol());} catch(error) {native=error;} + check('API-created DOMException',isError(native)); + const copy = realm.structuredClone(native); + check('cloned API-created exception',isError(copy)); + check('cloned API-created exception has data without a stack',copy instanceof DOM && copy.name === 'DataCloneError' && !Object.hasOwn(copy,'stack')); + const source = new DOM('message','AbortError'); + const cloned = realm.structuredClone([source,source]); + check('data clone preserves native brand and alias identity',isError(cloned[0]) && cloned[0] === cloned[1] && cloned[0] instanceof DOM); + const quota = realm.structuredClone(new realm.QuotaExceededError('full',{quota:0,requested:12.5})); + check('quota clone preserves native brand and data',isError(quota) && quota instanceof realm.QuotaExceededError && quota.quota === 0 && quota.requested === 12.5 && !Object.hasOwn(quota,'stack')); + const descriptor = Object.getOwnPropertyDescriptor(realm,'DOMException'); + try { + Object.defineProperty(realm,'DOMException',{configurable:true,get:poison}); + check('public constructor does not supply the brand',isError(source)); + check('public constructor does not brand forged objects',isError(Object.create(DOM.prototype)),false); + } finally {Object.defineProperty(realm,'DOMException',descriptor);} + check('author getters and traps were not observed',authorReads,0); + return {rows,failures}; +} diff --git a/moli-webapi/src/dom_exception.rs b/moli-webapi/src/dom_exception.rs index af31066d2e1..73d7b823fbb 100644 --- a/moli-webapi/src/dom_exception.rs +++ b/moli-webapi/src/dom_exception.rs @@ -16,7 +16,6 @@ pub use overconstrained_error::{ pub use rtc_error::{build_rtc_sdp_error, rtc_error_constructor_callback}; pub use web_transport_error::{ WebTransportErrorClonePayload, WebTransportErrorSource, build_web_transport_error, - build_web_transport_error_from_clone_payload, web_transport_error_clone_payload_from_object, web_transport_error_constructor_callback, }; @@ -31,6 +30,62 @@ const QUOTA_EXCEEDED_ERROR_REQUESTED_SLOT: &str = "__lmQuotaExceededErrorRequest const WEBSOCKET_ERROR_CLOSE_CODE_SLOT: &str = "__lmWebSocketErrorCloseCode"; const WEBSOCKET_ERROR_REASON_SLOT: &str = "__lmWebSocketErrorReason"; +pub fn install_dom_exception_error_classifier(isolate: &mut v8::Isolate) { + isolate.set_is_js_api_wrapper_native_error_callback(is_dom_exception_wrapper); +} + +unsafe extern "C" fn is_dom_exception_wrapper( + _isolate: *mut v8::RealIsolate, + object: v8::Local<'_, v8::Object>, +) -> bool { + // V8 has already excluded Proxies and ordinary JS objects. Read only the + // native interface identity; author properties and prototypes are irrelevant. + let scope = std::pin::pin!(unsafe { v8::CallbackScope::new(object) }); + let scope = &mut scope.init(); + web_api_interfaces::DOMException::is_instance(scope, object) +} + +fn build_dom_exception_instance<'s>( + scope: &mut v8::PinScope<'s, '_>, + interface: &str, +) -> Option> { + // Use the cached interface template without invoking its public constructor. + // A plain Object with a DOMException prototype cannot reach V8's native hook. + let prototype = global_constructor_prototype(scope, interface)?; + let callback = scope + .get_current_context() + .get_slot::() + .and_then(|callbacks| callbacks.new_interface_instance); + let object = callback + .and_then(|callback| callback(scope, interface)) + .unwrap_or_else(|| fallback_dom_exception_instance(scope)); + (object.set_prototype(scope, prototype.into()) == Some(true)).then_some(object) +} + +struct DomExceptionFallbackTemplate(v8::Global); + +fn bind_dom_exception_declaration<'s>( + scope: &mut v8::PinScope<'s, '_>, + interface: &str, + declaration: &impl moli_webapi_declare::WebApiObjectDeclaration<'s>, +) -> v8::Local<'s, v8::Object> { + if let Some(object) = build_dom_exception_instance(scope, interface) { + declaration + .initialize(scope, object) + .expect("native exception declaration should initialize"); + return object; + } + + // Facade and standalone host contexts may not register this interface. + // Preserve their declaration/prototype policy, but allocate an API wrapper + // so the same native error classifier can recognize the result. + let object = fallback_dom_exception_instance(scope); + declaration + .bind_into(scope, object) + .expect("native exception declaration should bind"); + object +} + #[derive(webidl::WebIdlArgs)] #[webidl(prefix = "DOMException")] struct DomExceptionConstructorArgs { @@ -534,22 +589,15 @@ fn websocket_error_declaration<'s>( /// Create exception data without inventing a construction or deserialization stack. pub fn build_dom_exception_object<'s>( - scope: &mut v8::PinScope<'s, '_>, message: &str, name: &str, ) -> v8::Local<'s, v8::Object> { - // The embedding resolver uses its canonical realm cache. It must not - // consult an author-controlled Window property, including after detach. - if let Some(prototype) = global_constructor_prototype(scope, "DOMException") { - let exception = v8::Object::new(scope); - initialize_dom_exception(scope, exception, message, name); - let _ = exception.set_prototype(scope, prototype.into()); - return exception; - } - dom_exception_declaration(scope, message, name) - .bind(scope) - .expect("DOMException declaration should bind") + // Retained native methods can throw after their WindowProxy is detached, + // before DOMException was first exposed in that realm. Use its intrinsic + // template/prototype rather than looking up the detached WindowProxy. + let declaration = dom_exception_declaration(scope, message, name); + bind_dom_exception_declaration(scope, "DOMException", &declaration) } pub fn new_dom_exception_value<'s>( @@ -690,9 +738,8 @@ pub fn build_quota_exceeded_error_object<'s>( quota: Option, requested: Option, ) -> v8::Local<'s, v8::Object> { - let exception = QuotaExceededErrorObjectDeclaration::new(v8_string(scope, message)) - .bind(scope) - .expect("QuotaExceededError declaration should bind"); + let declaration = QuotaExceededErrorObjectDeclaration::new(v8_string(scope, message)); + let exception = bind_dom_exception_declaration(scope, "QuotaExceededError", &declaration); QuotaExceededErrorOptions { quota, requested } .initialize_snapshot(scope, exception) .expect("QuotaExceededError options"); @@ -729,9 +776,8 @@ pub fn new_websocket_error_value<'s>( reason: &str, ) -> v8::Local<'s, v8::Value> { let message = v8_string(scope, message); - let exception = websocket_error_declaration(scope, message, close_code, reason) - .bind(scope) - .expect("WebSocketError declaration should bind"); + let declaration = websocket_error_declaration(scope, message, close_code, reason); + let exception = bind_dom_exception_declaration(scope, "WebSocketError", &declaration); capture_dom_exception_stack(scope, exception); exception.into() } @@ -758,3 +804,20 @@ pub fn websocket_error_close_info<'s>( .unwrap_or_default(); Some((close_code, reason)) } + +fn fallback_dom_exception_instance<'s>( + scope: &mut v8::PinScope<'s, '_>, +) -> v8::Local<'s, v8::Object> { + let template = if let Some(template) = scope.get_slot::() { + v8::Local::new(scope, &template.0) + } else { + let template = v8::ObjectTemplate::new(scope); + template.set_internal_field_count(1); + let cached = v8::Global::new(scope, template); + scope.set_slot(DomExceptionFallbackTemplate(cached)); + template + }; + template + .new_instance(scope) + .expect("native exception fallback instance should allocate") +} diff --git a/moli-webapi/src/dom_exception/overconstrained_error.rs b/moli-webapi/src/dom_exception/overconstrained_error.rs index 665ecfe1444..dc0ce727b47 100644 --- a/moli-webapi/src/dom_exception/overconstrained_error.rs +++ b/moli-webapi/src/dom_exception/overconstrained_error.rs @@ -87,8 +87,9 @@ pub fn build_overconstrained_error<'s>( constraint: &str, message: &str, ) -> Option> { - let object = ObjectDeclaration::new(v8_string(scope, constraint)?, v8_string(scope, message)?) - .bind(scope) + let object = build_dom_exception_instance(scope, "OverconstrainedError")?; + ObjectDeclaration::new(v8_string(scope, constraint)?, v8_string(scope, message)?) + .initialize(scope, object) .ok()?; capture_dom_exception_stack(scope, object); Some(object) diff --git a/moli-webapi/src/dom_exception/rtc_error.rs b/moli-webapi/src/dom_exception/rtc_error.rs index fde7fe23610..7b219b8788f 100644 --- a/moli-webapi/src/dom_exception/rtc_error.rs +++ b/moli-webapi/src/dom_exception/rtc_error.rs @@ -126,9 +126,7 @@ pub fn build_rtc_sdp_error<'s>( message: &str, line_number: i32, ) -> Option> { - let object = ObjectDeclaration::new(v8_string(scope, message)?) - .bind(scope) - .ok()?; + let object = build_dom_exception_instance(scope, "RTCError")?; ErrorInit { error_detail: ErrorDetail::SdpSyntaxError, received_alert: None, @@ -137,6 +135,9 @@ pub fn build_rtc_sdp_error<'s>( sent_alert: None, } .initialize_snapshot(scope, object)?; + ObjectDeclaration::new(v8_string(scope, message)?) + .initialize(scope, object) + .ok()?; capture_dom_exception_stack(scope, object); Some(object) diff --git a/moli-webapi/src/dom_exception/web_transport_error.rs b/moli-webapi/src/dom_exception/web_transport_error.rs index 5aada807c12..9a99c9ec9f0 100644 --- a/moli-webapi/src/dom_exception/web_transport_error.rs +++ b/moli-webapi/src/dom_exception/web_transport_error.rs @@ -159,8 +159,11 @@ pub fn build_web_transport_error_from_clone_payload<'s>( scope: &mut v8::PinScope<'s, '_>, payload: &WebTransportErrorClonePayload, ) -> Option> { - global_constructor_prototype(scope, "WebTransportError")?; - declaration(scope, payload)?.bind(scope).ok() + let object = build_dom_exception_instance(scope, "WebTransportError")?; + declaration(scope, payload)? + .initialize(scope, object) + .ok()?; + Some(object) } pub fn build_web_transport_error<'s>( diff --git a/moli-webapi/src/embedding.rs b/moli-webapi/src/embedding.rs index 804e90a9854..51b0b7874ee 100644 --- a/moli-webapi/src/embedding.rs +++ b/moli-webapi/src/embedding.rs @@ -14,6 +14,7 @@ pub type WebIdlCallbackInvocation<'s> = for<'i> fn( /// Bridges value bindings to the embedder without retaining its host or V8 handles. /// Callbacks execute in the current (callee) realm, including for borrowed methods. pub struct RealmCallbacks { + pub new_interface_instance: Option fn(&mut v8::PinScope<'s, 'i>, &str) -> Option>>, pub call_function: Option fn(&mut v8::PinScope<'s, 'i>, v8::Local<'s, v8::Function>, v8::Local<'s, v8::Value>, &[v8::Local<'s, v8::Value>], &str) -> Option>>, pub is_window_named_properties_object: Option fn(&mut v8::PinScope<'s, 'i>, v8::Local<'s, v8::Object>) -> bool>, /// Synchronizes a live SVG point from its owner before reading or writing it. diff --git a/moli-webapi/tests/value_objects.rs b/moli-webapi/tests/value_objects.rs index f359351c0ac..90d01bd0313 100644 --- a/moli-webapi/tests/value_objects.rs +++ b/moli-webapi/tests/value_objects.rs @@ -114,6 +114,7 @@ fn install_values( install_realm_callbacks( scope, RealmCallbacks { + new_interface_instance: None, call_function: None, is_window_named_properties_object: None, point_accessed: |_, _| {}, diff --git a/vendor/v8-152.2.0/src/isolate.rs b/vendor/v8-152.2.0/src/isolate.rs index 92c556ec444..c3306c3488b 100644 --- a/vendor/v8-152.2.0/src/isolate.rs +++ b/vendor/v8-152.2.0/src/isolate.rs @@ -99,6 +99,11 @@ pub enum AccessType { pub type FailedAccessCheckCallback = unsafe extern "C" fn(Local, AccessType, Local); +/// Classifies API wrappers for V8's native `Error.isError` implementation. +/// The callback must not invoke JavaScript or throw an exception. +pub type IsJSApiWrapperNativeErrorCallback = + unsafe extern "C" fn(*mut RealIsolate, Local) -> bool; + /// Memory pressure level for the MemoryPressureNotification. /// None hints V8 that there is no memory pressure. /// Moderate hints V8 to speed up incremental garbage collection at the cost @@ -836,6 +841,10 @@ unsafe extern "C" { isolate: *mut RealIsolate, callback: FailedAccessCheckCallback, ); + fn v8__Isolate__SetIsJSApiWrapperNativeErrorCallback( + isolate: *mut RealIsolate, + callback: IsJSApiWrapperNativeErrorCallback, + ); fn v8__Isolate__RequestInterrupt( isolate: *const RealIsolate, callback: InterruptCallback, @@ -922,6 +931,21 @@ impl UnsafeRawIsolatePtr { pub struct RealIsolate(Opaque); impl Isolate { + /// Installs the embedder's native error classifier for API wrappers. + /// Ordinary JavaScript errors and Proxies remain classified by V8 itself. + #[inline(always)] + pub fn set_is_js_api_wrapper_native_error_callback( + &mut self, + callback: IsJSApiWrapperNativeErrorCallback, + ) { + unsafe { + v8__Isolate__SetIsJSApiWrapperNativeErrorCallback( + self.as_real_ptr(), + callback, + ) + } + } + /// Installs the callback invoked when an object access check fails and no /// failed-access interceptor handles the operation. #[inline(always)] diff --git a/vendor/v8-152.2.0/src/isolate_ext.cc b/vendor/v8-152.2.0/src/isolate_ext.cc new file mode 100644 index 00000000000..0cc346c9664 --- /dev/null +++ b/vendor/v8-152.2.0/src/isolate_ext.cc @@ -0,0 +1,13 @@ +// Copyright 2026 the Moli authors. MIT license. + +#include "v8-callbacks.h" +#include "v8-isolate.h" + +extern "C" { + +void v8__Isolate__SetIsJSApiWrapperNativeErrorCallback( + v8::Isolate* isolate, v8::IsJSApiWrapperNativeErrorCallback callback) { + isolate->SetIsJSApiWrapperNativeErrorCallback(callback); +} + +} // extern "C" diff --git a/vendor/v8-152.2.0/src/lib.rs b/vendor/v8-152.2.0/src/lib.rs index 338ec1c2726..2cf55248657 100644 --- a/vendor/v8-152.2.0/src/lib.rs +++ b/vendor/v8-152.2.0/src/lib.rs @@ -124,6 +124,7 @@ pub use isolate::IntoSharedError; pub use isolate::IntoSharedErrorKind; pub use isolate::Isolate; pub use isolate::IsolateHandle; +pub use isolate::IsJSApiWrapperNativeErrorCallback; pub use isolate::MemoryPressureLevel; pub use isolate::MessageCallback; pub use isolate::MessageErrorLevel;