Truly independent web browser
LibWeb: Implement BroadcastChannel in Rust
Shannon Booth127b39f44812
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rs b/Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rsnew file mode 100644index 00000000000..102d7a84926--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rs@@ -0,0 +1,409 @@+/*+ * Copyright (c) 2024, Jamie Mansfield <[email protected]>+ * Copyright (c) 2024-2026, Shannon Booth <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! 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::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 liburl_rust::FfiOrigin;+use liburl_rust::origin::Origin;++use crate::bindings::event_target::{CppEvent, CppEventTarget, EventListenerListChanged, GetTheParent};+use crate::bindings::global_object::{+ relevant_global_object, window_from_global_object, worker_global_scope_from_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::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,+ on_origin: unsafe extern "C" fn(*mut c_void, *const FfiOrigin),+ );+ fn web_html_broadcast_channel_set_strongly_referenced(+ realm: *mut c_void,+ event_target: *mut c_void,+ strongly_referenced: bool,+ );+ fn web_html_broadcast_channel_post_message_to_other_processes(+ realm: *mut c_void,+ channel_name: usize,+ message: *const c_void,+ );+}++/// 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.+pub(crate) struct BroadcastChannelMessage {+ pub(crate) storage_key: StorageKey,+ pub(crate) channel_name: Utf16String,+ pub(crate) source_origin: Origin,+ pub(crate) serialized: SerializedMessage,+}++// https://html.spec.whatwg.org/multipage/web-messaging.html#broadcastchannel+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct BroadcastChannel {+ event_target: CppEventTarget,+ realm: Gc<Realm>,++ // A BroadcastChannel object has a channel name and a closed flag.+ #[gc(untraced)]+ channel_name: Utf16String,+ closed_flag: Cell<bool>,++ #[gc(untraced)]+ 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 {+ fn relevant_realm(&self) -> Option<Gc<Realm>> {+ Some(self.realm)+ }++ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.event_target.as_cpp_parent()+ }+}++impl GetTheParent for BroadcastChannel {+ fn get_the_parent(&self) -> Option<CppEventTarget> {+ None+ }+}++impl EventListenerListChanged for BroadcastChannel {+ fn event_listener_list_changed(this: Ref<Self>) {+ this.update_strong_reference_from_relevant_global_object();+ }+}++/// The channels of the thread's agent, in creation order: references that do not keep them alive, which a collected+/// channel leaves empty. The empty ones are pruned once the list has grown to twice what was live after the last+/// pruning.+struct BroadcastChannels {+ channels: Vec<GcWeak<EmbedderCell<Wrapped<BroadcastChannel>>>>,+ live_after_pruning: usize,+}++impl BroadcastChannels {+ const CHANNELS_BEFORE_FIRST_PRUNING: usize = 128;++ fn add(&mut self, vm: &Vm, channel: Ref<BroadcastChannel>) {+ if self.channels.len() >= (2 * self.live_after_pruning).max(Self::CHANNELS_BEFORE_FIRST_PRUNING) {+ self.channels.retain(|channel| channel.get().is_some());+ self.live_after_pruning = self.channels.len();+ }+ self.channels.push(GcWeak::new(vm.heap(), channel));+ }+}++thread_local! {+ static BROADCAST_CHANNELS: RefCell<BroadcastChannels> = const {+ RefCell::new(BroadcastChannels {+ channels: Vec::new(),+ live_after_pruning: 0,+ })+ };+}++fn relevant_settings_object_origin(realm: Gc<Realm>) -> Origin {+ unsafe extern "C" fn on_origin(ctx: *mut c_void, ffi_origin: *const FfiOrigin) {+ // SAFETY: ctx is the origin below, and LibWeb lends the origin for the call.+ unsafe { *ctx.cast::<Option<Origin>>() = Some((*ffi_origin).to_origin()) };+ }++ let mut origin: Option<Origin> = None;+ // SAFETY: The realm is live, and the origin outlives the call.+ unsafe {+ web_html_broadcast_channel_relevant_settings_object_origin(+ realm.as_ptr().cast(),+ (&raw mut origin).cast(),+ on_origin,+ );+ }+ origin.expect("LibWeb lends the origin")+}++impl BroadcastChannel {+ // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-broadcastchannel+ pub(crate) fn construct(cx: &mut CallContext, name: Utf16String) -> WebIdlResult<Ref<Self>> {+ let vm = cx.vm();+ let realm = cx.realm();+ let channel = allocate(vm, |_| Self {+ event_target: CppEventTarget::new(),+ realm,+ // 1. Set this's channel name to name.+ channel_name: name,+ // 2. Set this's closed flag to false.+ 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>();+ BROADCAST_CHANNELS.with_borrow_mut(|channels| channels.add(vm, channel));+ Ok(channel)+ }++ // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-broadcastchannel-name+ pub(crate) fn name(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ // The name getter steps are to return this's channel name.+ Ok(self.channel_name.clone())+ }++ // https://html.spec.whatwg.org/multipage/web-messaging.html#eligible-for-messaging+ fn is_eligible_for_messaging(&self) -> bool {+ // A BroadcastChannel object is said to be eligible for messaging when its relevant global object is either:+ let relevant_global_object = relevant_global_object(self);++ // * a Window object whose associated Document is fully active, or+ if let Some(window) = window_from_global_object(relevant_global_object) {+ return window.associated_document().is_fully_active();+ }++ // * a WorkerGlobalScope object whose closing flag is false and is not suspendable.+ // FIXME: Suspendable worker+ if let Some(worker_global_scope) = worker_global_scope_from_global_object(relevant_global_object) {+ return !worker_global_scope.is_closing();+ }++ false+ }++ // https://html.spec.whatwg.org/multipage/web-messaging.html#broadcasting-to-other-browsing-contexts+ fn update_strong_reference_from_relevant_global_object(&self) {+ // While a BroadcastChannel object whose closed flag is false has an event listener registered for message or+ // messageerror events, there must be a strong reference from the BroadcastChannel object's relevant global object+ // to the BroadcastChannel object itself.+ let strongly_referenced = !self.closed_flag.get()+ && (self.event_target.has_event_listener("message")+ || self.event_target.has_event_listener("messageerror"));+ // SAFETY: The realm and the EventTarget are live.+ unsafe {+ web_html_broadcast_channel_set_strongly_referenced(+ self.realm.as_ptr().cast(),+ self.event_target.as_ptr(),+ strongly_referenced,+ );+ }+ }++ // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-broadcastchannel-postmessage+ pub(crate) fn post_message(this: &Ref<Self>, cx: &mut CallContext, message: Value) -> WebIdlResult<()> {+ // 1. If this is not eligible for messaging, then return.+ if !this.is_eligible_for_messaging() {+ return Ok(());+ }++ // 2. If this's closed flag is true, then throw an "InvalidStateError" DOMException.+ if this.closed_flag.get() {+ return Err(Exception::Dom(+ "InvalidStateError",+ Utf16String::from_ascii(b"BroadcastChannel.postMessage() on a closed channel"),+ ));+ }++ // 3. Let serialized be StructuredSerialize(message). Rethrow any exceptions.+ // 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())?;++ // 4. Let sourceOrigin be this's relevant settings object's origin.+ let source_origin = this.origin.clone();++ // 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 {+ storage_key: source_storage_key,+ channel_name: this.channel_name.clone(),+ source_origin,+ serialized,+ });++ // Steps 6-9.+ 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.+ 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(),+ );+ }++ Ok(())+ }++ // 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>>) {+ // 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.+ // * Their channel name is this's channel name.+ // 7. Remove source from destinations.+ let destinations = MarkedVec::new(vm);+ BROADCAST_CHANNELS.with_borrow(|channels| {+ for channel in channels.channels.iter().filter_map(GcWeak::get) {+ if Some(channel) != source+ && channel.is_eligible_for_messaging()+ && channel.storage_key == message.storage_key+ && channel.channel_name == message.channel_name+ {+ destinations.push(channel);+ }+ }+ });++ // 8. Sort destinations such that all BroadcastChannel objects whose relevant agents are the same are sorted in creation order, oldest first.+ // (This does not define a complete ordering. Within this constraint, user agents may sort the list in any implementation-defined manner.)+ // NB: The channels of the thread's agent are listed in creation order, so destinations already are.++ // 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);+ },+ );+ }+ }++ fn message_task_steps(destination: Ref<Self>, vm: &Vm, message: &BroadcastChannelMessage) {+ // 1. If destination's closed flag is true, then abort these steps.+ if destination.closed_flag.get() {+ return;+ }++ // 2. Let targetRealm be destination's relevant realm.+ let target_realm = destination.realm;+ 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 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.+ let event = CppEvent::create_message_event_with_origin(+ target_realm,+ "messageerror",+ Value::NULL,+ &message.source_origin,+ );+ event.set_is_trusted(true);+ destination.event_target.dispatch_event(&event);+ return;+ };++ // 4. Fire an event named message at destination, using MessageEvent, with the data attribute initialized to data and+ // its origin initialized to sourceOrigin.+ let event = CppEvent::create_message_event_with_origin(target_realm, "message", data, &message.source_origin);+ event.set_is_trusted(true);+ destination.event_target.dispatch_event(&event);+ }++ // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-broadcastchannel-close+ pub(crate) fn close(&self, _: &mut CallContext) -> WebIdlResult<()> {+ // The close() method steps are to set this's closed flag to true.+ self.closed_flag.set(true);++ self.update_strong_reference_from_relevant_global_object();+ Ok(())+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rsindex 7564a96b146..d1f82d5b35f 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs@@ -7,20 +7,26 @@//! The C ABI through which LibWeb's C++ creates and reads the ImageData, ImageBitmap and MessagePort objects that it//! handles, which Libraries/LibWeb/HTML/ImageData.cpp, Libraries/LibWeb/HTML/ImageBitmap.cpp and//! Libraries/LibWeb/HTML/MessagePort.cpp declare. A cell is the cell of an object of the interface that the name of-//! the function says.+//! 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::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::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::storage_api::storage_key::StorageKey;/// The implementation of the object whose cell C++ lends, for as long as C++ keeps the cell alive.///@@ -335,3 +341,35 @@ pub unsafe extern "C" fn web_rust_message_port_disentangle_ports_of_realm(vm: *mlet (vm, realm) = unsafe { realm_arguments(vm, realm) };MessagePort::disentangle_ports_of_realm(vm, realm);}++/// Steps 6 to 9 of BroadcastChannel's postMessage(), for a message that another process posted, whose channel name+/// and serialized message 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.+#[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,+) {+ // SAFETY: The caller passes the live VM, lends the origins, and hands over the name and the message.+ let (vm, message) = 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),+ },+ )+ };+ BroadcastChannel::deliver_message_locally(vm, &Rc::new(message), None);+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rsindex 161b8a7680b..131866d4aaa 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs@@ -7,7 +7,7 @@//! The 2D canvas contexts, with the attributes and operations of each of their mixins in the module of its IDL file,//! the objects that they draw with, the images that they and WebGL read and write the pixels of, and the operations of//! a path that Path2D and the contexts share. The state that the contexts share is in crate::canvas_2d. The message-//! ports and channels of web messaging are here as well.+//! ports and channels of web messaging and the broadcast channels are here as well.pub(crate) mod canvas_path;pub(crate) mod color_stops;@@ -15,6 +15,8 @@ pub(crate) mod predefined_color_space;// What follows runs on the JS runtime, which the tests of the crate do not link.#[cfg(not(test))]+pub(crate) mod broadcast_channel;+#[cfg(not(test))]pub(crate) mod canvas_compositing;#[cfg(not(test))]pub(crate) mod canvas_draw_image;diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/exports.rsindex 1f6875a0026..bbd10da74f5 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/exports.rs@@ -16,8 +16,8 @@ use libwebcommon_rust::html::serialization_records::SerializationType;use crate::bindings::interface::realm_arguments;use crate::bindings::{CallContext, WebIdlResult};use crate::html::structured_serialize::cpp::{- IPCSerializationRecord, ReceivedIPCSerializationRecord, SerializedTransferRecord, SharedBuffers,- StorageSerializationRecord, TransferDataDecoder, TransferredValues,+ IPCSerializationRecord, ReceivedIPCSerializationRecord, SerializedTransferRecord, StorageSerializationRecord,+ TransferDataDecoder, TransferredValues,};use crate::html::structured_serialize::memory::{DeserializationMemory, SerializationMemory};use crate::html::structured_serialize::reader::StructuredSerializeReader;@@ -62,30 +62,23 @@ fn structured_serialize_in_current_realm<'vm>(})}-/// StructuredSerialize, which runs in the current realm, and sets the record. The record shares the cross-process-/// shared memory of SharedArrayBuffers through the list, if there is one.+/// StructuredSerialize, which runs in the current realm, and sets the record.////// # Safety///-/// The pointers must be the VM, a list that C++ lends or null, and a record that C++ lends. The value must be live.+/// The pointers must be the VM and a record that C++ lends. The value must be live.#[unsafe(no_mangle)]pub unsafe extern "C" fn web_rust_structured_serialize(vm: *mut c_void,value: u64,allow_shared_array_buffers: u8,- shared_buffers: *mut c_void,record: *mut c_void,) -> RawNativeFunctionResult {// SAFETY: The caller passes the VM.let vm = unsafe { &*vm.cast::<Vm>() };- // SAFETY: The caller passes a live value, and lends the list and the record.+ // SAFETY: The caller passes a live value, and lends the record.let (value, record) = unsafe { (Value::from_raw(value), IPCSerializationRecord::from_raw(record)) };- let serialized = if shared_buffers.is_null() {- StructuredSerializeWriter::new(vm, SerializationType::Ipc)- } else {- // SAFETY: The caller lends the list.- StructuredSerializeWriter::new_with_shared_buffers(vm, unsafe { SharedBuffers::from_raw(shared_buffers) })- };+ let serialized = StructuredSerializeWriter::new(vm, SerializationType::Ipc);if let Err(result) = structured_serialize_in_current_realm(vm,&serialized,@@ -128,30 +121,23 @@ pub unsafe extern "C" fn web_rust_structured_serialize_for_storage(RawNativeFunctionResult::from_completion(Ok(Value::UNDEFINED))}-/// StructuredDeserialize of the IPC record in the realm. The record shares the cross-process shared memory of-/// SharedArrayBuffers through the list, if there is one.+/// StructuredDeserialize of the IPC record in the realm.////// # Safety///-/// The pointers must be the VM, a live realm, a record that C++ lends, and a list that C++ lends or null.+/// The pointers must be the VM, a live realm, and a record that C++ lends.#[unsafe(no_mangle)]pub unsafe extern "C" fn web_rust_structured_deserialize(vm: *mut c_void,target_realm: *mut c_void,record: *const c_void,- shared_buffers: *mut c_void,) -> RawNativeFunctionResult {// SAFETY: The caller passes the VM and a live realm.let (vm, target_realm) = unsafe { realm_arguments(vm, target_realm) };let cx = CallContext::new(vm, target_realm);- // SAFETY: The caller lends the record, and the list if there is one.- let (record, shared_buffers) = unsafe {- (- ReceivedIPCSerializationRecord::from_raw(record),- (!shared_buffers.is_null()).then(|| SharedBuffers::from_raw(shared_buffers)),- )- };- let serialized = StructuredSerializeReader::new_ipc(target_realm, record, shared_buffers);+ // SAFETY: The caller lends the record.+ let record = unsafe { ReceivedIPCSerializationRecord::from_raw(record) };+ let serialized = StructuredSerializeReader::new_ipc(target_realm, record, None);let memory = DeserializationMemory::new(vm);completion(&cx, structured_deserialize_internal(&cx, &serialized, &memory, false))}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rsindex da8ce9d4d94..d14b5845392 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs@@ -34,8 +34,9 @@ use crate::bindings::structured_data::{SerializationReader, SerializationWriter}use crate::bindings::{CallContext, Exception, WebIdlResult};use crate::crypto::crypto_key;use crate::html::structured_serialize::cpp::{- OwnedSerializedTransferRecord, SerializableSteps, SerializedTransferRecord, TransferDataDecoder,- TransferDataHolder, create_transferred_platform_object, current_settings_object_agent_cluster,+ IPCSerializationRecord, OwnedSerializedTransferRecord, ReceivedIPCSerializationRecord, SerializableSteps,+ SerializedTransferRecord, SharedBuffers, 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,@@ -1807,6 +1808,48 @@ pub(crate) fn structured_deserialize_with_transfer_internal(Ok(value)}+// 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,+ value: Value,+ record: IPCSerializationRecord,+ shared_buffers: SharedBuffers,+) -> WebIdlResult<()> {+ let vm = cx.vm();+ let memory = SerializationMemory::new(vm);+ let serialized = StructuredSerializeWriter::new_with_shared_buffers(vm, shared_buffers);++ // 1. Return ? StructuredSerializeInternal(value, false).+ structured_serialize_internal(+ vm,+ Some(cx.realm()),+ &serialized,+ value,+ false,+ &memory,+ AllowSharedArrayBuffers::CrossOriginIsolatedOnly,+ )?;+ serialized.finish_ipc_record(record);+ Ok(())+}++// 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> {+ let target_realm = cx.realm();+ let serialized = StructuredSerializeReader::new_ipc(target_realm, serialized, Some(shared_buffers));+ let memory = DeserializationMemory::new(cx.vm());+ with_temporary_execution_context(target_realm, || {+ structured_deserialize_internal(cx, &serialized, &memory, false)+ })+}+// https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeforstoragepub(crate) fn structured_serialize_for_storage(cx: &CallContext, value: Value) -> WebIdlResult<Vec<u8>> {let vm = cx.vm();diff --git a/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_key.rs b/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_key.rsindex 13582ef9dc5..9c021a21a60 100644--- a/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_key.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_key.rs@@ -19,6 +19,11 @@ unsafe extern "C" {ctx: *mut c_void,on_origin: unsafe extern "C" fn(*mut c_void, *const FfiOrigin),) -> bool;+ fn web_storage_api_obtain_a_storage_key_for_non_storage_purposes(+ realm: *mut c_void,+ ctx: *mut c_void,+ on_origin: unsafe extern "C" fn(*mut c_void, *const FfiOrigin),+ );}// https://storage.spec.whatwg.org/#storage-keys@@ -50,3 +55,19 @@ pub(crate) fn obtain_a_storage_key(realm: Gc<Realm>) -> Option<StorageKey> {unsafe { web_storage_api_obtain_a_storage_key(realm.as_ptr().cast(), (&raw mut origin).cast(), on_origin) };origin.map(|origin| StorageKey { origin })}++/// https://storage.spec.whatwg.org/#obtain-a-storage-key-for-non-storage-purposes+pub(crate) fn obtain_a_storage_key_for_non_storage_purposes(realm: Gc<Realm>) -> StorageKey {+ let mut origin: Option<Origin> = None;+ // SAFETY: The realm is live, and the origin outlives the call.+ unsafe {+ web_storage_api_obtain_a_storage_key_for_non_storage_purposes(+ realm.as_ptr().cast(),+ (&raw mut origin).cast(),+ on_origin,+ );+ }+ StorageKey {+ origin: origin.expect("LibWeb lends the origin of the storage key"),+ }+}diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.hindex 89917c60d6a..59439c4d691 100644--- a/Libraries/LibWeb/Forward.h+++ b/Libraries/LibWeb/Forward.h@@ -641,7 +641,6 @@ class AudioTrackList;class AutoplaySettings;class BarProp;class BeforeUnloadEvent;-class BroadcastChannel;class BrowsingContext;class Canvas2DContextBase;class CanvasHost;diff --git a/Libraries/LibWeb/HTML/BroadcastChannel.cpp b/Libraries/LibWeb/HTML/BroadcastChannel.cppindex fa64bf01fc5..06586f56a0b 100644--- a/Libraries/LibWeb/HTML/BroadcastChannel.cpp+++ b/Libraries/LibWeb/HTML/BroadcastChannel.cpp@@ -5,306 +5,113 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/NeverDestroyed.h>-#include <AK/QuickSort.h>-#include <LibCore/System.h>-#include <LibGC/Heap.h>+#include <AK/Function.h>+#include <LibCore/AnonymousBuffer.h>+#include <LibJS/HostClassBuilder.h>#include <LibJS/Runtime/Realm.h>+#include <LibURL/RustIntegration.h>+#include <LibWeb/Bindings/MainThreadVM.h>#include <LibWeb/Bindings/PrincipalHostDefined.h>-#include <LibWeb/DOM/Document.h>#include <LibWeb/HTML/BroadcastChannel.h>-#include <LibWeb/HTML/EventNames.h>-#include <LibWeb/HTML/MessageEvent.h>#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/StructuredSerialize.h>-#include <LibWeb/HTML/Window.h>#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>-#include <LibWeb/HTML/WorkerGlobalScope.h>#include <LibWeb/Page/Page.h>-#include <LibWeb/StorageAPI/StorageKey.h>#include <LibWebCommon/HTML/BroadcastChannelMessage.h>-namespace Web::HTML {+// What the Rust implementation of BroadcastChannel asks of LibWeb's C++ code, declared on the Rust side in+// Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rs.-class BroadcastChannelRepository {-public:- void register_channel(GC::Ref<BroadcastChannel>);- void unregister_channel(GC::Ref<BroadcastChannel>);- auto const& registered_channels_for_key(StorageAPI::StorageKey) const;- [[nodiscard]] u64 next_channel_id() { return ++m_next_channel_id; }+namespace Web::HTML {-private:- HashMap<StorageAPI::StorageKey, Vector<GC::Weak<BroadcastChannel>>> m_channels;- u64 m_next_channel_id { 0 };+// The serialized message of a BroadcastChannel message, which the Rust implementation owns.+struct BroadcastChannelSerializedMessage {+ IPCSerializationRecord serialized_message;+ Vector<Core::AnonymousBuffer> shared_buffers;};-void BroadcastChannelRepository::register_channel(GC::Ref<BroadcastChannel> channel)-{- auto storage_key = channel->m_storage_key;- channel->m_channel_id = next_channel_id();- m_channels.ensure(storage_key).append(channel);-}--void BroadcastChannelRepository::unregister_channel(GC::Ref<BroadcastChannel> channel)-{- auto storage_key = channel->m_storage_key;- auto maybe_channels = m_channels.get(storage_key);- if (!maybe_channels.has_value())- return;-- auto& relevant_channels = maybe_channels.value();- // When called from the channel's finalizer, the GC may already have cleared our weak pointer to it.- relevant_channels.remove_all_matching([&](auto const& c) { return !c || c == channel; });- if (relevant_channels.is_empty())- m_channels.remove(storage_key);-}--auto const& BroadcastChannelRepository::registered_channels_for_key(StorageAPI::StorageKey key) const-{- static NeverDestroyed<Vector<GC::Weak<BroadcastChannel>>> empty_channels;-- auto maybe_channels = m_channels.get(key);- if (!maybe_channels.has_value())- return *empty_channels;-- return maybe_channels.value();-}--static BroadcastChannelRepository& broadcast_channel_repository()-{- static NeverDestroyed<BroadcastChannelRepository> repository;- return *repository;-}+extern "C" {-GC_DEFINE_ALLOCATOR(BroadcastChannel);+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*);-GC::Ref<BroadcastChannel> BroadcastChannel::create(GC::Ref<DOM::EventTarget> relevant_global_object, Utf16FlyString const& name, URL::Origin origin, StorageAPI::StorageKey storage_key)-{- auto channel = GC::Heap::the().allocate<BroadcastChannel>(relevant_global_object, name, move(origin), move(storage_key));- broadcast_channel_repository().register_channel(channel);- return channel;+// 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*);}-GC::Ref<BroadcastChannel> BroadcastChannel::create_for_constructor(JS::Object& relevant_global_object, Utf16String const& name)+static JS::Object& global_object_of(void* realm){- auto& global_scope = relevant_window_or_worker_global_scope(relevant_global_object);- auto& settings = relevant_settings_object(global_scope);- return create(global_scope.this_impl(), Utf16FlyString::from_utf16(name.utf16_view()), settings.origin(), StorageAPI::obtain_a_storage_key_for_non_storage_purposes(settings));+ return static_cast<JS::Realm*>(realm)->global_object();}-BroadcastChannel::BroadcastChannel(GC::Ref<DOM::EventTarget> relevant_global_object, Utf16FlyString const& name,- URL::Origin origin, StorageAPI::StorageKey storage_key)- : DOM::EventTarget()- , m_channel_name(name)- , m_origin(move(origin))- , m_storage_key(move(storage_key))- , m_global_object(relevant_global_object)+BroadcastChannelSerializedMessage* web_html_broadcast_channel_create_serialized_message(){+ return new BroadcastChannelSerializedMessage;}-void BroadcastChannel::finalize()+void web_html_broadcast_channel_destroy_serialized_message(BroadcastChannelSerializedMessage* message){- Base::finalize();- broadcast_channel_repository().unregister_channel(*this);+ delete message;}-void BroadcastChannel::visit_edges(Cell::Visitor& visitor)+IPCSerializationRecord* web_html_broadcast_channel_serialized_message_record(BroadcastChannelSerializedMessage* message){- Base::visit_edges(visitor);- visitor.visit(m_global_object);+ return &message->serialized_message;}-JS::Object& BroadcastChannel::relevant_global_object() const+Vector<Core::AnonymousBuffer>* web_html_broadcast_channel_serialized_message_shared_buffers(BroadcastChannelSerializedMessage* message){- return HTML::relevant_global_object(HTML::relevant_window_or_worker_global_scope(*m_global_object));+ return &message->shared_buffers;}-void BroadcastChannel::event_listener_list_changed()+void web_html_broadcast_channel_relevant_settings_object_origin(void* realm, void* ctx, void (*on_origin)(void*, URL::FFI::FfiOrigin const*)){- update_strong_reference_from_relevant_global_object();+ URL::RustIntegration::lend_origin_to_ffi(relevant_settings_object(global_object_of(realm)).origin(), [&](URL::FFI::FfiOrigin const& origin) {+ on_origin(ctx, &origin);+ });}-// https://html.spec.whatwg.org/multipage/web-messaging.html#broadcasting-to-other-browsing-contexts-void BroadcastChannel::update_strong_reference_from_relevant_global_object()+void web_html_broadcast_channel_set_strongly_referenced(void* realm, DOM::EventTarget* event_target, bool strongly_referenced){- // While a BroadcastChannel object whose closed flag is false has an event listener registered for message or- // messageerror events, there must be a strong reference from the BroadcastChannel object's relevant global object- // to the BroadcastChannel object itself.- // NB: Gecko/WebKit/Blink also keep an open channel alive while it has listeners, but count only message ones: Gecko- // KeepAliveIfHasListenersFor(nsGkAtoms::onmessage), WebKit m_hasRelevantEventListener, Blink HasPendingActivity().- // A messageerror listener counts here too, as the spec requires.- auto& global_scope = relevant_window_or_worker_global_scope(*m_global_object);- if (!m_closed_flag && (has_event_listener(EventNames::message) || has_event_listener(EventNames::messageerror)))- global_scope.add_strong_reference_to_broadcast_channel({}, *this);+ auto& global_scope = relevant_window_or_worker_global_scope(global_object_of(realm));+ if (strongly_referenced)+ global_scope.add_strong_reference_to_broadcast_channel(*event_target);else- global_scope.remove_strong_reference_to_broadcast_channel({}, *this);+ global_scope.remove_strong_reference_to_broadcast_channel(*event_target);}-// https://html.spec.whatwg.org/multipage/web-messaging.html#eligible-for-messaging-bool BroadcastChannel::is_eligible_for_messaging() const+void web_html_broadcast_channel_post_message_to_other_processes(void* realm, FlatPtr channel_name, BroadcastChannelSerializedMessage const* message){- // A BroadcastChannel object is said to be eligible for messaging when its relevant global object is either:- auto const& global = relevant_global_object();-- // * a Window object whose associated Document is fully active, or- if (auto* window = window_from_global_object(global))- return window->associated_document().is_fully_active();-- // * a WorkerGlobalScope object whose closing flag is false and is not suspendable.- // FIXME: Suspendable worker- if (auto* worker_global_scope = Bindings::worker_global_scope_from_global_object(global)) {- return !worker_global_scope->is_closing();- }-- return false;-}--// https://html.spec.whatwg.org/multipage/web-messaging.html#dom-broadcastchannel-postmessage-WebIDL::ExceptionOr<void> BroadcastChannel::post_message(JS::Realm& realm, JS::Value message)-{- // 1. If this is not eligible for messaging, then return.- if (!is_eligible_for_messaging())- return {};-- // 2. If this's closed flag is true, then throw an "InvalidStateError" DOMException.- if (m_closed_flag)- return WebIDL::InvalidStateError::create("BroadcastChannel.postMessage() on a closed channel"_utf16);-- // 3. Let serialized be StructuredSerialize(message). Rethrow any exceptions.- // 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.- Vector<Core::AnonymousBuffer> shared_buffers;- auto serialized = TRY(structured_serialize(realm.vm(), message, shared_buffers));-- // 4. Let sourceOrigin be this's relevant settings object's origin.- auto source_origin = m_origin;-- // 5. Let sourceStorageKey be the result of running obtain a storage key for non-storage purposes with this's relevant settings object.- auto source_storage_key = m_storage_key;-- BroadcastChannelMessage message_to_send {- .storage_key = source_storage_key,- .channel_name = name(),- .source_origin = source_origin,- .serialized_message = serialized,- .shared_buffers = move(shared_buffers),- .source_process_id = Core::System::getpid(),- .source_channel_id = m_channel_id,- };-- // Steps 6-9.- deliver_message_locally(message_to_send);+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ auto name = Utf16String::from_raw(channel_name);// 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(realm).id,- .channel_name = move(message_to_send.channel_name),- .serialized_message = move(message_to_send.serialized_message),- .shared_buffers = move(message_to_send.shared_buffers),- .source_channel_id = message_to_send.source_channel_id,+ .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,};- Bindings::principal_host_defined_page(realm).client().page_did_post_broadcast_channel_message(posted_message);-- return {};+ Bindings::principal_host_defined_page(js_realm).client().page_did_post_broadcast_channel_message(posted_message);}-// https://html.spec.whatwg.org/multipage/web-messaging.html#dom-broadcastchannel-postmessage-void BroadcastChannel::deliver_message_locally(BroadcastChannelMessage const& message)+void deliver_broadcast_channel_message_locally(BroadcastChannelMessage message){- // 6. Let destinations be a list of BroadcastChannel objects that match the following criteria:- GC::RootVector<GC::Ref<BroadcastChannel>> destinations;-- // * The result of running obtain a storage key for non-storage purposes with their relevant settings object equals sourceStorageKey.- auto same_origin_broadcast_channels = broadcast_channel_repository().registered_channels_for_key(message.storage_key);- for (auto const& channel : same_origin_broadcast_channels) {- // * They are eligible for messaging.- if (!channel->is_eligible_for_messaging())- continue;-- // * Their channel name is this's channel name.- if (channel->name() != message.channel_name)- continue;-- destinations.append(*channel);- }-- // 7. Remove source from destinations.- destinations.remove_all_matching([&](auto destination) {- return message.source_process_id == Core::System::getpid() && destination->m_channel_id == message.source_channel_id;+ auto* serialized_message = new BroadcastChannelSerializedMessage {+ .serialized_message = move(message.serialized_message),+ .shared_buffers = move(message.shared_buffers),+ };+ 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);+ });});-- // FIXME: 8. Sort destinations such that all BroadcastChannel objects whose relevant agents are the same are sorted in creation order, oldest first.- // (This does not define a complete ordering. Within this constraint, user agents may sort the list in any implementation-defined manner.)-- // 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 (auto destination : destinations) {- auto& target_global = destination->relevant_global_object();- HTML::queue_global_task(HTML::Task::Source::DOMManipulation, target_global, GC::create_function(GC::Heap::the(), [destination, message] {- // 1. If destination's closed flag is true, then abort these steps.- if (destination->m_closed_flag)- return;-- // 2. Let targetRealm be destination's relevant realm.- auto& target_realm = HTML::relevant_realm(destination->relevant_global_object());- auto& vm = target_realm.vm();-- // 3. Let data be StructuredDeserialize(serialized, targetRealm).- // 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.- auto data_or_error = structured_deserialize(vm, message.serialized_message, target_realm, &message.shared_buffers);- if (data_or_error.is_exception()) {- MessageEventInit event_init;- auto event = MessageEvent::create(target_realm.global_object(), HTML::EventNames::messageerror, event_init, message.source_origin);- event->set_is_trusted(true);- destination->dispatch_event(event);- return;- }-- // 4. Fire an event named message at destination, using MessageEvent, with the data attribute initialized to data and- // its origin initialized to sourceOrigin.- MessageEventInit event_init;- event_init.data = data_or_error.release_value();- auto event = MessageEvent::create(target_realm.global_object(), HTML::EventNames::message, event_init, message.source_origin);- event->set_is_trusted(true);- destination->dispatch_event(event);- }));- }-}--// https://html.spec.whatwg.org/multipage/web-messaging.html#dom-broadcastchannel-close-void BroadcastChannel::close()-{- // The close() method steps are to set this's closed flag to true.- m_closed_flag = true;-- update_strong_reference_from_relevant_global_object();- broadcast_channel_repository().unregister_channel(*this);-}--// https://html.spec.whatwg.org/multipage/web-messaging.html#handler-broadcastchannel-onmessage-void BroadcastChannel::set_onmessage(GC::Ptr<WebIDL::CallbackType> event_handler)-{- set_event_handler_attribute(HTML::EventNames::message, event_handler);-}--// https://html.spec.whatwg.org/multipage/web-messaging.html#handler-broadcastchannel-onmessage-GC::Ptr<WebIDL::CallbackType> BroadcastChannel::onmessage()-{- return event_handler_attribute(HTML::EventNames::message);-}--// https://html.spec.whatwg.org/multipage/web-messaging.html#handler-broadcastchannel-onmessageerror-void BroadcastChannel::set_onmessageerror(GC::Ptr<WebIDL::CallbackType> event_handler)-{- set_event_handler_attribute(HTML::EventNames::messageerror, event_handler);-}--// https://html.spec.whatwg.org/multipage/web-messaging.html#handler-broadcastchannel-onmessageerror-GC::Ptr<WebIDL::CallbackType> BroadcastChannel::onmessageerror()-{- return event_handler_attribute(HTML::EventNames::messageerror);}}diff --git a/Libraries/LibWeb/HTML/BroadcastChannel.h b/Libraries/LibWeb/HTML/BroadcastChannel.hindex 9fee4953319..1fe04802f8e 100644--- a/Libraries/LibWeb/HTML/BroadcastChannel.h+++ b/Libraries/LibWeb/HTML/BroadcastChannel.h@@ -7,60 +7,12 @@#pragma once-#include <LibJS/Forward.h>-#include <LibURL/Origin.h>-#include <LibWeb/DOM/EventTarget.h>-#include <LibWeb/StorageAPI/StorageKey.h>+#include <LibWeb/Export.h>+#include <LibWebCommon/Forward.h>namespace Web::HTML {-class BroadcastChannelRepository;--class BroadcastChannel final : public DOM::EventTarget {- WEB_WRAPPABLE(BroadcastChannel, DOM::EventTarget);- GC_DECLARE_ALLOCATOR(BroadcastChannel);--public:- [[nodiscard]] static GC::Ref<BroadcastChannel> create(GC::Ref<DOM::EventTarget> relevant_global_object, Utf16FlyString const& name, URL::Origin, StorageAPI::StorageKey);- [[nodiscard]] static GC::Ref<BroadcastChannel> create_for_constructor(JS::Object&, Utf16String const& name);-- // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-broadcastchannel-name- Utf16FlyString const& name() const- {- // The name getter steps are to return this's channel name.- return m_channel_name;- }-- WebIDL::ExceptionOr<void> post_message(JS::Realm&, JS::Value message);-- void close();-- void set_onmessage(GC::Ptr<WebIDL::CallbackType>);- GC::Ptr<WebIDL::CallbackType> onmessage();- void set_onmessageerror(GC::Ptr<WebIDL::CallbackType>);- GC::Ptr<WebIDL::CallbackType> onmessageerror();-- static WEB_API void deliver_message_locally(BroadcastChannelMessage const&);--private:- friend class BroadcastChannelRepository;-- BroadcastChannel(GC::Ref<DOM::EventTarget> relevant_global_object, Utf16FlyString const& name, URL::Origin,- StorageAPI::StorageKey);- virtual void finalize() override;- virtual void visit_edges(Cell::Visitor&) override;- virtual void event_listener_list_changed() override;-- JS::Object& relevant_global_object() const;- bool is_eligible_for_messaging() const;- void update_strong_reference_from_relevant_global_object();-- Utf16FlyString m_channel_name;- URL::Origin m_origin;- StorageAPI::StorageKey m_storage_key;- GC::Ref<DOM::EventTarget> m_global_object;- u64 m_channel_id { 0 };- bool m_closed_flag { false };-};+// Steps 6 to 9 of BroadcastChannel's postMessage(), for a message that another process posted.+WEB_API void deliver_broadcast_channel_message_locally(BroadcastChannelMessage);}diff --git a/Libraries/LibWeb/HTML/BroadcastChannel.idl b/Libraries/LibWeb/HTML/BroadcastChannel.idlindex 0af5e923ed1..00462560926 100644--- a/Libraries/LibWeb/HTML/BroadcastChannel.idl+++ b/Libraries/LibWeb/HTML/BroadcastChannel.idl@@ -1,5 +1,5 @@// https://html.spec.whatwg.org/multipage/web-messaging.html#broadcastchannel-[Exposed=(Window,Worker)]+[Exposed=(Window,Worker), ImplementedIn=Rust]interface BroadcastChannel : EventTarget {constructor(DOMString name);diff --git a/Libraries/LibWeb/HTML/StructuredSerialize.cpp b/Libraries/LibWeb/HTML/StructuredSerialize.cppindex 1ffa0ed454a..669aa3c973c 100644--- a/Libraries/LibWeb/HTML/StructuredSerialize.cpp+++ b/Libraries/LibWeb/HTML/StructuredSerialize.cpp@@ -82,9 +82,9 @@ WebIDL::Exception data_clone_error_from_serialization_error(JS::Realm& realm, AK// The algorithms of structured serialization, which Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize runs.extern "C" {-JSCompletion web_rust_structured_serialize(JSVM*, JSValue, u8 allow_shared_array_buffers, Vector<Core::AnonymousBuffer>* shared_buffers, IPCSerializationRecord*);+JSCompletion web_rust_structured_serialize(JSVM*, JSValue, u8 allow_shared_array_buffers, IPCSerializationRecord*);JSCompletion web_rust_structured_serialize_for_storage(JSVM*, JSValue, StorageSerializationRecord*);-JSCompletion web_rust_structured_deserialize(JSVM*, void* target_realm, IPCSerializationRecord const*, Vector<Core::AnonymousBuffer> const* shared_buffers);+JSCompletion web_rust_structured_deserialize(JSVM*, void* target_realm, IPCSerializationRecord const*);JSCompletion web_rust_structured_deserialize_for_storage(JSVM*, void* target_realm, ReadonlyBytes);JSCompletion web_rust_structured_serialize_with_transfer(JSVM*, void* realm, JSValue, JSObject* const* transfer_list, size_t count, SerializedTransferRecord** out_record);JSCompletion web_rust_structured_deserialize_with_transfer(JSVM*, void* target_realm, SerializedTransferRecord*, Vector<GC::Root<JS::Object>>* transferred_values);@@ -132,21 +132,7 @@ WebIDL::ExceptionOr<IPCSerializationRecord> structured_serialize(JS::VM& vm, JS:{// 1. Return ? StructuredSerializeInternal(value, false).IPCSerializationRecord serialized;- TRY(JS::HostABI::completion_from_abi<JS::Value>(web_rust_structured_serialize(JS::HostABI::vm_to_abi(vm), JS::HostABI::value_to_abi(value), to_underlying(allow_shared_array_buffers), nullptr, &serialized)));- return serialized;-}--// https://html.spec.whatwg.org/multipage/structured-data.html#structuredserialize-// AD-HOC: For a record that reaches agents in other processes. The record itself is bytes-only, so a shared-memory--// backed SharedArrayBuffer is handed over beside it, in shared_buffers, by file descriptor — and every-// receiver references the same [[ArrayBufferData]], rather than rebuilding the buffer from a byte copy.-WebIDL::ExceptionOr<IPCSerializationRecord> structured_serialize(JS::VM& vm, JS::Value value, Vector<Core::AnonymousBuffer>& shared_buffers)-{- // 1. Return ? StructuredSerializeInternal(value, false).- IPCSerializationRecord serialized;- Vector<Core::AnonymousBuffer> serialized_shared_buffers;- TRY(JS::HostABI::completion_from_abi<JS::Value>(web_rust_structured_serialize(JS::HostABI::vm_to_abi(vm), JS::HostABI::value_to_abi(value), to_underlying(AllowSharedArrayBuffers::CrossOriginIsolatedOnly), &serialized_shared_buffers, &serialized)));- shared_buffers = move(serialized_shared_buffers);+ TRY(JS::HostABI::completion_from_abi<JS::Value>(web_rust_structured_serialize(JS::HostABI::vm_to_abi(vm), JS::HostABI::value_to_abi(value), to_underlying(allow_shared_array_buffers), &serialized)));return serialized;}@@ -168,10 +154,10 @@ StorageSerializationRecord structured_serialize_undefined_or_null_for_storage(JS}// https://html.spec.whatwg.org/multipage/structured-data.html#structureddeserialize-WebIDL::ExceptionOr<JS::Value> structured_deserialize(JS::VM& vm, IPCSerializationRecord const& serialized, JS::Realm& target_realm, Vector<Core::AnonymousBuffer> const* shared_buffers)+WebIDL::ExceptionOr<JS::Value> structured_deserialize(JS::VM& vm, IPCSerializationRecord const& serialized, JS::Realm& target_realm){TemporaryExecutionContext execution_context { target_realm };- return TRY(JS::HostABI::completion_from_abi<JS::Value>(web_rust_structured_deserialize(JS::HostABI::vm_to_abi(vm), &target_realm, &serialized, shared_buffers)));+ return TRY(JS::HostABI::completion_from_abi<JS::Value>(web_rust_structured_deserialize(JS::HostABI::vm_to_abi(vm), &target_realm, &serialized)));}WebIDL::ExceptionOr<JS::Value> structured_deserialize(JS::VM& vm, StorageSerializationRecord const& serialized, JS::Realm& target_realm)diff --git a/Libraries/LibWeb/HTML/StructuredSerialize.h b/Libraries/LibWeb/HTML/StructuredSerialize.hindex 0b55bc14c93..19d59bfe493 100644--- a/Libraries/LibWeb/HTML/StructuredSerialize.h+++ b/Libraries/LibWeb/HTML/StructuredSerialize.h@@ -89,11 +89,10 @@ IPCSerializationRecord create_ipc_serialization_record(ReadonlyBytes data, VectoWEB_API WebIDL::ExceptionOr<IPCSerializationRecord> structured_serialize(JS::VM&, JS::Value);WEB_API WebIDL::ExceptionOr<IPCSerializationRecord> structured_serialize(JS::VM&, JS::Value, AllowSharedArrayBuffers);-WEB_API WebIDL::ExceptionOr<IPCSerializationRecord> structured_serialize(JS::VM&, JS::Value, Vector<Core::AnonymousBuffer>& shared_buffers);WEB_API WebIDL::ExceptionOr<StorageSerializationRecord> structured_serialize_for_storage(JS::VM&, JS::Value);WEB_API StorageSerializationRecord structured_serialize_undefined_or_null_for_storage(JS::Value);-WEB_API WebIDL::ExceptionOr<JS::Value> structured_deserialize(JS::VM&, IPCSerializationRecord const&, JS::Realm&, Vector<Core::AnonymousBuffer> const* shared_buffers = nullptr);+WEB_API WebIDL::ExceptionOr<JS::Value> structured_deserialize(JS::VM&, IPCSerializationRecord const&, JS::Realm&);WEB_API WebIDL::ExceptionOr<JS::Value> structured_deserialize(JS::VM&, StorageSerializationRecord const&, JS::Realm&);WEB_API WebIDL::Exception data_clone_error_from_serialization_error(JS::Realm&, AK::Error const&);diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cppindex 5802375c872..db5af897992 100644--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp@@ -36,7 +36,6 @@#include <LibWeb/EventTiming/PerformanceEventTiming.h>#include <LibWeb/Fetch/BindingsGlue.h>#include <LibWeb/Fetch/FetchMethod.h>-#include <LibWeb/HTML/BroadcastChannel.h>#include <LibWeb/HTML/Canvas/PredefinedColorSpace.h>#include <LibWeb/HTML/CanvasRenderingContext2D.h>#include <LibWeb/HTML/EventLoop/EventLoop.h>@@ -1445,12 +1444,12 @@ void WindowOrWorkerGlobalScopeMixin::forcibly_close_all_event_sources()event_source->forcibly_close();}-void WindowOrWorkerGlobalScopeMixin::add_strong_reference_to_broadcast_channel(Badge<BroadcastChannel>, GC::Ref<BroadcastChannel> channel)+void WindowOrWorkerGlobalScopeMixin::add_strong_reference_to_broadcast_channel(GC::Ref<DOM::EventTarget> channel){m_strongly_referenced_broadcast_channels.set(channel);}-void WindowOrWorkerGlobalScopeMixin::remove_strong_reference_to_broadcast_channel(Badge<BroadcastChannel>, GC::Ref<BroadcastChannel> channel)+void WindowOrWorkerGlobalScopeMixin::remove_strong_reference_to_broadcast_channel(GC::Ref<DOM::EventTarget> channel){m_strongly_referenced_broadcast_channels.remove(channel);}diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.hindex 208f130123f..71f16c39cff 100644--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h@@ -87,8 +87,8 @@ public:void unregister_event_source(Badge<EventSource>, GC::Ref<EventSource>);void forcibly_close_all_event_sources();- void add_strong_reference_to_broadcast_channel(Badge<BroadcastChannel>, GC::Ref<BroadcastChannel>);- void remove_strong_reference_to_broadcast_channel(Badge<BroadcastChannel>, GC::Ref<BroadcastChannel>);+ void add_strong_reference_to_broadcast_channel(GC::Ref<DOM::EventTarget>);+ void remove_strong_reference_to_broadcast_channel(GC::Ref<DOM::EventTarget>);void close_all_idb_connections();@@ -205,7 +205,7 @@ private:// https://html.spec.whatwg.org/multipage/web-messaging.html#broadcasting-to-other-browsing-contexts// The open BroadcastChannel objects with a message or messageerror listener, which this global keeps alive. They're// held here rather than rooted — so a channel that's never closed can't keep its global alive.- HashTable<GC::Ref<BroadcastChannel>> m_strongly_referenced_broadcast_channels;+ HashTable<GC::Ref<DOM::EventTarget>> m_strongly_referenced_broadcast_channels;Vector<GC::Weak<PermissionsAPI::PermissionStatus>> m_permission_statuses;GC::Ptr<HighResolutionTime::Performance> m_performance;diff --git a/Libraries/LibWeb/StorageAPI/StorageKey.cpp b/Libraries/LibWeb/StorageAPI/StorageKey.cppindex 9d1273e497d..caaede7fb33 100644--- a/Libraries/LibWeb/StorageAPI/StorageKey.cpp+++ b/Libraries/LibWeb/StorageAPI/StorageKey.cpp@@ -40,6 +40,7 @@ StorageKey obtain_a_storage_key_for_non_storage_purposes(HTML::Environment constextern "C" {bool web_storage_api_obtain_a_storage_key(void* realm, void* ctx, void (*on_origin)(void*, URL::FFI::FfiOrigin const*));+void web_storage_api_obtain_a_storage_key_for_non_storage_purposes(void* realm, void* ctx, void (*on_origin)(void*, URL::FFI::FfiOrigin const*));}bool web_storage_api_obtain_a_storage_key(void* realm, void* ctx, void (*on_origin)(void*, URL::FFI::FfiOrigin const*))@@ -54,4 +55,13 @@ bool web_storage_api_obtain_a_storage_key(void* realm, void* ctx, void (*on_origreturn true;}+void web_storage_api_obtain_a_storage_key_for_non_storage_purposes(void* realm, void* ctx, void (*on_origin)(void*, URL::FFI::FfiOrigin const*))+{+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ auto storage_key = StorageAPI::obtain_a_storage_key_for_non_storage_purposes(HTML::relevant_settings_object(js_realm.global_object()));+ URL::RustIntegration::lend_origin_to_ffi(storage_key.origin, [&](URL::FFI::FfiOrigin const& origin) {+ on_origin(ctx, &origin);+ });+}+}diff --git a/Libraries/LibWebCommon/HTML/BroadcastChannelMessage.cpp b/Libraries/LibWebCommon/HTML/BroadcastChannelMessage.cppindex d1e1b9242ce..659e9faf5f7 100644--- a/Libraries/LibWebCommon/HTML/BroadcastChannelMessage.cpp+++ b/Libraries/LibWebCommon/HTML/BroadcastChannelMessage.cpp@@ -19,8 +19,6 @@ ErrorOr<void> encode(Encoder& encoder, Web::HTML::BroadcastChannelMessage const&TRY(encoder.encode(message.source_origin));TRY(encoder.encode(message.serialized_message));TRY(encoder.encode(message.shared_buffers));- TRY(encoder.encode(message.source_process_id));- TRY(encoder.encode(message.source_channel_id));return {};}@@ -32,8 +30,6 @@ ErrorOr<Web::HTML::BroadcastChannelMessage> decode(Decoder& decoder)auto source_origin = TRY(decoder.decode<URL::Origin>());auto serialized_message = TRY(decoder.decode<Web::HTML::IPCSerializationRecord>());auto shared_buffers = TRY(decoder.decode<Vector<Core::AnonymousBuffer>>());- auto source_process_id = TRY(decoder.decode<i32>());- auto source_channel_id = TRY(decoder.decode<u64>());return Web::HTML::BroadcastChannelMessage {.storage_key = move(storage_key),@@ -41,8 +37,6 @@ ErrorOr<Web::HTML::BroadcastChannelMessage> decode(Decoder& decoder).source_origin = move(source_origin),.serialized_message = move(serialized_message),.shared_buffers = move(shared_buffers),- .source_process_id = source_process_id,- .source_channel_id = source_channel_id,};}@@ -53,7 +47,6 @@ ErrorOr<void> encode(Encoder& encoder, Web::HTML::PostedBroadcastChannelMessageTRY(encoder.encode(message.channel_name));TRY(encoder.encode(message.serialized_message));TRY(encoder.encode(message.shared_buffers));- TRY(encoder.encode(message.source_channel_id));return {};}@@ -64,14 +57,12 @@ ErrorOr<Web::HTML::PostedBroadcastChannelMessage> decode(Decoder& decoder)auto channel_name = TRY(decoder.decode<Utf16FlyString>());auto serialized_message = TRY(decoder.decode<Web::HTML::IPCSerializationRecord>());auto shared_buffers = TRY(decoder.decode<Vector<Core::AnonymousBuffer>>());- auto source_channel_id = TRY(decoder.decode<u64>());return Web::HTML::PostedBroadcastChannelMessage {.environment_id = move(environment_id),.channel_name = move(channel_name),.serialized_message = move(serialized_message),.shared_buffers = move(shared_buffers),- .source_channel_id = source_channel_id,};}diff --git a/Libraries/LibWebCommon/HTML/BroadcastChannelMessage.h b/Libraries/LibWebCommon/HTML/BroadcastChannelMessage.hindex 3eb13ddccae..9c772e218a9 100644--- a/Libraries/LibWebCommon/HTML/BroadcastChannelMessage.h+++ b/Libraries/LibWebCommon/HTML/BroadcastChannelMessage.h@@ -28,8 +28,6 @@ struct WEBCOMMON_API BroadcastChannelMessage {// — referenced by index from the record, whose bytes can't carry one. So the browser process's fan-out// hands every receiving process the same memory. See SerializedTransferRecord.Vector<Core::AnonymousBuffer> shared_buffers;- pid_t source_process_id { -1 };- u64 source_channel_id { 0 };};struct WEBCOMMON_API PostedBroadcastChannelMessage {@@ -37,7 +35,6 @@ struct WEBCOMMON_API PostedBroadcastChannelMessage {Utf16FlyString channel_name;IPCSerializationRecord serialized_message;Vector<Core::AnonymousBuffer> shared_buffers;- u64 source_channel_id { 0 };};}diff --git a/Libraries/LibWebView/WorkerProcessManager.cpp b/Libraries/LibWebView/WorkerProcessManager.cppindex c740cb4fff9..cd840dc16b7 100644--- a/Libraries/LibWebView/WorkerProcessManager.cpp+++ b/Libraries/LibWebView/WorkerProcessManager.cpp@@ -441,8 +441,6 @@ void WorkerProcessManager::post_broadcast_channel_message(Web::HTML::PostedBroad.source_origin = source_settings.origin(),.serialized_message = move(posted_message.serialized_message),.shared_buffers = move(posted_message.shared_buffers),- .source_process_id = source_process_id,- .source_channel_id = posted_message.source_channel_id,};WebContentClient::for_each_client([&](auto& client) {diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex 9f044d7d605..49386adf08d 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -56,7 +56,7 @@ ALLOWED_REALM_MENTIONS = {),"FileAPI": (2, 9, "Blob glue still creates streams and buffers in selected realms"),"HTML": (- 64,+ 63,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",@@ -74,7 +74,7 @@ ALLOWED_REALM_MENTIONS = {41,"service worker jobs, caches, and container promises still materialize results in selected realms",),- "StorageAPI": (1, 2, "the C++ glue of the Rust storage keys reads the settings object of a realm's global"),+ "StorageAPI": (1, 3, "the C++ glue of the Rust storage keys reads the settings object of a realm's global"),"Streams": (5, 13, "the C++ facade of the Rust streams creates streams and promises in caller-selected realms"),"TrustedTypes": (2, 9, "Trusted Types policy factory operations still use selected realms"),"WebAssembly": (diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cppindex 1f1b532885b..570d0286d8e 100644--- a/Services/WebContent/ConnectionFromClient.cpp+++ b/Services/WebContent/ConnectionFromClient.cpp@@ -3719,7 +3719,7 @@ void ConnectionFromClient::cookies_changed(Web::PageId page_id, Vector<HTTP::Coovoid ConnectionFromClient::broadcast_channel_message(Web::HTML::BroadcastChannelMessage message){- Web::HTML::BroadcastChannel::deliver_message_locally(message);+ Web::HTML::deliver_broadcast_channel_message_locally(move(message));}void ConnectionFromClient::did_worker_agent_fail_loading_script(Web::HTML::WorkerAgentOwnerToken owner_token)diff --git a/Services/WebWorker/ConnectionFromClient.cpp b/Services/WebWorker/ConnectionFromClient.cppindex 4cff64d66dd..2ffcc212106 100644--- a/Services/WebWorker/ConnectionFromClient.cpp+++ b/Services/WebWorker/ConnectionFromClient.cpp@@ -224,7 +224,7 @@ void ConnectionFromClient::did_worker_agent_die(Web::HTML::WorkerAgentOwnerTokenvoid ConnectionFromClient::broadcast_channel_message(Web::HTML::BroadcastChannelMessage message){- Web::HTML::BroadcastChannel::deliver_message_locally(message);+ Web::HTML::deliver_broadcast_channel_message_locally(move(message));}}