Skip to content

Truly independent web browser

Meta+LibWeb: Make interfaces implemented in Rust transferable

Andreas Kling8350b48b9de7
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs
index 1d69bb7dbed..afe99e2bbe3 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs
@@ -4,16 +4,18 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! What an interface implemented in Rust that is serializable does in a structured serialization,
-//! https://html.spec.whatwg.org/multipage/structured-data.html#serializable-objects
+//! What an interface implemented in Rust that is serializable or transferable does in a structured serialization,
+//! https://html.spec.whatwg.org/multipage/structured-data.html#serializable-objects and
+//! https://html.spec.whatwg.org/multipage/structured-data.html#transferable-objects
//!
//! StructuredSerialize of LibWeb's C++ runs the algorithms, and runs the steps of such an interface through the entry
//! points that the generated bindings of the interface define, which call the functions here. The steps read and
//! write the records of the serialization through 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 return.
+//! deserialization steps and its transfer-receiving steps return.
+use core::cell::Cell;
use core::ffi::c_void;
use core::marker::PhantomData;
use core::ptr::NonNull;
@@ -100,6 +102,46 @@ pub(crate) trait Serializable: Interface {
fn deserialization_steps(cx: &mut CallContext, serialized: &mut SerializationReader) -> WebIdlResult<Self>;
}
+/// The data holder of a transferred object, which its transfer steps write to: a Web::Bindings::RustTransferDataWriter
+/// that C++ lends for the steps.
+pub(crate) struct TransferDataWriter<'a> {
+ raw: NonNull<c_void>,
+ _lent: PhantomData<&'a mut c_void>,
+}
+
+impl TransferDataWriter<'_> {
+ /// 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()
+ }
+}
+
+/// The data holder of a received object, which its transfer-receiving steps read from: a
+/// Web::Bindings::RustTransferDataReader that C++ lends for the steps.
+pub(crate) struct TransferDataReader<'a> {
+ raw: NonNull<c_void>,
+ _lent: PhantomData<&'a mut c_void>,
+}
+
+impl TransferDataReader<'_> {
+ /// 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()
+ }
+}
+
+/// An interface that is transferable, [Transferable] in its IDL.
+pub(crate) trait Transferable: Interface {
+ /// The [[Detached]] internal slot of the object, https://html.spec.whatwg.org/multipage/structured-data.html#detached
+ fn detached(&self) -> &Cell<bool>;
+
+ /// https://html.spec.whatwg.org/multipage/structured-data.html#transfer-steps
+ fn transfer_steps(&self, cx: &mut CallContext, data_holder: &mut TransferDataWriter) -> WebIdlResult<()>;
+
+ /// https://html.spec.whatwg.org/multipage/structured-data.html#transfer-receiving-steps, which create the object.
+ fn transfer_receiving_steps(cx: &mut CallContext, data_holder: &mut TransferDataReader) -> WebIdlResult<Self>;
+}
+
/// The completion of steps, as the entry points return it to C++.
fn completion(cx: &CallContext, result: WebIdlResult<Value>) -> RawNativeFunctionResult {
let result: ThrowCompletionOr<Value> = result.map_err(|exception| exception.throw(cx));
@@ -154,3 +196,68 @@ pub(crate) unsafe fn deserialization_steps<T: Serializable>(
let result = T::deserialization_steps(&mut cx, &mut 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 = object.transfer_steps(&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/RustSerialization.h b/Libraries/LibWeb/Bindings/RustSerialization.h
index fce428cef2f..4d439dfa1eb 100644
--- a/Libraries/LibWeb/Bindings/RustSerialization.h
+++ b/Libraries/LibWeb/Bindings/RustSerialization.h
@@ -13,9 +13,15 @@
#include <LibWeb/HTML/StructuredSerializeTypes.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
+namespace Web::HTML {
+
+struct ImageBitmapSharedPixels;
+
+}
+
namespace Web::Bindings {
-// What the steps of a serializable interface implemented in Rust read and write, which the Rust bindings
+// What the steps of a serializable or transferable interface implemented in Rust read and write, which the Rust bindings
// hold as opaque pointers (Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs). They read and write through
// the C ABI of RustBindingsServices.cpp, and through that of the C++ class of their interface for what only C++
// encodes.
@@ -37,6 +43,20 @@ struct RustSerializationReader {
HTML::DeserializationMemory& memory;
};
+// 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/HTML/ImageBitmap.cpp b/Libraries/LibWeb/HTML/ImageBitmap.cpp
index 26bb59f5b30..d9e458cba5d 100644
--- a/Libraries/LibWeb/HTML/ImageBitmap.cpp
+++ b/Libraries/LibWeb/HTML/ImageBitmap.cpp
@@ -204,7 +204,7 @@ WebIDL::ExceptionOr<void> ImageBitmap::transfer_steps(JS::Realm&, HTML::Transfer
return transfer_steps(data_holder, nullptr);
}
-WebIDL::ExceptionOr<void> ImageBitmap::transfer_steps(HTML::TransferDataEncoder& data_holder, SharedPixels* shared_pixels)
+WebIDL::ExceptionOr<void> ImageBitmap::transfer_steps(HTML::TransferDataEncoder& data_holder, ImageBitmapSharedPixels* shared_pixels)
{
// FIXME: 1. If value's origin-clean flag is not set, then throw a "DataCloneError" DOMException.
diff --git a/Libraries/LibWeb/HTML/ImageBitmap.h b/Libraries/LibWeb/HTML/ImageBitmap.h
index 695328daf9a..475c709d775 100644
--- a/Libraries/LibWeb/HTML/ImageBitmap.h
+++ b/Libraries/LibWeb/HTML/ImageBitmap.h
@@ -26,6 +26,15 @@ using ResizeQuality = Bindings::ResizeQuality;
// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#imagebitmapoptions
using ImageBitmapOptions = Bindings::ImageBitmapOptions;
+// AD-HOC: The pixels of every ImageBitmap that one message transfers share one buffer of shared memory, which the
+// message carries alongside the memory of its SharedArrayBuffers. However many bitmaps a message transfers,
+// their pixels then take one attachment, and the receiver uses them without copying.
+struct ImageBitmapSharedPixels {
+ Core::AnonymousBuffer buffer;
+ u32 buffer_index { 0 };
+ size_t used_size { 0 };
+};
+
class WEB_API ImageBitmap final
: public Bindings::GCAllocatedWrappable
, public Web::Bindings::Serializable
@@ -53,16 +62,8 @@ public:
// Implementation specific:
- // AD-HOC: The pixels of every ImageBitmap that one message transfers share one buffer of shared memory, which the
- // message carries alongside the memory of its SharedArrayBuffers. However many bitmaps a message transfers,
- // their pixels then take one attachment, and the receiver uses them without copying.
- struct SharedPixels {
- Core::AnonymousBuffer buffer;
- u32 buffer_index { 0 };
- size_t used_size { 0 };
- };
static size_t shared_pixels_size(Gfx::Bitmap const&);
- WebIDL::ExceptionOr<void> transfer_steps(HTML::TransferDataEncoder&, SharedPixels*);
+ WebIDL::ExceptionOr<void> transfer_steps(HTML::TransferDataEncoder&, ImageBitmapSharedPixels*);
void set_bitmap(RefPtr<Gfx::Bitmap>);
Gfx::Bitmap* bitmap() const;
diff --git a/Libraries/LibWeb/HTML/StructuredSerialize.cpp b/Libraries/LibWeb/HTML/StructuredSerialize.cpp
index 4d0442f77e1..b2f1cbbe710 100644
--- a/Libraries/LibWeb/HTML/StructuredSerialize.cpp
+++ b/Libraries/LibWeb/HTML/StructuredSerialize.cpp
@@ -2249,7 +2249,7 @@ WebIDL::ExceptionOr<SerializedTransferRecord> structured_serialize_with_transfer
// 1. If transferable has neither an [[ArrayBufferData]] internal slot nor a [[Detached]] internal slot, then throw a "DataCloneError" DOMException.
// FIXME: Handle transferring objects with [[Detached]] internal slot.
- if (!as_array_buffer && !Bindings::transferable_from_object(*transferable))
+ if (!as_array_buffer && !Bindings::transferable_from_object(*transferable).has_value())
return WebIDL::DataCloneError::create("Cannot transfer type"_utf16);
// 2. If transferable has an [[ArrayBufferData]] internal slot and IsSharedArrayBuffer(transferable) is true, then throw a "DataCloneError" DOMException.
@@ -2274,7 +2274,7 @@ WebIDL::ExceptionOr<SerializedTransferRecord> structured_serialize_with_transfer
// 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.
- Optional<ImageBitmap::SharedPixels> image_bitmap_pixels;
+ Optional<ImageBitmapSharedPixels> image_bitmap_pixels;
Checked<size_t> image_bitmap_pixels_size = 0;
for (auto const& transferable : transfer_list) {
if (auto* image_bitmap = Bindings::impl_from<ImageBitmap>(transferable.ptr()); image_bitmap && image_bitmap->bitmap())
@@ -2282,7 +2282,7 @@ WebIDL::ExceptionOr<SerializedTransferRecord> structured_serialize_with_transfer
}
if (!image_bitmap_pixels_size.has_overflow() && image_bitmap_pixels_size.value() > 0) {
if (auto buffer = Core::AnonymousBuffer::create_with_size(image_bitmap_pixels_size.value(), Core::AnonymousBuffer::Sealability::Sealable); !buffer.is_error()) {
- image_bitmap_pixels = ImageBitmap::SharedPixels { .buffer = buffer.release_value(), .buffer_index = static_cast<u32>(serialized_writer.shared_buffers().size()) };
+ image_bitmap_pixels = ImageBitmapSharedPixels { .buffer = buffer.release_value(), .buffer_index = static_cast<u32>(serialized_writer.shared_buffers().size()) };
serialized_writer.shared_buffers().append(image_bitmap_pixels->buffer);
}
}
@@ -2301,7 +2301,7 @@ WebIDL::ExceptionOr<SerializedTransferRecord> structured_serialize_with_transfer
return WebIDL::DataCloneError::create("Cannot transfer detached buffer"_utf16);
// 2. If transferable has a [[Detached]] internal slot and transferable.[[Detached]] is true, then throw a "DataCloneError" DOMException.
- if (auto* transferable_object = Bindings::transferable_from_object(*transferable)) {
+ if (auto transferable_object = Bindings::transferable_from_object(*transferable); transferable_object.has_value()) {
if (transferable_object->is_detached())
return WebIDL::DataCloneError::create("Value already transferred"_utf16);
}
@@ -2343,11 +2343,11 @@ WebIDL::ExceptionOr<SerializedTransferRecord> structured_serialize_with_transfer
// 5. Otherwise:
else {
// 1. Assert: transferable is a platform object that is a transferable object.
- auto& transferable_object = *Bindings::transferable_from_object(*transferable);
+ auto transferable_object = Bindings::transferable_from_object(*transferable).release_value();
VERIFY(Bindings::is_platform_object(*transferable));
// 2. Let interfaceName be the identifier of the primary interface of transferable.
- auto interface_name = transferable_object.primary_interface();
+ auto interface_name = transferable_object.primary_interface;
// 3. Set dataHolder.[[Type]] to interfaceName.
MUST(data_holder.encode(interface_name));
@@ -2356,10 +2356,10 @@ WebIDL::ExceptionOr<SerializedTransferRecord> structured_serialize_with_transfer
if (interface_name == TransferType::ImageBitmap)
TRY(Bindings::impl_from<ImageBitmap>(transferable.ptr())->transfer_steps(data_holder, image_bitmap_pixels.has_value() ? &image_bitmap_pixels.value() : nullptr));
else
- TRY(transferable_object.transfer_steps(realm, data_holder));
+ TRY(transferable_object.transfer_steps(realm, data_holder, image_bitmap_pixels.has_value() ? &image_bitmap_pixels.value() : nullptr));
// 5. Set transferable.[[Detached]] to true.
- transferable_object.set_detached(true);
+ transferable_object.set_detached();
}
// 6. Append dataHolder to transferDataHolders.
diff --git a/Libraries/LibWeb/HTML/StructuredSerialize.h b/Libraries/LibWeb/HTML/StructuredSerialize.h
index 7462d817bd4..d5dda91db71 100644
--- a/Libraries/LibWeb/HTML/StructuredSerialize.h
+++ b/Libraries/LibWeb/HTML/StructuredSerialize.h
@@ -226,6 +226,12 @@ WEB_API WebIDL::ExceptionOr<JS::Value> structured_deserialize_with_transfer_inte
}
+namespace Web::HTML {
+
+struct ImageBitmapSharedPixels;
+
+}
+
namespace Web::Bindings {
class RustInterfaceCell;
@@ -243,7 +249,21 @@ struct SerializablePlatformObject {
WebIDL::ExceptionOr<void> serialization_steps(HTML::StructuredSerializeWriter&, bool for_storage, HTML::SerializationMemory&) const;
};
-WEB_API Transferable* transferable_from_object(JS::Object&);
+// 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 GC::Ref<JS::HostObject> create_serialized_platform_object(InterfaceName, JS::Realm&);
diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.py
index 09660511abf..17ca9a0eb63 100644
--- a/Meta/Generators/libweb_bindings/rust_bindings.py
+++ b/Meta/Generators/libweb_bindings/rust_bindings.py
@@ -66,9 +66,11 @@ SUPPORTED_INTERFACE_EXTENDED_ATTRIBUTES = {
"LegacyNoInterfaceObject",
"NavigatorCompatibilityMode",
"SecureContext",
- # 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.
+ # 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.
"Serializable",
+ "Transferable",
}
@@ -592,7 +594,7 @@ def write_rust_interface(
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, which Meta/Generators/libweb_bindings/structured_serialize.py declares."""
+ serializable or transferable, which Meta/Generators/libweb_bindings/structured_serialize.py declares."""
if "Serializable" in interface.extended_attributes:
out.write(
f"""
@@ -627,6 +629,63 @@ 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.py
index 7632ad36098..79272e39f73 100644
--- a/Meta/Generators/libweb_bindings/structured_serialize.py
+++ b/Meta/Generators/libweb_bindings/structured_serialize.py
@@ -21,10 +21,12 @@ SUPPORTED_TRANSFER_TYPES = (
)
-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:
+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:
return
out.write('\nextern "C" {\n')
for interface in serializable:
@@ -33,6 +35,16 @@ def write_rust_entry_point_declarations(out: TextIO, serializable: List[Interfac
// The serialization steps and the deserialization steps of {interface.name}.
JSCompletion {rust_entry_point_name(interface, "serialization_steps")}(JSVM*, void* realm, void* cell, RustSerializationWriter*, bool for_storage);
JSCompletion {rust_entry_point_name(interface, "deserialization_steps")}(JSVM*, void* realm, RustSerializationReader*);
+"""
+ )
+ 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")
@@ -50,8 +62,9 @@ def write_structured_serialize_bindings_implementation(out: TextIO, interfaces:
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 interface is implemented in C++.
+ # the Rust bindings run. Every other serializable or transferable 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>
@@ -76,7 +89,7 @@ def write_structured_serialize_bindings_implementation(out: TextIO, interfaces:
namespace Web::Bindings {
"""
)
- write_rust_entry_point_declarations(out, rust_serializable)
+ write_rust_entry_point_declarations(out, rust_serializable, rust_transferable)
out.write(
"""
bool is_platform_object(JS::Object const& object)
@@ -84,13 +97,92 @@ bool is_platform_object(JS::Object const& object)
return object.is_platform_object();
}
-Transferable* transferable_from_object(JS::Object& object)
+Optional<TransferablePlatformObject> transferable_from_object(JS::Object& object)
{
+"""
+ )
+ for interface in rust_transferable:
+ out.write(
+ f""" if (auto* cell = Bindings::impl_from<{fully_qualified_name_for_interface(interface)}>(&object))
+ return TransferablePlatformObject {{ .rust_object = cell, .primary_interface = HTML::TransferType::{interface.name} }};
+"""
+ )
+ out.write(
+ """
auto* wrappable = Bindings::wrappable_impl_from(&object);
if (!wrappable)
- return nullptr;
+ 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);
- return as_if<Transferable>(*wrappable);
+ [[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)
@@ -204,6 +296,15 @@ WebIDL::ExceptionOr<GC::Ref<JS::HostObject>> create_transferred_platform_object(
)
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 == "MessagePort":
out.write(""" auto transferable = HTML::MessagePort::create(Bindings::impl_from<DOM::EventTarget>(target_realm.global_object()));
""")
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index b7835177622..f1e556085dd 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -53,7 +53,7 @@ ALLOWED_REALM_MENTIONS = {
"Geometry": (8, 8, "geometry constructors and structured clone still materialize JS-facing geometry objects"),
"HTML": (
71,
- 216,
+ 217,
"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",
),
"IndexedDB": (