Truly independent web browser
LibWeb/Bindings: Let Rust task steps enter their own execution context
Shannon Booth82db77edbb79
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rsindex eeb31397675..b907bc545d2 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs@@ -37,18 +37,9 @@ unsafe extern "C" {steps: unsafe extern "C" fn(*mut c_void, *mut c_void),);- /// Queues a task on the task source, an HTML::Task::Source, that calls the steps with the VM and the cell while an- /// execution context of the realm is on the stack, as HTML::queue_a_task() queues one without a document. The- /// cell lives until then.+ /// Queues a task on the task source, an HTML::Task::Source, that calls the steps with the VM and the cell, as+ /// HTML::queue_a_task() queues one without a document. The cell lives until then.fn web_bindings_queue_a_task(- realm: *mut c_void,- task_source: u8,- cell: *mut c_void,- steps: unsafe extern "C" fn(*mut c_void, *mut c_void),- );-- /// Queues a task on the task source as web_bindings_queue_a_task() does, but with no execution context on the stack.- fn web_bindings_queue_a_task_without_execution_context(task_source: u8,cell: *mut c_void,steps: unsafe extern "C" fn(*mut c_void, *mut c_void),@@ -620,23 +611,8 @@ pub(crate) fn in_parallel<C: Trace + Copy + 'static>(vm: &Vm, realm: Gc<Realm>,unsafe { web_bindings_run_in_parallel(realm.as_ptr().cast(), cell, run_pending_steps) };}-/// Queues a task on the task source that performs the steps with the captures,/// https://html.spec.whatwg.org/multipage/webappapis.html#queue-a-task-pub(crate) fn queue_a_task<C: Trace + Copy + 'static>(- vm: &Vm,- realm: Gc<Realm>,- task_source: TaskSource,- captures: C,- steps: fn(&Vm, C),-) {- let cell = pending_steps(vm, captures, steps);- // SAFETY: The realm and the cell are live.- unsafe { web_bindings_queue_a_task(realm.as_ptr().cast(), task_source as u8, cell, run_pending_steps) };-}--/// Queues a task on the task source that performs the steps with the captures, as queue_a_task() does, but with no-/// execution context of its own on the stack, https://html.spec.whatwg.org/multipage/webappapis.html#queue-a-task-pub(crate) fn queue_a_task_without_execution_context<C: Trace + Clone + 'static>(+pub(crate) fn queue_a_task<C: Trace + Clone + 'static>(vm: &Vm,task_source: TaskSource,captures: C,@@ -644,11 +620,11 @@ pub(crate) fn queue_a_task_without_execution_context<C: Trace + Clone + 'static>) {let cell = pending_steps(vm, captures, steps);// SAFETY: The cell is live.- unsafe { web_bindings_queue_a_task_without_execution_context(task_source as u8, cell, run_pending_steps) };+ unsafe { web_bindings_queue_a_task(task_source as u8, cell, run_pending_steps) };}/// Queues a global task on the task source, given the global object, that performs the steps with the captures,-/// https://html.spec.whatwg.org/multipage/webappapis.html#queue-a-global-task. Unlike queue_a_task(), the steps run+/// https://html.spec.whatwg.org/multipage/webappapis.html#queue-a-global-task. As with queue_a_task(), the steps run/// with no execution context of their own on the stack.pub(crate) fn queue_a_global_task<C: Trace + Clone + 'static>(vm: &Vm,diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/font_face_set.rs b/Libraries/LibWeb/Bindings/Rust/src/css/font_face_set.rsindex f939fd0f379..839f9001838 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/font_face_set.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/font_face_set.rs@@ -733,8 +733,10 @@ impl FontFaceSet {}// 4. Queue a task to fire a font load event named loading at font face set.- queue_a_task(vm, self.realm, TaskSource::FontLoading, self.this(), |vm, this| {- this.fire_a_font_load_event(vm, "loading", &MarkedVec::new(vm));+ queue_a_task(vm, TaskSource::FontLoading, self.this(), |vm, this| {+ with_temporary_execution_context_and_callbacks(this.realm, || {+ this.fire_a_font_load_event(vm, "loading", &MarkedVec::new(vm));+ });});}@@ -773,21 +775,23 @@ impl FontFaceSet {}// 5. Queue a task to perform the following steps synchronously:- queue_a_task(vm, realm, TaskSource::FontLoading, self.this(), |vm, this| {- // 1. Let loaded fonts be the (possibly empty) contents of font face set’s [[LoadedFonts]] slot.- // 2. Let failed fonts be the (possibly empty) contents of font face set’s [[FailedFonts]] slot.- // 3. Reset the [[LoadedFonts]] and [[FailedFonts]] slots to empty lists.- let loaded_fonts = take_font_faces(vm, &this.loaded_fonts);- let failed_fonts = take_font_faces(vm, &this.failed_fonts);-- // 4. Fire a font load event named loadingdone at font face set with loaded fonts.- this.fire_a_font_load_event(vm, "loadingdone", &loaded_fonts);-- // 5. If font face set’s failed fonts is non-empty, fire a font load event named loadingerror at font face- // set with failed fonts.- if !failed_fonts.is_empty() {- this.fire_a_font_load_event(vm, "loadingerror", &failed_fonts);- }+ queue_a_task(vm, TaskSource::FontLoading, self.this(), |vm, this| {+ with_temporary_execution_context_and_callbacks(this.realm, || {+ // 1. Let loaded fonts be the (possibly empty) contents of font face set’s [[LoadedFonts]] slot.+ // 2. Let failed fonts be the (possibly empty) contents of font face set’s [[FailedFonts]] slot.+ // 3. Reset the [[LoadedFonts]] and [[FailedFonts]] slots to empty lists.+ let loaded_fonts = take_font_faces(vm, &this.loaded_fonts);+ let failed_fonts = take_font_faces(vm, &this.failed_fonts);++ // 4. Fire a font load event named loadingdone at font face set with loaded fonts.+ this.fire_a_font_load_event(vm, "loadingdone", &loaded_fonts);++ // 5. If font face set’s failed fonts is non-empty, fire a font load event named loadingerror at font face+ // set with failed fonts.+ if !failed_fonts.is_empty() {+ this.fire_a_font_load_event(vm, "loadingerror", &failed_fonts);+ }+ });});}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/geolocation/geolocation.rs b/Libraries/LibWeb/Bindings/Rust/src/geolocation/geolocation.rsindex 756fa0d4302..7ef1c1eb695 100644--- a/Libraries/LibWeb/Bindings/Rust/src/geolocation/geolocation.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/geolocation/geolocation.rs@@ -22,7 +22,7 @@ use crate::bindings::global_object::CppWindow;use crate::bindings::interface::{Ref, Wrappable, allocate, cell_from_abi, cell_into_abi, with_temporary_execution_context, wrap,};-use crate::bindings::promise::{TaskSource, deferred_invoke, queue_a_task_without_execution_context};+use crate::bindings::promise::{TaskSource, deferred_invoke, queue_a_task};use crate::bindings::{CallContext, WebIdlResult};use crate::dom::document::{CppDocument, WeakCppDocument};use crate::geolocation::geolocation_coordinates::{CoordinatesData, GeolocationCoordinates};@@ -196,7 +196,7 @@ impl Geolocation {}fn queue_success_callback(&self, vm: &Vm, callback: CallbackFunction, position: Ref<GeolocationPosition>) {- queue_a_task_without_execution_context(+ queue_a_task(vm,TaskSource::Geolocation,(callback, position),@@ -787,7 +787,7 @@ impl Geolocation {let error = GeolocationPositionError::create(vm, code);// 3. Queue a task on the geolocation task source with a step that invokes callback with « error » and "report".- queue_a_task_without_execution_context(+ queue_a_task(vm,TaskSource::Geolocation,(callback, error),diff --git a/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/performance_timeline.rs b/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/performance_timeline.rsindex d5c6bf33a49..2a8d9929e33 100644--- a/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/performance_timeline.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/performance_timeline.rs@@ -428,15 +428,11 @@ impl PerformanceTimeline {self.resource_timing_buffer_full_event_pending.set(true);// b. Queue a task on the performance timeline task source to run fire a buffer full event.- queue_a_task(- vm,- self.realm,- TaskSource::PerformanceTimeline,- self.realm,- |vm, realm| {+ queue_a_task(vm, TaskSource::PerformanceTimeline, self.realm, |vm, realm| {+ with_temporary_execution_context_and_callbacks(realm, || {Self::of(vm, realm).fire_resource_timing_buffer_full_event(vm);- },- );+ });+ });}// 3. Add new entry to the resource timing secondary buffer.diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/web_assembly.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/web_assembly.rsindex 128df518040..b62f096780b 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/web_assembly.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/web_assembly.rs@@ -21,7 +21,7 @@ use libjs_rust::api::{#[cfg(web_idl_bindings)]use crate::bindings::conversions::ToJs;use crate::bindings::conversions::{BufferSource, UsvString};-use crate::bindings::interface::{Ref, allocate, wrap};+use crate::bindings::interface::{Ref, allocate, with_temporary_execution_context_and_callbacks, wrap};use crate::bindings::promise::{TaskSource, WebIdlPromise, create_promise, in_parallel, queue_a_task, react_to_promise, reject_promise,resolve_promise,@@ -123,55 +123,56 @@ fn asynchronously_compile_a_webassembly_module(*job.result.borrow_mut() = Some(result);// 2. Queue a task on taskSource, if provided, to perform the following steps:- queue_a_task(vm, realm, task_source, (promise, job), |vm, (promise, job)| {+ queue_a_task(vm, task_source, (promise, job), |vm, (promise, job)| {let realm = crate::bindings::promise::promise_realm(promise);-- // 1. If module is error, reject promise with a CompileError exception and return.- let module = match job.result.take().expect("the module is compiled before the task runs") {- Ok(module) => module,- Err(exception) => {- reject_promise(vm, promise, exception);- return;- }- };-- let options = job.options.take();-- // 2. Let builtinSetNames be options["builtins"].- let builtin_set_names = options.builtins;-- // 3. Let importedStringModule be options["importedStringConstants"].- let imported_string_module = options.imported_string_constants;-- // 4. If validating builtins and imported strings for module with builtinSetNames and importedStringModule is- // false, reject promise with a CompileError exception.- if !validate_builtins_and_imported_strings(- vm,- &module,- &builtin_set_names,- imported_string_module.as_ref(),- ) {- let throw = throw_webassembly_error(+ with_temporary_execution_context_and_callbacks(realm, || {+ // 1. If module is error, reject promise with a CompileError exception and return.+ let module = match job.result.take().expect("the module is compiled before the task runs") {+ Ok(module) => module,+ Err(exception) => {+ reject_promise(vm, promise, exception);+ return;+ }+ };++ let options = job.options.take();++ // 2. Let builtinSetNames be options["builtins"].+ let builtin_set_names = options.builtins;++ // 3. Let importedStringModule be options["importedStringConstants"].+ let imported_string_module = options.imported_string_constants;++ // 4. If validating builtins and imported strings for module with builtinSetNames and importedStringModule is+ // false, reject promise with a CompileError exception.+ if !validate_builtins_and_imported_strings(vm,- realm,- WebAssemblyError::Compile,- "Invalid builtin or imported string",- );- reject_promise(vm, promise, throw.value());- }- // 5. Otherwise,- else {- // 1. Construct a WebAssembly module object from module, bytes, builtinSetNames, importedStringModule, and- // let moduleObject be the result.- let bytes = job.bytes.take();- let module_object = allocate(vm, |_| {- Module::new(module, bytes, builtin_set_names, imported_string_module)- });-- // 2. Resolve promise with moduleObject.- let cx = CallContext::new(vm, realm);- resolve_promise(vm, promise, Value::from_object(wrap(&cx, module_object)));- }+ &module,+ &builtin_set_names,+ imported_string_module.as_ref(),+ ) {+ let throw = throw_webassembly_error(+ vm,+ realm,+ WebAssemblyError::Compile,+ "Invalid builtin or imported string",+ );+ reject_promise(vm, promise, throw.value());+ }+ // 5. Otherwise,+ else {+ // 1. Construct a WebAssembly module object from module, bytes, builtinSetNames, importedStringModule, and+ // let moduleObject be the result.+ let bytes = job.bytes.take();+ let module_object = allocate(vm, |_| {+ Module::new(module, bytes, builtin_set_names, imported_string_module)+ });++ // 2. Resolve promise with moduleObject.+ let cx = CallContext::new(vm, realm);+ resolve_promise(vm, promise, Value::from_object(wrap(&cx, module_object)));+ }+ });});},);@@ -214,30 +215,31 @@ fn asynchronously_instantiate_a_webassembly_module(// 1. Queue a task to perform the following steps: Note: Implementation-specific work may be performed here.queue_a_task(vm,- realm,TaskSource::Unspecified,(promise, module_object, imports),|vm, (promise, module_object, imports)| {let realm = crate::bindings::promise::promise_realm(promise);- let module = module_object.compiled_module().clone();-- // 1. Instantiate the core of a WebAssembly module module with imports, and let instance be the result.- // If this throws an exception, catch it, reject promise with the exception, and terminate these substeps.- let instance = match instantiate_the_core_of_a_webassembly_module(vm, &module, &imports) {- Ok(instance) => instance,- Err(throw) => {- reject_promise(vm, promise, throw.value());- return;- }- };-- // 2. Let instanceObject be a new Instance.- // 3. Initialize instanceObject from module and instance. If this throws an exception, catch it, reject promise with the exception, and terminate these substeps.- let instance_object = allocate(vm, |_| Instance::initialize(vm, realm, instance));-- // 4. Resolve promise with instanceObject.- let cx = CallContext::new(vm, realm);- resolve_promise(vm, promise, Value::from_object(wrap(&cx, instance_object)));+ with_temporary_execution_context_and_callbacks(realm, || {+ let module = module_object.compiled_module().clone();++ // 1. Instantiate the core of a WebAssembly module module with imports, and let instance be the result.+ // If this throws an exception, catch it, reject promise with the exception, and terminate these substeps.+ let instance = match instantiate_the_core_of_a_webassembly_module(vm, &module, &imports) {+ Ok(instance) => instance,+ Err(throw) => {+ reject_promise(vm, promise, throw.value());+ return;+ }+ };++ // 2. Let instanceObject be a new Instance.+ // 3. Initialize instanceObject from module and instance. If this throws an exception, catch it, reject promise with the exception, and terminate these substeps.+ let instance_object = allocate(vm, |_| Instance::initialize(vm, realm, instance));++ // 4. Resolve promise with instanceObject.+ let cx = CallContext::new(vm, realm);+ resolve_promise(vm, promise, Value::from_object(wrap(&cx, instance_object)));+ });},);diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/context_loss.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/context_loss.rsindex aa6cd77fbf4..f09162f2f4a 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/context_loss.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/context_loss.rs@@ -13,7 +13,7 @@ use super::canvas::Canvas;use super::exports::create_remote_context;use super::state::{ContextRef, RenderingContext, WebGL1, WebGL2};use super::web_gl_context_event::{WebGLContextEvent, WebGLContextEventInit};-use crate::bindings::interface::Wrapped;+use crate::bindings::interface::{Wrapped, with_temporary_execution_context_and_callbacks};use crate::bindings::promise::{TaskSource, queue_a_task};use crate::dom::event::EventInit;@@ -110,12 +110,14 @@ pub(crate) fn lose_contexts_of_this_thread(vm: &Vm) {if !state.mark_lost() {continue;}- queue_a_task(vm, state.realm(), TaskSource::WebGL, context, |vm, context| {- let state = context.state();- let page_wants_context_restored = !fire_webgl_context_event(vm, state.canvas(), "webglcontextlost");- state.set_context_restore_requested(page_wants_context_restored);- // NB: A Compositor that came back before the page asked for the context is not announced again.- restore_context_if_wanted(vm, context);+ queue_a_task(vm, TaskSource::WebGL, context, |vm, context| {+ with_temporary_execution_context_and_callbacks(context.state().realm(), || {+ let state = context.state();+ let page_wants_context_restored = !fire_webgl_context_event(vm, state.canvas(), "webglcontextlost");+ state.set_context_restore_requested(page_wants_context_restored);+ // NB: A Compositor that came back before the page asked for the context is not announced again.+ restore_context_if_wanted(vm, context);+ });});}}@@ -132,8 +134,10 @@ fn restore_context_if_wanted(vm: &Vm, context: ContextRef) {};state.restore(remote_context, supported_opengl_extensions);state.canvas().did_create_backing_storage();- queue_a_task(vm, state.realm(), TaskSource::WebGL, context, |vm, context| {- fire_webgl_context_event(vm, context.state().canvas(), "webglcontextrestored");+ queue_a_task(vm, TaskSource::WebGL, context, |vm, context| {+ with_temporary_execution_context_and_callbacks(context.state().realm(), || {+ fire_webgl_context_event(vm, context.state().canvas(), "webglcontextrestored");+ });});}diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cppindex 3b2fa50248d..dbb25ef1de8 100644--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp@@ -90,8 +90,7 @@ void web_bindings_set_rust_wrapper(void* realm, void* cell, JSObject* wrapper);void web_bindings_queue_a_microtask(void* realm, JSObject* function);void web_bindings_deferred_invoke(void* cell, void (*steps)(JSVM*, void*));void web_bindings_run_in_parallel(void* realm, void* cell, void (*steps)(JSVM*, void*));-void web_bindings_queue_a_task(void* realm, u8 task_source, void* cell, void (*steps)(JSVM*, void*));-void web_bindings_queue_a_task_without_execution_context(u8 task_source, void* cell, void (*steps)(JSVM*, void*));+void web_bindings_queue_a_task(u8 task_source, void* cell, void (*steps)(JSVM*, void*));u64 web_bindings_queue_a_global_task(JSObject* global_object, u8 task_source, void* cell, void (*steps)(JSVM*, void*));void web_bindings_remove_tasks(void* realm, ReadonlySpan<u64> task_ids);u64 web_bindings_currently_running_task(void* realm);@@ -552,17 +551,7 @@ static_assert(to_underlying(HTML::Task::Source::WebGL) == 26);static_assert(to_underlying(HTML::Task::Source::Crypto) == 27);static_assert(to_underlying(HTML::Task::Source::Storage) == 29);-void web_bindings_queue_a_task(void* realm, u8 task_source, void* cell, void (*steps)(JSVM*, void*))-{- GC::Ref<JS::Realm> js_realm = *static_cast<JS::Realm*>(realm);- // NB: The task's captures, which the collector traces, keep the cell alive until the steps run.- HTML::queue_a_task(static_cast<HTML::Task::Source>(task_source), nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(js_realm, GC::Ref { *static_cast<GC::Cell*>(cell) }, steps), [](auto& js_realm, auto& cell, auto& steps) {- HTML::TemporaryExecutionContext execution_context { js_realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };- steps(JS::HostABI::vm_to_abi(js_realm->vm()), cell.ptr());- }));-}--void web_bindings_queue_a_task_without_execution_context(u8 task_source, void* cell, void (*steps)(JSVM*, void*))+void web_bindings_queue_a_task(u8 task_source, void* cell, void (*steps)(JSVM*, void*)){// NB: The task's captures, which the collector traces, keep the cell alive until the steps run.HTML::queue_a_task(static_cast<HTML::Task::Source>(task_source), nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *static_cast<GC::Cell*>(cell) }, steps), [](auto& cell, auto& steps) {