Truly independent web browser
LibWeb: Dispatch transfers in Rust
Shannon Booth0d9b9d6b776e
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rsindex c6ff07b8902..aa41af78432 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs@@ -8,13 +8,13 @@//! https://html.spec.whatwg.org/multipage/structured-data.html#serializable-objects and//! https://html.spec.whatwg.org/multipage/structured-data.html#transferable-objects//!-//! The algorithms of crate::html::structured_serialize run the steps of such an interface through LibWeb's C++, which-//! dispatches to the entry points that the generated bindings of the interface define, which call the functions here.-//! The serialization and deserialization steps write and read the record of the algorithm, which it passes through C++-//! to them. The transfer steps and the transfer-receiving steps read and write what C++ lends them; the structs that it-//! lends are in Libraries/LibWeb/Bindings/RustSerialization.h. Unlike an object of an interface implemented in C++,-//! which is created before its deserialization steps fill it in, an object of an interface implemented in Rust is what-//! its deserialization steps and its transfer-receiving steps return.+//! The algorithms of crate::html::structured_serialize run the serialization steps of such an interface through+//! LibWeb's C++, which dispatches to the entry points that the generated bindings of the interface define, which call+//! the functions here. Those steps write and read the record of the algorithm, which it passes through C++ to them.+//! The algorithms run the transfer steps and the transfer-receiving steps themselves, which write and read the C+++//! data holders of the transfer. Unlike an object of an interface implemented in C++, which is created before its+//! deserialization steps fill it in, an object of an interface implemented in Rust is what its deserialization steps+//! and its transfer-receiving steps return.use core::cell::Cell;use core::ffi::c_void;@@ -22,14 +22,15 @@ use core::marker::PhantomData;use core::ptr::NonNull;use ak::Utf16String;-use libjs_rust::api::{RawNativeFunctionResult, ThrowCompletionOr, Value};+use libjs_rust::api::{Gc, RawNativeFunctionResult, Realm, ThrowCompletionOr, Value};use libwebcommon_rust::html::serialization_records::SerializationType;use crate::bindings::interface::{ConstructedObject, Interface, Ref, cell_from_abi, realm_arguments, wrap};use crate::bindings::transport::TransportHandle;use crate::bindings::{CallContext, WebIdlResult};use crate::html::structured_serialize::cpp::{- OwnedSerializedTransferRecord, TransferDataDecoder, data_clone_error_from_serialization_error,+ ImageBitmapSharedPixels, OwnedSerializedTransferRecord, TransferDataDecoder, TransferDataHolder,+ data_clone_error_from_serialization_error,};use crate::html::structured_serialize::reader::StructuredSerializeReader;use crate::html::structured_serialize::writer::StructuredSerializeWriter;@@ -45,18 +46,20 @@ unsafe extern "C" {fn web_bindings_transfer_data_extend(data_holder: *mut c_void, record: *mut c_void);fn web_bindings_transfer_data_decode_bool(data_holder: *mut c_void,+ realm: *mut c_void,out_value: &mut bool,) -> RawNativeFunctionResult;fn web_bindings_transfer_data_decode_records(data_holder: *mut c_void,+ realm: *mut c_void,records: *mut c_void,append: unsafe extern "C" fn(*mut c_void, *mut c_void),) -> RawNativeFunctionResult;fn web_bindings_transfer_data_decode_transport_handle(data_holder: *mut c_void,+ realm: *mut c_void,out_handle: &mut *mut c_void,) -> RawNativeFunctionResult;- fn web_bindings_transfer_data_decoder(data_holder: *mut c_void) -> *mut c_void;}/// The record of a structured serialization, which the serialization steps of an object write to, and the serialization@@ -241,14 +244,51 @@ pub(crate) trait Serializable: Interface {) -> WebIdlResult<impl ConstructedObject<Self> + use<Self>>;}-/// The data holder of a transferred object, which its transfer steps write to: a Web::Bindings::RustTransferDataWriter-/// that C++ lends for the steps.+/// The data holder of a transferred object, which its transfer steps write to: an HTML::TransferDataEncoder, in the+/// realm of the transfer, which creates what the steps throw.pub(crate) struct TransferDataWriter<'a> {raw: NonNull<c_void>,+ realm: Gc<Realm>,+ /// AD-HOC: The shared memory that the transfer gathers the pixels of its ImageBitmaps in, if it has some.+ image_bitmap_pixels: Option<NonNull<c_void>>,_lent: PhantomData<&'a mut c_void>,}-impl TransferDataWriter<'_> {+impl<'a> TransferDataWriter<'a> {+ pub(crate) fn new(+ data_holder: &'a TransferDataHolder,+ realm: Gc<Realm>,+ image_bitmap_pixels: &'a ImageBitmapSharedPixels,+ ) -> Self {+ Self {+ raw: data_holder.as_raw(),+ realm,+ image_bitmap_pixels: image_bitmap_pixels.as_raw(),+ _lent: PhantomData,+ }+ }++ /// # Safety+ ///+ /// `data_holder` must be an HTML::TransferDataEncoder that C++ lends for `'a`.+ pub(crate) unsafe fn from_lent(data_holder: *mut c_void, realm: Gc<Realm>) -> Self {+ Self {+ raw: NonNull::new(data_holder).expect("C++ lends a data holder"),+ realm,+ image_bitmap_pixels: None,+ _lent: PhantomData,+ }+ }++ pub(crate) fn realm(&self) -> Gc<Realm> {+ self.realm+ }++ /// The shared pixels as the C ABI of ImageBitmap's C++ code takes them, or null.+ pub(crate) fn image_bitmap_pixels_as_raw(&self) -> *mut c_void {+ self.image_bitmap_pixels.map_or(core::ptr::null_mut(), NonNull::as_ptr)+ }+/// The data holder as the C ABI of an interface's C++ class takes it, which encodes what the steps write.pub(crate) fn as_raw(&mut self) -> *mut c_void {self.raw.as_ptr()@@ -282,24 +322,38 @@ impl TransferDataWriter<'_> {}}-/// The data holder of a received object, which its transfer-receiving steps read from: a-/// Web::Bindings::RustTransferDataReader that C++ lends for the steps. What it reads that the data holder does not hold+/// The data holder of a received object, which its transfer-receiving steps read from: an HTML::TransferDataDecoder+/// that C++ lends, in the realm that the object is created in. What the steps read that the data holder does not hold/// throws a "DataCloneError" DOMException.pub(crate) struct TransferDataReader<'a> {- raw: NonNull<c_void>,+ decoder: TransferDataDecoder,+ realm: Gc<Realm>,_lent: PhantomData<&'a mut c_void>,}impl TransferDataReader<'_> {+ pub(crate) fn new(decoder: TransferDataDecoder, realm: Gc<Realm>) -> Self {+ Self {+ decoder,+ realm,+ _lent: PhantomData,+ }+ }++ pub(crate) fn realm(&self) -> Gc<Realm> {+ self.realm+ }+/// The data holder as the C ABI of an interface's C++ class takes it, which decodes what the steps read.pub(crate) fn as_raw(&mut self) -> *mut c_void {- self.raw.as_ptr()+ self.decoder.as_raw()}pub(crate) fn read_bool(&mut self) -> WebIdlResult<bool> {let mut value = false;- // SAFETY: The data holder is lent for the steps.- unsafe { web_bindings_transfer_data_decode_bool(self.raw.as_ptr(), &mut value) }.into_completion()?;+ // SAFETY: The data holder is lent for the steps, and the realm is live.+ unsafe { web_bindings_transfer_data_decode_bool(self.as_raw(), self.realm.as_ptr().cast(), &mut value) }+ .into_completion()?;Ok(value)}@@ -313,18 +367,27 @@ impl TransferDataReader<'_> {}}let mut records = Vec::new();- // SAFETY: The data holder and the records are lent for the steps.- unsafe { web_bindings_transfer_data_decode_records(self.raw.as_ptr(), (&raw mut records).cast(), append) }- .into_completion()?;+ // SAFETY: The data holder and the records are lent for the steps, and the realm is live.+ unsafe {+ web_bindings_transfer_data_decode_records(+ self.as_raw(),+ self.realm.as_ptr().cast(),+ (&raw mut records).cast(),+ append,+ )+ }+ .into_completion()?;Ok(records)}/// Reads what TransferDataWriter::write_transport_handle() writes.pub(crate) fn read_transport_handle(&mut self) -> WebIdlResult<TransportHandle> {let mut handle = core::ptr::null_mut();- // SAFETY: The data holder is lent for the steps.- unsafe { web_bindings_transfer_data_decode_transport_handle(self.raw.as_ptr(), &mut handle) }- .into_completion()?;+ // SAFETY: The data holder is lent for the steps, and the realm is live.+ unsafe {+ web_bindings_transfer_data_decode_transport_handle(self.as_raw(), self.realm.as_ptr().cast(), &mut handle)+ }+ .into_completion()?;// SAFETY: LibWeb hands over the handle it read.Ok(unsafe { TransportHandle::from_raw(handle) })}@@ -332,9 +395,7 @@ impl TransferDataReader<'_> {/// ! StructuredDeserializeWithTransfer(dataHolder, the current Realm).[[Deserialized]] for what/// TransferDataWriter::write_transferred_value() wrote: the transferred value, created in the realm.pub(crate) fn read_transferred_value(&mut self, cx: &CallContext) -> WebIdlResult<Value> {- // SAFETY: The data holder is lent for the steps, and LibWeb returns its decoder.- let decoder = unsafe { TransferDataDecoder::from_raw(web_bindings_transfer_data_decoder(self.raw.as_ptr())) };- structured_deserialize_with_transfer_internal(cx, decoder)+ structured_deserialize_with_transfer_internal(cx, self.decoder)}}@@ -403,68 +464,3 @@ pub(crate) unsafe fn deserialization_steps<T: Serializable>(let result = T::deserialization_steps(&mut cx, serialized);completion(&cx, result.map(|implementation| wrap_new_object(&cx, implementation)))}--/// The entry point that reads the [[Detached]] internal slot of an object of `T`.-///-/// # Safety-///-/// `cell` must be the live cell of an object of `T`.-pub(crate) unsafe fn is_detached<T: Transferable>(cell: *mut c_void) -> bool {- // SAFETY: The caller passes a live cell of an object of T.- let object = unsafe { cell_from_abi::<T>(cell) };- object.detached().get()-}--/// The entry point that sets the [[Detached]] internal slot of an object of `T` to true.-///-/// # Safety-///-/// `cell` must be the live cell of an object of `T`.-pub(crate) unsafe fn set_detached<T: Transferable>(cell: *mut c_void) {- // SAFETY: The caller passes a live cell of an object of T.- let object = unsafe { cell_from_abi::<T>(cell) };- object.detached().set(true);-}--/// The entry point of the transfer steps of `T`.-///-/// # Safety-///-/// The pointers must be the VM, a live realm, the live cell of an object of `T`, and a data holder that C++ lends.-pub(crate) unsafe fn transfer_steps<T: Transferable>(- vm: *mut c_void,- realm: *mut c_void,- cell: *mut c_void,- data_holder: *mut c_void,-) -> RawNativeFunctionResult {- // SAFETY: The caller passes the VM, a live realm and a live cell of an object of T.- let ((vm, realm), object) = unsafe { (realm_arguments(vm, realm), cell_from_abi::<T>(cell)) };- let mut cx = CallContext::new(vm, realm);- let mut data_holder = TransferDataWriter {- raw: NonNull::new(data_holder).expect("C++ lends a data holder"),- _lent: PhantomData,- };- let result = T::transfer_steps(&object, &mut cx, &mut data_holder);- completion(&cx, result.map(|()| Value::UNDEFINED))-}--/// The entry point of the transfer-receiving steps of `T`, which returns the wrapper of the new object.-///-/// # Safety-///-/// The pointers must be the VM, a live realm, and a data holder that C++ lends.-pub(crate) unsafe fn transfer_receiving_steps<T: Transferable>(- vm: *mut c_void,- realm: *mut c_void,- data_holder: *mut c_void,-) -> RawNativeFunctionResult {- // SAFETY: The caller passes the VM and a live realm.- let (vm, realm) = unsafe { realm_arguments(vm, realm) };- let mut cx = CallContext::new(vm, realm);- let mut data_holder = TransferDataReader {- raw: NonNull::new(data_holder).expect("C++ lends a data holder"),- _lent: PhantomData,- };- let result = T::transfer_receiving_steps(&mut cx, &mut data_holder);- completion(&cx, result.map(|implementation| wrap_new_object(&cx, implementation)))-}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rsindex f345e5e95cd..553ff4b2772 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs@@ -28,8 +28,10 @@ use crate::bindings::CallContext;use crate::bindings::conversions::UsvString;use crate::bindings::environment_settings_object::relevant_settings_object;use crate::bindings::event_target::CppEventTarget;-use crate::bindings::interface::{Interface, Ref, cell_from_abi, cell_into_abi, realm_arguments};+use crate::bindings::interface::{Interface, Ref, cell_from_abi, cell_into_abi, realm_arguments, wrap};+use crate::bindings::structured_data::{TransferDataReader, TransferDataWriter, Transferable};use crate::dom::event::EventInit;+use crate::html::structured_serialize::cpp::TransferDataDecoder;use crate::html::structured_serialize::message_record::MessageRecord;use crate::storage_api::storage_area_mirror::StorageEndpointType;use crate::storage_api::storage_bottle::{obtain_a_local_storage_bottle_map, obtain_a_session_storage_bottle_map};@@ -339,6 +341,58 @@ pub unsafe extern "C" fn web_rust_message_port_fail_next_transfer_for_testing(pounsafe { cell_from_abi::<MessagePort>(port) }.fail_next_transfer_for_testing();}+/// The transfer steps of the MessagePort, which C++ runs outside StructuredSerializeWithTransfer, writing to a data+/// holder that it lends, which holds no type.+///+/// # Safety+///+/// `vm` must be the live VM, `realm` a live realm, `port` a live cell of a MessagePort, and `data_holder` an+/// HTML::TransferDataEncoder that C++ lends for the call.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_message_port_transfer_steps(+ vm: *mut c_void,+ realm: *mut c_void,+ port: *mut c_void,+ data_holder: *mut c_void,+) -> RawNativeFunctionResult {+ // SAFETY: The caller passes the live VM, a live realm and a live cell of a MessagePort.+ let ((vm, realm), port) = unsafe { (realm_arguments(vm, realm), cell_from_abi::<MessagePort>(port)) };+ let mut cx = CallContext::new(vm, realm);+ // SAFETY: The caller lends the data holder for the call.+ let mut data_holder = unsafe { TransferDataWriter::from_lent(data_holder, realm) };+ let result = MessagePort::transfer_steps(&port, &mut cx, &mut data_holder);+ RawNativeFunctionResult::from_completion(+ result+ .map(|()| Value::UNDEFINED)+ .map_err(|exception| exception.throw(&cx)),+ )+}++/// The transfer-receiving steps of a MessagePort that C++ runs outside StructuredDeserializeWithTransfer, which return+/// the wrapper of the new MessagePort.+///+/// # Safety+///+/// `vm` must be the live VM, `realm` a live realm, and `data_holder` an HTML::TransferDataDecoder that C++ lends for+/// the call.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_message_port_transfer_receiving_steps(+ vm: *mut c_void,+ realm: *mut c_void,+ data_holder: *mut c_void,+) -> RawNativeFunctionResult {+ // SAFETY: The caller passes the live VM and a live realm, and lends the data holder for the call.+ let ((vm, realm), decoder) = unsafe { (realm_arguments(vm, realm), TransferDataDecoder::from_raw(data_holder)) };+ let mut cx = CallContext::new(vm, realm);+ let mut data_holder = TransferDataReader::new(decoder, realm);+ let result = MessagePort::transfer_receiving_steps(&mut cx, &mut data_holder);+ RawNativeFunctionResult::from_completion(+ result+ .map(|port| Value::from_object(wrap(&cx, port)))+ .map_err(|exception| exception.throw(&cx)),+ )+}+/// # Safety////// `vm` must be the live VM, and `realm` a live realm.diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/image_bitmap.rs b/Libraries/LibWeb/Bindings/Rust/src/html/image_bitmap.rsindex a08c7dd0aed..ce9820aa836 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/image_bitmap.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/image_bitmap.rs@@ -48,8 +48,14 @@ unsafe extern "C" {pixels: &FramePixels,out_frame: &mut *mut c_void,) -> RawNativeFunctionResult;- fn web_image_bitmap_transfer_bitmap(data_holder: *mut c_void, frame: *const c_void) -> RawNativeFunctionResult;+ fn web_image_bitmap_transfer_bitmap(+ realm: *mut c_void,+ data_holder: *mut c_void,+ image_bitmap_pixels: *mut c_void,+ frame: *const c_void,+ ) -> RawNativeFunctionResult;fn web_image_bitmap_receive_bitmap(+ realm: *mut c_void,data_holder: *mut c_void,out_frame: &mut *mut c_void,) -> RawNativeFunctionResult;@@ -415,8 +421,17 @@ impl Transferable for ImageBitmap {// 2. Set dataHolder.[[BitmapData]] to value's bitmap data.// NB: The pixels go to the shared memory of the transfer if there is room for them there, and inline otherwise.- // SAFETY: The data holder is lent for the steps, and the frame lives while the bitmap data is set.- unsafe { web_image_bitmap_transfer_bitmap(data_holder.as_raw(), this.raw_frame()) }.into_completion()?;+ // SAFETY: The realm is live, the data holder and the pixels are lent for the steps, and the frame lives while+ // the bitmap data is set.+ unsafe {+ web_image_bitmap_transfer_bitmap(+ data_holder.realm().as_ptr().cast(),+ data_holder.as_raw(),+ data_holder.image_bitmap_pixels_as_raw(),+ this.raw_frame(),+ )+ }+ .into_completion()?;// 3. Unset value's bitmap data.this.bitmap.replace(None);@@ -428,8 +443,11 @@ impl Transferable for ImageBitmap {fn transfer_receiving_steps(cx: &mut CallContext, data_holder: &mut TransferDataReader) -> WebIdlResult<Ref<Self>> {// 1. Set value's bitmap data to dataHolder.[[BitmapData]].let mut frame = core::ptr::null_mut();- // SAFETY: The data holder is lent for the steps.- unsafe { web_image_bitmap_receive_bitmap(data_holder.as_raw(), &mut frame) }.into_completion()?;+ // SAFETY: The realm is live, and the data holder is lent for the steps.+ unsafe {+ web_image_bitmap_receive_bitmap(data_holder.realm().as_ptr().cast(), data_holder.as_raw(), &mut frame)+ }+ .into_completion()?;// SAFETY: C++ hands over the frame it decoded, or null.Ok(allocate(cx.vm(), |_| {Self::new(unsafe { BitmapData::from_handed_over_frame(frame) })diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rsindex 87d2e2717a5..781998b4a78 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs@@ -67,6 +67,8 @@ pub(crate) mod message_port;#[cfg(not(test))]pub(crate) mod numbers;#[cfg(not(test))]+pub(crate) mod offscreen_canvas;+#[cfg(not(test))]pub(crate) mod offscreen_canvas_rendering_context2d;#[cfg(not(test))]pub(crate) mod path2d;diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/offscreen_canvas.rs b/Libraries/LibWeb/Bindings/Rust/src/html/offscreen_canvas.rsnew file mode 100644index 00000000000..84de0eb3429--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/html/offscreen_canvas.rs@@ -0,0 +1,69 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What StructuredSerializeWithTransfer asks of OffscreenCanvas, which LibWeb implements in C++, in+//! Libraries/LibWeb/HTML/OffscreenCanvas.cpp.++use core::ffi::c_void;++use libjs_rust::api::{Gc, Object, RawNativeFunctionResult, Value};++use crate::bindings::WebIdlResult;+use crate::bindings::conversions::implements_cpp_interface;+use crate::bindings::structured_data::{TransferDataReader, TransferDataWriter};++unsafe extern "C" {+ fn web_offscreen_canvas_interface_name() -> u16;+ fn web_offscreen_canvas_is_detached(object: *mut c_void) -> bool;+ fn web_offscreen_canvas_transfer_steps(+ realm: *mut c_void,+ object: *mut c_void,+ data_holder: *mut c_void,+ ) -> RawNativeFunctionResult;+ fn web_offscreen_canvas_create_from_transfer(+ realm: *mut c_void,+ data_holder: *mut c_void,+ ) -> RawNativeFunctionResult;+}++/// Web::Bindings::InterfaceName of OffscreenCanvas.+pub(crate) fn interface_name() -> u16 {+ // SAFETY: The call has no arguments.+ unsafe { web_offscreen_canvas_interface_name() }+}++pub(crate) fn is_offscreen_canvas(object: Gc<Object>) -> bool {+ implements_cpp_interface(object, interface_name())+}++/// The [[Detached]] internal slot of the OffscreenCanvas, which is its detached context mode.+pub(crate) fn is_detached(object: Gc<Object>) -> bool {+ // SAFETY: The object is a live OffscreenCanvas.+ unsafe { web_offscreen_canvas_is_detached(object.as_ptr().cast()) }+}++/// https://html.spec.whatwg.org/multipage/canvas.html#the-offscreencanvas-interface:transfer-steps+pub(crate) fn transfer_steps(object: Gc<Object>, data_holder: &mut TransferDataWriter) -> WebIdlResult<()> {+ // SAFETY: The realm and the object are live, and the data holder is lent for the steps.+ unsafe {+ web_offscreen_canvas_transfer_steps(+ data_holder.realm().as_ptr().cast(),+ object.as_ptr().cast(),+ data_holder.as_raw(),+ )+ }+ .into_completion()?;+ Ok(())+}++/// https://html.spec.whatwg.org/multipage/canvas.html#the-offscreencanvas-interface:transfer-receiving-steps+pub(crate) fn create_from_transfer(data_holder: &mut TransferDataReader) -> WebIdlResult<Value> {+ // SAFETY: The realm is live, and the data holder is lent for the steps.+ Ok(+ unsafe { web_offscreen_canvas_create_from_transfer(data_holder.realm().as_ptr().cast(), data_holder.as_raw()) }+ .into_completion()?,+ )+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rsindex 394e90ff9b0..acdd1ee9f18 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs@@ -87,22 +87,6 @@ unsafe extern "C" {serialized: *mut c_void,) -> RawNativeFunctionResult;- fn web_structured_serialize_is_transferable(object: *mut c_void) -> bool;- fn web_structured_serialize_transferable_is_detached(object: *mut c_void) -> bool;- fn web_structured_serialize_transferable_set_detached(object: *mut c_void);- fn web_structured_serialize_transferable_primary_interface(object: *mut c_void) -> u8;- fn web_structured_serialize_transfer_steps(- realm: *mut c_void,- object: *mut c_void,- data_holder: *mut c_void,- image_bitmap_pixels: *mut c_void,- ) -> RawNativeFunctionResult;- fn web_structured_serialize_is_transferable_interface_exposed(transfer_type: u8, realm: *mut c_void) -> bool;- fn web_structured_serialize_create_transferred_platform_object(- transfer_type: u8,- realm: *mut c_void,- decoder: *mut c_void,- ) -> RawNativeFunctionResult;fn web_structured_serialize_gather_image_bitmap_pixels(shared_buffers: *mut c_void,transfer_list: *const *mut c_void,@@ -505,75 +489,16 @@ pub(crate) fn deserialize_rust_platform_object(})}-/// Whether the object is a platform object that is a transferable object, which has a [[Detached]] internal slot.-pub(crate) fn is_transferable(object: Gc<Object>) -> bool {- // SAFETY: The object is live.- unsafe { web_structured_serialize_is_transferable(object_into_abi(object)) }-}--/// The [[Detached]] internal slot of the transferable platform object.-pub(crate) fn transferable_is_detached(object: Gc<Object>) -> bool {- // SAFETY: The object is live.- unsafe { web_structured_serialize_transferable_is_detached(object_into_abi(object)) }-}--pub(crate) fn transferable_set_detached(object: Gc<Object>) {- // SAFETY: The object is live.- unsafe { web_structured_serialize_transferable_set_detached(object_into_abi(object)) };-}--/// The identifier of the primary interface of the transferable platform object, an HTML::TransferType.-pub(crate) fn transferable_primary_interface(object: Gc<Object>) -> u8 {- // SAFETY: The object is live.- unsafe { web_structured_serialize_transferable_primary_interface(object_into_abi(object)) }-}--/// The transfer steps of the interface of the transferable platform object, given it and the data holder.-pub(crate) fn transfer_steps(- cx: &CallContext,- object: Gc<Object>,- data_holder: &TransferDataHolder,- image_bitmap_pixels: &ImageBitmapSharedPixels,-) -> WebIdlResult<()> {- // SAFETY: The realm and the object are live, and the data holder and the pixels are live while borrowed.- completion(unsafe {- web_structured_serialize_transfer_steps(- cx.realm().as_ptr().cast(),- object_into_abi(object),- data_holder.0.as_ptr(),- image_bitmap_pixels.0.map_or(core::ptr::null_mut(), NonNull::as_ptr),- )- })?;- Ok(())-}--/// Whether the interface that the HTML::TransferType identifies is exposed in the realm.-pub(crate) fn is_transferable_interface_exposed(transfer_type: u8, realm: Gc<Realm>) -> bool {- // SAFETY: The realm is live.- unsafe { web_structured_serialize_is_transferable_interface_exposed(transfer_type, realm.as_ptr().cast()) }-}--/// A new instance of the interface that the HTML::TransferType identifies, created in the realm, after the-/// transfer-receiving steps of the interface given the data holder.-pub(crate) fn create_transferred_platform_object(- transfer_type: u8,- realm: Gc<Realm>,- decoder: TransferDataDecoder,-) -> WebIdlResult<Value> {- // SAFETY: The realm is live, and the decoder is lent.- completion(unsafe {- web_structured_serialize_create_transferred_platform_object(- transfer_type,- realm.as_ptr().cast(),- decoder.0.as_ptr(),- )- })-}-/// HTML::ImageBitmapSharedPixels that this owns: the shared memory that a transfer gathers the pixels of its/// ImageBitmaps in, if it has some.pub(crate) struct ImageBitmapSharedPixels(Option<NonNull<c_void>>);+impl ImageBitmapSharedPixels {+ pub(crate) fn as_raw(&self) -> Option<NonNull<c_void>> {+ self.0+ }+}+impl Drop for ImageBitmapSharedPixels {fn drop(&mut self) {if let Some(image_bitmap_pixels) = self.0 {@@ -594,6 +519,10 @@ impl TransferDataHolder {)}+ pub(crate) fn as_raw(&self) -> NonNull<c_void> {+ self.0+ }+pub(crate) fn encode_u8(&self, value: u8) {// SAFETY: This owns the data holder.unsafe { web_structured_serialize_transfer_data_holder_encode_u8(self.0.as_ptr(), value) };@@ -759,6 +688,10 @@ impl TransferDataDecoder {Self(NonNull::new(decoder).expect("C++ lends a decoder"))}+ pub(crate) fn as_raw(self) -> *mut c_void {+ self.0.as_ptr()+ }+pub(crate) fn decode_u8(self, realm: Gc<Realm>) -> WebIdlResult<u8> {let mut value = 0;// SAFETY: The decoder is lent, and the realm is live.diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rsindex e34d2c71e71..5fb9f43f2f3 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs@@ -30,23 +30,29 @@ use libjs_rust::api::{};use libwebcommon_rust::html::serialization_records::SerializationType;-use crate::bindings::interface::with_temporary_execution_context;-use crate::bindings::structured_data::{SerializationReader, SerializationWriter};+use crate::bindings::interface::{Interface, Ref, implementation_if_wrapper, with_temporary_execution_context, wrap};+use crate::bindings::structured_data::{+ SerializationReader, SerializationWriter, TransferDataReader, TransferDataWriter, Transferable,+};use crate::bindings::{CallContext, Exception, WebIdlResult};use crate::crypto::crypto_key;+use crate::html::image_bitmap::ImageBitmap;+use crate::html::message_port::MessagePort;+use crate::html::offscreen_canvas;use crate::html::structured_serialize::cpp::{OwnedSerializedTransferRecord, SerializableSteps, SerializedTransferRecord, TransferDataDecoder,- TransferDataHolder, create_transferred_platform_object, current_settings_object_agent_cluster,+ TransferDataHolder, current_settings_object_agent_cluster,current_settings_object_cross_origin_isolated_capability, data_clone_error_from_serialization_error,- deserialize_rust_platform_object, is_exposed, is_platform_object, is_transferable,- is_transferable_interface_exposed, realm_agent_cluster, serializable_interface_name,+ deserialize_rust_platform_object, is_exposed, is_platform_object, realm_agent_cluster, serializable_interface_name,serializable_interface_storage_identifier, serializable_payload_version, serializable_steps, serialization_steps,- transfer_steps, transferable_is_detached, transferable_primary_interface, transferable_set_detached,};use crate::html::structured_serialize::memory::{DeserializationMemory, SerializationMemory};use crate::html::structured_serialize::message_record::MessageRecord;use crate::html::structured_serialize::reader::StructuredSerializeReader;use crate::html::structured_serialize::writer::StructuredSerializeWriter;+use crate::streams::readable_stream::ReadableStream;+use crate::streams::transform_stream::TransformStream;+use crate::streams::writable_stream::WritableStream;use crate::webidl::dom_exception::{self, DOMExceptionFields};use crate::webidl::quota_exceeded_error::{self, QuotaExceededErrorFields};@@ -117,12 +123,135 @@ impl ValueTag {}}-/// HTML::TransferType, the types of the data holders of a transfer.+/// The types of the data holders of a transfer, which only IPC carries.#[derive(Clone, Copy, PartialEq, Eq)]#[repr(u8)]enum TransferType {+ MessagePort = 1,ArrayBuffer = 2,ResizableArrayBuffer = 3,+ ReadableStream = 4,+ WritableStream = 5,+ TransformStream = 6,+ ImageBitmap = 7,+ OffscreenCanvas = 8,+}++impl TransferType {+ fn from_u8(value: u8) -> Option<Self> {+ Some(match value {+ 1 => Self::MessagePort,+ 2 => Self::ArrayBuffer,+ 3 => Self::ResizableArrayBuffer,+ 4 => Self::ReadableStream,+ 5 => Self::WritableStream,+ 6 => Self::TransformStream,+ 7 => Self::ImageBitmap,+ 8 => Self::OffscreenCanvas,+ _ => return None,+ })+ }+}++/// A platform object that is a transferable object, which has a [[Detached]] internal slot.+#[derive(Clone, Copy)]+enum TransferablePlatformObject {+ MessagePort(Ref<MessagePort>),+ ReadableStream(Ref<ReadableStream>),+ WritableStream(Ref<WritableStream>),+ TransformStream(Ref<TransformStream>),+ ImageBitmap(Ref<ImageBitmap>),+ OffscreenCanvas(Gc<Object>),+}++impl TransferablePlatformObject {+ fn from_object(object: Gc<Object>) -> Option<Self> {+ if let Some(port) = implementation_if_wrapper(object) {+ return Some(Self::MessagePort(port));+ }+ if let Some(stream) = implementation_if_wrapper(object) {+ return Some(Self::ReadableStream(stream));+ }+ if let Some(stream) = implementation_if_wrapper(object) {+ return Some(Self::WritableStream(stream));+ }+ if let Some(stream) = implementation_if_wrapper(object) {+ return Some(Self::TransformStream(stream));+ }+ if let Some(image_bitmap) = implementation_if_wrapper(object) {+ return Some(Self::ImageBitmap(image_bitmap));+ }+ offscreen_canvas::is_offscreen_canvas(object).then_some(Self::OffscreenCanvas(object))+ }++ /// The identifier of the primary interface of the object.+ fn primary_interface(self) -> TransferType {+ match self {+ Self::MessagePort(_) => TransferType::MessagePort,+ Self::ReadableStream(_) => TransferType::ReadableStream,+ Self::WritableStream(_) => TransferType::WritableStream,+ Self::TransformStream(_) => TransferType::TransformStream,+ Self::ImageBitmap(_) => TransferType::ImageBitmap,+ Self::OffscreenCanvas(_) => TransferType::OffscreenCanvas,+ }+ }++ // https://html.spec.whatwg.org/multipage/structured-data.html#detached+ fn is_detached(self) -> bool {+ match self {+ Self::MessagePort(port) => port.detached().get(),+ Self::ReadableStream(stream) => stream.detached().get(),+ Self::WritableStream(stream) => stream.detached().get(),+ Self::TransformStream(stream) => stream.detached().get(),+ Self::ImageBitmap(image_bitmap) => image_bitmap.detached().get(),+ Self::OffscreenCanvas(object) => offscreen_canvas::is_detached(object),+ }+ }++ fn set_detached(self) {+ match self {+ Self::MessagePort(port) => port.detached().set(true),+ Self::ReadableStream(stream) => stream.detached().set(true),+ Self::WritableStream(stream) => stream.detached().set(true),+ Self::TransformStream(stream) => stream.detached().set(true),+ Self::ImageBitmap(image_bitmap) => image_bitmap.detached().set(true),+ // NB: The [[Detached]] internal slot of an OffscreenCanvas is its detached context mode, which its transfer+ // steps set.+ Self::OffscreenCanvas(_) => {}+ }+ }++ // https://html.spec.whatwg.org/multipage/structured-data.html#transfer-steps+ fn transfer_steps(self, cx: &mut CallContext, data_holder: &mut TransferDataWriter) -> WebIdlResult<()> {+ match self {+ Self::MessagePort(port) => MessagePort::transfer_steps(&port, cx, data_holder),+ Self::ReadableStream(stream) => ReadableStream::transfer_steps(&stream, cx, data_holder),+ Self::WritableStream(stream) => WritableStream::transfer_steps(&stream, cx, data_holder),+ Self::TransformStream(stream) => TransformStream::transfer_steps(&stream, cx, data_holder),+ Self::ImageBitmap(image_bitmap) => ImageBitmap::transfer_steps(&image_bitmap, cx, data_holder),+ Self::OffscreenCanvas(object) => offscreen_canvas::transfer_steps(object, data_holder),+ }+ }+}++/// Web::Bindings::InterfaceName of the interface that the type of a data holder identifies, if it identifies one.+fn transferable_interface_name(transfer_type: TransferType) -> Option<u16> {+ Some(match transfer_type {+ TransferType::MessagePort => MessagePort::INTERFACE_NAME,+ TransferType::ReadableStream => ReadableStream::INTERFACE_NAME,+ TransferType::WritableStream => WritableStream::INTERFACE_NAME,+ TransferType::TransformStream => TransformStream::INTERFACE_NAME,+ TransferType::ImageBitmap => ImageBitmap::INTERFACE_NAME,+ TransferType::OffscreenCanvas => offscreen_canvas::interface_name(),+ TransferType::ArrayBuffer | TransferType::ResizableArrayBuffer => return None,+ })+}++/// The wrapper of a new object of `T` in the realm of the data holder, after the transfer-receiving steps of `T`.+fn receive_transferred<T: Transferable>(cx: &CallContext, data_holder: &mut TransferDataReader) -> WebIdlResult<Value> {+ let mut cx = CallContext::new(cx.vm(), data_holder.realm());+ let object = T::transfer_receiving_steps(&mut cx, data_holder)?;+ Ok(Value::from_object(wrap(&cx, object)))}/// Error, followed by the native errors of LibJS, in the order of JS_ENUMERATE_NATIVE_ERRORS, which IPC records hold.@@ -741,7 +870,8 @@ impl<'memory> Serializer<'_, '_, 'memory> {else if let Some(interface_name) = serializable_interface_name(object) {// 1. If value has a [[Detached]] internal slot whose value is true, then throw a "DataCloneError" DOMException.// NB: The platform objects that have a [[Detached]] internal slot are the transferable objects.- if is_transferable(object) && transferable_is_detached(object) {+ if TransferablePlatformObject::from_object(object).is_some_and(TransferablePlatformObject::is_detached)+ {return Err(data_clone_error("Cannot serialize a detached platform object"));}@@ -1571,7 +1701,7 @@ pub(crate) fn structured_serialize_with_transfer(// 1. If transferable has neither an [[ArrayBufferData]] internal slot nor a [[Detached]] internal slot, then throw a "DataCloneError" DOMException.// NB: The platform objects that have a [[Detached]] internal slot are the transferable objects.- if as_array_buffer.is_none() && !is_transferable(*transferable) {+ if as_array_buffer.is_none() && TransferablePlatformObject::from_object(*transferable).is_none() {return Err(data_clone_error("Cannot transfer type"));}@@ -1620,6 +1750,7 @@ pub(crate) fn structured_serialize_with_transfer(for transferable in transfer_list {let array_buffer = transferable.downcast::<ArrayBuffer>();let is_detached = array_buffer.is_some_and(|array_buffer| array_buffer.is_detached());+ let platform_object = TransferablePlatformObject::from_object(*transferable);// 1. If transferable has an [[ArrayBufferData]] internal slot and IsDetachedBuffer(transferable) is true, then throw a "DataCloneError" DOMException.if is_detached {@@ -1627,7 +1758,7 @@ pub(crate) fn structured_serialize_with_transfer(}// 2. If transferable has a [[Detached]] internal slot and transferable.[[Detached]] is true, then throw a "DataCloneError" DOMException.- if is_transferable(*transferable) && transferable_is_detached(*transferable) {+ if platform_object.is_some_and(TransferablePlatformObject::is_detached) {return Err(data_clone_error("Value already transferred"));}@@ -1668,22 +1799,24 @@ pub(crate) fn structured_serialize_with_transfer(// 5. Otherwise:else {// 1. Assert: transferable is a platform object that is a transferable object.- assert!(is_transferable(*transferable));+ let platform_object = platform_object.expect("transferable is a transferable object");assert!(is_platform_object(*transferable));// 2. Let interfaceName be the identifier of the primary interface of transferable.- let interface_name = transferable_primary_interface(*transferable);+ let interface_name = platform_object.primary_interface();// 3. Set dataHolder.[[Type]] to interfaceName.- data_holder.encode_u8(interface_name);+ data_holder.encode_u8(interface_name as u8);// FIXME: 4. If transferable's primary interface is decorated with [SameAgentCluster], then restrict dataHolder to the same agent cluster.// 5. Perform the appropriate transfer steps for the interface identified by interfaceName, given transferable and dataHolder.- transfer_steps(cx, *transferable, &data_holder, &image_bitmap_pixels)?;+ let mut steps_cx = CallContext::new(vm, cx.realm());+ let mut writer = TransferDataWriter::new(&data_holder, cx.realm(), &image_bitmap_pixels);+ platform_object.transfer_steps(&mut steps_cx, &mut writer)?;// 6. Set transferable.[[Detached]] to true.- transferable_set_detached(*transferable);+ platform_object.set_detached();}// 6. Append dataHolder to transferDataHolders.@@ -1773,7 +1906,9 @@ pub(crate) fn structured_deserialize_with_transfer_internal() -> WebIdlResult<Value> {let target_realm = cx.realm();- let transfer_type = decoder.decode_u8(target_realm)?;+ let Some(transfer_type) = TransferType::from_u8(decoder.decode_u8(target_realm)?) else {+ return Err(data_clone_error("Unknown type transferred"));+ };// 1. Let value be an uninitialized value.#[allow(clippy::needless_late_init, reason = "the steps let value be uninitialized first")]@@ -1786,7 +1921,7 @@ pub(crate) fn structured_deserialize_with_transfer_internal(// this step is unlikely to throw an exception, as no new memory needs to be allocated: the memory occupied by// [[ArrayBufferData]] is instead just getting transferred into the new ArrayBuffer. This could be true, for example,// when both the source and target realms are in the same process.- if transfer_type == TransferType::ArrayBuffer as u8 {+ if transfer_type == TransferType::ArrayBuffer {let buffer = decoder.decode_byte_buffer(target_realm)?;value = Value::from_object(buffer.into_array_buffer(target_realm, ArrayBufferShared::No));}@@ -1795,7 +1930,7 @@ pub(crate) fn structured_deserialize_with_transfer_internal(// [[ArrayBufferByteLength]] internal slot value is transferDataHolder.[[ArrayBufferByteLength]], and whose// [[ArrayBufferMaxByteLength]] internal slot value is transferDataHolder.[[ArrayBufferMaxByteLength]].// NOTE: For the same reason as the previous step, this step is also unlikely to throw an exception.- else if transfer_type == TransferType::ResizableArrayBuffer as u8 {+ else if transfer_type == TransferType::ResizableArrayBuffer {let buffer = decoder.decode_byte_buffer(target_realm)?;let max_byte_length = decoder.decode_size(target_realm)?;@@ -1814,13 +1949,25 @@ pub(crate) fn structured_deserialize_with_transfer_internal(// 1. Let interfaceName be transferDataHolder.[[Type]].// NB: Step 3 of StructuredDeserializeWithTransfer checks that every transferred interface is exposed before any// transfer-receiving steps run. The check runs here, per data holder, instead.- if !is_transferable_interface_exposed(transfer_type, target_realm) {+ let interface_name = transferable_interface_name(transfer_type).expect("the type names an interface");+ if !is_exposed(interface_name, target_realm) {return Err(data_clone_error("Unknown type transferred"));}// 2. Set value to a new instance of the interface identified by interfaceName, created in targetRealm.// 3. Perform the appropriate transfer-receiving steps for the interface identified by interfaceName given transferDataHolder and value.- value = create_transferred_platform_object(transfer_type, target_realm, decoder)?;+ let mut data_holder = TransferDataReader::new(decoder, target_realm);+ value = match transfer_type {+ TransferType::MessagePort => receive_transferred::<MessagePort>(cx, &mut data_holder)?,+ TransferType::ReadableStream => receive_transferred::<ReadableStream>(cx, &mut data_holder)?,+ TransferType::WritableStream => receive_transferred::<WritableStream>(cx, &mut data_holder)?,+ TransferType::TransformStream => receive_transferred::<TransformStream>(cx, &mut data_holder)?,+ TransferType::ImageBitmap => receive_transferred::<ImageBitmap>(cx, &mut data_holder)?,+ TransferType::OffscreenCanvas => offscreen_canvas::create_from_transfer(&mut data_holder)?,+ TransferType::ArrayBuffer | TransferType::ResizableArrayBuffer => {+ unreachable!("the type names an interface")+ }+ };}Ok(value)diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cppindex e84b615d509..14dbfc949f0 100644--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp@@ -86,13 +86,14 @@ JSCompletion completion_to_abi(JS::Realm& realm, WebIDL::ExceptionOr<JS::Value>// A value of the type that the data holder of a received object holds next, which its transfer-receiving steps read.template<typename T>-static JSCompletion decode_transfer_data(RustTransferDataReader* reader, T* out_value)+static JSCompletion decode_transfer_data(HTML::TransferDataDecoder* data_holder, void* realm, T* out_value){- auto value = HTML::decode_or_throw_data_clone_error<T>(reader->realm, reader->data_holder);+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ auto value = HTML::decode_or_throw_data_clone_error<T>(js_realm, *data_holder);if (value.is_exception())- return completion_to_abi(reader->realm, value.exception());+ return completion_to_abi(js_realm, value.exception());*out_value = value.release_value();- return completion_to_abi(reader->realm, JS::js_undefined());+ return completion_to_abi(js_realm, JS::js_undefined());}extern "C" {@@ -131,14 +132,13 @@ void web_bindings_with_temporary_execution_context(void* realm, bool callbacks_ebool web_bindings_object_implements_interface(JSObject* object, u16 interface_name);JSObject* web_bindings_create_dom_exception(void* realm, ReadonlyBytes name, FlatPtr message);bool web_bindings_extract_an_origin(JSObject* object, void* ctx, void (*on_origin)(void*, URL::FFI::FfiOrigin const*));-void web_bindings_transfer_data_encode_bool(RustTransferDataWriter*, bool);-void web_bindings_transfer_data_encode_records(RustTransferDataWriter*, HTML::SerializedTransferRecord const* const*, size_t count);-void web_bindings_transfer_data_encode_transport_handle(RustTransferDataWriter*, IPC::TransportHandle const*);-void web_bindings_transfer_data_extend(RustTransferDataWriter*, HTML::SerializedTransferRecord*);-JSCompletion web_bindings_transfer_data_decode_bool(RustTransferDataReader*, bool* out_value);-JSCompletion web_bindings_transfer_data_decode_records(RustTransferDataReader*, void* records, void (*append)(void*, HTML::SerializedTransferRecord*));-JSCompletion web_bindings_transfer_data_decode_transport_handle(RustTransferDataReader*, IPC::TransportHandle** out_handle);-HTML::TransferDataDecoder* web_bindings_transfer_data_decoder(RustTransferDataReader*);+void web_bindings_transfer_data_encode_bool(HTML::TransferDataEncoder*, bool);+void web_bindings_transfer_data_encode_records(HTML::TransferDataEncoder*, HTML::SerializedTransferRecord const* const*, size_t count);+void web_bindings_transfer_data_encode_transport_handle(HTML::TransferDataEncoder*, IPC::TransportHandle const*);+void web_bindings_transfer_data_extend(HTML::TransferDataEncoder*, HTML::SerializedTransferRecord*);+JSCompletion web_bindings_transfer_data_decode_bool(HTML::TransferDataDecoder*, void* realm, bool* out_value);+JSCompletion web_bindings_transfer_data_decode_records(HTML::TransferDataDecoder*, void* realm, void* records, void (*append)(void*, HTML::SerializedTransferRecord*));+JSCompletion web_bindings_transfer_data_decode_transport_handle(HTML::TransferDataDecoder*, void* realm, IPC::TransportHandle** out_handle);void web_bindings_transport_handle_destroy(IPC::TransportHandle*);IPC::Transport* web_bindings_transport_handle_create_transport(IPC::TransportHandle*);IPC::Transport* web_bindings_message_port_transport_create_paired(IPC::TransportHandle** out_remote_handle);@@ -317,59 +317,55 @@ bool web_bindings_extract_an_origin(JSObject* object, void* ctx, void (*on_origireturn true;}-void web_bindings_transfer_data_encode_bool(RustTransferDataWriter* writer, bool value)+void web_bindings_transfer_data_encode_bool(HTML::TransferDataEncoder* data_holder, bool value){- MUST(writer->data_holder.encode(value));+ MUST(data_holder->encode(value));}// Writes the records as a Vector of them is encoded, which web_bindings_transfer_data_decode_records() and C++ read.-void web_bindings_transfer_data_encode_records(RustTransferDataWriter* writer, HTML::SerializedTransferRecord const* const* records, size_t count)+void web_bindings_transfer_data_encode_records(HTML::TransferDataEncoder* data_holder, HTML::SerializedTransferRecord const* const* records, size_t count){- MUST(writer->data_holder.encode_size(count));+ MUST(data_holder->encode_size(count));for (size_t i = 0; i < count; ++i)- MUST(writer->data_holder.encode(*records[i]));+ MUST(data_holder->encode(*records[i]));}-void web_bindings_transfer_data_encode_transport_handle(RustTransferDataWriter* writer, IPC::TransportHandle const* handle)+void web_bindings_transfer_data_encode_transport_handle(HTML::TransferDataEncoder* data_holder, IPC::TransportHandle const* handle){- MUST(writer->data_holder.encode(*handle));+ MUST(data_holder->encode(*handle));}-void web_bindings_transfer_data_extend(RustTransferDataWriter* writer, HTML::SerializedTransferRecord* record)+void web_bindings_transfer_data_extend(HTML::TransferDataEncoder* data_holder, HTML::SerializedTransferRecord* record){- writer->data_holder.extend(move(record->transfer_data_holders));+ data_holder->extend(move(record->transfer_data_holders));}-JSCompletion web_bindings_transfer_data_decode_bool(RustTransferDataReader* reader, bool* out_value)+JSCompletion web_bindings_transfer_data_decode_bool(HTML::TransferDataDecoder* data_holder, void* realm, bool* out_value){- return decode_transfer_data(reader, out_value);+ return decode_transfer_data(data_holder, realm, out_value);}// Reads what web_bindings_transfer_data_encode_records() writes, and hands each record over.-JSCompletion web_bindings_transfer_data_decode_records(RustTransferDataReader* reader, void* records, void (*append)(void*, HTML::SerializedTransferRecord*))+JSCompletion web_bindings_transfer_data_decode_records(HTML::TransferDataDecoder* data_holder, void* realm, void* records, void (*append)(void*, HTML::SerializedTransferRecord*)){- auto decoded = HTML::decode_or_throw_data_clone_error<Vector<HTML::SerializedTransferRecord>>(reader->realm, reader->data_holder);+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ auto decoded = HTML::decode_or_throw_data_clone_error<Vector<HTML::SerializedTransferRecord>>(js_realm, *data_holder);if (decoded.is_exception())- return completion_to_abi(reader->realm, decoded.exception());+ return completion_to_abi(js_realm, decoded.exception());for (auto& record : decoded.value())append(records, new HTML::SerializedTransferRecord(move(record)));- return completion_to_abi(reader->realm, JS::js_undefined());+ return completion_to_abi(js_realm, JS::js_undefined());}// Reads a transport handle, and hands it over.-JSCompletion web_bindings_transfer_data_decode_transport_handle(RustTransferDataReader* reader, IPC::TransportHandle** out_handle)+JSCompletion web_bindings_transfer_data_decode_transport_handle(HTML::TransferDataDecoder* data_holder, void* realm, IPC::TransportHandle** out_handle){- auto handle = HTML::decode_or_throw_data_clone_error<IPC::TransportHandle>(reader->realm, reader->data_holder);+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ auto handle = HTML::decode_or_throw_data_clone_error<IPC::TransportHandle>(js_realm, *data_holder);if (handle.is_exception())- return completion_to_abi(reader->realm, handle.exception());+ return completion_to_abi(js_realm, handle.exception());*out_handle = new IPC::TransportHandle(handle.release_value());- return completion_to_abi(reader->realm, JS::js_undefined());-}--// The decoder of the data holder, for what the transfer-receiving steps read through structured deserialization.-HTML::TransferDataDecoder* web_bindings_transfer_data_decoder(RustTransferDataReader* reader)-{- return &reader->data_holder;+ return completion_to_abi(js_realm, JS::js_undefined());}void web_bindings_transport_handle_destroy(IPC::TransportHandle* handle)diff --git a/Libraries/LibWeb/Bindings/RustSerialization.h b/Libraries/LibWeb/Bindings/RustSerialization.hindex 96a9c66daf3..c0edeec68e9 100644--- a/Libraries/LibWeb/Bindings/RustSerialization.h+++ b/Libraries/LibWeb/Bindings/RustSerialization.h@@ -13,28 +13,8 @@#include <LibWeb/HTML/StructuredSerializeTypes.h>#include <LibWeb/WebIDL/ExceptionOr.h>-namespace Web::HTML {--struct ImageBitmapSharedPixels;--}-namespace Web::Bindings {-// The data holder of a transferred object. What the steps throw is created in the realm of the transfer.-struct RustTransferDataWriter {- GC::Ref<JS::Realm> realm;- HTML::TransferDataEncoder& data_holder;- // AD-HOC: The shared memory that the transfer gathers the pixels of its ImageBitmaps in, if it has some.- HTML::ImageBitmapSharedPixels* image_bitmap_pixels { nullptr };-};--// The data holder of a received object, in the realm that the object is created in.-struct RustTransferDataReader {- GC::Ref<JS::Realm> realm;- HTML::TransferDataDecoder& data_holder;-};-// What a function of the C ABI that the steps call returns to them: the value, or the exception, for which a// DOMException is created in the realm.WEB_API JSCompletion completion_to_abi(JS::Realm&, WebIDL::ExceptionOr<JS::Value>);diff --git a/Libraries/LibWeb/Bindings/Transferable.h b/Libraries/LibWeb/Bindings/Transferable.hdeleted file mode 100644index 3a65b72344c..00000000000--- a/Libraries/LibWeb/Bindings/Transferable.h+++ /dev/null@@ -1,37 +0,0 @@-/*- * Copyright (c) 2023, Andrew Kaster <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Vector.h>-#include <LibIPC/Forward.h>-#include <LibJS/Forward.h>-#include <LibWeb/WebIDL/ExceptionOr.h>--namespace Web::Bindings {--// https://html.spec.whatwg.org/multipage/structured-data.html#transferable-objects-class Transferable {-public:- virtual ~Transferable() = default;-- // NOTE: It is an error to call Base::transfer_steps in your impl- virtual WebIDL::ExceptionOr<void> transfer_steps(JS::Realm&, HTML::TransferDataEncoder&) = 0;-- // NOTE: It is an error to call Base::transfer_receiving_steps in your impl- virtual WebIDL::ExceptionOr<void> transfer_receiving_steps(JS::Realm&, HTML::TransferDataDecoder&) = 0;-- virtual HTML::TransferType primary_interface() const = 0;-- bool is_detached() const { return m_detached; }- void set_detached(bool b) { m_detached = b; }--private:- // https://html.spec.whatwg.org/multipage/structured-data.html#detached- bool m_detached = false;-};--}diff --git a/Libraries/LibWeb/HTML/ImageBitmap.cpp b/Libraries/LibWeb/HTML/ImageBitmap.cppindex f6f8760e552..c87f17d3c88 100644--- a/Libraries/LibWeb/HTML/ImageBitmap.cpp+++ b/Libraries/LibWeb/HTML/ImageBitmap.cpp@@ -306,8 +306,8 @@ struct FramePixels {size_t web_image_bitmap_frame_size_in_bytes(Gfx::DecodedImageFrame const*);void web_image_bitmap_frame_pixels(Gfx::DecodedImageFrame const*, FramePixels*);JSCompletion web_image_bitmap_create_frame(void* realm, FramePixels const*, Gfx::DecodedImageFrame** out_frame);-JSCompletion web_image_bitmap_transfer_bitmap(Bindings::RustTransferDataWriter*, Gfx::DecodedImageFrame const*);-JSCompletion web_image_bitmap_receive_bitmap(Bindings::RustTransferDataReader*, Gfx::DecodedImageFrame** out_frame);+JSCompletion web_image_bitmap_transfer_bitmap(void* realm, HTML::TransferDataEncoder*, ImageBitmapSharedPixels*, Gfx::DecodedImageFrame const*);+JSCompletion web_image_bitmap_receive_bitmap(void* realm, HTML::TransferDataDecoder*, Gfx::DecodedImageFrame** out_frame);size_t web_image_bitmap_frame_size_in_bytes(Gfx::DecodedImageFrame const* frame){@@ -386,21 +386,23 @@ JSCompletion web_image_bitmap_create_frame(void* realm, FramePixels const* pixelreturn Bindings::completion_to_abi(js_realm, JS::js_undefined());}-JSCompletion web_image_bitmap_transfer_bitmap(Bindings::RustTransferDataWriter* writer, Gfx::DecodedImageFrame const* frame)+JSCompletion web_image_bitmap_transfer_bitmap(void* realm, HTML::TransferDataEncoder* data_holder, ImageBitmapSharedPixels* image_bitmap_pixels, Gfx::DecodedImageFrame const* frame){- auto result = transfer_bitmap(writer->data_holder, writer->image_bitmap_pixels, frame);+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ auto result = transfer_bitmap(*data_holder, image_bitmap_pixels, frame);if (result.is_exception())- return Bindings::completion_to_abi(writer->realm, result.release_error());- return Bindings::completion_to_abi(writer->realm, JS::js_undefined());+ return Bindings::completion_to_abi(js_realm, result.release_error());+ return Bindings::completion_to_abi(js_realm, JS::js_undefined());}-JSCompletion web_image_bitmap_receive_bitmap(Bindings::RustTransferDataReader* reader, Gfx::DecodedImageFrame** out_frame)+JSCompletion web_image_bitmap_receive_bitmap(void* realm, HTML::TransferDataDecoder* data_holder, Gfx::DecodedImageFrame** out_frame){- auto frame = receive_bitmap(reader->realm, reader->data_holder);+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ auto frame = receive_bitmap(js_realm, *data_holder);if (frame.is_exception())- return Bindings::completion_to_abi(reader->realm, frame.release_error());+ return Bindings::completion_to_abi(js_realm, frame.release_error());*out_frame = frame_to_hand_over(frame.release_value());- return Bindings::completion_to_abi(reader->realm, JS::js_undefined());+ return Bindings::completion_to_abi(js_realm, JS::js_undefined());}}diff --git a/Libraries/LibWeb/HTML/MessagePort.cpp b/Libraries/LibWeb/HTML/MessagePort.cppindex 06db6773e7f..9ae733b7b5a 100644--- a/Libraries/LibWeb/HTML/MessagePort.cpp+++ b/Libraries/LibWeb/HTML/MessagePort.cpp@@ -29,10 +29,8 @@ void web_rust_message_port_discard_pending_messages(void* port);size_t web_rust_message_port_pending_outgoing_message_count(void* port);void web_rust_message_port_fail_next_transfer_for_testing(void* port);void web_rust_message_port_disentangle_ports_of_realm(JSVM*, void* realm);--// The entry points of the generated bindings of the interface.-JSCompletion web_rust_message_port_transfer_steps(JSVM*, void* realm, void* port, Bindings::RustTransferDataWriter*);-JSCompletion web_rust_message_port_transfer_receiving_steps(JSVM*, void* realm, Bindings::RustTransferDataReader*);+JSCompletion web_rust_message_port_transfer_steps(JSVM*, void* realm, void* port, TransferDataEncoder*);+JSCompletion web_rust_message_port_transfer_receiving_steps(JSVM*, void* realm, TransferDataDecoder*);}static JSVM* vm_abi()@@ -47,8 +45,7 @@ GC::Ref<MessagePort> MessagePort::create(JS::Realm& realm)GC::Ref<MessagePort> MessagePort::create_from_transfer(JS::Realm& realm, TransferDataDecoder& data_holder){- Bindings::RustTransferDataReader reader { .realm = realm, .data_holder = data_holder };- auto wrapper = MUST(JS::HostABI::completion_from_abi<JS::Value>(web_rust_message_port_transfer_receiving_steps(vm_abi(), &realm, &reader)));+ auto wrapper = MUST(JS::HostABI::completion_from_abi<JS::Value>(web_rust_message_port_transfer_receiving_steps(vm_abi(), &realm, &data_holder)));return *Bindings::impl_from<MessagePort>(&wrapper.as_object());}@@ -99,8 +96,7 @@ void MessagePort::discard_pending_messages()WebIDL::ExceptionOr<void> MessagePort::transfer_steps(JS::Realm& realm, TransferDataEncoder& data_holder){- Bindings::RustTransferDataWriter writer { .realm = realm, .data_holder = data_holder };- TRY(JS::HostABI::completion_from_abi<void>(web_rust_message_port_transfer_steps(vm_abi(), &realm, this, &writer)));+ TRY(JS::HostABI::completion_from_abi<void>(web_rust_message_port_transfer_steps(vm_abi(), &realm, this, &data_holder)));return {};}diff --git a/Libraries/LibWeb/HTML/OffscreenCanvas.cpp b/Libraries/LibWeb/HTML/OffscreenCanvas.cppindex 28affec7dd5..45accd931a7 100644--- a/Libraries/LibWeb/HTML/OffscreenCanvas.cpp+++ b/Libraries/LibWeb/HTML/OffscreenCanvas.cpp@@ -8,9 +8,11 @@#include <AK/TypeCasts.h>#include <LibGC/Heap.h>#include <LibGfx/Bitmap.h>+#include <LibJS/HostClassBuilder.h>#include <LibJS/Runtime/VM.h>#include <LibWeb/Bindings/CanvasRenderingContext2DSettings.h>#include <LibWeb/Bindings/PrincipalHostDefined.h>+#include <LibWeb/Bindings/RustSerialization.h>#include <LibWeb/Bindings/WrapperWorld.h>#include <LibWeb/CSS/ComputedValues.h>#include <LibWeb/CSS/FontComputer.h>@@ -96,7 +98,9 @@ WebIDL::ExceptionOr<void> OffscreenCanvas::transfer_steps(JS::Realm& realm, HTMLreturn WebIDL::InvalidStateError::create("Cannot transfer an OffscreenCanvas that has a rendering context"_utf16);// 2. Set value's context mode to detached.- // NB: The [[Detached]] internal slot is set once these steps return, and it also stands for this context mode.+ // NB: This context mode is the [[Detached]] internal slot, which StructuredSerializeWithTransfer sets again once+ // these steps return.+ m_detached = true;// 3. Let width and height be the dimensions of value's bitmap.auto width = m_width;@@ -149,11 +153,6 @@ WebIDL::ExceptionOr<void> OffscreenCanvas::transfer_receiving_steps(JS::Realm& rreturn {};}-HTML::TransferType OffscreenCanvas::primary_interface() const-{- return TransferType::OffscreenCanvas;-}-void OffscreenCanvas::replace_bitmap(){auto size = bitmap_size_for_canvas();@@ -511,3 +510,47 @@ JS::ThrowCompletionOr<HTML::OffscreenRenderingContext> get_context(JS::Realm& re}}++// What the transfer steps in Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize ask of OffscreenCanvas,+// declared on the Rust side in Libraries/LibWeb/Bindings/Rust/src/html/offscreen_canvas.rs.+extern "C" {++u16 web_offscreen_canvas_interface_name();+bool web_offscreen_canvas_is_detached(JSObject*);+JSCompletion web_offscreen_canvas_transfer_steps(void* realm, JSObject*, Web::HTML::TransferDataEncoder*);+JSCompletion web_offscreen_canvas_create_from_transfer(void* realm, Web::HTML::TransferDataDecoder*);++u16 web_offscreen_canvas_interface_name()+{+ return to_underlying(Web::Bindings::InterfaceName::OffscreenCanvas);+}++bool web_offscreen_canvas_is_detached(JSObject* object)+{+ return Web::Bindings::impl_from<Web::HTML::OffscreenCanvas>(JS::HostABI::object_from_abi(object))->is_detached();+}++JSCompletion web_offscreen_canvas_transfer_steps(void* realm, JSObject* object, Web::HTML::TransferDataEncoder* data_holder)+{+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ auto* offscreen_canvas = Web::Bindings::impl_from<Web::HTML::OffscreenCanvas>(JS::HostABI::object_from_abi(object));+ auto result = offscreen_canvas->transfer_steps(js_realm, *data_holder);+ if (result.is_exception())+ return Web::Bindings::completion_to_abi(js_realm, result.release_error());+ return Web::Bindings::completion_to_abi(js_realm, JS::js_undefined());+}++// A new OffscreenCanvas in the realm, after its transfer-receiving steps, as the value of the completion.+JSCompletion web_offscreen_canvas_create_from_transfer(void* realm, Web::HTML::TransferDataDecoder* data_holder)+{+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ auto* global_scope = Web::HTML::window_or_worker_global_scope_from_global_object(js_realm.global_object());+ VERIFY(global_scope);+ auto offscreen_canvas = Web::HTML::OffscreenCanvas::create(global_scope->this_impl(), 0, 0);+ auto result = offscreen_canvas->transfer_receiving_steps(js_realm, *data_holder);+ if (result.is_exception())+ return Web::Bindings::completion_to_abi(js_realm, result.release_error());+ auto wrapper = Web::Bindings::wrap(Web::Bindings::host_defined_wrapper_world(js_realm), js_realm, offscreen_canvas);+ return Web::Bindings::completion_to_abi(js_realm, JS::Value { wrapper });+}+}diff --git a/Libraries/LibWeb/HTML/OffscreenCanvas.h b/Libraries/LibWeb/HTML/OffscreenCanvas.hindex 709658cd765..050ae448e98 100644--- a/Libraries/LibWeb/HTML/OffscreenCanvas.h+++ b/Libraries/LibWeb/HTML/OffscreenCanvas.h@@ -8,7 +8,6 @@#include <LibGfx/Forward.h>#include <LibJS/Forward.h>-#include <LibWeb/Bindings/Transferable.h>#include <LibWeb/Compositor/CompositorHost.h>#include <LibWeb/DOM/EventTarget.h>#include <LibWeb/Forward.h>@@ -26,7 +25,6 @@ using OffscreenRenderingContext = Variant<GC::Ref<OffscreenCanvasRenderingContex// https://html.spec.whatwg.org/multipage/canvas.html#offscreencanvasclass OffscreenCanvas : public DOM::EventTarget- , public Web::Bindings::Transferable, public CanvasHost {WEB_WRAPPABLE(OffscreenCanvas, DOM::EventTarget);GC_DECLARE_ALLOCATOR(OffscreenCanvas);@@ -43,10 +41,10 @@ public:virtual GC::Ptr<Bindings::Wrappable> relevant_global_impl() const override { return m_global_object; }- // ^Web::Bindings::Transferable- virtual WebIDL::ExceptionOr<void> transfer_steps(JS::Realm&, HTML::TransferDataEncoder&) override;- virtual WebIDL::ExceptionOr<void> transfer_receiving_steps(JS::Realm&, HTML::TransferDataDecoder&) override;- virtual HTML::TransferType primary_interface() const override;+ WebIDL::ExceptionOr<void> transfer_steps(JS::Realm&, HTML::TransferDataEncoder&);+ WebIDL::ExceptionOr<void> transfer_receiving_steps(JS::Realm&, HTML::TransferDataDecoder&);++ bool is_detached() const { return m_detached; }WebIDL::UnsignedLongLong width() const { return m_width; }WebIDL::UnsignedLongLong height() const { return m_height; }@@ -102,6 +100,8 @@ private:Optional<Compositor::PlaceholderCanvasLink> m_placeholder_link;bool m_placeholder_commit_is_pending { false };++ bool m_detached { false };};}diff --git a/Libraries/LibWeb/HTML/StructuredSerialize.h b/Libraries/LibWeb/HTML/StructuredSerialize.hindex 19d59bfe493..1cc7b4129db 100644--- a/Libraries/LibWeb/HTML/StructuredSerialize.h+++ b/Libraries/LibWeb/HTML/StructuredSerialize.h@@ -129,16 +129,9 @@ WEB_API WebIDL::ExceptionOr<JS::Value> structured_deserialize_with_transfer_inte}-namespace Web::HTML {--struct ImageBitmapSharedPixels;--}-namespace Web::Bindings {class RustInterfaceCell;-class Transferable;// A platform object that is a serializable object: an implementation object of an interface implemented in C++, whose// steps run in Rust over its fields, or the cell of an object of an interface implemented in Rust, whose steps the Rust@@ -152,24 +145,8 @@ struct SerializablePlatformObject {WebIDL::ExceptionOr<void> serialization_steps(void* serialized, bool for_storage) const;};-// A platform object that is a transferable object, of an interface implemented in C++ or in Rust.-struct TransferablePlatformObject {- Transferable* transferable { nullptr };- GC::Ptr<RustInterfaceCell> rust_object { nullptr };- HTML::TransferType primary_interface { HTML::TransferType::Unknown };-- // https://html.spec.whatwg.org/multipage/structured-data.html#detached- bool is_detached() const;- void set_detached() const;-- // The pixels of a transferred ImageBitmap go to the shared memory of the transfer, if there is room for them.- WebIDL::ExceptionOr<void> transfer_steps(JS::Realm&, HTML::TransferDataEncoder&, HTML::ImageBitmapSharedPixels*) const;-};--WEB_API Optional<TransferablePlatformObject> transferable_from_object(JS::Object&);WEB_API Optional<SerializablePlatformObject> serializable_from_object(JS::Object&);WEB_API bool is_platform_object(JS::Object const&);-WEB_API WebIDL::ExceptionOr<GC::Ref<JS::HostObject>> create_transferred_platform_object(HTML::TransferType, JS::Realm&, HTML::TransferDataDecoder&);// The deserialization steps of an interface implemented in Rust create its object from what they read, rather than// fill in an object that was created before them. The record that they read is the Rust SerializationReader that thediff --git a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cppindex 57a27eb6d20..5ed7efddbe6 100644--- a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp+++ b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp@@ -14,14 +14,9 @@#include <LibJS/HostClassBuilder.h>#include <LibJS/Runtime/ArrayBuffer.h>#include <LibJS/Runtime/Realm.h>-#include <LibWeb/Bindings/ImageBitmap.h>#include <LibWeb/Bindings/Intrinsics.h>-#include <LibWeb/Bindings/MessagePort.h>#include <LibWeb/Bindings/PrincipalHostDefined.h>-#include <LibWeb/Bindings/ReadableStream.h>#include <LibWeb/Bindings/RustSerialization.h>-#include <LibWeb/Bindings/TransformStream.h>-#include <LibWeb/Bindings/WritableStream.h>#include <LibWeb/HTML/ImageBitmap.h>#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/StructuredSerialize.h>@@ -74,13 +69,6 @@ bool web_structured_serialize_is_exposed(u16 interface_name, void* realm);u8 web_structured_serialize_serializable_steps(u16 interface_name);JSCompletion web_structured_serialize_deserialize_rust_platform_object(u16 interface_name, void* realm, void* serialized);-bool web_structured_serialize_is_transferable(JSObject*);-bool web_structured_serialize_transferable_is_detached(JSObject*);-void web_structured_serialize_transferable_set_detached(JSObject*);-u8 web_structured_serialize_transferable_primary_interface(JSObject*);-JSCompletion web_structured_serialize_transfer_steps(void* realm, JSObject*, TransferDataEncoder*, ImageBitmapSharedPixels*);-bool web_structured_serialize_is_transferable_interface_exposed(u8 type, void* realm);-JSCompletion web_structured_serialize_create_transferred_platform_object(u8 type, void* realm, TransferDataDecoder*);ImageBitmapSharedPixels* web_structured_serialize_gather_image_bitmap_pixels(Vector<Core::AnonymousBuffer>*, JSObject* const* transfer_list, size_t count);void web_structured_serialize_image_bitmap_pixels_destroy(ImageBitmapSharedPixels*);@@ -321,68 +309,6 @@ JSCompletion web_structured_serialize_deserialize_rust_platform_object(u16 interreturn JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<JS::Value> { object.release_value() });}-bool web_structured_serialize_is_transferable(JSObject* object)-{- return Bindings::transferable_from_object(*JS::HostABI::object_from_abi(object)).has_value();-}--bool web_structured_serialize_transferable_is_detached(JSObject* object)-{- return Bindings::transferable_from_object(*JS::HostABI::object_from_abi(object))->is_detached();-}--void web_structured_serialize_transferable_set_detached(JSObject* object)-{- Bindings::transferable_from_object(*JS::HostABI::object_from_abi(object))->set_detached();-}--u8 web_structured_serialize_transferable_primary_interface(JSObject* object)-{- return to_underlying(Bindings::transferable_from_object(*JS::HostABI::object_from_abi(object))->primary_interface);-}--JSCompletion web_structured_serialize_transfer_steps(void* realm, JSObject* object, TransferDataEncoder* data_holder, ImageBitmapSharedPixels* image_bitmap_pixels)-{- auto& js_realm = realm_from_abi(realm);- auto transferable = Bindings::transferable_from_object(*JS::HostABI::object_from_abi(object));- return void_completion_to_abi(js_realm, transferable->transfer_steps(js_realm, *data_holder, image_bitmap_pixels));-}--bool web_structured_serialize_is_transferable_interface_exposed(u8 type, void* realm)-{- auto& js_realm = realm_from_abi(realm);- auto name = static_cast<TransferType>(type);- switch (name) {- case TransferType::MessagePort:- return is_exposed(Bindings::InterfaceName::MessagePort, js_realm);- case TransferType::ReadableStream:- return is_exposed(Bindings::InterfaceName::ReadableStream, js_realm);- case TransferType::WritableStream:- return is_exposed(Bindings::InterfaceName::WritableStream, js_realm);- case TransferType::TransformStream:- return is_exposed(Bindings::InterfaceName::TransformStream, js_realm);- case TransferType::ImageBitmap:- return is_exposed(Bindings::InterfaceName::ImageBitmap, js_realm);- case TransferType::OffscreenCanvas:- return is_exposed(Bindings::InterfaceName::OffscreenCanvas, js_realm);- case TransferType::Unknown:- dbgln("Unknown interface type for transfer: {}", to_underlying(name));- break;- default:- break;- }- return false;-}--JSCompletion web_structured_serialize_create_transferred_platform_object(u8 type, void* realm, TransferDataDecoder* decoder)-{- auto& js_realm = realm_from_abi(realm);- auto object = Bindings::create_transferred_platform_object(static_cast<TransferType>(type), js_realm, *decoder);- if (object.is_exception())- return Bindings::completion_to_abi(js_realm, WebIDL::ExceptionOr<JS::Value> { object.release_error() });- return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<JS::Value> { object.release_value() });-}-// AD-HOC: Gather the pixels of the transferred ImageBitmaps in one buffer of shared memory. Without it, as when there// is not enough memory for it, the pixels travel inline.ImageBitmapSharedPixels* web_structured_serialize_gather_image_bitmap_pixels(Vector<Core::AnonymousBuffer>* shared_buffers, JSObject* const* transfer_list, size_t count)diff --git a/Libraries/LibWeb/HTML/StructuredSerializeTypes.h b/Libraries/LibWeb/HTML/StructuredSerializeTypes.hindex e7e67afd792..0547b3af754 100644--- a/Libraries/LibWeb/HTML/StructuredSerializeTypes.h+++ b/Libraries/LibWeb/HTML/StructuredSerializeTypes.h@@ -16,18 +16,6 @@namespace Web::HTML {-enum class TransferType : u8 {- Unknown = 0,- MessagePort = 1,- ArrayBuffer = 2,- ResizableArrayBuffer = 3,- ReadableStream = 4,- WritableStream = 5,- TransformStream = 6,- ImageBitmap = 7,- OffscreenCanvas = 8,-};-// The per-interface payload version encoded after every SerializableObject's interface name in// storage records. The decoder requires an exact match, so a bump orphans stored records of every// type unless migration support is added alongside it.diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.pyindex 9e623249627..5a7e0cd9ada 100644--- a/Meta/Generators/libweb_bindings/rust_bindings.py+++ b/Meta/Generators/libweb_bindings/rust_bindings.py@@ -88,9 +88,9 @@ SUPPORTED_INTERFACE_EXTENDED_ATTRIBUTES = {"LegacyNoInterfaceObject","NavigatorCompatibilityMode","SecureContext",- # NB: The implementation implements structured_data::Serializable or structured_data::Transferable, whose steps- # StructuredSerialize of LibWeb's C++ runs through the entry points that write_rust_structured_data_entry_points()- # writes.+ # NB: The implementation implements structured_data::Serializable, whose steps StructuredSerialize of LibWeb's C+++ # runs through the entry points that write_rust_structured_data_entry_points() writes, or+ # structured_data::Transferable, whose steps crate::html::structured_serialize runs."Serializable","Transferable",}@@ -2023,7 +2023,7 @@ def write_rust_static_operation(def write_rust_structured_data_entry_points(out: TextIO, interface: Interface) -> None:"""The entry points through which StructuredSerialize of LibWeb's C++ runs the steps of an interface that is- serializable or transferable, which Meta/Generators/libweb_bindings/structured_serialize.py declares."""+ serializable, which Meta/Generators/libweb_bindings/structured_serialize.py declares."""if "Serializable" in interface.extended_attributes:out.write(f"""@@ -2058,63 +2058,6 @@ def write_rust_structured_data_entry_points(out: TextIO, interface: Interface) -// SAFETY: The caller passes live pointers.unsafe {{ structured_data::deserialization_steps::<Implementation>(vm, realm, serialized) }}}}-"""- )- if "Transferable" in interface.extended_attributes:- out.write(- f"""- /// The [[Detached]] internal slot of an object of the interface, for StructuredSerialize of LibWeb's C++.- ///- /// # Safety- ///- /// The cell must be the live cell of an object of the interface.- #[unsafe(no_mangle)]- pub unsafe extern "C" fn {rust_entry_point_name(interface, "is_detached")}(cell: *mut c_void) -> bool {{- // SAFETY: The caller passes a live cell.- unsafe {{ structured_data::is_detached::<Implementation>(cell) }}- }}-- /// Sets the [[Detached]] internal slot of an object of the interface to true.- ///- /// # Safety- ///- /// The cell must be the live cell of an object of the interface.- #[unsafe(no_mangle)]- pub unsafe extern "C" fn {rust_entry_point_name(interface, "set_detached")}(cell: *mut c_void) {{- // SAFETY: The caller passes a live cell.- unsafe {{ structured_data::set_detached::<Implementation>(cell) }}- }}-- /// The transfer steps of the interface.- ///- /// # Safety- ///- /// The pointers must be the VM, a live realm, the live cell of an object of the interface, and a lent data holder.- #[unsafe(no_mangle)]- pub unsafe extern "C" fn {rust_entry_point_name(interface, "transfer_steps")}(- vm: *mut c_void,- realm: *mut c_void,- cell: *mut c_void,- data_holder: *mut c_void,- ) -> RawNativeFunctionResult {{- // SAFETY: The caller passes live pointers.- unsafe {{ structured_data::transfer_steps::<Implementation>(vm, realm, cell, data_holder) }}- }}-- /// The transfer-receiving steps of the interface, which return the wrapper of the new object.- ///- /// # Safety- ///- /// The pointers must be the VM, a live realm, and a lent data holder.- #[unsafe(no_mangle)]- pub unsafe extern "C" fn {rust_entry_point_name(interface, "transfer_receiving_steps")}(- vm: *mut c_void,- realm: *mut c_void,- data_holder: *mut c_void,- ) -> RawNativeFunctionResult {{- // SAFETY: The caller passes live pointers.- unsafe {{ structured_data::transfer_receiving_steps::<Implementation>(vm, realm, data_holder) }}- }}""")diff --git a/Meta/Generators/libweb_bindings/structured_serialize.py b/Meta/Generators/libweb_bindings/structured_serialize.pyindex 804e06f9014..ca6e9f3f87a 100644--- a/Meta/Generators/libweb_bindings/structured_serialize.py+++ b/Meta/Generators/libweb_bindings/structured_serialize.py@@ -5,29 +5,16 @@from typing import Listfrom typing import TextIO-from Generators.libweb_bindings.cpp_types import fully_qualified_name_for_interface-from Generators.libweb_bindings.cpp_types import implementation_header_for_interfacefrom Generators.libweb_bindings.rust_bindings import rust_entry_point_namefrom Generators.libweb_bindings.rust_bindings import wrapper_host_class_symbolfrom Generators.libweb_bindings.rust_types import is_implemented_in_rustfrom Utils.webidl_parser import Interface-SUPPORTED_TRANSFER_TYPES = (- "ImageBitmap",- "MessagePort",- "OffscreenCanvas",- "ReadableStream",- "TransformStream",- "WritableStream",-)--def write_rust_entry_point_declarations(- out: TextIO, serializable: List[Interface], transferable: List[Interface]-) -> None:- """The entry points of the Rust bindings that run the steps of the serializable and transferable interfaces that- are implemented in Rust, which Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs describes."""- if not serializable and not transferable:+def write_rust_entry_point_declarations(out: TextIO, serializable: List[Interface]) -> None:+ """The entry points of the Rust bindings that run the steps of the serializable interfaces that are implemented in+ Rust, which Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs describes."""+ if not serializable:returnout.write('\nextern "C" {\n')for interface in serializable:@@ -36,64 +23,41 @@ def write_rust_entry_point_declarations(// The serialization steps and the deserialization steps of {interface.name}.JSCompletion {rust_entry_point_name(interface, "serialization_steps")}(JSVM*, void* realm, void* cell, void* serialized, bool for_storage);JSCompletion {rust_entry_point_name(interface, "deserialization_steps")}(JSVM*, void* realm, void* serialized);-"""- )- for interface in transferable:- out.write(- f"""-// The [[Detached]] internal slot, the transfer steps and the transfer-receiving steps of {interface.name}.-bool {rust_entry_point_name(interface, "is_detached")}(void* cell);-void {rust_entry_point_name(interface, "set_detached")}(void* cell);-JSCompletion {rust_entry_point_name(interface, "transfer_steps")}(JSVM*, void* realm, void* cell, RustTransferDataWriter*);-JSCompletion {rust_entry_point_name(interface, "transfer_receiving_steps")}(JSVM*, void* realm, RustTransferDataReader*);""")out.write("\n}\n")def write_structured_serialize_bindings_implementation(out: TextIO, interfaces: List[Interface]) -> None:- serializable = [interface for interface in interfaces if "Serializable" in interface.extended_attributes]- transferable = [- interface- for interface in interfaces- if "Transferable" in interface.extended_attributes and interface.name in SUPPORTED_TRANSFER_TYPES- ]- included_interfaces = sorted(- {interface.name: interface for interface in serializable + transferable}.values(),+ serializable = sorted(+ (interface for interface in interfaces if "Serializable" in interface.extended_attributes),key=lambda interface: interface.name,)# NB: The objects of an interface implemented in Rust are cells in the host data of their wrappers, whose steps- # the Rust bindings run. Every other serializable or transferable interface is implemented in C++.+ # the Rust bindings run. Every other serializable interface is implemented in C++.rust_serializable = [interface for interface in serializable if is_implemented_in_rust(interface)]- rust_transferable = [interface for interface in transferable if is_implemented_in_rust(interface)]out.write("""#include <LibGC/Heap.h>#include <LibJS/HostClassBuilder.h>#include <LibWeb/Bindings/RustInterface.h>#include <LibWeb/Bindings/RustSerialization.h>-#include <LibWeb/Bindings/Transferable.h>#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Bindings/WrapperWorld.h>-#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/StructuredSerialize.h>-#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>""")- for interface in included_interfaces:- out.write(f"#include <LibWeb/Bindings/{interface.implemented_name}.h>\n")+ for interface in serializable:# NB: The bindings find the cells of the objects of an interface implemented in Rust by the class of their# wrappers, which LibWeb/Bindings/<interface>.h declares, so they need no C++ class of the interface. A# serializable interface implemented in C++ needs none either, as its steps run in Rust.- if interface in transferable and not is_implemented_in_rust(interface):- out.write(f"#include <{implementation_header_for_interface(interface)}>\n")+ out.write(f"#include <LibWeb/Bindings/{interface.implemented_name}.h>\n")out.write("""namespace Web::Bindings {""")- write_rust_entry_point_declarations(out, rust_serializable, rust_transferable)+ write_rust_entry_point_declarations(out, rust_serializable)out.write("""bool is_platform_object(JS::Object const& object)@@ -101,94 +65,6 @@ bool is_platform_object(JS::Object const& object)return object.is_platform_object();}-Optional<TransferablePlatformObject> transferable_from_object(JS::Object& object)-{-"""- )- for interface in rust_transferable:- out.write(- f""" if (auto* cell = rust_interface_cell_of_wrapper(object, {wrapper_host_class_symbol(interface)}))- return TransferablePlatformObject {{ .rust_object = cell, .primary_interface = HTML::TransferType::{interface.name} }};-"""- )- out.write(- """- auto* wrappable = Bindings::wrappable_impl_from(&object);- if (!wrappable)- return {};-- auto* transferable = as_if<Transferable>(*wrappable);- if (!transferable)- return {};-- return TransferablePlatformObject { .transferable = transferable, .primary_interface = transferable->primary_interface() };-}--bool TransferablePlatformObject::is_detached() const-{- if (transferable)- return transferable->is_detached();-- switch (primary_interface) {-"""- )- for interface in rust_transferable:- out.write(- f""" case HTML::TransferType::{interface.name}:- return {rust_entry_point_name(interface, "is_detached")}(rust_object.ptr());-"""- )- out.write(- """ default:- VERIFY_NOT_REACHED();- }-}--void TransferablePlatformObject::set_detached() const-{- if (transferable) {- transferable->set_detached(true);- return;- }-- switch (primary_interface) {-"""- )- for interface in rust_transferable:- out.write(- f""" case HTML::TransferType::{interface.name}:- {rust_entry_point_name(interface, "set_detached")}(rust_object.ptr());- return;-"""- )- out.write(- """ default:- VERIFY_NOT_REACHED();- }-}--WebIDL::ExceptionOr<void> TransferablePlatformObject::transfer_steps(JS::Realm& realm, HTML::TransferDataEncoder& data_holder, [[maybe_unused]] HTML::ImageBitmapSharedPixels* image_bitmap_pixels) const-{- if (transferable)- return transferable->transfer_steps(realm, data_holder);-- [[maybe_unused]] RustTransferDataWriter writer { .realm = realm, .data_holder = data_holder, .image_bitmap_pixels = image_bitmap_pixels };- switch (primary_interface) {-"""- )- for interface in rust_transferable:- out.write(- f""" case HTML::TransferType::{interface.name}:- TRY(JS::HostABI::completion_from_abi<void>({rust_entry_point_name(interface, "transfer_steps")}(JS::HostABI::vm_to_abi(realm.vm()), &realm, rust_object.ptr(), &writer)));- return {{}};-"""- )- out.write(- """ default:- VERIFY_NOT_REACHED();- }-}-Optional<SerializablePlatformObject> serializable_from_object(JS::Object& object){"""@@ -276,45 +152,6 @@ WebIDL::ExceptionOr<GC::Ref<JS::HostObject>> deserialize_rust_platform_object(In}}-WebIDL::ExceptionOr<GC::Ref<JS::HostObject>> create_transferred_platform_object(HTML::TransferType name, JS::Realm& target_realm, HTML::TransferDataDecoder& decoder)-{- auto& wrapper_world = Bindings::host_defined_wrapper_world(target_realm);-- switch (name) {-"""- )- for interface in transferable:- out.write(f" case HTML::TransferType::{interface.name}: {{\n")- if is_implemented_in_rust(interface):- out.write(- f""" RustTransferDataReader reader {{ .realm = target_realm, .data_holder = decoder }};- auto wrapper = TRY(JS::HostABI::completion_from_abi<JS::Value>({rust_entry_point_name(interface, "transfer_receiving_steps")}(JS::HostABI::vm_to_abi(target_realm.vm()), &target_realm, &reader)));- return GC::Ref {{ as<JS::HostObject>(wrapper.as_object()) }};- }}-"""- )- continue- if interface.name == "OffscreenCanvas":- out.write(""" auto* global_scope = HTML::window_or_worker_global_scope_from_global_object(target_realm.global_object());- VERIFY(global_scope);- auto transferable = HTML::OffscreenCanvas::create(global_scope->this_impl(), 0, 0);-""")- else:- out.write(f" auto transferable = {fully_qualified_name_for_interface(interface)}::create();\n")- out.write(""" TRY(transferable->transfer_receiving_steps(target_realm, decoder));- return Bindings::wrap(wrapper_world, target_realm, transferable);- }-""")-- out.write(- """ case HTML::TransferType::ArrayBuffer:- case HTML::TransferType::ResizableArrayBuffer:- case HTML::TransferType::Unknown:- break;- }- VERIFY_NOT_REACHED();-}-}""")diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex 98acb70e7f4..02b9a4b8d0d 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -61,7 +61,7 @@ ALLOWED_REALM_MENTIONS = {"FileAPI": (2, 9, "Blob glue still creates streams and buffers in selected realms"),"HTML": (64,- 183,+ 185,"HTML algorithms still contain structured serialization, including posted-message preparation, canvas, navigation transfer/reconstruction, worker/worklet, and event realm use, and cross-origin Window/Location property functions are created in the current realm; RemoteWindow mirrors Window's postMessage; ""the C++ glue of the Rust structured serialization creates platform objects and SharedArrayBuffers in a given realm; ""the C++ glue of the Rust Storage and StorageEvent creates them in a given realm",