From 528d48f6bb8ab2009f8a4f6a357109ad4100e7fc Mon Sep 17 00:00:00 2001 From: ldm0 Date: Sun, 8 Nov 2026 02:05:49 +0800 Subject: [PATCH] fix(events): convert beforeunload results inside callback contexts Keep nullable DOMString return conversion within the callback relevant and incumbent contexts, before callback cleanup can run microtasks. Preserve window.event throughout conversion and report conversion exceptions after cleanup. Cover bound native postMessage calls from child callbacks, conversion/microtask order, and error identity and reporting order. --- moli-renderer-v8/src/callback_invocation.rs | 37 +++++- moli-renderer-v8/src/host/events.rs | 77 +++++------ .../tests/browser_api/event_handlers.rs | 1 + .../event_handlers/beforeunload_return.rs | 123 ++++++++++++++++++ 4 files changed, 200 insertions(+), 38 deletions(-) create mode 100644 moli-renderer-v8/src/script_vm/tests/browser_api/event_handlers/beforeunload_return.rs diff --git a/moli-renderer-v8/src/callback_invocation.rs b/moli-renderer-v8/src/callback_invocation.rs index 46c40bb84bf..22c36113f81 100644 --- a/moli-renderer-v8/src/callback_invocation.rs +++ b/moli-renderer-v8/src/callback_invocation.rs @@ -219,6 +219,7 @@ impl CallbackInvoker { log_level, callback_name, invocation, + |_scope, value| CallbackInvocationOutcome::Returned(value), |_scope, outcome| outcome, ) } @@ -239,6 +240,35 @@ impl CallbackInvoker { log_level, callback_name, invocation, + |_scope, value| CallbackInvocationOutcome::Returned(value), + complete, + ) + } + + /// Converts the Web IDL return value before leaving the callback's + /// relevant/incumbent contexts and before its cleanup checkpoint. + #[allow(clippy::too_many_arguments)] + pub(crate) fn invoke_event_and_convert<'s, R>( + scope: &mut v8::PinScope<'s, '_>, + callback_kind: &str, + log_label: &str, + log_level: CallbackExceptionLogLevel, + callback_name: &str, + invocation: CallbackInvocation<'s, '_>, + convert_return: impl FnOnce( + &mut v8::PinScope<'s, '_>, + v8::Global, + ) -> CallbackInvocationOutcome, + complete: impl FnOnce(&mut v8::PinScope<'s, '_>, CallbackInvocationOutcome) -> R, + ) -> R { + Self::invoke_with_completion( + scope, + callback_kind, + log_label, + log_level, + callback_name, + invocation, + convert_return, complete, ) } @@ -251,6 +281,10 @@ impl CallbackInvoker { log_level: CallbackExceptionLogLevel, callback_name: &str, invocation: CallbackInvocation<'s, '_>, + convert_return: impl FnOnce( + &mut v8::PinScope<'s, '_>, + v8::Global, + ) -> CallbackInvocationOutcome, complete: impl FnOnce(&mut v8::PinScope<'s, '_>, CallbackInvocationOutcome) -> R, ) -> R { if let Some(host_ptr) = invocation.host_ptr { @@ -340,6 +374,7 @@ impl CallbackInvoker { receiver, arguments, ) + .map(|value| convert_return(scope, value)) }, |scope, failure| { capture_callback_resolution_failure( @@ -363,7 +398,7 @@ impl CallbackInvoker { crate::script_cleanup::perform_callback_cleanup_checkpoint(scope); let outcome = match result { - Ok(value) => CallbackInvocationOutcome::Returned(value), + Ok(outcome) => outcome, Err(report) => CallbackInvocationOutcome::Threw(report), }; let completed = complete(scope, outcome); diff --git a/moli-renderer-v8/src/host/events.rs b/moli-renderer-v8/src/host/events.rs index 69c0afc547a..5c45ac99871 100644 --- a/moli-renderer-v8/src/host/events.rs +++ b/moli-renderer-v8/src/host/events.rs @@ -522,55 +522,23 @@ pub(crate) fn invoke_prepared_before_unload_event_handler<'s>( (!invocation_target_in_shadow_tree).then_some(view.event), ) .with_execution_context_currentness(callback_host, relevant_identity); - CallbackInvoker::invoke_event_and_then( + CallbackInvoker::invoke_event_and_convert( scope, "event listener", "host event listener threw", crate::exception_reporting::CallbackExceptionLogLevel::Debug, callback_name, invocation, + convert_before_unload_event_handler_result, |scope, outcome| match outcome { CallbackInvocationOutcome::Returned(value) => { let value = v8::Local::new(scope, value); if value.is_null_or_undefined() { return; } - let conversion_report = { - let try_catch = std::pin::pin!(v8::TryCatch::new(scope)); - let mut conversion_scope = try_catch.init(); - match value.to_string(&conversion_scope) { - Some(value) => { - apply_before_unload_event_handler_return_value( - &mut conversion_scope, - event, - value, - ); - None - } - None if conversion_scope.has_caught() => { - let exception = conversion_scope.exception(); - let message = conversion_scope.message(); - let stack_trace = conversion_scope.stack_trace(); - Some(build_event_handler_exception_report( - &mut conversion_scope, - exception, - message, - stack_trace, - )) - } - None => None, - } - }; - if let Some(report) = conversion_report { - report_event_callback_exception( - scope, - callback_host, - event_type, - relevant_identity, - None, - &report, - ); - } + let value = v8::Local::::try_from(value) + .expect("the beforeunload callback result was converted to DOMString"); + apply_before_unload_event_handler_return_value(scope, event, value); } CallbackInvocationOutcome::Threw(report) => { report_event_callback_exception( @@ -587,6 +555,41 @@ pub(crate) fn invoke_prepared_before_unload_event_handler<'s>( ); } +fn convert_before_unload_event_handler_result<'s>( + scope: &mut v8::PinScope<'s, '_>, + value: v8::Global, +) -> CallbackInvocationOutcome { + let local = v8::Local::new(scope, &value); + if local.is_null_or_undefined() { + return CallbackInvocationOutcome::Returned(value); + } + let try_catch = std::pin::pin!(v8::TryCatch::new(scope)); + let mut scope = try_catch.init(); + match local.to_string(&scope) { + Some(value) => { + let value: v8::Local = value.into(); + CallbackInvocationOutcome::Returned(v8::Global::new(&scope, value)) + } + None if scope.has_caught() => { + let exception = scope.exception(); + let message = scope.message(); + let stack_trace = scope.stack_trace(); + CallbackInvocationOutcome::Threw(Box::new(build_event_handler_exception_report( + &mut scope, + exception, + message, + stack_trace, + ))) + } + None => { + // A terminated conversion has no nullable DOMString to apply. + // Leave termination reporting to the execution owner. + let value: v8::Local = v8::undefined(&scope).into(); + CallbackInvocationOutcome::Returned(v8::Global::new(&scope, value)) + } + } +} + fn invoke_event_handler_property<'s>( registry: &mut HostEventTargetRegistry, scope: &mut v8::PinScope<'s, '_>, diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/event_handlers.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/event_handlers.rs index 0be6ca09031..4579920f108 100644 --- a/moli-renderer-v8/src/script_vm/tests/browser_api/event_handlers.rs +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/event_handlers.rs @@ -1,5 +1,6 @@ use super::*; +mod beforeunload_return; mod child_window; mod compilation; mod csp_admission; diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/event_handlers/beforeunload_return.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/event_handlers/beforeunload_return.rs new file mode 100644 index 00000000000..ea0c777151d --- /dev/null +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/event_handlers/beforeunload_return.rs @@ -0,0 +1,123 @@ +use super::*; + +#[tokio::test(flavor = "current_thread")] +async fn beforeunload_return_conversion_keeps_the_callback_incumbent() { + let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap(); + for registration in ["attribute", "idl"] { + let mut vm = + new_storage_page_task_executor_test_vm("https://beforeunload-return-incumbent.test/"); + vm.eval( + r#" +const root = document.documentElement || document.appendChild(document.createElement('html')); +const body = document.body || root.appendChild(document.createElement('body')); +globalThis.frameLoaded = false; +const frame = document.createElement('iframe'); +frame.onload = () => { frameLoaded = true; }; +body.appendChild(frame); +"#, + ) + .unwrap(); + advance_page_task_executor_until_eval_equals( + &mut vm, + &loader, + "String(frameLoaded)", + "true", + "finish the child's initial document load before registering callbacks", + ) + .await; + vm.eval(&format!( + r#" +const child = frame.contentWindow; +child.name = 'iframe'; +child.__callbackCalls = 0; +globalThis.messages = []; +addEventListener('message', event => messages.push([ + event.data, event.source === child, event.source === window, event.source.name +])); +if ('{registration}' === 'attribute') {{ + child.document.body.setAttribute('onbeforeunload', + "__callbackCalls++; return {{toString:parent.postMessage.bind(parent,'coerced','*')}};"); +}} else {{ + child.eval("onbeforeunload = () => {{ __callbackCalls++; return {{toString:parent.postMessage.bind(parent,'coerced','*')}}; }}"); +}} +child.dispatchEvent(new child.Event('beforeunload', {{cancelable:true}})); +"# + )) + .expect("invoke the child callback from a parent script"); + assert_eq!(vm.eval("String(child.__callbackCalls)").unwrap(), "1"); + advance_page_task_executor_until_eval_equals( + &mut vm, + &loader, + "String(messages.length)", + "1", + "deliver the message queued during return conversion", + ) + .await; + assert_eq!( + vm.eval("JSON.stringify(messages)").unwrap(), + r#"[["coerced",true,false,"iframe"]]"#, + "{registration}" + ); + } +} + +#[test] +fn beforeunload_return_conversion_precedes_callback_cleanup_microtasks() { + let mut vm = new_storage_test_vm("https://beforeunload-return-order.test/"); + vm.eval( + r#" +globalThis.steps = []; +onbeforeunload = event => { + globalThis.seenEvent = event; + steps.push('handler'); + queueMicrotask(() => steps.push(['microtask', window.event === event, event.returnValue])); + return {toString() { steps.push(['convert', window.event === event]); return 'leave'; }}; +}; +"#, + ) + .unwrap(); + vm.with_default_context_scope(|scope, _| { + let window = scope.get_current_context().global(scope); + crate::context_bootstrap::dispatch_beforeunload_for_runtime_owner(scope, window); + Ok(()) + }) + .unwrap(); + assert_eq!( + vm.eval("JSON.stringify({steps, value:seenEvent.returnValue, canceled:seenEvent.defaultPrevented})") + .unwrap(), + r#"{"steps":["handler",["convert",true],["microtask",true,""]],"value":"leave","canceled":true}"# + ); +} + +#[test] +fn beforeunload_conversion_exceptions_report_after_callback_cleanup() { + let mut vm = new_storage_test_vm("https://beforeunload-return-error.test/"); + vm.eval( + r#" +globalThis.steps = []; +const marker = new Error('conversion'); +addEventListener('error', event => { + steps.push(['error', event.error === marker, window.event === event]); + event.preventDefault(); +}); +onbeforeunload = event => { + globalThis.seenEvent = event; + steps.push('handler'); + queueMicrotask(() => steps.push('microtask')); + return {toString() { steps.push('convert'); throw marker; }}; +}; +"#, + ) + .unwrap(); + vm.with_default_context_scope(|scope, _| { + let window = scope.get_current_context().global(scope); + crate::context_bootstrap::dispatch_beforeunload_for_runtime_owner(scope, window); + Ok(()) + }) + .unwrap(); + assert_eq!( + vm.eval("JSON.stringify({steps, value:seenEvent.returnValue, canceled:seenEvent.defaultPrevented})") + .unwrap(), + r#"{"steps":["handler","convert","microtask",["error",true,true]],"value":"","canceled":false}"# + ); +}