Skip to content

Truly independent web browser

LibWeb: Hold BroadcastChannel messages as Rust records

Shannon Booth0ed3a0137b9a
diff --git a/Libraries/LibJS/Rust/src/api.rs b/Libraries/LibJS/Rust/src/api.rs
index 45369464805..06774508ff3 100644
--- a/Libraries/LibJS/Rust/src/api.rs
+++ b/Libraries/LibJS/Rust/src/api.rs
@@ -20,6 +20,9 @@ pub use crate::gc::embedder_cell::{EmbedderCell, EmbedderClass, EmbedderValue};
pub use crate::gc::foreign::ForeignCellSlot;
pub use crate::gc::gc_ref_cell::{GcRefCell, GcRefMut};
pub use crate::gc::root::{CellRoot, MarkedVec, Root};
+pub use crate::gc::shared_memory::{
+ AsSharedMemory, OwnedSharedMemory, borrowed_from_raw_descriptor, into_raw_descriptor,
+};
pub use crate::gc::visitor::{Trace, Visitor};
pub use crate::gc::weak::GcWeak;
pub use crate::interpreter::vm::{TypeErrorRealmScope, Vm};
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rs b/Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rs
index 102d7a84926..a95c2c79ed0 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rs
@@ -9,13 +9,11 @@
//! BroadcastChannel, https://html.spec.whatwg.org/multipage/web-messaging.html#broadcasting-to-other-browsing-contexts
use core::cell::{Cell, RefCell};
-use core::ffi::c_void;
+use core::ffi::{c_int, c_void};
use core::ptr::NonNull;
-use std::collections::VecDeque;
-use std::rc::Rc;
use ak::Utf16String;
-use libjs_rust::api::{EmbedderCell, Gc, GcWeak, MarkedVec, Realm, Trace, Value, Vm};
+use libjs_rust::api::{EmbedderCell, EmbedderClass, EmbedderValue, Gc, GcWeak, MarkedVec, Realm, Trace, Value, Vm};
use liburl_rust::FfiOrigin;
use liburl_rust::origin::Origin;
@@ -26,17 +24,11 @@ use crate::bindings::global_object::{
use crate::bindings::interface::{Ref, Wrappable, Wrapped, allocate};
use crate::bindings::promise::{TaskSource, queue_a_global_task};
use crate::bindings::{CallContext, Exception, WebIdlResult};
-use crate::html::structured_serialize::cpp::{IPCSerializationRecord, ReceivedIPCSerializationRecord, SharedBuffers};
-use crate::html::structured_serialize::{
- structured_deserialize_with_shared_buffers, structured_serialize_with_shared_buffers,
-};
+use crate::html::structured_serialize::message_record::MessageRecord;
+use crate::html::structured_serialize::{structured_deserialize_message, structured_serialize_for_message};
use crate::storage_api::storage_key::{StorageKey, obtain_a_storage_key_for_non_storage_purposes};
unsafe extern "C" {
- fn web_html_broadcast_channel_create_serialized_message() -> *mut c_void;
- fn web_html_broadcast_channel_destroy_serialized_message(message: *mut c_void);
- fn web_html_broadcast_channel_serialized_message_record(message: *mut c_void) -> *mut c_void;
- fn web_html_broadcast_channel_serialized_message_shared_buffers(message: *mut c_void) -> *mut c_void;
fn web_html_broadcast_channel_relevant_settings_object_origin(
realm: *mut c_void,
ctx: *mut c_void,
@@ -50,69 +42,36 @@ unsafe extern "C" {
fn web_html_broadcast_channel_post_message_to_other_processes(
realm: *mut c_void,
channel_name: usize,
- message: *const c_void,
+ serialized_message: ak::Span<'_, u8>,
+ shared_memory: *const c_int,
+ shared_memory_sizes: *const usize,
+ shared_memory_count: usize,
);
}
-/// The serialized message and the shared memory of its SharedArrayBuffers, which LibWeb's C++ code keeps as a
-/// BroadcastChannelSerializedMessage that this owns.
-pub(crate) struct SerializedMessage(NonNull<c_void>);
-
-impl SerializedMessage {
- fn new() -> Self {
- // SAFETY: LibWeb returns a new message, which this owns.
- Self(NonNull::new(unsafe { web_html_broadcast_channel_create_serialized_message() }).expect("LibWeb allocates"))
- }
-
- /// # Safety
- ///
- /// `message` must be a message that LibWeb hands over.
- pub(crate) unsafe fn from_raw(message: *mut c_void) -> Self {
- Self(NonNull::new(message).expect("LibWeb hands over a message"))
- }
-
- fn record(&self) -> IPCSerializationRecord {
- // SAFETY: This owns the message, which lends its record for as long as it lives.
- unsafe {
- IPCSerializationRecord::from_raw(web_html_broadcast_channel_serialized_message_record(self.0.as_ptr()))
- }
- }
-
- fn received_record(&self) -> ReceivedIPCSerializationRecord<'_> {
- // SAFETY: This owns the message, which lends its record for as long as it lives.
- unsafe {
- ReceivedIPCSerializationRecord::from_raw(web_html_broadcast_channel_serialized_message_record(
- self.0.as_ptr(),
- ))
- }
- }
-
- fn shared_buffers(&self) -> SharedBuffers {
- // SAFETY: This owns the message, which lends its list for as long as it lives.
- unsafe {
- SharedBuffers::from_raw(web_html_broadcast_channel_serialized_message_shared_buffers(
- self.0.as_ptr(),
- ))
- }
- }
-}
-
-impl Drop for SerializedMessage {
- fn drop(&mut self) {
- // SAFETY: This owns the message.
- unsafe { web_html_broadcast_channel_destroy_serialized_message(self.0.as_ptr()) };
- }
-}
-
/// A message that a BroadcastChannel posted, in this agent or in another process: what the tasks that steps 6 to 9 of
/// postMessage() queue read.
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
pub(crate) struct BroadcastChannelMessage {
+ #[gc(untraced)]
pub(crate) storage_key: StorageKey,
+ #[gc(untraced)]
pub(crate) channel_name: Utf16String,
+ #[gc(untraced)]
pub(crate) source_origin: Origin,
- pub(crate) serialized: SerializedMessage,
+ pub(crate) serialized: MessageRecord,
+}
+
+pub(crate) static BROADCAST_CHANNEL_MESSAGE_CLASS: EmbedderClass<BroadcastChannelMessage> =
+ EmbedderClass::new("BroadcastChannelMessage");
+
+impl EmbedderValue for BroadcastChannelMessage {
+ const CLASS: &'static EmbedderClass<Self> = &BROADCAST_CHANNEL_MESSAGE_CLASS;
}
+pub(crate) type BroadcastChannelMessageRef = Gc<EmbedderCell<BroadcastChannelMessage>>;
+
// https://html.spec.whatwg.org/multipage/web-messaging.html#broadcastchannel
#[derive(Trace)]
#[gc(crate = libjs_rust)]
@@ -129,10 +88,6 @@ pub(crate) struct BroadcastChannel {
origin: Origin,
#[gc(untraced)]
storage_key: StorageKey,
-
- // The messages whose tasks have not run yet. Each task takes the message at the front.
- #[gc(untraced)]
- queued_messages: RefCell<VecDeque<Rc<BroadcastChannelMessage>>>,
}
impl Wrappable for BroadcastChannel {
@@ -218,7 +173,6 @@ impl BroadcastChannel {
closed_flag: Cell::new(false),
origin: relevant_settings_object_origin(realm),
storage_key: obtain_a_storage_key_for_non_storage_purposes(realm),
- queued_messages: RefCell::new(VecDeque::new()),
});
channel.event_target.set_owner(channel);
channel.event_target.set_event_listener_list_changed_steps::<Self>();
@@ -288,8 +242,7 @@ impl BroadcastChannel {
// AD-HOC: This message reaches agents in other processes through the browser process — so a shared-memory-backed
// SharedArrayBuffer travels beside the record, by file descriptor, and every receiver references the same
// [[ArrayBufferData]] rather than a copy.
- let serialized = SerializedMessage::new();
- structured_serialize_with_shared_buffers(cx, message, serialized.record(), serialized.shared_buffers())?;
+ let serialized = structured_serialize_for_message(cx.vm(), cx.realm(), message)?;
// 4. Let sourceOrigin be this's relevant settings object's origin.
let source_origin = this.origin.clone();
@@ -297,22 +250,27 @@ impl BroadcastChannel {
// 5. Let sourceStorageKey be the result of running obtain a storage key for non-storage purposes with this's relevant settings object.
let source_storage_key = this.storage_key.clone();
- let message = Rc::new(BroadcastChannelMessage {
+ let message = BROADCAST_CHANNEL_MESSAGE_CLASS.allocate(cx.vm(), |defer_gc| BroadcastChannelMessage {
storage_key: source_storage_key,
channel_name: this.channel_name.clone(),
source_origin,
- serialized,
+ serialized: serialized.finish_message_record(defer_gc),
});
// Steps 6-9.
- Self::deliver_message_locally(cx.vm(), &message, Some(*this));
+ Self::deliver_message_locally(cx.vm(), message, Some(*this));
- // SAFETY: The realm is live, and the name and the message are lent for the call.
+ let (shared_memory, shared_memory_sizes) = message.serialized.duplicate_shared_memory();
+ // SAFETY: The realm is live, the name and the bytes are lent for the call, and the call takes over the
+ // duplicated descriptors.
unsafe {
web_html_broadcast_channel_post_message_to_other_processes(
this.realm.as_ptr().cast(),
message.channel_name.raw_identity(),
- message.serialized.0.as_ptr(),
+ ak::Span::new(&message.serialized.bytes),
+ shared_memory.as_ptr(),
+ shared_memory_sizes.as_ptr(),
+ shared_memory.len(),
);
}
@@ -320,7 +278,7 @@ impl BroadcastChannel {
}
// https://html.spec.whatwg.org/multipage/web-messaging.html#dom-broadcastchannel-postmessage
- pub(crate) fn deliver_message_locally(vm: &Vm, message: &Rc<BroadcastChannelMessage>, source: Option<Ref<Self>>) {
+ pub(crate) fn deliver_message_locally(vm: &Vm, message: BroadcastChannelMessageRef, source: Option<Ref<Self>>) {
// 6. Let destinations be a list of BroadcastChannel objects that match the following criteria:
// * They are eligible for messaging.
// * The result of running obtain a storage key for non-storage purposes with their relevant settings object equals sourceStorageKey.
@@ -345,18 +303,12 @@ impl BroadcastChannel {
// 9. For each destination in destinations, queue a global task on the DOM manipulation task source given destination's relevant global object to perform the following steps:
for destination in destinations.values().iter() {
- destination.queued_messages.borrow_mut().push_back(Rc::clone(message));
queue_a_global_task(
vm,
destination.realm,
TaskSource::DOMManipulation,
- *destination,
- |vm, destination| {
- let Some(message) = destination.queued_messages.borrow_mut().pop_front() else {
- return;
- };
- Self::message_task_steps(destination, vm, &message);
- },
+ (*destination, message),
+ |vm, (destination, message)| Self::message_task_steps(destination, vm, &message),
);
}
}
@@ -372,11 +324,7 @@ impl BroadcastChannel {
let cx = CallContext::new(vm, target_realm);
// 3. Let data be StructuredDeserialize(serialized, targetRealm).
- let data = structured_deserialize_with_shared_buffers(
- &cx,
- message.serialized.received_record(),
- message.serialized.shared_buffers(),
- );
+ let data = structured_deserialize_message(&cx, &message.serialized);
let Ok(data) = data else {
// If this throws an exception, catch it, fire an event named messageerror at destination, using MessageEvent, with its
// origin initialized to sourceOrigin, and then abort these steps.
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
index d1f82d5b35f..c91c7af5d20 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
@@ -10,22 +10,22 @@
//! the function says. Libraries/LibWeb/HTML/BroadcastChannel.cpp hands the BroadcastChannel objects the messages that
//! other processes post.
-use core::ffi::c_void;
+use core::ffi::{c_int, c_void};
use core::ptr::NonNull;
-use std::rc::Rc;
use ak::Utf16String;
use libgfx_rust::image_frame::ImageFrameHandle;
use libjs_rust::api::{Gc, MarkedVec, Object, RawNativeFunctionResult, Value, Vm};
use liburl_rust::FfiOrigin;
-use super::broadcast_channel::{BroadcastChannel, BroadcastChannelMessage, SerializedMessage};
+use super::broadcast_channel::{BROADCAST_CHANNEL_MESSAGE_CLASS, BroadcastChannel, BroadcastChannelMessage};
use super::image_bitmap::ImageBitmap;
use super::image_data::ImageData;
use super::message_port::MessagePort;
use crate::bindings::CallContext;
use crate::bindings::event_target::CppEventTarget;
use crate::bindings::interface::{Interface, Ref, cell_from_abi, cell_into_abi, realm_arguments};
+use crate::html::structured_serialize::message_record::MessageRecord;
use crate::storage_api::storage_key::StorageKey;
/// The implementation of the object whose cell C++ lends, for as long as C++ keeps the cell alive.
@@ -343,33 +343,50 @@ pub unsafe extern "C" fn web_rust_message_port_disentangle_ports_of_realm(vm: *m
}
/// Steps 6 to 9 of BroadcastChannel's postMessage(), for a message that another process posted, whose channel name
-/// and serialized message C++ hands over.
+/// C++ hands over.
///
/// # Safety
///
-/// `vm` must be the live VM, the origins lent, `channel_name` an owned AK::Utf16String, and `serialized_message` a
-/// BroadcastChannelSerializedMessage that LibWeb hands over.
+/// `vm` must be the live VM, the origins and the bytes lent, `channel_name` an owned AK::Utf16String, and
+/// `shared_memory` and `shared_memory_sizes` arrays of `shared_memory_count` descriptors that are open for the call and
+/// their sizes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn web_rust_broadcast_channel_deliver_message_locally(
vm: *mut c_void,
storage_key_origin: *const FfiOrigin,
channel_name: usize,
source_origin: *const FfiOrigin,
- serialized_message: *mut c_void,
+ serialized_message: ak::Span<'_, u8>,
+ shared_memory: *const c_int,
+ shared_memory_sizes: *const usize,
+ shared_memory_count: usize,
) {
- // SAFETY: The caller passes the live VM, lends the origins, and hands over the name and the message.
- let (vm, message) = unsafe {
+ // SAFETY: The caller passes the live VM, lends the origins and the descriptors, and hands over the name.
+ let (vm, storage_key, channel_name, source_origin, shared_memory, shared_memory_sizes) = unsafe {
(
&*vm.cast::<Vm>(),
- BroadcastChannelMessage {
- storage_key: StorageKey {
- origin: (*storage_key_origin).to_origin(),
- },
- channel_name: Utf16String::from_raw_owned(channel_name),
- source_origin: (*source_origin).to_origin(),
- serialized: SerializedMessage::from_raw(serialized_message),
+ StorageKey {
+ origin: (*storage_key_origin).to_origin(),
},
+ Utf16String::from_raw_owned(channel_name),
+ (*source_origin).to_origin(),
+ ak::slice_from_raw_parts(shared_memory, shared_memory_count),
+ ak::slice_from_raw_parts(shared_memory_sizes, shared_memory_count),
)
};
- BroadcastChannel::deliver_message_locally(vm, &Rc::new(message), None);
+ let message = BROADCAST_CHANNEL_MESSAGE_CLASS.allocate(vm, |defer_gc| BroadcastChannelMessage {
+ storage_key,
+ channel_name,
+ source_origin,
+ // SAFETY: The caller keeps the descriptors open for the call.
+ serialized: unsafe {
+ MessageRecord::received(
+ defer_gc,
+ serialized_message.as_slice(),
+ shared_memory,
+ shared_memory_sizes,
+ )
+ },
+ });
+ BroadcastChannel::deliver_message_locally(vm, message, None);
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/message_record.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/message_record.rs
new file mode 100644
index 00000000000..98eea76f2ba
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/message_record.rs
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The record of a message that may reach agents in other processes, which Rust owns: the bytes of the values, the
+//! SharedArrayBuffers that agents in this process share, and the shared memory that agents in other processes map.
+//! C++ sees the record only when it is sent to or received from other processes.
+
+use core::ffi::c_int;
+
+use libjs_rust::api::{
+ ArrayBuffer, AsSharedMemory, DeferGc, Gc, OwnedSharedMemory, Trace, borrowed_from_raw_descriptor,
+ into_raw_descriptor,
+};
+
+pub(crate) struct SharedMemory {
+ pub(crate) descriptor: OwnedSharedMemory,
+ pub(crate) size: usize,
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct MessageRecord {
+ #[gc(untraced)]
+ pub(crate) bytes: Vec<u8>,
+ /// The same-process side table, by index from the bytes.
+ pub(crate) shared_array_buffers: Vec<Gc<ArrayBuffer>>,
+ /// The shared memory of the SharedArrayBuffers, by index from the bytes.
+ #[gc(untraced)]
+ pub(crate) shared_memory: Vec<SharedMemory>,
+}
+
+impl MessageRecord {
+ /// A record that another process sent, for the caller to allocate a cell with under the deferral. A descriptor that
+ /// cannot be duplicated leaves out the shared memory from it on, which deserializing then throws for.
+ ///
+ /// # Safety
+ ///
+ /// Each descriptor must stay open for the call.
+ pub(crate) unsafe fn received(_: &DeferGc<'_>, bytes: &[u8], descriptors: &[c_int], sizes: &[usize]) -> Self {
+ let shared_memory = descriptors
+ .iter()
+ .zip(sizes)
+ .map_while(|(&descriptor, &size)| {
+ // SAFETY: The caller keeps the descriptor open.
+ let descriptor = unsafe { borrowed_from_raw_descriptor(descriptor) }
+ .try_clone_to_owned()
+ .ok()?;
+ Some(SharedMemory { descriptor, size })
+ })
+ .collect();
+ Self {
+ bytes: bytes.to_vec(),
+ shared_array_buffers: Vec::new(),
+ shared_memory,
+ }
+ }
+
+ /// Duplicates of the descriptors of the shared memory, which the caller owns, and their sizes, for sending the
+ /// record to other processes.
+ pub(crate) fn duplicate_shared_memory(&self) -> (Vec<c_int>, Vec<usize>) {
+ self.shared_memory
+ .iter()
+ .map_while(|shared_memory| {
+ let descriptor = shared_memory.descriptor.as_shared_memory().try_clone_to_owned().ok()?;
+ Some((into_raw_descriptor(descriptor), shared_memory.size))
+ })
+ .unzip()
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs
index 79cdd9c3c4f..4e24665a979 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs
@@ -15,6 +15,7 @@
pub(crate) mod cpp;
pub(crate) mod exports;
pub(crate) mod memory;
+pub(crate) mod message_record;
pub(crate) mod reader;
pub(crate) mod writer;
@@ -34,9 +35,8 @@ use crate::bindings::structured_data::{SerializationReader, SerializationWriter}
use crate::bindings::{CallContext, Exception, WebIdlResult};
use crate::crypto::crypto_key;
use crate::html::structured_serialize::cpp::{
- IPCSerializationRecord, OwnedSerializedTransferRecord, ReceivedIPCSerializationRecord, SerializableSteps,
- SerializedTransferRecord, SharedBuffers, TransferDataDecoder, TransferDataHolder,
- create_transferred_platform_object, current_settings_object_agent_cluster,
+ OwnedSerializedTransferRecord, SerializableSteps, SerializedTransferRecord, TransferDataDecoder,
+ TransferDataHolder, create_transferred_platform_object, 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, serializable_payload_version,
@@ -44,6 +44,7 @@ use crate::html::structured_serialize::cpp::{
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::webidl::dom_exception::{self, DOMExceptionFields};
@@ -349,9 +350,7 @@ fn serialize_array_buffer(
// descriptor survive structured clone, whose main record is bytes-only, so an agent in another
// process references the same [[ArrayBufferData]]. Without a side list (e.g., serialization for
// storage) or a shared backing (e.g., a zero-length buffer), fall back to copying the bytes.
- let shared_buffer_index = data_holder
- .shared_buffers()
- .and_then(|shared_buffers| shared_buffers.append_shared_memory_of(array_buffer));
+ let shared_buffer_index = data_holder.append_shared_memory_of(array_buffer);
data_holder.encode_bool(shared_buffer_index.is_some());
if let Some(index) = shared_buffer_index {
data_holder.encode_u32(index);
@@ -1140,7 +1139,7 @@ impl Deserializer<'_, '_, '_> {
let shared_object_id = self.serialized.decode_u64()?;
value = self
.serialized
- .array_buffer_from_shared_memory(index, shared_object_id)?;
+ .array_buffer_from_shared_memory(vm, index, shared_object_id)?;
break 'shared_array_buffer;
}
@@ -1806,41 +1805,34 @@ pub(crate) fn structured_deserialize_with_transfer_internal(
}
// https://html.spec.whatwg.org/multipage/structured-data.html#structuredserialize
-// AD-HOC: For a record that reaches agents in other processes, whose shared-memory-backed SharedArrayBuffers are handed
-// over beside it, in shared_buffers.
-pub(crate) fn structured_serialize_with_shared_buffers(
- cx: &CallContext,
+// AD-HOC: For a message that reaches agents in other processes, whose shared-memory-backed SharedArrayBuffers are handed
+// over beside it. The caller finishes the writer into a MessageRecord.
+pub(crate) fn structured_serialize_for_message(
+ vm: &Vm,
+ realm: Gc<Realm>,
value: Value,
- record: IPCSerializationRecord,
- shared_buffers: SharedBuffers,
-) -> WebIdlResult<()> {
- let vm = cx.vm();
+) -> WebIdlResult<StructuredSerializeWriter<'_>> {
let memory = SerializationMemory::new(vm);
- let serialized = StructuredSerializeWriter::new_with_shared_buffers(vm, shared_buffers);
+ let serialized = StructuredSerializeWriter::new_for_message(vm);
// 1. Return ? StructuredSerializeInternal(value, false).
structured_serialize_internal(
vm,
- Some(cx.realm()),
+ Some(realm),
&serialized,
value,
false,
&memory,
AllowSharedArrayBuffers::CrossOriginIsolatedOnly,
)?;
- serialized.finish_ipc_record(record);
- Ok(())
+ Ok(serialized)
}
// https://html.spec.whatwg.org/multipage/structured-data.html#structureddeserialize
-// NB: In the realm of the call, for a record whose SharedArrayBuffers are shared through the list.
-pub(crate) fn structured_deserialize_with_shared_buffers(
- cx: &CallContext,
- serialized: ReceivedIPCSerializationRecord<'_>,
- shared_buffers: SharedBuffers,
-) -> WebIdlResult<Value> {
+// NB: In the realm of the call.
+pub(crate) fn structured_deserialize_message(cx: &CallContext, serialized: &MessageRecord) -> WebIdlResult<Value> {
let target_realm = cx.realm();
- let serialized = StructuredSerializeReader::new_ipc(target_realm, serialized, Some(shared_buffers));
+ let serialized = StructuredSerializeReader::new_message(target_realm, serialized);
let memory = DeserializationMemory::new(cx.vm());
with_temporary_execution_context(target_realm, || {
structured_deserialize_internal(cx, &serialized, &memory, false)
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs
index 5f8ad866f7b..18f5969dd6b 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs
@@ -18,8 +18,8 @@ use core::ptr::NonNull;
use ak::Utf16String;
use libjs_rust::api::{
- ArrayBuffer, ArrayBufferShared, BigInt, DataBlock, DataBlockStorage, ExternalPrimitiveStorage, ForeignCellSlot,
- GC_PRIMITIVE_STORAGE_NULL_HANDLE, Gc, Realm, SharedBackingStore, Value, Vm,
+ ArrayBuffer, ArrayBufferShared, AsSharedMemory, BigInt, DataBlock, DataBlockStorage, ExternalPrimitiveStorage,
+ ForeignCellSlot, GC_PRIMITIVE_STORAGE_NULL_HANDLE, Gc, Realm, SharedBackingStore, Value, Vm,
};
use libwebcommon_rust::html::serialization_records::{DecodeError, DecodedString, RecordDecoder, SerializationType};
@@ -28,12 +28,20 @@ use crate::html::structured_serialize::cpp::{
ReceivedIPCSerializationRecord, SharedBuffers, data_clone_error_from_serialization_error,
serializable_interface_name_from_storage_identifier, serializable_interface_storage_identifier,
};
+use crate::html::structured_serialize::message_record::MessageRecord;
+
+/// Where the record keeps the SharedArrayBuffers that it shares.
+#[derive(Clone, Copy)]
+enum SharedArrayBuffers<'a> {
+ None,
+ Lent(ReceivedIPCSerializationRecord<'a>, Option<SharedBuffers>),
+ Message(&'a MessageRecord),
+}
pub(crate) struct StructuredSerializeReader<'a> {
decoder: RecordDecoder<'a>,
realm: Gc<Realm>,
- ipc_record: Option<ReceivedIPCSerializationRecord<'a>>,
- shared_buffers: Option<SharedBuffers>,
+ shared_array_buffers: SharedArrayBuffers<'a>,
}
impl<'a> StructuredSerializeReader<'a> {
@@ -45,8 +53,15 @@ impl<'a> StructuredSerializeReader<'a> {
Self {
decoder: RecordDecoder::new(SerializationType::Ipc, record.data()).expect("an IPC record has no prologue"),
realm,
- ipc_record: Some(record),
- shared_buffers,
+ shared_array_buffers: SharedArrayBuffers::Lent(record, shared_buffers),
+ }
+ }
+
+ pub(crate) fn new_message(realm: Gc<Realm>, record: &'a MessageRecord) -> Self {
+ Self {
+ decoder: RecordDecoder::new(SerializationType::Ipc, &record.bytes).expect("an IPC record has no prologue"),
+ realm,
+ shared_array_buffers: SharedArrayBuffers::Message(record),
}
}
@@ -57,8 +72,7 @@ impl<'a> StructuredSerializeReader<'a> {
Ok(Self {
decoder,
realm,
- ipc_record: None,
- shared_buffers: None,
+ shared_array_buffers: SharedArrayBuffers::None,
})
}
@@ -180,14 +194,37 @@ impl<'a> StructuredSerializeReader<'a> {
)))
}
- pub(crate) fn array_buffer_from_shared_memory(&self, index: u32, shared_object_id: u64) -> WebIdlResult<Value> {
- let Some(shared_buffers) = self.shared_buffers else {
- return Err(data_clone_error_from_serialization_error(
- self.realm,
- "SharedArrayBuffer side-list index out of range",
- ));
- };
- shared_buffers.shared_array_buffer(self.realm, index, shared_object_id)
+ pub(crate) fn array_buffer_from_shared_memory(
+ &self,
+ vm: &Vm,
+ index: u32,
+ shared_object_id: u64,
+ ) -> WebIdlResult<Value> {
+ let index_out_of_range =
+ || data_clone_error_from_serialization_error(self.realm, "SharedArrayBuffer side-list index out of range");
+ match self.shared_array_buffers {
+ SharedArrayBuffers::Lent(_, Some(shared_buffers)) => {
+ shared_buffers.shared_array_buffer(self.realm, index, shared_object_id)
+ }
+ SharedArrayBuffers::Message(record) => {
+ let shared_memory = record
+ .shared_memory
+ .get(index as usize)
+ .ok_or_else(index_out_of_range)?;
+ let array_buffer = ArrayBuffer::create_from_shared_memory(
+ vm,
+ self.realm,
+ shared_memory.descriptor.as_shared_memory(),
+ shared_memory.size,
+ shared_object_id,
+ )
+ .map_err(|_| {
+ data_clone_error_from_serialization_error(self.realm, "Unable to map SharedArrayBuffer memory")
+ })?;
+ Ok(Value::from_object(array_buffer))
+ }
+ SharedArrayBuffers::None | SharedArrayBuffers::Lent(_, None) => Err(index_out_of_range()),
+ }
}
/// A new SharedArrayBuffer that shares the storage of the buffer at the index of the record's same-process side
@@ -199,7 +236,11 @@ impl<'a> StructuredSerializeReader<'a> {
byte_length: usize,
preserve_growability: bool,
) -> Option<Gc<ArrayBuffer>> {
- let source_buffer = self.ipc_record?.shared_array_buffer(side_table_index)?;
+ let source_buffer = match self.shared_array_buffers {
+ SharedArrayBuffers::None => return None,
+ SharedArrayBuffers::Lent(record, _) => record.shared_array_buffer(side_table_index)?,
+ SharedArrayBuffers::Message(record) => *record.shared_array_buffers.get(side_table_index as usize)?,
+ };
array_buffer_sharing_storage_with(vm, self.realm, source_buffer, byte_length, preserve_growability)
}
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rs
index 59eb4e92792..a636c21c6a7 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rs
@@ -11,18 +11,26 @@
//! The record that a structured serialization writes: the bytes of the values in the format of the record
//! (libwebcommon_rust::html::serialization_records), and the SharedArrayBuffers that the record shares beside them.
//! C++ code and the UI process carry records without reading them, so a writer hands what it wrote over to LibWeb's
-//! C++ record when it finishes.
+//! C++ record when it finishes, or to a MessageRecord that Rust keeps.
use core::cell::RefCell;
use ak::{Utf16String, Utf16StringUnits};
-use libjs_rust::api::{ArrayBuffer, BigInt, Gc, MarkedVec, Vm};
+use libjs_rust::api::{ArrayBuffer, BigInt, DataBlockStorage, DeferGc, Gc, MarkedVec, Vm};
use libwebcommon_rust::html::serialization_records::{RecordEncoder, SerializationType};
use crate::html::structured_serialize::cpp::{
IPCSerializationRecord, SerializedTransferRecord, SharedBuffers, StorageSerializationRecord,
serializable_interface_storage_identifier,
};
+use crate::html::structured_serialize::message_record::{MessageRecord, SharedMemory};
+
+/// Where a record that reaches agents in other processes hands the shared memory of its SharedArrayBuffers over.
+enum CrossProcessSharedMemory {
+ None,
+ Lent(SharedBuffers),
+ Owned(RefCell<Vec<SharedMemory>>),
+}
/// The record of a structured serialization, which the serialization writes its values to.
pub(crate) struct StructuredSerializeWriter<'vm> {
@@ -30,7 +38,7 @@ pub(crate) struct StructuredSerializeWriter<'vm> {
/// The SharedArrayBuffers that an IPC record shares with a deserialization in the same process, by their index in
/// this same-process side table.
shared_array_buffers: MarkedVec<'vm, Gc<ArrayBuffer>>,
- shared_buffers: Option<SharedBuffers>,
+ shared_memory: CrossProcessSharedMemory,
}
impl<'vm> StructuredSerializeWriter<'vm> {
@@ -38,14 +46,22 @@ impl<'vm> StructuredSerializeWriter<'vm> {
Self {
encoder: RefCell::new(RecordEncoder::new(serialization_type)),
shared_array_buffers: MarkedVec::new(vm),
- shared_buffers: None,
+ shared_memory: CrossProcessSharedMemory::None,
}
}
/// The writer of an IPC record whose SharedArrayBuffers share their cross-process shared memory through the list.
pub(crate) fn new_with_shared_buffers(vm: &'vm Vm, shared_buffers: SharedBuffers) -> Self {
Self {
- shared_buffers: Some(shared_buffers),
+ shared_memory: CrossProcessSharedMemory::Lent(shared_buffers),
+ ..Self::new(vm, SerializationType::Ipc)
+ }
+ }
+
+ /// The writer of a MessageRecord.
+ pub(crate) fn new_for_message(vm: &'vm Vm) -> Self {
+ Self {
+ shared_memory: CrossProcessSharedMemory::Owned(RefCell::new(Vec::new())),
..Self::new(vm, SerializationType::Ipc)
}
}
@@ -142,10 +158,27 @@ impl<'vm> StructuredSerializeWriter<'vm> {
index
}
- /// The side list that the record shares the cross-process shared memory of its SharedArrayBuffers through, if it
- /// has one.
- pub(crate) fn shared_buffers(&self) -> Option<SharedBuffers> {
- self.shared_buffers
+ /// Hands the cross-process shared memory of the SharedArrayBuffer over beside the record, and returns its index
+ /// there, if the buffer is backed by some, and the record reaches agents in other processes.
+ pub(crate) fn append_shared_memory_of(&self, array_buffer: Gc<ArrayBuffer>) -> Option<u32> {
+ let shared_memory = match &self.shared_memory {
+ CrossProcessSharedMemory::None => return None,
+ CrossProcessSharedMemory::Lent(shared_buffers) => {
+ return shared_buffers.append_shared_memory_of(array_buffer);
+ }
+ CrossProcessSharedMemory::Owned(shared_memory) => shared_memory,
+ };
+ let descriptor = array_buffer.with_data_block(|data_block| match &data_block.byte_buffer {
+ DataBlockStorage::Shared(store) => Some(SharedMemory {
+ descriptor: store.shared_memory().try_clone_to_owned().ok()?,
+ size: store.size(),
+ }),
+ _ => None,
+ })?;
+ let mut shared_memory = shared_memory.borrow_mut();
+ let index = u32::try_from(shared_memory.len()).expect("a record shares fewer than 2^32 buffers");
+ shared_memory.push(descriptor);
+ Some(index)
}
/// Sets the IPC record that C++ lends to what the writer wrote.
@@ -154,6 +187,20 @@ impl<'vm> StructuredSerializeWriter<'vm> {
record.set(self.encoder.borrow().bytes(), &self.shared_array_buffers.values());
}
+ /// The MessageRecord that the writer wrote. Its SharedArrayBuffers are traced once it is in a cell, which the caller
+ /// allocates under the deferral.
+ pub(crate) fn finish_message_record(self, _: &DeferGc<'_>) -> MessageRecord {
+ assert_eq!(self.serialization_type(), SerializationType::Ipc);
+ let CrossProcessSharedMemory::Owned(shared_memory) = self.shared_memory else {
+ unreachable!("the writer is a message's");
+ };
+ MessageRecord {
+ bytes: self.encoder.into_inner().into_bytes(),
+ shared_array_buffers: self.shared_array_buffers.values().to_vec(),
+ shared_memory: shared_memory.into_inner(),
+ }
+ }
+
/// The bytes of the storage record that the writer wrote, for Rust code that keeps them, as IndexedDB does.
pub(crate) fn into_storage_bytes(self) -> Vec<u8> {
assert_eq!(self.serialization_type(), SerializationType::Storage);
diff --git a/Libraries/LibWeb/HTML/BroadcastChannel.cpp b/Libraries/LibWeb/HTML/BroadcastChannel.cpp
index 06586f56a0b..0b18b7634ca 100644
--- a/Libraries/LibWeb/HTML/BroadcastChannel.cpp
+++ b/Libraries/LibWeb/HTML/BroadcastChannel.cpp
@@ -14,6 +14,7 @@
#include <LibWeb/Bindings/PrincipalHostDefined.h>
#include <LibWeb/HTML/BroadcastChannel.h>
#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/StructuredSerialize.h>
#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
#include <LibWeb/Page/Page.h>
#include <LibWebCommon/HTML/BroadcastChannelMessage.h>
@@ -23,24 +24,14 @@
namespace Web::HTML {
-// The serialized message of a BroadcastChannel message, which the Rust implementation owns.
-struct BroadcastChannelSerializedMessage {
- IPCSerializationRecord serialized_message;
- Vector<Core::AnonymousBuffer> shared_buffers;
-};
-
extern "C" {
-BroadcastChannelSerializedMessage* web_html_broadcast_channel_create_serialized_message();
-void web_html_broadcast_channel_destroy_serialized_message(BroadcastChannelSerializedMessage*);
-IPCSerializationRecord* web_html_broadcast_channel_serialized_message_record(BroadcastChannelSerializedMessage*);
-Vector<Core::AnonymousBuffer>* web_html_broadcast_channel_serialized_message_shared_buffers(BroadcastChannelSerializedMessage*);
void web_html_broadcast_channel_relevant_settings_object_origin(void* realm, void* ctx, void (*on_origin)(void*, URL::FFI::FfiOrigin const*));
void web_html_broadcast_channel_set_strongly_referenced(void* realm, DOM::EventTarget*, bool strongly_referenced);
-void web_html_broadcast_channel_post_message_to_other_processes(void* realm, FlatPtr channel_name, BroadcastChannelSerializedMessage const*);
+void web_html_broadcast_channel_post_message_to_other_processes(void* realm, FlatPtr channel_name, ReadonlyBytes serialized_message, int const* shared_memory, size_t const* shared_memory_sizes, size_t shared_memory_count);
// Defined on the Rust side.
-void web_rust_broadcast_channel_deliver_message_locally(JSVM*, URL::FFI::FfiOrigin const* storage_key_origin, FlatPtr channel_name, URL::FFI::FfiOrigin const* source_origin, BroadcastChannelSerializedMessage*);
+void web_rust_broadcast_channel_deliver_message_locally(JSVM*, URL::FFI::FfiOrigin const* storage_key_origin, FlatPtr channel_name, URL::FFI::FfiOrigin const* source_origin, ReadonlyBytes serialized_message, int const* shared_memory, size_t const* shared_memory_sizes, size_t shared_memory_count);
}
static JS::Object& global_object_of(void* realm)
@@ -48,26 +39,6 @@ static JS::Object& global_object_of(void* realm)
return static_cast<JS::Realm*>(realm)->global_object();
}
-BroadcastChannelSerializedMessage* web_html_broadcast_channel_create_serialized_message()
-{
- return new BroadcastChannelSerializedMessage;
-}
-
-void web_html_broadcast_channel_destroy_serialized_message(BroadcastChannelSerializedMessage* message)
-{
- delete message;
-}
-
-IPCSerializationRecord* web_html_broadcast_channel_serialized_message_record(BroadcastChannelSerializedMessage* message)
-{
- return &message->serialized_message;
-}
-
-Vector<Core::AnonymousBuffer>* web_html_broadcast_channel_serialized_message_shared_buffers(BroadcastChannelSerializedMessage* message)
-{
- return &message->shared_buffers;
-}
-
void web_html_broadcast_channel_relevant_settings_object_origin(void* realm, void* ctx, void (*on_origin)(void*, URL::FFI::FfiOrigin const*))
{
URL::RustIntegration::lend_origin_to_ffi(relevant_settings_object(global_object_of(realm)).origin(), [&](URL::FFI::FfiOrigin const& origin) {
@@ -84,32 +55,42 @@ void web_html_broadcast_channel_set_strongly_referenced(void* realm, DOM::EventT
global_scope.remove_strong_reference_to_broadcast_channel(*event_target);
}
-void web_html_broadcast_channel_post_message_to_other_processes(void* realm, FlatPtr channel_name, BroadcastChannelSerializedMessage const* message)
+void web_html_broadcast_channel_post_message_to_other_processes(void* realm, FlatPtr channel_name, ReadonlyBytes serialized_message, int const* shared_memory, size_t const* shared_memory_sizes, size_t shared_memory_count)
{
auto& js_realm = *static_cast<JS::Realm*>(realm);
auto name = Utf16String::from_raw(channel_name);
+ Vector<Core::AnonymousBuffer> shared_buffers;
+ shared_buffers.ensure_capacity(shared_memory_count);
+ for (size_t i = 0; i < shared_memory_count; ++i)
+ shared_buffers.unchecked_append(MUST(Core::AnonymousBuffer::create_from_anon_fd(shared_memory[i], shared_memory_sizes[i])));
+
// NB: The UI process forwards the message to the other processes hosting an environment with its storage key, and
// each delivers it to its own BroadcastChannel objects.
PostedBroadcastChannelMessage posted_message {
.environment_id = principal_realm_settings_object(js_realm).id,
.channel_name = Utf16FlyString::from_utf16(name.utf16_view()),
- .serialized_message = message->serialized_message,
- .shared_buffers = message->shared_buffers,
+ .serialized_message = create_ipc_serialization_record(serialized_message, {}),
+ .shared_buffers = move(shared_buffers),
};
Bindings::principal_host_defined_page(js_realm).client().page_did_post_broadcast_channel_message(posted_message);
}
void deliver_broadcast_channel_message_locally(BroadcastChannelMessage message)
{
- auto* serialized_message = new BroadcastChannelSerializedMessage {
- .serialized_message = move(message.serialized_message),
- .shared_buffers = move(message.shared_buffers),
- };
+ Vector<int> shared_memory;
+ Vector<size_t> shared_memory_sizes;
+ shared_memory.ensure_capacity(message.shared_buffers.size());
+ shared_memory_sizes.ensure_capacity(message.shared_buffers.size());
+ for (auto const& shared_buffer : message.shared_buffers) {
+ shared_memory.unchecked_append(shared_buffer.fd());
+ shared_memory_sizes.unchecked_append(shared_buffer.size());
+ }
+
auto channel_name = Utf16String::from_utf16(message.channel_name.view());
URL::RustIntegration::lend_origin_to_ffi(message.storage_key.origin, [&](URL::FFI::FfiOrigin const& storage_key_origin) {
URL::RustIntegration::lend_origin_to_ffi(message.source_origin, [&](URL::FFI::FfiOrigin const& source_origin) {
- web_rust_broadcast_channel_deliver_message_locally(JS::HostABI::vm_to_abi(Bindings::main_thread_vm()), &storage_key_origin, move(channel_name).into_raw(), &source_origin, serialized_message);
+ web_rust_broadcast_channel_deliver_message_locally(JS::HostABI::vm_to_abi(Bindings::main_thread_vm()), &storage_key_origin, move(channel_name).into_raw(), &source_origin, message.serialized_message.data.span(), shared_memory.data(), shared_memory_sizes.data(), shared_memory.size());
});
});
}