Truly independent web browser
LibWeb+LibWebView+WebContent: Connect ports in a process directly
Andreas Kling7ffcadc13762
diff --git a/Libraries/LibJS/Rust/src/api.rs b/Libraries/LibJS/Rust/src/api.rsindex b2a8e0e5dea..7965146d299 100644--- a/Libraries/LibJS/Rust/src/api.rs+++ b/Libraries/LibJS/Rust/src/api.rs@@ -86,9 +86,8 @@ pub use crate::runtime::regexp_object::{RegExpObject, regexp_create};pub use crate::runtime::set::Set;pub use crate::runtime::set_iterator::SetIterator;pub use crate::runtime::shared_backing_store::{- SharedBackingStore, SharedStoreLifeline, duplicate_lifeline_from_raw_descriptor, lifeline_from_raw_descriptor,- lifeline_into_raw_descriptor,- pin_stores_for_a_message, release_stores_of_lost_messages,+ SharedBackingStore, SharedStoreLifeline, SharedStorePin, duplicate_lifeline_from_raw_descriptor,+ lifeline_from_raw_descriptor, lifeline_into_raw_descriptor, release_stores_of_lost_messages,};pub use crate::runtime::string_object::StringObject;pub use crate::runtime::typed_array::{diff --git a/Libraries/LibJS/Rust/src/runtime/shared_backing_store.rs b/Libraries/LibJS/Rust/src/runtime/shared_backing_store.rsindex 1d95957b8dd..70806a36807 100644--- a/Libraries/LibJS/Rust/src/runtime/shared_backing_store.rs+++ b/Libraries/LibJS/Rust/src/runtime/shared_backing_store.rs@@ -12,10 +12,13 @@//! id. The id gives nothing to the process of a receiver that is not this one, which is where a message goes that//! deserialization then rejects.//!-//! A message can wait in a socket for a long time, and every agent may drop its buffer meanwhile. So a message holds a-//! lifeline: the read end of a pipe that the sender's process keeps the store for. The kernel keeps track of where that-//! read end is, as it does for any descriptor in flight, so it does not matter whether the message is delivered to one-//! receiver, to many, to a process that has no use for it, or to nobody.+//! A message can wait for a long time, and every agent may drop its buffer meanwhile. So a message holds a pin. While the+//! message stays in memory of this process, that is just a count on the stores. A message that goes through a socket can+//! still come back here: BroadcastChannel reaches agents of this process through the browser process, and the ends of a+//! MessagePort can both be in this process with a socket between them. So such a message holds a lifeline instead: the+//! read end of a pipe that the sender's process keeps the stores for. The kernel keeps track of where that read end is,+//! as it does for any descriptor in flight, so it does not matter whether the message is delivered to one receiver, to+//! many, to a process that has no use for it, or to nobody.use core::ffi::c_int;use std::collections::HashMap;@@ -142,6 +145,41 @@ pub unsafe fn duplicate_lifeline_from_raw_descriptor(descriptor: c_int) -> std::}}+/// What keeps the stores that a message names.+pub enum SharedStorePin {+ /// For a message in memory of this process.+ Counted(Vec<Arc<SharedBackingStore>>),+ /// For a message that has been through a socket, or is about to go through one.+ Lifeline(SharedStoreLifeline),+}++impl SharedStorePin {+ /// A lifeline that keeps the same stores, if the system has a descriptor left.+ pub fn duplicate_lifeline(&self) -> Option<SharedStoreLifeline> {+ match self {+ Self::Counted(stores) => pin_stores_for_a_message(stores.clone()).ok(),+ Self::Lifeline(lifeline) => lifeline.try_clone().ok(),+ }+ }++ /// This pin as a lifeline, if the system has a descriptor left. Without one, the stores may go before the message+ /// arrives, which deserializing throws for.+ pub fn into_lifeline(self) -> Option<SharedStoreLifeline> {+ match self {+ Self::Counted(stores) => pin_stores_for_a_message(stores).ok(),+ Self::Lifeline(lifeline) => Some(lifeline),+ }+ }++ /// Lets go of the stores, for a message that is destroyed.+ pub fn release(self) {+ if let Self::Lifeline(lifeline) = self {+ drop(lifeline);+ release_stores_of_lost_messages();+ }+ }+}+/// Stores that a message keeps alive, until the last duplicate of its lifeline is closed.struct PinnedStores {/// The write end of the pipe, which only ever reports that the read end is gone.@@ -199,7 +237,7 @@ pub fn release_stores_of_lost_messages() {}/// A new lifeline that keeps `stores` for as long as it, or a duplicate of it, is open anywhere.-pub fn pin_stores_for_a_message(stores: Vec<Arc<SharedBackingStore>>) -> std::io::Result<SharedStoreLifeline> {+fn pin_stores_for_a_message(stores: Vec<Arc<SharedBackingStore>>) -> std::io::Result<SharedStoreLifeline> {release_stores_of_lost_messages();let (read_end, write_end) = std::io::pipe()?;pinned_stores().push(PinnedStores {diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rsindex d8c78e4517b..c7548489ee9 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs@@ -18,6 +18,7 @@use core::cell::Cell;use core::ffi::c_void;use core::ptr::NonNull;+use std::collections::VecDeque;use ak::Utf16String;use libipc_rust::{Decode, DecodeError, Decoder, Encode};@@ -26,12 +27,12 @@ use libwebcommon_rust::html::serialization_records::SerializationType;use crate::bindings::interface::{ConstructedObject, Interface, Ref, implementation_of, wrap};use crate::bindings::{CallContext, Exception, WebIdlResult};-use crate::html::message_port::TransportHandle;+use crate::html::message_port::{TransferredTransport, TransportHandle};use crate::html::structured_serialize::cpp::{ImageBitmapSharedPixels, SharedPixelBuffers, data_clone_error_from_serialization_error,};use crate::html::structured_serialize::reader::StructuredSerializeReader;-use crate::html::structured_serialize::transfer_data_holder::{TransferDataHolder, TransferPayload};+use crate::html::structured_serialize::transfer_data_holder::{CarriedChannelEnd, TransferDataHolder, TransferPayload};use crate::html::structured_serialize::transfer_record::{TransferRecord, TransferRecordRef};use crate::html::structured_serialize::writer::StructuredSerializeWriter;use crate::html::structured_serialize::{@@ -273,12 +274,21 @@ impl<'a> TransferDataWriter<'a> {});}- /// Writes the handle of one end of an IPC transport, whose rights the data holder takes.- pub(crate) fn write_transport_handle(&mut self, handle: TransportHandle) {- self.data_holder.with_encoder(|encoder| {- handle.encode_into(encoder);- Ok(())- });+ /// Writes what a MessagePort reaches its peer with, which the data holder takes.+ pub(crate) fn write_transport(&mut self, transport: TransferredTransport) {+ match transport {+ TransferredTransport::Channel(end) => {+ self.write_bool(true);+ self.data_holder.add_channel_end(end);+ }+ TransferredTransport::Socket(handle) => {+ self.write_bool(false);+ self.data_holder.with_encoder(|encoder| {+ handle.encode_into(encoder);+ Ok(())+ });+ }+ }}/// Writes ! StructuredSerializeWithTransfer(value, « value ») as the data holder of value, which is all that the@@ -297,6 +307,7 @@ impl<'a> TransferDataWriter<'a> {/// created in. What the steps read that the data holder does not hold throws a "DataCloneError" DOMException.pub(crate) struct TransferDataReader<'a> {decoder: Decoder<'a>,+ channel_ends: VecDeque<CarriedChannelEnd>,realm: Gc<Realm>,shared_pixels: Option<&'a SharedPixelBuffers<'a>>,}@@ -305,6 +316,7 @@ impl<'a> TransferDataReader<'a> {pub(crate) fn new(payload: &'a mut TransferPayload, realm: Gc<Realm>) -> Self {Self {decoder: Decoder::new(&payload.bytes, core::mem::take(&mut payload.attachments)),+ channel_ends: core::mem::take(&mut payload.channel_ends),realm,shared_pixels: None,}@@ -373,9 +385,15 @@ impl<'a> TransferDataReader<'a> {Ok(records)}- /// Reads what TransferDataWriter::write_transport_handle() writes.- pub(crate) fn read_transport_handle(&mut self) -> WebIdlResult<TransportHandle> {- self.decoded(TransportHandle::decode)+ /// Reads what TransferDataWriter::write_transport() writes.+ pub(crate) fn read_transport(&mut self) -> WebIdlResult<TransferredTransport> {+ if !self.read::<bool>()? {+ return Ok(TransferredTransport::Socket(self.decoded(TransportHandle::decode)?));+ }+ let end = self.channel_ends.pop_front().ok_or_else(|| {+ data_clone_error_from_serialization_error(self.realm, "Missing channel end in transfer data")+ })?;+ Ok(TransferredTransport::Channel(end.into_end()))}/// ! StructuredDeserializeWithTransfer(dataHolder, the current Realm).[[Deserialized]] for whatdiff --git a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rsindex 6b023abcfb8..f5794c482d7 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs@@ -34,6 +34,7 @@ use crate::bindings::event_target::CppEventTarget;use crate::bindings::interface::{Interface, Ref, cell_from_abi, cell_into_abi, realm_arguments, wrap};use crate::bindings::structured_data::{TransferDataReader, TransferDataWriter, Transferable};use crate::dom::event::EventInit;+use crate::html::port_channel::give_up_on_parked_end;use crate::html::structured_serialize::cpp::SerializedTransferRecord;use crate::html::structured_serialize::message_record::MessageRecord;use crate::html::structured_serialize::transfer_data_holder::{TransferDataHolder, TransferPayload};@@ -353,8 +354,9 @@ pub unsafe extern "C" fn web_rust_message_port_fail_next_transfer_for_testing(pounsafe { cell_from_abi::<MessagePort>(port) }.fail_next_transfer_for_testing();}-/// The transfer steps of the MessagePort, which C++ runs outside StructuredSerializeWithTransfer, into a data holder-/// that holds no type, whose carrier it hands over.+/// The transfer steps of the MessagePort of a new channel to a worker, which C++ runs outside+/// StructuredSerializeWithTransfer, into a data holder that holds no type, whose carrier it hands over. The data holder+/// goes through the browser process, and the token in `out_parked_end_token` is for settling what became of it.////// # Safety///@@ -364,7 +366,9 @@ pub unsafe extern "C" fn web_rust_message_port_transfer_steps(vm: *mut c_void,realm: *mut c_void,port: *mut c_void,+ may_leave_process: bool,out_data_holder: &mut *mut c_void,+ out_parked_end_token: &mut u64,) -> RawNativeFunctionResult {// SAFETY: The caller passes the live VM, a live realm and a live cell of a MessagePort.let ((vm, realm), port) = unsafe { (realm_arguments(vm, realm), cell_from_abi::<MessagePort>(port)) };@@ -372,7 +376,9 @@ pub unsafe extern "C" fn web_rust_message_port_transfer_steps(let data_holder = TransferDataHolder::new();let result = MessagePort::transfer_steps(&port, &mut cx, &mut TransferDataWriter::new(&data_holder, realm, None));if result.is_ok() {- *out_data_holder = data_holder.finish().into_cpp();+ let mut payload = data_holder.finish();+ *out_parked_end_token = payload.park_channel_end(may_leave_process);+ *out_data_holder = payload.into_cpp();}RawNativeFunctionResult::from_completion(result@@ -381,6 +387,28 @@ pub unsafe extern "C" fn web_rust_message_port_transfer_steps()}+/// Tells that nobody in this process is going to claim the channel end of the token, unless somebody did.+#[unsafe(no_mangle)]+pub extern "C" fn web_rust_message_port_give_up_on_parked_end(token: u64) {+ give_up_on_parked_end(token);+}++/// How the port reaches the port it is entangled with, as an ASCII string that lives forever, for tests.+///+/// # Safety+///+/// `port` must be a live cell of a MessagePort, and `out_kind` must be valid for a write.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_message_port_entanglement_kind(+ port: *mut c_void,+ out_kind: *mut ak::Span<'static, u8>,+) {+ // SAFETY: The caller passes a live cell of a MessagePort.+ let kind = unsafe { cell_from_abi::<MessagePort>(port) }.entanglement_kind();+ // SAFETY: The caller passes a pointer that is valid for a write.+ unsafe { out_kind.write(ak::Span::new(kind.as_bytes())) };+}+/// The transfer-receiving steps of a MessagePort that C++ runs outside StructuredDeserializeWithTransfer, which return/// the wrapper of the new MessagePort.///diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs b/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rsindex dec2a301403..bc037c0734b 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs@@ -13,7 +13,9 @@ use core::any::Any;use core::cell::{Cell, RefCell};use core::ffi::c_void;use core::ptr::NonNull;-use std::collections::VecDeque;+use core::sync::atomic::{AtomicU64, Ordering};+use std::collections::{HashMap, VecDeque};+use std::sync::Arc;use ak::Utf16String;use libipc_rust::{Attachment, DecodeError, Decoder, Encoder};@@ -29,10 +31,11 @@ use crate::bindings::interface::{use crate::bindings::promise::{TaskSource, queue_a_global_task};use crate::bindings::structured_data::{TransferDataReader, TransferDataWriter, Transferable};use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::html::port_channel::{PeerState, PortChannelEnd};use crate::html::structured_serialize::transfer_data_holder::{RawAttachment, ReceivePayload, TransferPayload, append_attachments,};-use crate::html::structured_serialize::transfer_record::{TransferRecord, TransferRecordRef};+use crate::html::structured_serialize::transfer_record::{PortMessage, TransferRecord, TransferRecordRef};use crate::html::structured_serialize::{structured_deserialize_with_transfer, structured_serialize_with_transfer};/// The dictionary StructuredSerializeOptions of HTML/MessagePort.idl, whose members the bindings convert.@@ -202,6 +205,18 @@ impl MessagePort {self.pending_outgoing_messages.borrow().len()}+ /// How this port reaches the port it is entangled with, for tests.+ pub(crate) fn entanglement_kind(&self) -> &'static str {+ if self.remote_port.get().is_some() {+ return "same agent";+ }+ match &*self.transport.borrow() {+ Some(transport) if transport.is_channel() => "channel",+ Some(_) => "socket",+ None => "none",+ }+ }+pub(crate) fn fail_next_transfer_for_testing(&self) {self.fail_next_transfer_for_testing.set(true);}@@ -654,7 +669,8 @@ impl Transferable for MessagePort {this.has_been_shipped.set(true);// NB: A port entangled over a transport hands its transport over. Stop the transport's IO thread before draining- // it below, so that no message arrives between the drain and the handle going to the new owner.+ // it below, so that no message arrives between the drain and the handle going to the new owner. A channel+ // keeps the messages that wait for its end, for whoever owns that next.let released_transport = this.transport.borrow()@@ -680,8 +696,8 @@ impl Transferable for MessagePort {// 1. Set remotePort's has been shipped flag to true.remote_port.has_been_shipped.set(true);- let (transport, handle) = MessagePortTransport::create_paired();- (Some((remote_port, transport)), Some(handle))+ let (transport, transferred) = MessagePortTransport::create_channel();+ (Some((remote_port, transport)), Some(transferred))}None => (None, released_transport),};@@ -690,7 +706,7 @@ impl Transferable for MessagePort {// 4. Otherwise, set dataHolder.[[RemotePort]] to null.data_holder.write_bool(remote_port_handle.is_some());if let Some(remote_port_handle) = remote_port_handle {- data_holder.write_transport_handle(remote_port_handle);+ data_holder.write_transport(remote_port_handle);}if let Some((remote_port, mut transport)) = remote_port {@@ -736,7 +752,7 @@ impl Transferable for MessagePort {// 3. If dataHolder.[[RemotePort]] is not null, then entangle dataHolder.[[RemotePort]] and value.// (This will disentangle dataHolder.[[RemotePort]] from the original port that was transferred.)if data_holder.read_bool()? {- let mut transport = data_holder.read_transport_handle()?.create_transport();+ let mut transport = data_holder.read_transport()?.create_transport();value.has_ever_been_entangled.set(true);transport.set_up_read_hook(ReadHookState::new(vm, value), ReadHookState::read_from_transport);@@ -758,6 +774,13 @@ unsafe extern "C" {count: usize,) -> *mut c_void;fn web_bindings_message_port_transport_create_paired(out_remote_handle: &mut *mut c_void) -> *mut c_void;+ fn web_bindings_message_port_current_event_loop() -> *mut c_void;+ fn web_bindings_message_port_release_event_loop(event_loop: *mut c_void);+ fn web_bindings_message_port_post_to_event_loop(+ event_loop: *mut c_void,+ steps: unsafe extern "C" fn(u64),+ argument: u64,+ );fn web_bindings_message_port_transport_destroy(transport: *mut c_void);fn web_bindings_message_port_transport_release_for_transfer(transport: *mut c_void) -> *mut c_void;fn web_bindings_message_port_transport_set_up_read_hook(@@ -842,16 +865,12 @@ impl TransportHandle {Ok(Self { attachments })}- /// The transport of the end that the handle holds the rights of, which it gives up.- pub(crate) fn create_transport(self) -> MessagePortTransport {- let payload = TransferPayload {- bytes: Vec::new(),- attachments: self.attachments,- };- payload.with_raw(|bytes, attachments| {+ /// The IPC transport of the end that the handle holds the rights of, which it gives up.+ fn create_socket(self) -> SocketTransport {+ TransferPayload::new(Vec::new(), self.attachments).with_raw(|bytes, attachments| {// SAFETY: The call takes every right, and LibWeb hands over the transport.unsafe {- MessagePortTransport::from_raw(web_bindings_transport_handle_create_transport(+ SocketTransport::from_raw(web_bindings_transport_handle_create_transport(bytes,attachments.as_ptr(),attachments.len(),@@ -861,6 +880,22 @@ impl TransportHandle {}}+/// What a data holder carries for a port to reach its peer with.+pub(crate) enum TransferredTransport {+ Socket(TransportHandle),+ Channel(PortChannelEnd),+}++impl TransferredTransport {+ /// The transport of the end, which it gives up.+ pub(crate) fn create_transport(self) -> MessagePortTransport {+ MessagePortTransport::new(match self {+ Self::Socket(handle) => Connection::Socket(handle.create_socket()),+ Self::Channel(end) => Connection::Channel(end),+ })+ }+}+/// Whether the peer of a transport is gone, so that nothing more arrives: IPC::Transport::ShouldShutdown.#[derive(Clone, Copy, PartialEq, Eq)]pub(crate) enum ShouldShutdown {@@ -874,90 +909,84 @@ struct ReadHook<S> {steps: fn(&S),}-/// The transport of one end of the channel between two MessagePorts entangled across agents, whose messages are the-/// records of structured serializations with transfer: an IPC::Transport that this owns. Its IO thread receives the-/// messages, and its read hook runs on the owner thread when they arrive.-pub(crate) struct MessagePortTransport {- raw: NonNull<c_void>,- /// The read hook, which the transport is lent until it is destroyed: drop() destroys the transport before this.- read_hook: Option<Box<dyn Any>>,+/// The hook of a transport as its IPC transport or the wake of its channel calls it, with what the hook is called with.+#[derive(Clone, Copy)]+struct RawReadHook {+ hook: *mut c_void,+ run: unsafe extern "C" fn(*mut c_void),}-impl MessagePortTransport {- /// IPC::Transport::create_paired(): the transport of one end of a new channel, and the handle of the other end.- pub(crate) fn create_paired() -> (Self, TransportHandle) {- let mut remote_handle = core::ptr::null_mut();- // SAFETY: LibWeb hands over a new transport and the handle.- unsafe {- let transport = web_bindings_message_port_transport_create_paired(&mut remote_handle);- (Self::from_raw(transport), TransportHandle::from_raw(remote_handle))- }+thread_local! {+ /// The read hooks of the transports of this thread that are on a channel, by the id that their wakes carry. A wake+ /// can outlive its transport, and the agent of its thread, so this is what it goes through to reach either.+ static CHANNEL_READ_HOOKS: RefCell<HashMap<u64, RawReadHook>> = RefCell::new(HashMap::new());+}++/// Runs on the owner thread of the transport, from its event loop.+unsafe extern "C" fn run_channel_read_hook(id: u64) {+ let Some(hook) = CHANNEL_READ_HOOKS.with_borrow(|hooks| hooks.get(&id).copied()) else {+ return;+ };+ // SAFETY: The transport removes the hook from the list before it destroys the hook.+ unsafe { (hook.run)(hook.hook) };+}++/// The event loop of a thread as any thread may reach it: Core::WeakEventLoopReference.+struct EventLoopReference(NonNull<c_void>);++// SAFETY: The reference counts atomically, and it finds out under a lock whether its event loop is still there.+unsafe impl Send for EventLoopReference {}+unsafe impl Sync for EventLoopReference {}++impl EventLoopReference {+ fn current() -> Self {+ // SAFETY: The call hands over a reference.+ let reference = unsafe { web_bindings_message_port_current_event_loop() };+ Self(NonNull::new(reference).expect("the thread of a port has an event loop"))}+ /// Has the event loop run the read hook with the id, if the event loop is still there.+ fn post_read_hook(&self, id: u64) {+ // SAFETY: This holds a reference.+ unsafe { web_bindings_message_port_post_to_event_loop(self.0.as_ptr(), run_channel_read_hook, id) };+ }+}++impl Drop for EventLoopReference {+ fn drop(&mut self) {+ // SAFETY: This holds a reference.+ unsafe { web_bindings_message_port_release_event_loop(self.0.as_ptr()) };+ }+}++/// An IPC::Transport that this owns.+struct SocketTransport {+ raw: NonNull<c_void>,+}++impl SocketTransport {/// # Safety////// `transport` must be a transport that LibWeb hands over.unsafe fn from_raw(transport: *mut c_void) -> Self {Self {raw: NonNull::new(transport).expect("LibWeb hands over a transport"),- read_hook: None,}}- /// Takes the rights of this end back as a handle, for a data holder to carry to another agent. The IO thread stops- /// first, so that what the peer sends from then on arrives at the handle's new owner, while what it sent before can- /// still be read.- pub(crate) fn release_for_transfer(&self) -> TransportHandle {- // SAFETY: This owns the transport, and LibWeb hands over the handle.+ fn set_up_read_hook(&self, hook: RawReadHook) {+ // SAFETY: This owns the transport, and the hook outlives it.unsafe {- TransportHandle::from_raw(web_bindings_message_port_transport_release_for_transfer(- self.raw.as_ptr(),- ))+ web_bindings_message_port_transport_set_up_read_hook(self.raw.as_ptr(), hook.hook, hook.run);}}- /// Runs the steps with the state on the owner thread whenever messages arrive, for as long as the transport lives.- pub(crate) fn set_up_read_hook<S: 'static>(&mut self, state: S, steps: fn(&S)) {- unsafe extern "C" fn run<S>(hook: *mut c_void) {- // SAFETY: The transport calls its hook with the one that set_up_read_hook() lent it, which outlives the- // transport.- let hook = unsafe { &*hook.cast::<ReadHook<S>>() };- (hook.steps)(&hook.state);- }- let hook = Box::new(ReadHook { state, steps });- let raw_hook: *const ReadHook<S> = &raw const *hook;- // SAFETY: This owns the transport, and lends it the hook until it is destroyed, before the hook.- unsafe {- web_bindings_message_port_transport_set_up_read_hook(- self.raw.as_ptr(),- raw_hook.cast_mut().cast(),- run::<S>,- );- }- self.read_hook = Some(hook);- }-- pub(crate) fn is_open(&self) -> bool {- // SAFETY: This owns the transport.- unsafe { web_bindings_message_port_transport_is_open(self.raw.as_ptr()) }- }-- pub(crate) fn close(&self) {- // SAFETY: This owns the transport.- unsafe { web_bindings_message_port_transport_close(self.raw.as_ptr()) };- }-- pub(crate) fn close_after_sending_all_pending_messages(&self) {- // SAFETY: This owns the transport.- unsafe { web_bindings_message_port_transport_close_after_sending_all_pending_messages(self.raw.as_ptr()) };- }-- /// Sends the record to the peer as one message. False if the transport failed, which LibWeb logs.- pub(crate) fn send(&self, vm: &Vm, record: TransferRecordRef) -> bool {+ /// Sends the message to the peer. False if the transport failed, which LibWeb logs.+ fn send(&self, message: PortMessage) -> bool {let mut encoder = Encoder::new();- TransferRecord::encode_into(record, vm, &mut encoder).expect("a message record encodes");+ message.encode_into(&mut encoder).expect("a message record encodes");let (bytes, attachments) = encoder.finish();- TransferPayload { bytes, attachments }.with_raw(|bytes, attachments| {+ TransferPayload::new(bytes, attachments).with_raw(|bytes, attachments| {// SAFETY: This owns the transport. The call copies the bytes and takes every native attachment.unsafe {web_bindings_message_port_transport_send(@@ -970,8 +999,7 @@ impl MessagePortTransport {})}- /// Appends every message that has arrived, each a record, and tells whether the peer is gone.- pub(crate) fn read_as_many_messages_as_possible_without_blocking(+ fn read_as_many_messages_as_possible_without_blocking(&self,vm: &Vm,records: &MarkedVec<'_, TransferRecordRef>,@@ -1010,9 +1038,227 @@ impl MessagePortTransport {}}-impl Drop for MessagePortTransport {+impl Drop for SocketTransport {fn drop(&mut self) {// SAFETY: This owns the transport. Its read hook, which the state outlives, goes with it.unsafe { web_bindings_message_port_transport_destroy(self.raw.as_ptr()) };}}++/// What a transport reaches its peer over: a channel if the peer is in this process, as far as anybody knows, and+/// otherwise an IPC transport.+enum Connection {+ Socket(SocketTransport),+ Channel(PortChannelEnd),+ /// The channel end went to a new owner, along with the port.+ Released,+}++/// The transport of one end of the channel between two MessagePorts entangled across agents, whose messages are the+/// records of structured serializations with transfer. Its read hook runs on the owner thread when they arrive.+pub(crate) struct MessagePortTransport {+ connection: RefCell<Connection>,+ /// What this took off the channel as it changed over to a socket, which comes first.+ channel_leftovers: RefCell<VecDeque<PortMessage>>,+ is_closed: Cell<bool>,+ raw_read_hook: Option<RawReadHook>,+ channel_read_hook_id: Option<u64>,+ /// The read hook, which the transport is lent until it is destroyed: this goes after the connection.+ read_hook: Option<Box<dyn Any>>,+}++impl MessagePortTransport {+ fn new(connection: Connection) -> Self {+ Self {+ connection: RefCell::new(connection),+ channel_leftovers: RefCell::new(VecDeque::new()),+ is_closed: Cell::new(false),+ raw_read_hook: None,+ channel_read_hook_id: None,+ read_hook: None,+ }+ }++ /// The transport of one end of a new channel in this process, and the other end.+ pub(crate) fn create_channel() -> (Self, TransferredTransport) {+ let (end, other_end) = PortChannelEnd::create_pair();+ (+ Self::new(Connection::Channel(end)),+ TransferredTransport::Channel(other_end),+ )+ }++ /// IPC::Transport::create_paired(), for both ends to go elsewhere.+ pub(crate) fn create_paired_handles() -> (TransportHandle, TransportHandle) {+ let mut remote_handle = core::ptr::null_mut();+ // SAFETY: LibWeb hands over a new transport and the handle.+ unsafe {+ let transport =+ SocketTransport::from_raw(web_bindings_message_port_transport_create_paired(&mut remote_handle));+ let local_handle = TransportHandle::from_raw(web_bindings_message_port_transport_release_for_transfer(+ transport.raw.as_ptr(),+ ));+ (local_handle, TransportHandle::from_raw(remote_handle))+ }+ }++ pub(crate) fn is_channel(&self) -> bool {+ matches!(&*self.connection.borrow(), Connection::Channel(_))+ }++ /// Takes this end back, for a data holder to carry to another agent. The IO thread of a socket stops first, so that+ /// what the peer sends from then on arrives at the new owner, while what it sent before can still be read.+ pub(crate) fn release_for_transfer(&self) -> TransferredTransport {+ let mut connection = self.connection.borrow_mut();+ if let Connection::Socket(socket) = &*connection {+ // SAFETY: This owns the transport, and LibWeb hands over the handle.+ return TransferredTransport::Socket(unsafe {+ TransportHandle::from_raw(web_bindings_message_port_transport_release_for_transfer(+ socket.raw.as_ptr(),+ ))+ });+ }+ let Connection::Channel(end) = core::mem::replace(&mut *connection, Connection::Released) else {+ unreachable!("a transport is released once");+ };+ end.set_wake(None);+ TransferredTransport::Channel(end)+ }++ /// Runs the steps with the state on the owner thread whenever messages arrive, for as long as the transport lives.+ pub(crate) fn set_up_read_hook<S: 'static>(&mut self, state: S, steps: fn(&S)) {+ unsafe extern "C" fn run<S>(hook: *mut c_void) {+ // SAFETY: The transport calls its hook with the one that set_up_read_hook() lent it, which outlives the+ // transport.+ let hook = unsafe { &*hook.cast::<ReadHook<S>>() };+ (hook.steps)(&hook.state);+ }+ let hook = Box::new(ReadHook { state, steps });+ let raw_hook = RawReadHook {+ hook: (&raw const *hook).cast_mut().cast(),+ run: run::<S>,+ };+ self.raw_read_hook = Some(raw_hook);+ self.read_hook = Some(hook);+ match &*self.connection.borrow() {+ Connection::Socket(socket) => socket.set_up_read_hook(raw_hook),+ Connection::Channel(end) => {+ static NEXT_ID: AtomicU64 = AtomicU64::new(1);+ let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);+ CHANNEL_READ_HOOKS.with_borrow_mut(|hooks| hooks.insert(id, raw_hook));+ self.channel_read_hook_id = Some(id);+ let event_loop = EventLoopReference::current();+ end.set_wake(Some(Arc::new(move || event_loop.post_read_hook(id))));+ }+ Connection::Released => unreachable!("a released transport has no owner to read"),+ }+ }++ /// Changes over to the socket of the handle, keeping the messages that wait on the channel for the next read, and has+ /// the read hook run for them.+ fn change_over_to_socket(&self, handle: TransportHandle, messages: VecDeque<PortMessage>) {+ let socket = handle.create_socket();+ if let Some(hook) = self.raw_read_hook {+ socket.set_up_read_hook(hook);+ }+ self.channel_leftovers.borrow_mut().extend(messages);+ *self.connection.borrow_mut() = Connection::Socket(socket);+ if let Some(id) = self.channel_read_hook_id+ && !self.channel_leftovers.borrow().is_empty()+ {+ EventLoopReference::current().post_read_hook(id);+ }+ }++ pub(crate) fn is_open(&self) -> bool {+ if self.is_closed.get() {+ return false;+ }+ match &*self.connection.borrow() {+ // SAFETY: This owns the transport.+ Connection::Socket(socket) => unsafe { web_bindings_message_port_transport_is_open(socket.raw.as_ptr()) },+ Connection::Channel(end) => end.is_open(),+ Connection::Released => false,+ }+ }++ pub(crate) fn close(&self) {+ self.is_closed.set(true);+ if let Connection::Socket(socket) = &*self.connection.borrow() {+ // SAFETY: This owns the transport.+ unsafe { web_bindings_message_port_transport_close(socket.raw.as_ptr()) };+ }+ }++ pub(crate) fn close_after_sending_all_pending_messages(&self) {+ if let Connection::Socket(socket) = &*self.connection.borrow() {+ // SAFETY: This owns the transport.+ unsafe {+ web_bindings_message_port_transport_close_after_sending_all_pending_messages(socket.raw.as_ptr());+ }+ }+ }++ /// Sends the record to the peer as one message. False if the transport failed, which LibWeb logs.+ pub(crate) fn send(&self, vm: &Vm, record: TransferRecordRef) -> bool {+ let mut message = TransferRecord::into_port_message(record, vm);+ if let Connection::Channel(end) = &*self.connection.borrow() {+ match end.send(message) {+ Ok(()) => return true,+ Err(returned) => message = returned,+ }+ }+ // NB: The peer left the process, which the channel says only after everything that waits on it.+ let change_over = match &*self.connection.borrow() {+ Connection::Channel(end) => Some(end.read()),+ _ => None,+ };+ if let Some((messages, PeerState::Transport(handle))) = change_over {+ self.change_over_to_socket(handle, messages);+ }+ match &*self.connection.borrow() {+ Connection::Socket(socket) => socket.send(message),+ _ => false,+ }+ }++ /// Appends every message that has arrived, each a record, and tells whether the peer is gone.+ pub(crate) fn read_as_many_messages_as_possible_without_blocking(+ &self,+ vm: &Vm,+ records: &MarkedVec<'_, TransferRecordRef>,+ ) -> ShouldShutdown {+ for message in self.channel_leftovers.borrow_mut().drain(..) {+ records.push(TransferRecord::from_port_message(vm, message));+ }+ let channel_read = match &*self.connection.borrow() {+ Connection::Channel(end) => Some(end.read()),+ Connection::Socket(_) | Connection::Released => None,+ };+ if let Some((messages, state)) = channel_read {+ for message in messages {+ records.push(TransferRecord::from_port_message(vm, message));+ }+ match state {+ PeerState::Connected => return ShouldShutdown::No,+ PeerState::Gone => return ShouldShutdown::Yes,+ PeerState::Transport(handle) => self.change_over_to_socket(handle, VecDeque::new()),+ }+ }+ match &*self.connection.borrow() {+ Connection::Socket(socket) => socket.read_as_many_messages_as_possible_without_blocking(vm, records),+ _ => ShouldShutdown::No,+ }+ }+}++impl Drop for MessagePortTransport {+ fn drop(&mut self) {+ if let Some(id) = self.channel_read_hook_id {+ // NB: A thread that goes away has no hooks left to run, and has no list left to speak of.+ let _ = CHANNEL_READ_HOOKS.try_with(|hooks| hooks.borrow_mut().remove(&id));+ }+ // NB: The connection goes first, as the hook is lent to it.+ *self.connection.borrow_mut() = Connection::Released;+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rsindex 1f383a23900..a4f7015cfb3 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs@@ -73,6 +73,8 @@ pub(crate) mod offscreen_canvas_rendering_context2d;#[cfg(not(test))]pub(crate) mod path2d;#[cfg(not(test))]+pub(crate) mod port_channel;+#[cfg(not(test))]pub(crate) mod storage;#[cfg(not(test))]pub(crate) mod storage_event;diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/port_channel.rs b/Libraries/LibWeb/Bindings/Rust/src/html/port_channel.rsnew file mode 100644index 00000000000..712da05ef28--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/html/port_channel.rs@@ -0,0 +1,279 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The channel between two MessagePorts in one process, which may be in the agents of different threads.+//!+//! As in WebKit's MessagePortChannel, the channel owns the queues, so that a message waits in the queue of its side no+//! matter who owns that side, and a port that is transferred leaves its messages where they are. Only plain data is ever+//! in it: nothing of a heap crosses, and the receiver makes its record from the plain data on its own thread. An end+//! holds a share of the channel, so either side can go first, and a wake only names a read hook that the event loop looks+//! up on the thread of the receiver, where it finds nothing if the port went away.+//!+//! A channel stops being one when an end leaves the process. Its peer then finds a transport handle on its side, and+//! changes over to that when it gets to it. This happens at most once: an end that goes away never comes back, and a+//! channel does not form again between ports that a transport connects.++use core::hash::{BuildHasher, Hasher};+use std::collections::{HashMap, VecDeque};+use std::hash::RandomState;+use std::sync::{Arc, LazyLock, Mutex, MutexGuard, PoisonError};++use crate::html::message_port::{MessagePortTransport, TransportHandle};+use crate::html::structured_serialize::transfer_record::PortMessage;++/// Tells the owner of an end that there is something to read. Any thread may call it.+pub(crate) type Wake = Arc<dyn Fn() + Send + Sync>;++#[derive(Default)]+struct Side {+ /// The messages that wait for this side.+ queue: VecDeque<PortMessage>,+ wake: Option<Wake>,+ is_wake_pending: bool,+ /// The end of this side is gone, closed or out of this process, so nothing reaches it through the channel anymore.+ is_gone: bool,+ /// What this side changes over to, once the other side has left the process.+ transport: Option<TransportHandle>,+}++impl Side {+ fn has_news(&self, peer: &Side) -> bool {+ !self.queue.is_empty() || self.transport.is_some() || peer.is_gone+ }++ /// The wake to call once the channel is unlocked, unless the owner of this side has one on its way.+ fn wake_to_call(&mut self) -> Option<Wake> {+ if self.is_wake_pending {+ return None;+ }+ let wake = self.wake.clone()?;+ self.is_wake_pending = true;+ Some(wake)+ }+}++type Sides = [Side; 2];++fn lock(sides: &Mutex<Sides>) -> MutexGuard<'_, Sides> {+ sides.lock().unwrap_or_else(PoisonError::into_inner)+}++/// What read() found.+pub(crate) enum PeerState {+ Connected,+ Gone,+ /// The peer has left the process, and this is how to reach it.+ Transport(TransportHandle),+}++/// One end of a channel, which is what a MessagePortTransport or a data holder owns. Dropping it closes the end, and+/// what the end has sent stays readable for the peer.+pub(crate) struct PortChannelEnd {+ sides: Arc<Mutex<Sides>>,+ index: usize,+}++impl PortChannelEnd {+ pub(crate) fn create_pair() -> (Self, Self) {+ let sides = Arc::new(Mutex::new(Sides::default()));+ (+ Self {+ sides: Arc::clone(&sides),+ index: 0,+ },+ Self { sides, index: 1 },+ )+ }++ /// An end that another process handed over: its queued messages, and how to reach the peer, if it is still there.+ pub(crate) fn from_elsewhere(messages: Vec<PortMessage>, transport: Option<TransportHandle>) -> Self {+ let (end, peer) = Self::create_pair();+ {+ let mut sides = lock(&end.sides);+ sides[0].queue = messages.into();+ sides[0].transport = transport;+ }+ drop(peer);+ end+ }++ fn peer_index(&self) -> usize {+ 1 - self.index+ }++ /// Sets what tells the owner of this end that there is something to read, or nothing for an end on its way to another+ /// owner. Calls it if there is already something to read.+ pub(crate) fn set_wake(&self, wake: Option<Wake>) {+ let mut sides = lock(&self.sides);+ let has_news = sides[self.index].has_news(&sides[self.peer_index()]);+ let side = &mut sides[self.index];+ side.wake = wake;+ side.is_wake_pending = false;+ let wake = if has_news { side.wake_to_call() } else { None };+ drop(sides);+ if let Some(wake) = wake {+ wake();+ }+ }++ /// Whether a message sent now can arrive.+ pub(crate) fn is_open(&self) -> bool {+ let sides = lock(&self.sides);+ sides[self.index].transport.is_some() || !sides[self.peer_index()].is_gone+ }++ /// Adds the message to the queue of the peer. A message for a peer that is gone is dropped, and one that has to go+ /// over a transport comes back.+ pub(crate) fn send(&self, message: PortMessage) -> Result<(), PortMessage> {+ let mut sides = lock(&self.sides);+ if sides[self.index].transport.is_some() {+ return Err(message);+ }+ let peer = &mut sides[self.peer_index()];+ if peer.is_gone {+ drop(sides);+ drop(message);+ return Ok(());+ }+ peer.queue.push_back(message);+ let wake = peer.wake_to_call();+ drop(sides);+ if let Some(wake) = wake {+ wake();+ }+ Ok(())+ }++ /// Takes all the messages that wait for this end, and tells what became of the peer.+ pub(crate) fn read(&self) -> (VecDeque<PortMessage>, PeerState) {+ let mut sides = lock(&self.sides);+ let peer_is_gone = sides[self.peer_index()].is_gone;+ let side = &mut sides[self.index];+ side.is_wake_pending = false;+ let messages = core::mem::take(&mut side.queue);+ let state = match side.transport.take() {+ Some(transport) => PeerState::Transport(transport),+ None if peer_is_gone => PeerState::Gone,+ None => PeerState::Connected,+ };+ (messages, state)+ }++ /// Moves the channel over to a transport as this end goes to another process, which gets what this returns: the+ /// messages that wait for this end, and the transport handle of its side, if the peer is still there.+ pub(crate) fn leave_process(self) -> (Vec<PortMessage>, Option<TransportHandle>) {+ let needs_new_transport = {+ let sides = lock(&self.sides);+ sides[self.index].transport.is_none() && !sides[self.peer_index()].is_gone+ };+ let new_transport = needs_new_transport.then(MessagePortTransport::create_paired_handles);++ // NB: The queue and the change over are one step: the peer can send until it finds its transport, and what it+ // sends must be in the queue that goes along, or on that transport.+ let mut sides = lock(&self.sides);+ let peer_is_gone = sides[self.peer_index()].is_gone;+ let side = &mut sides[self.index];+ let messages: Vec<_> = core::mem::take(&mut side.queue).into();+ // NB: If the peer left the process at the same time, the transport that it made for this end is the one.+ if let Some(transport) = side.transport.take() {+ return (messages, Some(transport));+ }+ if peer_is_gone {+ return (messages, None);+ }+ let (own_handle, peer_handle) = new_transport.expect("a peer that is still there got a new transport");+ self.hand_peer_transport(sides, peer_handle);+ (messages, Some(own_handle))+ }++ /// Gives the peer the handle to change over to, and ends this side.+ fn hand_peer_transport(&self, mut sides: MutexGuard<'_, Sides>, handle: TransportHandle) {+ sides[self.index].is_gone = true;+ let peer = &mut sides[self.peer_index()];+ peer.transport = Some(handle);+ let wake = peer.wake_to_call();+ drop(sides);+ if let Some(wake) = wake {+ wake();+ }+ }+}++impl Drop for PortChannelEnd {+ fn drop(&mut self) {+ let mut sides = lock(&self.sides);+ let peer_index = self.peer_index();+ let side = &mut sides[self.index];+ let was_gone = core::mem::replace(&mut side.is_gone, true);+ side.wake = None;+ let queue = core::mem::take(&mut side.queue);+ let transport = side.transport.take();+ let wake = if was_gone {+ None+ } else {+ sides[peer_index].wake_to_call()+ };+ drop(sides);++ // NB: A message can hold ends of other channels, which lock these.+ drop(queue);+ drop(transport);+ if let Some(wake) = wake {+ wake();+ }+ }+}++/// An end on its way through the browser process, to a thread that its data holder does not reach directly. What reaches+/// the thread is a token, which finds the end here if it arrives in this process.+struct ParkedEnd {+ end: PortChannelEnd,+ /// The handle for the peer of the end, if the data holder also carries a transport, for the case that it arrives+ /// in another process.+ peer_transport: Option<TransportHandle>,+}++fn parked_ends() -> MutexGuard<'static, HashMap<u64, ParkedEnd>> {+ static PARKED_ENDS: LazyLock<Mutex<HashMap<u64, ParkedEnd>>> = LazyLock::new(Mutex::default);+ PARKED_ENDS.lock().unwrap_or_else(PoisonError::into_inner)+}++/// Parks the end, and returns its token. If the end may arrive in another process, this also returns what the data+/// holder has to carry for that case.+pub(crate) fn park_end(end: PortChannelEnd, may_leave_process: bool) -> (u64, Option<TransportHandle>) {+ let (carried_transport, peer_transport) = if may_leave_process {+ let (carried_transport, peer_transport) = MessagePortTransport::create_paired_handles();+ (Some(carried_transport), Some(peer_transport))+ } else {+ (None, None)+ };+ let mut parked_ends = parked_ends();+ // NB: The token can arrive in another process, where it must not stand for an end of that process.+ let mut token = RandomState::new().build_hasher().finish();+ while token == 0 || parked_ends.contains_key(&token) {+ token = token.wrapping_add(1);+ }+ parked_ends.insert(token, ParkedEnd { end, peer_transport });+ (token, carried_transport)+}++/// The end that the token stands for, if it is still parked in this process.+pub(crate) fn claim_parked_end(token: u64) -> Option<PortChannelEnd> {+ let parked_end = parked_ends().remove(&token)?;+ Some(parked_end.end)+}++/// For an end that nobody in this process is going to claim: the peer goes on over the transport that the data holder+/// carries, if it has one, and otherwise finds its peer gone. An end that was claimed is left alone.+pub(crate) fn give_up_on_parked_end(token: u64) {+ let Some(ParkedEnd { end, peer_transport }) = parked_ends().remove(&token) else {+ return;+ };+ if let Some(peer_transport) = peer_transport {+ let sides = lock(&end.sides);+ end.hand_peer_transport(sides, peer_transport);+ }+}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.rsindex 97077ca217d..19496d17f1e 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/message_record.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/message_record.rs@@ -5,15 +5,15 @@*///! 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 agent's realms share, the lifeline of the stores that the bytes name, and the+//! SharedArrayBuffers that agents in this agent's realms share, the pin of the stores that the bytes name, and the//! shared memory that hands the pixels of ImageBitmaps over.//! 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, DeferGc, Gc, OwnedSharedMemory, SharedStoreLifeline, Trace, borrowed_from_raw_descriptor,- duplicate_lifeline_from_raw_descriptor, lifeline_into_raw_descriptor, release_stores_of_lost_messages,+ ArrayBuffer, DeferGc, Gc, OwnedSharedMemory, SharedStorePin, Trace, borrowed_from_raw_descriptor,+ duplicate_lifeline_from_raw_descriptor, lifeline_into_raw_descriptor,};pub(crate) struct SharedMemory {@@ -47,7 +47,7 @@ pub(crate) struct MessageRecord {#[gc(untraced)]pub(crate) shared_memory: Vec<SharedMemory>,#[gc(untraced)]- pub(crate) shared_store_lifeline: Option<SharedStoreLifeline>,+ pub(crate) shared_store_pin: Option<SharedStorePin>,}impl MessageRecord {@@ -75,26 +75,27 @@ impl MessageRecord {shared_array_buffers: Vec::new(),shared_memory,// SAFETY: The caller keeps the descriptor open.- shared_store_lifeline: (shared_store_lifeline >= 0)+ shared_store_pin: (shared_store_lifeline >= 0).then(|| unsafe { duplicate_lifeline_from_raw_descriptor(shared_store_lifeline) }.ok())- .flatten(),+ .flatten()+ .map(SharedStorePin::Lifeline),}}- /// A duplicate of the descriptor of the lifeline, which the caller owns, or a negative value for no lifeline, for+ /// The descriptor of a lifeline for the stores, which the caller owns, or a negative value for no lifeline, for/// sending the record to other processes.pub(crate) fn duplicate_shared_store_lifeline(&self) -> c_int {- self.shared_store_lifeline+ self.shared_store_pin.as_ref()- .and_then(|lifeline| lifeline.try_clone().ok())+ .and_then(SharedStorePin::duplicate_lifeline).map_or(-1, lifeline_into_raw_descriptor)}}impl Drop for MessageRecord {fn drop(&mut self) {- if self.shared_store_lifeline.take().is_some() {- release_stores_of_lost_messages();+ if let Some(pin) = self.shared_store_pin.take() {+ pin.release();}}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rsindex e81b4a7b88b..17ce4a69dd4 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs@@ -1738,9 +1738,7 @@ pub(crate) fn structured_serialize_with_transfer(AllowSharedArrayBuffers::CrossOriginIsolatedOnly,)?;- serialized- .pin_named_stores()- .map_err(|_| data_clone_error("Cannot share SharedArrayBuffer"))?;+ serialized.pin_named_stores();// AD-HOC: Gather the pixels of the transferred ImageBitmaps in one buffer of shared memory. Without it, as when there// is not enough memory for it, the pixels travel inline.@@ -2006,9 +2004,7 @@ pub(crate) fn structured_serialize_for_message(&memory,AllowSharedArrayBuffers::CrossOriginIsolatedOnly,)?;- serialized- .pin_named_stores()- .map_err(|_| data_clone_error("Cannot share SharedArrayBuffer"))?;+ serialized.pin_named_stores();Ok(serialized)}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/transfer_data_holder.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/transfer_data_holder.rsindex d26cd39d176..f7410c488f3 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/transfer_data_holder.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/transfer_data_holder.rs@@ -10,6 +10,11 @@use core::cell::RefCell;use core::ffi::{c_int, c_void};use libipc_rust::{Attachment, Decode, DecodeError, Decoder, Encode, EncodeError, Encoder};+use std::collections::VecDeque;++use crate::html::message_port::TransportHandle;+use crate::html::port_channel::{PortChannelEnd, claim_parked_end, park_end};+use crate::html::structured_serialize::transfer_record::PortMessage;#[repr(C)]pub(crate) struct RawAttachment {@@ -118,14 +123,99 @@ pub(crate) fn append_attachments(encoder: &mut Encoder, attachments: Vec<Attachm}}+/// A channel end that a data holder carries.+pub(crate) enum CarriedChannelEnd {+ Held(PortChannelEnd),+ /// Parked in this process, under the token, for the data holder to go through the browser process. The transport is+ /// for a data holder that may arrive in another process.+ Parked(u64, Option<TransportHandle>),+}++impl CarriedChannelEnd {+ /// A data holder that is encoded leaves the process, as far as this end knows, so the end changes over to a transport.+ fn encode_owned(self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ let (token, messages, transport) = match self {+ Self::Held(end) => {+ let (messages, transport) = end.leave_process();+ (0, messages, transport)+ }+ Self::Parked(token, transport) => (token, Vec::new(), transport),+ };+ encoder.encode(&token)?;+ encoder.encode_size(messages.len())?;+ for message in messages {+ message.encode_into(encoder)?;+ }+ encoder.encode(&transport.is_some())?;+ if let Some(transport) = transport {+ transport.encode_into(encoder);+ }+ Ok(())+ }++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ let token = decoder.decode::<u64>()?;+ let count = decoder.decode_size()?;+ let mut messages = Vec::new();+ for _ in 0..count {+ messages.push(PortMessage::decode(decoder)?);+ }+ let transport = decoder+ .decode::<bool>()?+ .then(|| TransportHandle::decode(decoder))+ .transpose()?;+ if token != 0+ && let Some(end) = claim_parked_end(token)+ {+ return Ok(Self::Held(end));+ }+ Ok(Self::Held(PortChannelEnd::from_elsewhere(messages, transport)))+ }++ pub(crate) fn into_end(self) -> PortChannelEnd {+ match self {+ Self::Held(end) => end,+ Self::Parked(..) => unreachable!("a parked end is only ever encoded"),+ }+ }+}+pub(crate) struct TransferPayload {pub(crate) bytes: Vec<u8>,pub(crate) attachments: Vec<Attachment>,+ /// The channel ends of the MessagePorts that the data holder carries, which its readers take in the order its writers+ /// added them.+ pub(crate) channel_ends: VecDeque<CarriedChannelEnd>,}impl TransferPayload {+ pub(crate) fn new(bytes: Vec<u8>, attachments: Vec<Attachment>) -> Self {+ Self {+ bytes,+ attachments,+ channel_ends: VecDeque::new(),+ }+ }++ /// Parks the channel end of a data holder that goes through the browser process to a thread of a worker, and returns+ /// the token that settling it takes. This is for a holder with one end, of a new channel.+ pub(crate) fn park_channel_end(&mut self, may_leave_process: bool) -> u64 {+ let end = self+ .channel_ends+ .pop_front()+ .expect("the data holder of a new channel holds its end")+ .into_end();+ let (token, transport) = park_end(end, may_leave_process);+ self.channel_ends.push_back(CarriedChannelEnd::Parked(token, transport));+ token+ }++ /// The carrier of this data holder for C++, for which it is opaque. Encoding makes it fit to leave the process.pub(crate) fn into_cpp(self) -> *mut c_void {- self.with_raw(|bytes, attachments| {+ let mut encoder = Encoder::new();+ self.encode_owned(&mut encoder).expect("a data holder encodes");+ let (bytes, attachments) = encoder.finish();+ Self::new(bytes, attachments).with_raw(|bytes, attachments| {// SAFETY: C++ copies the lent bytes and takes all attachments.unsafe {web_structured_serialize_transfer_data_holder_create(bytes, attachments.as_ptr(), attachments.len())@@ -140,7 +230,12 @@ impl TransferPayload {let mut payload = None;// SAFETY: The holder is handed over, and the callback fills the lent result slot.unsafe { web_structured_serialize_transfer_data_holder_take(holder, (&raw mut payload).cast(), Self::receive) };- payload.expect("C++ hands over the payload")+ let payload: Self = payload.expect("C++ hands over the payload");+ // NB: What cannot be decoded holds nothing, which is what reading from it reports.+ let mut decoder = Decoder::new(&payload.bytes, payload.attachments);+ decoder+ .decode::<Self>()+ .unwrap_or_else(|_| Self::new(Vec::new(), Vec::new()))}pub(crate) unsafe extern "C" fn receive(@@ -152,10 +247,7 @@ impl TransferPayload {// SAFETY: The caller lends this result slot and bytes, and transfers every raw attachment.let attachments = unsafe { RawAttachment::take_all(attachments, count) };unsafe {- *context.cast::<Option<Self>>() = Some(Self {- bytes: bytes.as_slice().to_vec(),- attachments,- });+ *context.cast::<Option<Self>>() = Some(Self::new(bytes.as_slice().to_vec(), attachments));};}@@ -180,6 +272,10 @@ impl Encode for TransferPayload {encoder.encode(self.bytes.as_slice())?;encoder.encode_size(self.attachments.len())?;append_attachments(encoder, self.attachments);+ encoder.encode_size(self.channel_ends.len())?;+ for end in self.channel_ends {+ end.encode_owned(encoder)?;+ }Ok(())}}@@ -196,15 +292,30 @@ impl Decode for TransferPayload {let attachments = (0..count).map(|_| decoder.take_attachment()).collect::<Result<_, _>>()?;- Ok(Self { bytes, attachments })+ let end_count = decoder.decode_size()?;+ let mut channel_ends = VecDeque::new();+ for _ in 0..end_count {+ channel_ends.push_back(CarriedChannelEnd::decode(decoder)?);+ }+ Ok(Self {+ bytes,+ attachments,+ channel_ends,+ })}}-pub(crate) struct TransferDataHolder(RefCell<Encoder>);+pub(crate) struct TransferDataHolder {+ encoder: RefCell<Encoder>,+ channel_ends: RefCell<VecDeque<CarriedChannelEnd>>,+}impl TransferDataHolder {pub(crate) fn new() -> Self {- Self(RefCell::new(Encoder::new()))+ Self {+ encoder: RefCell::new(Encoder::new()),+ channel_ends: RefCell::new(VecDeque::new()),+ }}pub(crate) fn encode<T: Encode + ?Sized>(&self, value: &T) {@@ -212,17 +323,26 @@ impl TransferDataHolder {}pub(crate) fn with_encoder(&self, write: impl FnOnce(&mut Encoder) -> Result<(), EncodeError>) {- write(&mut self.0.borrow_mut()).expect("a data holder encodes what it is given");+ write(&mut self.encoder.borrow_mut()).expect("a data holder encodes what it is given");+ }++ pub(crate) fn add_channel_end(&self, end: PortChannelEnd) {+ self.channel_ends.borrow_mut().push_back(CarriedChannelEnd::Held(end));}pub(crate) fn extend(&self, payload: TransferPayload) {- let mut encoder = self.0.borrow_mut();+ let mut encoder = self.encoder.borrow_mut();encoder.append_bytes(&payload.bytes);append_attachments(&mut encoder, payload.attachments);+ self.channel_ends.borrow_mut().extend(payload.channel_ends);}pub(crate) fn finish(self) -> TransferPayload {- let (bytes, attachments) = self.0.into_inner().finish();- TransferPayload { bytes, attachments }+ let (bytes, attachments) = self.encoder.into_inner().finish();+ TransferPayload {+ bytes,+ attachments,+ channel_ends: self.channel_ends.into_inner(),+ }}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/transfer_record.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/transfer_record.rsindex c011efaf0a3..1eb6795cc41 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/transfer_record.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/transfer_record.rs@@ -12,8 +12,8 @@ use core::ffi::{c_int, c_void};use core::ptr::NonNull;use libjs_rust::api::{- ArrayBuffer, DeferGc, EmbedderCell, EmbedderClass, EmbedderValue, Gc, GcRefCell, Trace, Vm, into_raw_descriptor,- lifeline_into_raw_descriptor,+ ArrayBuffer, DeferGc, EmbedderCell, EmbedderClass, EmbedderValue, Gc, GcRefCell, SharedStorePin, Trace, Vm,+ into_raw_descriptor, lifeline_into_raw_descriptor,};use super::cpp::{OwnedSerializedTransferRecord, SerializedTransferRecord, objects_into_abi};@@ -80,6 +80,101 @@ impl EmbedderValue for TransferRecord {pub(crate) type TransferRecordRef = Gc<EmbedderCell<TransferRecord>>;+/// A record on its way to a MessagePort, which is plain data that any thread can own: the bytes, the data holders, the+/// shared memory of ImageBitmap pixels, and the pin of the stores that the bytes name.+#[derive(Default)]+pub(crate) struct PortMessage {+ bytes: Vec<u8>,+ data_holders: Vec<TransferPayload>,+ shared_memory: Vec<SharedMemory>,+ shared_store_pin: Option<SharedStorePin>,+}++impl PortMessage {+ pub(crate) fn encode_into(mut self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ encoder.encode(self.bytes.as_slice())?;+ encoder.encode_owned(core::mem::take(&mut self.data_holders))?;+ encoder.encode_size(self.shared_memory.len())?;+ for memory in core::mem::take(&mut self.shared_memory) {+ encoder.encode(&true)?;+ encoder.encode(&(memory.size as u64))?;+ encoder.encode_owned(file_from_raw_descriptor(into_raw_descriptor(memory.descriptor)))?;+ }+ let shared_store_lifeline = self.shared_store_pin.take().and_then(SharedStorePin::into_lifeline);+ encoder.encode(&shared_store_lifeline.is_some())?;+ if let Some(lifeline) = shared_store_lifeline {+ encoder.encode_owned(file_from_raw_descriptor(lifeline_into_raw_descriptor(lifeline)))?;+ }+ Ok(())+ }++ pub(crate) fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ let bytes = decoder.decode::<Vec<u8>>()?;+ let data_holders = decoder.decode::<Vec<TransferPayload>>()?;+ let count = decoder.decode_size()?;+ let mut shared_memory = Vec::new();+ let mut keep_prefix = true;+ for _ in 0..count {+ if !decoder.decode::<bool>()? {+ // Match importing an invalid C++ AnonymousBuffer: its missing descriptor truncates the side table.+ keep_prefix = false;+ continue;+ }+ let size = usize::try_from(decoder.decode::<u64>()?)+ .map_err(|_| DecodeError::InvalidValue("shared memory size does not fit"))?;+ let File(descriptor) = decoder.decode::<File>()?;+ #[cfg(unix)]+ let raw = std::os::fd::IntoRawFd::into_raw_fd(descriptor);+ #[cfg(windows)]+ let raw = descriptor.into_raw();+ // SAFETY: File hands its descriptor over to the shared-memory owner.+ let memory = SharedMemory {+ descriptor: unsafe { owned_from_raw_descriptor(raw) },+ size,+ };+ // The native backing size and seal checks must run before any bitmap or ArrayBuffer can map the claim.+ // SAFETY: The owner keeps the descriptor open for validation.+ if !unsafe {+ web_structured_serialize_validate_shared_memory(+ raw_descriptor(memory.descriptor.as_shared_memory()),+ size,+ )+ } {+ return Err(DecodeError::InvalidValue("invalid shared memory backing"));+ }+ if keep_prefix {+ shared_memory.push(memory);+ }+ }+ let shared_store_pin = decoder+ .decode::<bool>()?+ .then(|| decoder.decode::<File>())+ .transpose()?+ .map(|File(descriptor)| {+ #[cfg(unix)]+ let raw = std::os::fd::IntoRawFd::into_raw_fd(descriptor);+ #[cfg(windows)]+ let raw = descriptor.into_raw();+ // SAFETY: File hands its descriptor over to the lifeline.+ SharedStorePin::Lifeline(unsafe { lifeline_from_raw_descriptor(raw) })+ });+ Ok(Self {+ bytes,+ data_holders,+ shared_memory,+ shared_store_pin,+ })+ }+}++impl Drop for PortMessage {+ fn drop(&mut self) {+ if let Some(pin) = self.shared_store_pin.take() {+ pin.release();+ }+ }+}+impl TransferRecord {pub(crate) fn discard(record: TransferRecordRef) {record.serialized.replace(None);@@ -106,8 +201,9 @@ impl TransferRecord {.map(|memory| (into_raw_descriptor(memory.descriptor), memory.size)).unzip();let shared_store_lifeline = message- .shared_store_lifeline+ .shared_store_pin.take()+ .and_then(SharedStorePin::into_lifeline).map_or(-1, lifeline_into_raw_descriptor);let holders: Vec<_> = record.data_holders@@ -133,88 +229,42 @@ impl TransferRecord {})}- /// The IPC encoding of a SerializedTransferRecord, without its same-process SharedArrayBuffers.+ /// The IPC encoding of a SerializedTransferRecord, without its same-agent SharedArrayBuffers.pub(crate) fn encode_into(record: TransferRecordRef, vm: &Vm, encoder: &mut Encoder) -> Result<(), EncodeError> {+ Self::into_port_message(record, vm).encode_into(encoder)+ }++ /// What of the record can leave the heap of the sender. The side table of same-agent SharedArrayBuffers stays behind,+ /// as the bytes name those by the id of their store too.+ pub(crate) fn into_port_message(record: TransferRecordRef, vm: &Vm) -> PortMessage {DeferGc::scope(vm, |_| {let mut message = record.serialized.replace(None).expect("a record is handed over once");- encoder.encode(message.bytes.as_slice())?;- let holders = core::mem::take(&mut *record.data_holders.borrow_mut());- encoder.encode_owned(holders)?;- encoder.encode_size(message.shared_memory.len())?;- for memory in core::mem::take(&mut message.shared_memory) {- encoder.encode(&true)?;- encoder.encode(&(memory.size as u64))?;- encoder.encode_owned(file_from_raw_descriptor(into_raw_descriptor(memory.descriptor)))?;- }- let shared_store_lifeline = message.shared_store_lifeline.take();- encoder.encode(&shared_store_lifeline.is_some())?;- if let Some(lifeline) = shared_store_lifeline {- encoder.encode_owned(file_from_raw_descriptor(lifeline_into_raw_descriptor(lifeline)))?;+ PortMessage {+ bytes: core::mem::take(&mut message.bytes),+ data_holders: core::mem::take(&mut *record.data_holders.borrow_mut()),+ shared_memory: core::mem::take(&mut message.shared_memory),+ shared_store_pin: message.shared_store_pin.take(),}- Ok(())})}- pub(crate) fn decode(vm: &Vm, decoder: &mut Decoder<'_>) -> Result<TransferRecordRef, DecodeError> {- let bytes = decoder.decode::<Vec<u8>>()?;- let holders = decoder.decode::<Vec<TransferPayload>>()?;- let count = decoder.decode_size()?;- let mut shared_memory = Vec::new();- let mut keep_prefix = true;- for _ in 0..count {- if !decoder.decode::<bool>()? {- // Match importing an invalid C++ AnonymousBuffer: its missing descriptor truncates the side table.- keep_prefix = false;- continue;- }- let size = usize::try_from(decoder.decode::<u64>()?)- .map_err(|_| DecodeError::InvalidValue("shared memory size does not fit"))?;- let File(descriptor) = decoder.decode::<File>()?;- #[cfg(unix)]- let raw = std::os::fd::IntoRawFd::into_raw_fd(descriptor);- #[cfg(windows)]- let raw = descriptor.into_raw();- // SAFETY: File hands its descriptor over to the shared-memory owner.- let memory = SharedMemory {- descriptor: unsafe { owned_from_raw_descriptor(raw) },- size,- };- // The native backing size and seal checks must run before any bitmap or ArrayBuffer can map the claim.- // SAFETY: The owner keeps the descriptor open for validation.- if !unsafe {- web_structured_serialize_validate_shared_memory(- raw_descriptor(memory.descriptor.as_shared_memory()),- size,- )- } {- return Err(DecodeError::InvalidValue("invalid shared memory backing"));- }- if keep_prefix {- shared_memory.push(memory);- }- }- let shared_store_lifeline = decoder- .decode::<bool>()?- .then(|| decoder.decode::<File>())- .transpose()?- .map(|File(descriptor)| {- #[cfg(unix)]- let raw = std::os::fd::IntoRawFd::into_raw_fd(descriptor);- #[cfg(windows)]- let raw = descriptor.into_raw();- // SAFETY: File hands its descriptor over to the lifeline.- unsafe { lifeline_from_raw_descriptor(raw) }- });- Ok(Self::create(+ /// The record of a message, in the heap of the receiver.+ pub(crate) fn from_port_message(vm: &Vm, mut message: PortMessage) -> TransferRecordRef {+ let holders = core::mem::take(&mut message.data_holders);+ Self::create(vm,|_| MessageRecord {- bytes,+ bytes: core::mem::take(&mut message.bytes),shared_array_buffers: Vec::new(),- shared_memory,- shared_store_lifeline,+ shared_memory: core::mem::take(&mut message.shared_memory),+ shared_store_pin: message.shared_store_pin.take(),},holders,- ))+ )+ }++ pub(crate) fn decode(vm: &Vm, decoder: &mut Decoder<'_>) -> Result<TransferRecordRef, DecodeError> {+ Ok(Self::from_port_message(vm, PortMessage::decode(decoder)?))}pub(crate) fn from_cpp(vm: &Vm, record: SerializedTransferRecord) -> TransferRecordRef {diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rsindex 3051f820dc4..119c28cfa31 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rs@@ -18,8 +18,7 @@ use std::sync::Arc;use ak::{Utf16String, Utf16StringUnits};use libjs_rust::api::{- ArrayBuffer, BigInt, DataBlockStorage, DeferGc, Gc, MarkedVec, SharedBackingStore, SharedStoreLifeline, Vm,- pin_stores_for_a_message,+ ArrayBuffer, BigInt, DataBlockStorage, DeferGc, Gc, MarkedVec, SharedBackingStore, SharedStorePin, Vm,};use libwebcommon_rust::html::serialization_records::{RecordEncoder, SerializationType};@@ -37,7 +36,7 @@ pub(crate) struct StructuredSerializeWriter<'vm> {shared_memory: Option<RefCell<Vec<SharedMemory>>>,/// The stores that a message names, which only a record that may reach an agent on another thread has.stores_of_message: Option<RefCell<Vec<Arc<SharedBackingStore>>>>,- shared_store_lifeline: RefCell<Option<SharedStoreLifeline>>,+ shared_store_pin: RefCell<Option<SharedStorePin>>,}impl<'vm> StructuredSerializeWriter<'vm> {@@ -47,7 +46,7 @@ impl<'vm> StructuredSerializeWriter<'vm> {shared_array_buffers: MarkedVec::new(vm),shared_memory: None,stores_of_message: None,- shared_store_lifeline: RefCell::new(None),+ shared_store_pin: RefCell::new(None),}}@@ -188,13 +187,12 @@ impl<'vm> StructuredSerializeWriter<'vm> {Some(id)}- /// Gives the message its lifeline, if it names stores. Fails if the system has no descriptors left.- pub(crate) fn pin_named_stores(&self) -> std::io::Result<()> {+ /// Gives the message its pin, if it names stores.+ pub(crate) fn pin_named_stores(&self) {let stores = self.stores_of_message.as_ref().map(RefCell::take).unwrap_or_default();if !stores.is_empty() {- *self.shared_store_lifeline.borrow_mut() = Some(pin_stores_for_a_message(stores)?);+ *self.shared_store_pin.borrow_mut() = Some(SharedStorePin::Counted(stores));}- Ok(())}/// Sets the IPC record that C++ lends to what the writer wrote.@@ -209,7 +207,7 @@ impl<'vm> StructuredSerializeWriter<'vm> {assert_eq!(self.serialization_type(), SerializationType::Ipc);let shared_memory = self.shared_memory.expect("the writer is a message's");MessageRecord {- shared_store_lifeline: self.shared_store_lifeline.take(),+ shared_store_pin: self.shared_store_pin.take(),bytes: self.encoder.into_inner().into_bytes(),shared_array_buffers: self.shared_array_buffers.values().to_vec(),shared_memory: shared_memory.into_inner(),diff --git a/Libraries/LibWeb/HTML/MessagePort.cpp b/Libraries/LibWeb/HTML/MessagePort.cppindex 896d901c2d1..9584a07cba7 100644--- a/Libraries/LibWeb/HTML/MessagePort.cpp+++ b/Libraries/LibWeb/HTML/MessagePort.cpp@@ -7,6 +7,7 @@*/#include <AK/MemoryStream.h>+#include <LibCore/EventLoop.h>#include <LibIPC/Decoder.h>#include <LibIPC/Encoder.h>#include <LibIPC/Transport.h>@@ -34,12 +35,17 @@ void web_rust_message_port_discard_pending_messages(void* port);size_t web_rust_message_port_pending_outgoing_message_count(void* port);void web_rust_message_port_fail_next_transfer_for_testing(void* port);void web_rust_message_port_disentangle_ports_of_realm(JSVM*, void* realm);-JSCompletion web_rust_message_port_transfer_steps(JSVM*, void* realm, void* port, TransferDataEncoder** out_data_holder);+JSCompletion web_rust_message_port_transfer_steps(JSVM*, void* realm, void* port, bool may_leave_process, TransferDataEncoder** out_data_holder, u64* out_parked_end_token);+void web_rust_message_port_give_up_on_parked_end(u64 token);+void web_rust_message_port_entanglement_kind(void* port, ReadonlyBytes* out_kind);JSCompletion web_rust_message_port_transfer_receiving_steps(JSVM*, void* realm, TransferDataEncoder*);// Declared in Bindings/Rust/src/html/message_port.rs.IPC::Transport* web_bindings_message_port_transport_create_paired(IPC::TransportHandle** out_remote_handle);void web_bindings_message_port_transport_destroy(IPC::Transport*);+Core::WeakEventLoopReference* web_bindings_message_port_current_event_loop();+void web_bindings_message_port_release_event_loop(Core::WeakEventLoopReference*);+void web_bindings_message_port_post_to_event_loop(Core::WeakEventLoopReference*, void (*steps)(u64), u64 argument);IPC::TransportHandle* web_bindings_message_port_transport_release_for_transfer(IPC::Transport*);void web_bindings_message_port_transport_set_up_read_hook(IPC::Transport*, void* state, void (*steps)(void*));bool web_bindings_message_port_transport_is_open(IPC::Transport*);@@ -112,15 +118,28 @@ void MessagePort::discard_pending_messages()web_rust_message_port_discard_pending_messages(this);}-WebIDL::ExceptionOr<TransferDataEncoder> MessagePort::transfer_steps(JS::Realm& realm)+WebIDL::ExceptionOr<MessagePort::TransferredToWorker> MessagePort::transfer_to_worker(JS::Realm& realm, WorkerMayBeInOtherProcess worker_may_be_in_other_process){TransferDataEncoder* data_holder = nullptr;- TRY(JS::HostABI::completion_from_abi<void>(web_rust_message_port_transfer_steps(vm_abi(), &realm, this, &data_holder)));- auto result = move(*data_holder);+ u64 parked_end_token = 0;+ TRY(JS::HostABI::completion_from_abi<void>(web_rust_message_port_transfer_steps(vm_abi(), &realm, this, worker_may_be_in_other_process == WorkerMayBeInOtherProcess::Yes, &data_holder, &parked_end_token)));+ TransferredToWorker result { move(*data_holder), parked_end_token };delete data_holder;return result;}+void MessagePort::give_up_on_parked_end(u64 parked_end_token)+{+ web_rust_message_port_give_up_on_parked_end(parked_end_token);+}++StringView MessagePort::entanglement_kind_for_testing() const+{+ ReadonlyBytes kind;+ web_rust_message_port_entanglement_kind(const_cast<MessagePort*>(this), &kind);+ return StringView { kind };+}+size_t MessagePort::pending_outgoing_message_count() const{return web_rust_message_port_pending_outgoing_message_count(const_cast<MessagePort*>(this));@@ -143,6 +162,23 @@ void web_bindings_message_port_transport_destroy(IPC::Transport* transport)delete transport;}+// A reference to the event loop of the calling thread, which any thread may use, handed over.+Core::WeakEventLoopReference* web_bindings_message_port_current_event_loop()+{+ return &Core::EventLoop::current_weak().leak_ref();+}++void web_bindings_message_port_release_event_loop(Core::WeakEventLoopReference* event_loop)+{+ event_loop->unref();+}++void web_bindings_message_port_post_to_event_loop(Core::WeakEventLoopReference* event_loop, void (*steps)(u64), u64 argument)+{+ if (auto strong_event_loop = event_loop->take(); strong_event_loop.is_alive())+ strong_event_loop->deferred_invoke([steps, argument] { steps(argument); });+}+// The rights of the transport's end as a handle, handed over, after its IO thread stops.IPC::TransportHandle* web_bindings_message_port_transport_release_for_transfer(IPC::Transport* transport){diff --git a/Libraries/LibWeb/HTML/MessagePort.h b/Libraries/LibWeb/HTML/MessagePort.hindex 83b23880788..d8ff4746878 100644--- a/Libraries/LibWeb/HTML/MessagePort.h+++ b/Libraries/LibWeb/HTML/MessagePort.h@@ -49,8 +49,23 @@ public:void discard_pending_messages();// https://html.spec.whatwg.org/multipage/web-messaging.html#message-ports:transfer-steps- WebIDL::ExceptionOr<TransferDataEncoder> transfer_steps(JS::Realm&);-+ // For the port of a new channel, whose data holder goes through the browser process to the thread of a worker. As+ // long as nobody took up the other end, it waits in this process, under the token.+ struct TransferredToWorker {+ TransferDataEncoder data_holder;+ u64 parked_end_token { 0 };+ };+ enum class WorkerMayBeInOtherProcess {+ No,+ Yes,+ };+ WebIDL::ExceptionOr<TransferredToWorker> transfer_to_worker(JS::Realm&, WorkerMayBeInOtherProcess);++ // Tells that the data holder is not going to arrive in this process, unless it did already: the port goes on over the+ // socket that the data holder carries, if it may leave the process, and otherwise its peer is gone.+ static void give_up_on_parked_end(u64 parked_end_token);++ StringView entanglement_kind_for_testing() const;size_t pending_outgoing_message_count() const;void fail_next_transfer_for_testing();};diff --git a/Libraries/LibWeb/HTML/WorkerAgentParent.cpp b/Libraries/LibWeb/HTML/WorkerAgentParent.cppindex aff4adf5f54..7369477ed6f 100644--- a/Libraries/LibWeb/HTML/WorkerAgentParent.cpp+++ b/Libraries/LibWeb/HTML/WorkerAgentParent.cpp@@ -90,7 +90,10 @@ void WorkerAgentParent::start()m_message_port = MessagePort::create(realm);m_message_port->entangle_with(*m_outside_port);- auto data_holder = MUST(m_message_port->transfer_steps(realm));+ // NB: A dedicated worker always runs in the process of its owner, and the browser process picks that of a shared one.+ auto [data_holder, parked_end_token] = MUST(m_message_port->transfer_to_worker(realm,+ m_agent_type == AgentType::DedicatedWorker ? MessagePort::WorkerMayBeInOtherProcess::No : MessagePort::WorkerMayBeInOtherProcess::Yes));+ m_parked_end_token = parked_end_token;// FIXME: Specification says this supposed to happen in step 11 of onComplete handler defined in https://html.spec.whatwg.org/multipage/workers.html#run-a-worker// but that would require introducing a new IPC message type to communicate this from the worker to its owner,@@ -131,7 +134,17 @@ void WorkerAgentParent::start()// NB: This blocking IPC call may launch another process.// If spinning the event loop for this can cause other javascript to execute, we're in trouble.worker_agent_parents().set(m_owner_token, *this);- m_agent_id = Bindings::principal_host_defined_page(realm).client().start_worker_agent(move(request));+ auto started_agent = Bindings::principal_host_defined_page(realm).client().start_worker_agent(move(request));+ m_agent_id = started_agent.agent_id;++ // NB: This is before any script can use the port, so that it finds out right now whether its peer is in this process.+ if (!started_agent.is_hosted_in_this_process)+ give_up_on_parked_end();+}++void WorkerAgentParent::give_up_on_parked_end()+{+ MessagePort::give_up_on_parked_end(exchange(m_parked_end_token, 0));}void WorkerAgentParent::did_fail_loading_worker_script(WorkerAgentOwnerToken owner_token)@@ -191,6 +204,7 @@ void WorkerAgentParent::terminate()void WorkerAgentParent::forget_agent(){m_agent_id = 0;+ give_up_on_parked_end();worker_agent_parents().remove(m_owner_token);m_outside_settings->remove_owned_worker_agent(*this);}diff --git a/Libraries/LibWeb/HTML/WorkerAgentParent.h b/Libraries/LibWeb/HTML/WorkerAgentParent.hindex 5101eac8ed9..2493d050576 100644--- a/Libraries/LibWeb/HTML/WorkerAgentParent.h+++ b/Libraries/LibWeb/HTML/WorkerAgentParent.h@@ -56,6 +56,7 @@ private:void start();void forget_agent();+ void give_up_on_parked_end();void dispatch_error_event();void dispatch_worker_exception(Utf16String message, Utf16String filename, u32 lineno, u32 colno);void report_content_security_policy_violation(u64 policy_index, String effective_directive, URL::URL resource);@@ -68,6 +69,7 @@ private:URL::URL m_url;WorkerAgentId m_agent_id { 0 };WorkerAgentOwnerToken m_owner_token { 0 };+ u64 m_parked_end_token { 0 };GC::Ptr<MessagePort> m_message_port;GC::Ptr<MessagePort> m_outside_port;diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex 1bb910e0cc4..3328dfadf62 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -531,6 +531,11 @@ void Internals::fail_next_message_port_transfer(HTML::MessagePort& port)port.fail_next_transfer_for_testing();}+String Internals::message_port_entanglement_kind(HTML::MessagePort& port)+{+ return MUST(String::from_utf8(port.entanglement_kind_for_testing()));+}+bool Internals::message_ports_are_directly_entangled(HTML::MessagePort& first, HTML::MessagePort& second){return first.entangled_port().ptr() == &second && second.entangled_port().ptr() == &first;diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.hindex e4f758bd853..67a4852c6a0 100644--- a/Libraries/LibWeb/Internals/Internals.h+++ b/Libraries/LibWeb/Internals/Internals.h@@ -83,6 +83,7 @@ public:WebIDL::UnsignedLongLong html_collection_cache_generation(DOM::HTMLCollection&);void fail_next_message_port_transfer(HTML::MessagePort&);bool message_ports_are_directly_entangled(HTML::MessagePort&, HTML::MessagePort&);+ String message_port_entanglement_kind(HTML::MessagePort&);GC::Ref<XHR::XMLHttpRequest> create_xml_http_request_for_document(DOM::Document&);Optional<Painting::HitTestResult> hit_test(double x, double y);GC::Ptr<JS::Object> hit_test_result(double x, double y);diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idlindex 90e3dc16017..5e65a3c91e7 100644--- a/Libraries/LibWeb/Internals/Internals.idl+++ b/Libraries/LibWeb/Internals/Internals.idl@@ -46,6 +46,7 @@ interface Internals {unsigned long long htmlCollectionCacheGeneration(HTMLCollection collection);undefined failNextMessagePortTransfer(MessagePort port);boolean messagePortsAreDirectlyEntangled(MessagePort first, MessagePort second);+ DOMString messagePortEntanglementKind(MessagePort port);XMLHttpRequest createXMLHttpRequestForDocument(Document document);[ImplementedAs=hit_test_result] object hitTest(double x, double y);object? takeContextMenuRequest();diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.hindex 39edec0d4d9..9e751a41527 100644--- a/Libraries/LibWeb/Page/Page.h+++ b/Libraries/LibWeb/Page/Page.h@@ -1015,7 +1015,11 @@ public:virtual void page_did_register_javascript_source([[maybe_unused]] DOM::Document&, [[maybe_unused]] HTML::ScriptRegistry::Description const&) { }virtual void page_did_post_broadcast_channel_message([[maybe_unused]] HTML::PostedBroadcastChannelMessage const& message) { }- virtual HTML::WorkerAgentId start_worker_agent([[maybe_unused]] HTML::WorkerAgentStartRequest&& request) { return {}; }+ struct StartedWorkerAgent {+ HTML::WorkerAgentId agent_id { 0 };+ bool is_hosted_in_this_process { false };+ };+ virtual StartedWorkerAgent start_worker_agent([[maybe_unused]] HTML::WorkerAgentStartRequest&& request) { return {}; }virtual void close_worker_agent([[maybe_unused]] HTML::WorkerAgentId agent_id, [[maybe_unused]] HTML::WorkerAgentOwnerToken owner_token) { }virtual void rtc_transform_init([[maybe_unused]] HTML::WorkerAgentId agent_id, [[maybe_unused]] u64 transform_id, [[maybe_unused]] HTML::SerializedTransferRecord options_record) { }virtual void rtc_transform_teardown([[maybe_unused]] HTML::WorkerAgentId agent_id, [[maybe_unused]] u64 transform_id) { }diff --git a/Libraries/LibWebView/WebContentClient.cpp b/Libraries/LibWebView/WebContentClient.cppindex 02d5b9c30c0..2005e7e23f8 100644--- a/Libraries/LibWebView/WebContentClient.cpp+++ b/Libraries/LibWebView/WebContentClient.cpp@@ -820,7 +820,7 @@ Messages::WebContentClient::StartWorkerAgentResponse WebContentClient::start_worif (auto* page = this->page(page_id))return page->start_worker_agent(move(request));- return { Web::HTML::WorkerAgentId {}, Optional<IPC::TransportHandle> {} };+ return { Web::HTML::WorkerAgentId {}, Optional<IPC::TransportHandle> {}, false };}void WebContentClient::did_close_browsing_context(Web::PageId page_id)diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cppindex 4952b9a06cd..84ae353b813 100644--- a/Libraries/LibWebView/WebContentPage.cpp+++ b/Libraries/LibWebView/WebContentPage.cpp@@ -3354,7 +3354,7 @@ Messages::WebContentClient::StartWorkerAgentResponse WebContentPage::start_worke// A page hosting an isolated iframe's document belongs to its tab's view as much as the view's own page does.auto outside_settings = hosted_environment(request.outside_settings.id);auto started_agent = WorkerProcessManager::the().start_worker_agent(client(), m_id, outside_settings, move(request));- return { started_agent.agent_id, move(started_agent.thread_transport) };+ return { started_agent.agent_id, move(started_agent.thread_transport), started_agent.is_hosted_in_owner_process };}Messages::WebContentClient::DidRequestStorageUsageResponse WebContentPage::did_request_storage_usage(Web::HTML::EnvironmentId environment_id)diff --git a/Libraries/LibWebView/WebWorkerClient.cpp b/Libraries/LibWebView/WebWorkerClient.cppindex 9e09e14c0e1..6f893eacf68 100644--- a/Libraries/LibWebView/WebWorkerClient.cpp+++ b/Libraries/LibWebView/WebWorkerClient.cpp@@ -227,7 +227,7 @@ Messages::WebWorkerClient::StartWorkerAgentResponse WebWorkerClient::start_worke{auto outside_settings = hosted_environment(request.outside_settings.id);auto started_agent = WorkerProcessManager::the().start_worker_agent(*this, outside_settings, move(request));- return { started_agent.agent_id, move(started_agent.thread_transport) };+ return { started_agent.agent_id, move(started_agent.thread_transport), started_agent.is_hosted_in_owner_process };}void WebWorkerClient::close_worker_agent(Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token)diff --git a/Libraries/LibWebView/WorkerProcessManager.cpp b/Libraries/LibWebView/WorkerProcessManager.cppindex 1106d92ad26..19c7ff400ce 100644--- a/Libraries/LibWebView/WorkerProcessManager.cpp+++ b/Libraries/LibWebView/WorkerProcessManager.cpp@@ -152,7 +152,14 @@ WorkerProcessManager::StartedWorkerAgent WorkerProcessManager::start_worker_agenagent.owners.append(owner);agent.extended_lifetime_timer = nullptr;agent.client->async_connect_shared_worker(move(request.outside_port), request.outside_settings);- return { agent.id, {} };+ auto const* owner_host = owner.client.visit(+ [](WebContentOwner const& web_content_owner) -> WebContentClient const* {+ return web_content_owner.client.ptr();+ },+ [](WebWorkerOwner const& web_worker_owner) -> WebContentClient const* {+ return web_worker_owner.client->host();+ });+ return { agent.id, {}, owner_host && owner_host == agent.client->host() };}}@@ -343,7 +350,7 @@ WorkerProcessManager::StartedWorkerAgent WorkerProcessManager::start_worker_agenm_agents.set(agent_id, move(agent));client->async_start_worker(request.url, request.type, request.credentials, request.name, move(request.outside_port), request.outside_settings, request.agent_type, move(inside_origin), move(environment_id), host_has_only_this_worker);- return { agent_id, move(thread_transport) };+ return { agent_id, move(thread_transport), !host_has_only_this_worker };}// Sites decide what runs together in a process, as for the documents of CanonicalNavigable::process_to_host(). The worker'sdiff --git a/Libraries/LibWebView/WorkerProcessManager.h b/Libraries/LibWebView/WorkerProcessManager.hindex 57dafd9aad4..749158675ae 100644--- a/Libraries/LibWebView/WorkerProcessManager.h+++ b/Libraries/LibWebView/WorkerProcessManager.h@@ -57,6 +57,7 @@ public:struct StartedWorkerAgent {Web::HTML::WorkerAgentId agent_id { 0 };Optional<IPC::TransportHandle> thread_transport;+ bool is_hosted_in_owner_process { false };};StartedWorkerAgent start_worker_agent(WebContentClient&, Web::PageId page_id, Optional<CanonicalEnvironmentSettingsObject const&> outside_settings, Web::HTML::WorkerAgentStartRequest);StartedWorkerAgent start_worker_agent(WebWorkerClient&, Optional<CanonicalEnvironmentSettingsObject const&> outside_settings, Web::HTML::WorkerAgentStartRequest);diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cppindex 6b7ae363f22..80cf202be25 100644--- a/Services/WebContent/PageClient.cpp+++ b/Services/WebContent/PageClient.cpp@@ -2262,7 +2262,7 @@ void PageClient::reset_gamepad_access_for_testing()test_connection->async_reset_gamepad_access_for_testing(m_id);}-Web::HTML::WorkerAgentId PageClient::start_worker_agent(Web::HTML::WorkerAgentStartRequest&& request)+Web::PageClient::StartedWorkerAgent PageClient::start_worker_agent(Web::HTML::WorkerAgentStartRequest&& request){auto agent_type = request.agent_type;auto response = client().send_sync_but_allow_failure<Messages::WebContentClient::StartWorkerAgent>(m_id, move(request));@@ -2277,7 +2277,7 @@ Web::HTML::WorkerAgentId PageClient::start_worker_agent(Web::HTML::WorkerAgentStdbgln("Unable to start a thread for a worker: {}", result.error());}- return response->agent_id();+ return { response->agent_id(), response->is_hosted_in_caller_process() };}void PageClient::close_worker_agent(Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token)diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.hindex 5a6108ae341..dd831fdc636 100644--- a/Services/WebContent/PageClient.h+++ b/Services/WebContent/PageClient.h@@ -411,7 +411,7 @@ private:virtual Web::Gamepad::ReceivedRumbleEffects virtual_gamepad_received_rumble_effects(Web::Gamepad::GamepadHandle) override;virtual void pump_gamepad_events() override;virtual void reset_gamepad_access_for_testing() override;- virtual Web::HTML::WorkerAgentId start_worker_agent(Web::HTML::WorkerAgentStartRequest&&) override;+ virtual Web::PageClient::StartedWorkerAgent start_worker_agent(Web::HTML::WorkerAgentStartRequest&&) override;virtual void close_worker_agent(Web::HTML::WorkerAgentId, Web::HTML::WorkerAgentOwnerToken) override;virtual void rtc_transform_init(Web::HTML::WorkerAgentId, u64 transform_id, Web::HTML::SerializedTransferRecord options_record) override;virtual void rtc_transform_teardown(Web::HTML::WorkerAgentId, u64 transform_id) override;diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipcindex c9b4a385da4..c531b096c5d 100644--- a/Services/WebContent/WebContentClient.ipc+++ b/Services/WebContent/WebContentClient.ipc@@ -320,7 +320,7 @@ endpoint WebContentClient routed by Web::PageId page_iddid_find_in_page(Web::PageId page_id, size_t current_match_index, Optional<size_t> total_match_count) =|- [NotRouted] start_worker_agent(Web::PageId page_id, Web::HTML::WorkerAgentStartRequest request) => (Web::HTML::WorkerAgentId agent_id, Optional<IPC::TransportHandle> thread_transport)+ [NotRouted] start_worker_agent(Web::PageId page_id, Web::HTML::WorkerAgentStartRequest request) => (Web::HTML::WorkerAgentId agent_id, Optional<IPC::TransportHandle> thread_transport, bool is_hosted_in_caller_process)[NotRouted] close_worker_agent(Web::PageId page_id, Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token) =|rtc_transform_init(Web::PageId page_id, Web::HTML::WorkerAgentId agent_id, u64 transform_id, Web::HTML::SerializedTransferRecord options_record) =|rtc_transform_teardown(Web::PageId page_id, Web::HTML::WorkerAgentId agent_id, u64 transform_id) =|diff --git a/Services/WebContent/WebWorkerClient.ipc b/Services/WebContent/WebWorkerClient.ipcindex 4edb945cf07..a63e827181b 100644--- a/Services/WebContent/WebWorkerClient.ipc+++ b/Services/WebContent/WebWorkerClient.ipc@@ -27,7 +27,7 @@ endpoint WebWorkerClient {request_image_decoder_connection() => (Optional<IPC::TransportHandle> handle)did_release_image_decoder() =|did_post_broadcast_channel_message(Web::HTML::PostedBroadcastChannelMessage message) =|- start_worker_agent(Web::HTML::WorkerAgentStartRequest request) => (Web::HTML::WorkerAgentId agent_id, Optional<IPC::TransportHandle> thread_transport)+ start_worker_agent(Web::HTML::WorkerAgentStartRequest request) => (Web::HTML::WorkerAgentId agent_id, Optional<IPC::TransportHandle> thread_transport, bool is_hosted_in_caller_process)close_worker_agent(Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token) =|rtc_transform_encoded_audio_frame_written(u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number) =|diff --git a/Services/WebContent/Worker/PageHost.cpp b/Services/WebContent/Worker/PageHost.cppindex e94148ef6a8..586284915ac 100644--- a/Services/WebContent/Worker/PageHost.cpp+++ b/Services/WebContent/Worker/PageHost.cpp@@ -156,19 +156,19 @@ Optional<Web::FileAPI::SerializedBlobURLEntry> PageHost::page_did_request_blob_ureturn response->take_entry();}-Web::HTML::WorkerAgentId PageHost::start_worker_agent(Web::HTML::WorkerAgentStartRequest&& request)+Web::PageClient::StartedWorkerAgent PageHost::start_worker_agent(Web::HTML::WorkerAgentStartRequest&& request){auto agent_type = request.agent_type;auto response = m_client.send_sync_but_allow_failure<Messages::WebWorkerClient::StartWorkerAgent>(move(request));if (!response)- return 0;+ return {};// NB: The UI process notices a transport that nobody takes up, and tells the owner that its worker is gone.if (auto transport = response->take_thread_transport(); transport.has_value()) {if (auto result = start_worker_thread(transport.release_value(), agent_type); result.is_error())dbgln("Unable to start a thread for a worker: {}", result.error());}- return response->agent_id();+ return { response->agent_id(), response->is_hosted_in_caller_process() };}void PageHost::close_worker_agent(Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token)diff --git a/Services/WebContent/Worker/PageHost.h b/Services/WebContent/Worker/PageHost.hindex 7acf1bc7e96..df95d24fa60 100644--- a/Services/WebContent/Worker/PageHost.h+++ b/Services/WebContent/Worker/PageHost.h@@ -49,7 +49,7 @@ public:virtual URL::BlobURLEntry::Token page_did_add_blob_url_entry(Web::HTML::EnvironmentSettingsObject const&, Utf16String const& url, Web::FileAPI::SerializedBlobURLEntry const&) override;virtual void page_did_remove_blob_url_entries(Web::HTML::EnvironmentSettingsObject const&, Vector<Utf16String> const& urls) override;virtual Optional<Web::FileAPI::SerializedBlobURLEntry> page_did_request_blob_url_entry(Utf16String const& url, Optional<URL::BlobURLEntry::Token> token) override;- virtual Web::HTML::WorkerAgentId start_worker_agent(Web::HTML::WorkerAgentStartRequest&&) override;+ virtual Web::PageClient::StartedWorkerAgent start_worker_agent(Web::HTML::WorkerAgentStartRequest&&) override;virtual void close_worker_agent(Web::HTML::WorkerAgentId, Web::HTML::WorkerAgentOwnerToken) override;virtual bool supports_compositor() const override { return true; }virtual void ensure_compositor_host() override;diff --git a/Tests/LibWeb/StructuredSerializeTestHelpers.h b/Tests/LibWeb/StructuredSerializeTestHelpers.hindex 412efef8e9d..223f99bee3b 100644--- a/Tests/LibWeb/StructuredSerializeTestHelpers.h+++ b/Tests/LibWeb/StructuredSerializeTestHelpers.h@@ -8,6 +8,7 @@#include <AK/Array.h>#include <AK/BitCast.h>+#include <AK/ByteBuffer.h>#include <AK/Endian.h>#include <AK/LEB128.h>#include <AK/MemoryStream.h>@@ -116,6 +117,30 @@ inline JS::Realm& test_realm()return *realm;}+// A data holder as C++ carries it: the bytes and attachments that its writers added, then its channel ends, of which+// this one has none.+inline IPC::MessageBuffer carried_transfer_data_holder(IPC::MessageBuffer data_holder)+{+ IPC::MessageBuffer carried;+ IPC::Encoder encoder { carried };+ MUST(encoder.encode(data_holder.data().span()));+ auto attachments = data_holder.take_attachments();+ MUST(encoder.encode_size(attachments.size()));+ for (auto& attachment : attachments)+ MUST(encoder.append_attachment(move(attachment)));+ MUST(encoder.encode_size(0));+ return carried;+}++// The bytes that the writers of a data holder added.+inline ByteBuffer transfer_data_holder_bytes(IPC::MessageBuffer const& carried)+{+ FixedMemoryStream stream { carried.data().span() };+ Queue<IPC::Attachment> no_attachments;+ IPC::Decoder decoder { stream, no_attachments };+ return MUST(decoder.decode<ByteBuffer>());+}+// StructuredDeserializeWithTransfer of a record whose [[Serialized]] is undefined and whose only data holder is the// bytes: the transferred value, or the exception.inline Web::WebIDL::ExceptionOr<JS::Value> receive_transfer_data_holder(IPC::MessageBuffer data_holder, Vector<Core::AnonymousBuffer> shared_buffers = {})@@ -123,7 +148,7 @@ inline Web::WebIDL::ExceptionOr<JS::Value> receive_transfer_data_holder(IPC::Mesauto& realm = test_realm();Web::HTML::SerializedTransferRecord record;record.serialized = MUST(Web::HTML::structured_serialize(realm.vm(), JS::js_undefined()));- record.transfer_data_holders.append(Web::HTML::TransferDataEncoder { move(data_holder) });+ record.transfer_data_holders.append(Web::HTML::TransferDataEncoder { carried_transfer_data_holder(move(data_holder)) });record.shared_buffers = move(shared_buffers);auto deserialized = TRY(Web::HTML::structured_deserialize_with_transfer(record, realm));return JS::Value { deserialized.transferred_values[0].ptr() };@@ -133,13 +158,15 @@ inline Web::WebIDL::ExceptionOr<JS::Value> receive_transfer_data_holder(IPC::Messtruct TransferDataHolderReader {explicit TransferDataHolderReader(Web::HTML::TransferDataEncoder const& data_holder): buffer(data_holder.take_buffer())- , stream(buffer.data().span())+ , bytes(transfer_data_holder_bytes(buffer))+ , stream(bytes.bytes()){for (auto& attachment : buffer.take_attachments())attachments.enqueue(move(attachment));}IPC::MessageBuffer buffer;+ ByteBuffer bytes;FixedMemoryStream stream;Queue<IPC::Attachment> attachments;IPC::Decoder decoder { stream, attachments };diff --git a/Tests/LibWeb/TestStructuredSerializeFormat.cpp b/Tests/LibWeb/TestStructuredSerializeFormat.cppindex 11cdb470365..72bea1b85b5 100644--- a/Tests/LibWeb/TestStructuredSerializeFormat.cpp+++ b/Tests/LibWeb/TestStructuredSerializeFormat.cpp@@ -615,6 +615,26 @@ TEST_CASE(image_bitmap_with_padded_rows_transfers_its_pixels)received.close();}+// A message queued on a port goes with the data holder of the port, in which its data holders are not those of C++.+static Web::HTML::SerializedTransferRecord decode_queued_message(IPC::Decoder& decoder)+{+ auto serialized = MUST(decoder.decode<Web::HTML::IPCSerializationRecord>());++ Vector<Web::HTML::TransferDataEncoder> data_holders;+ for (auto count = MUST(decoder.decode_size()); count > 0; --count) {+ auto data = MUST(decoder.decode<IPC::MessageDataType>());+ Vector<IPC::Attachment> attachments;+ for (auto attachment_count = MUST(decoder.decode_size()); attachment_count > 0; --attachment_count)+ attachments.append(decoder.attachments().dequeue());+ EXPECT_EQ(MUST(decoder.decode_size()), 0u); // Channel ends.+ data_holders.append(Web::HTML::TransferDataEncoder { carried_transfer_data_holder(IPC::MessageBuffer { move(data), move(attachments) }) });+ }++ auto shared_buffers = MUST(decoder.decode<Vector<Core::AnonymousBuffer>>());+ auto shared_store_lifeline = MUST(decoder.decode<Web::HTML::SharedStoreLifeline>());+ return { move(serialized), move(data_holders), move(shared_buffers), move(shared_store_lifeline) };+}+TEST_CASE(image_bitmaps_queued_on_a_transferred_message_port_keep_their_pixels){auto& realm = test_realm();@@ -640,10 +660,10 @@ TEST_CASE(image_bitmaps_queued_on_a_transferred_message_port_keep_their_pixels)TransferDataHolderReader port_holder { record.transfer_data_holders[0] };EXPECT_EQ(MUST(port_holder.decoder.decode<u8>()), message_port_transfer_type);- EXPECT(MUST(port_holder.decoder.decode<Vector<Web::HTML::SerializedTransferRecord>>()).is_empty());- auto queued_messages = MUST(port_holder.decoder.decode<Vector<Web::HTML::SerializedTransferRecord>>());- EXPECT_EQ(queued_messages.size(), 1u);- auto received_values = deserialize_transferred_values(realm, queued_messages[0]);+ EXPECT_EQ(MUST(port_holder.decoder.decode_size()), 0u);+ EXPECT_EQ(MUST(port_holder.decoder.decode_size()), 1u);+ auto queued_message = decode_queued_message(port_holder.decoder);+ auto received_values = deserialize_transferred_values(realm, queued_message);EXPECT_EQ(received_values.size(), count);for (auto value : received_values) {auto& received = unwrap_wrappable<Web::HTML::ImageBitmap>(value);@@ -747,7 +767,7 @@ TEST_CASE(image_bitmap_transfer_protects_against_backing_truncation)record.shared_buffers[0] = move(backing);# endifauto buffer = record.shared_buffers[0];- EXPECT_EQ(record.transfer_data_holders[0].buffer().data()[0], image_bitmap_transfer_type);+ EXPECT_EQ(transfer_data_holder_bytes(record.transfer_data_holders[0].buffer())[0], image_bitmap_transfer_type);auto received_values = deserialize_transferred_values(realm, record);auto& receiver = unwrap_wrappable<Web::HTML::ImageBitmap>(received_values[0]);# if defined(AK_OS_LINUX)diff --git a/Tests/LibWeb/Text/expected/Workers/shared-worker-port-in-other-process.txt b/Tests/LibWeb/Text/expected/Workers/shared-worker-port-in-other-process.txtnew file mode 100644index 00000000000..c03bbd7c6a5--- /dev/null+++ b/Tests/LibWeb/Text/expected/Workers/shared-worker-port-in-other-process.txt@@ -0,0 +1,4 @@+crossOriginIsolated: true+echo: hello+port: socket+messageerrordiff --git a/Tests/LibWeb/Text/expected/Workers/shared-worker-port-in-process.txt b/Tests/LibWeb/Text/expected/Workers/shared-worker-port-in-process.txtnew file mode 100644index 00000000000..81f60b9e445--- /dev/null+++ b/Tests/LibWeb/Text/expected/Workers/shared-worker-port-in-process.txt@@ -0,0 +1,3 @@+crossOriginIsolated: false+echo: hello+port: channeldiff --git a/Tests/LibWeb/Text/expected/Workers/worker-message-channel-between-threads.txt b/Tests/LibWeb/Text/expected/Workers/worker-message-channel-between-threads.txtnew file mode 100644index 00000000000..41fbea848ba--- /dev/null+++ b/Tests/LibWeb/Text/expected/Workers/worker-message-channel-between-threads.txt@@ -0,0 +1,14 @@+before the transfer: same agent+after the transfer: channel+echoes in order: true+after start: a b c+kind of the port back on this thread: channel+after two transfers: 1 2 3 4+a port in a queued message: channel+carries a port+from a closed port: last words+after the close: none+after terminate: channel+remote got sent early, remote got sent late, remote got sent after it left+peer in another process: socket+remote got from the worker, early, remote got from the worker, latediff --git a/Tests/LibWeb/Text/input/Workers/shared-worker-port-in-other-process.html b/Tests/LibWeb/Text/input/Workers/shared-worker-port-in-other-process.htmlnew file mode 100644index 00000000000..708adaee949--- /dev/null+++ b/Tests/LibWeb/Text/input/Workers/shared-worker-port-in-other-process.html@@ -0,0 +1,26 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ const SCRIPT = `+ onconnect = event => {+ const port = event.ports[0];+ port.onmessage = event => port.postMessage("echo: " + event.data);+ port.onmessageerror = () => port.postMessage("messageerror");+ };+ `;++ promiseTest(async () => {+ const scriptURL = URL.createObjectURL(new Blob([SCRIPT], { type: "text/javascript" }));+ const worker = new SharedWorker(scriptURL, uniqueID());+ println(`crossOriginIsolated: ${self.crossOriginIsolated}`);+ const reply = new Promise(resolve => (worker.port.onmessage = event => resolve(event.data)));+ worker.port.postMessage("hello");+ println(await reply);+ println(`port: ${internals.messagePortEntanglementKind(worker.port)}`);++ // NB: A shared worker is an agent cluster of its own.+ const error = new Promise(resolve => (worker.port.onmessage = event => resolve(event.data)));+ worker.port.postMessage(new SharedArrayBuffer(8));+ println(await error);+ });+</script>diff --git a/Tests/LibWeb/Text/input/Workers/shared-worker-port-in-other-process.html.headers b/Tests/LibWeb/Text/input/Workers/shared-worker-port-in-other-process.html.headersnew file mode 100644index 00000000000..63b60e490f4--- /dev/null+++ b/Tests/LibWeb/Text/input/Workers/shared-worker-port-in-other-process.html.headers@@ -0,0 +1,2 @@+Cross-Origin-Opener-Policy: same-origin+Cross-Origin-Embedder-Policy: require-corpdiff --git a/Tests/LibWeb/Text/input/Workers/shared-worker-port-in-process.html b/Tests/LibWeb/Text/input/Workers/shared-worker-port-in-process.htmlnew file mode 100644index 00000000000..b7886fcbe4b--- /dev/null+++ b/Tests/LibWeb/Text/input/Workers/shared-worker-port-in-process.html@@ -0,0 +1,21 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ const SCRIPT = `+ onconnect = event => {+ const port = event.ports[0];+ port.onmessage = event => port.postMessage("echo: " + event.data);+ port.onmessageerror = () => port.postMessage("messageerror");+ };+ `;++ promiseTest(async () => {+ const scriptURL = URL.createObjectURL(new Blob([SCRIPT], { type: "text/javascript" }));+ const worker = new SharedWorker(scriptURL, uniqueID());+ println(`crossOriginIsolated: ${self.crossOriginIsolated}`);+ const reply = new Promise(resolve => (worker.port.onmessage = event => resolve(event.data)));+ worker.port.postMessage("hello");+ println(await reply);+ println(`port: ${internals.messagePortEntanglementKind(worker.port)}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/Workers/worker-message-channel-between-threads.html b/Tests/LibWeb/Text/input/Workers/worker-message-channel-between-threads.htmlnew file mode 100644index 00000000000..b27060f68a1--- /dev/null+++ b/Tests/LibWeb/Text/input/Workers/worker-message-channel-between-threads.html@@ -0,0 +1,227 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ const WORKER_SCRIPT = `+ let kept = null;+ onmessage = ({ data, ports }) => {+ switch (data.op) {+ case "echo":+ ports[0].onmessage = event => event.target.postMessage(event.data);+ break;+ case "keep":+ kept = ports[0];+ postMessage("kept");+ break;+ case "report":+ kept.onmessage = event => postMessage(event.data);+ break;+ case "send":+ kept.postMessage(data.value);+ postMessage("sent");+ break;+ case "give back":+ postMessage("given back", [kept]);+ kept = null;+ break;+ case "close":+ kept.postMessage("last words");+ kept.close();+ postMessage("closed");+ break;+ }+ };+ `;++ const scriptURL = URL.createObjectURL(new Blob([WORKER_SCRIPT], { type: "text/javascript" }));++ function nextMessage(target) {+ return new Promise(resolve => target.addEventListener("message", resolve, { once: true }));+ }++ async function ask(worker, data, transfer = []) {+ const reply = nextMessage(worker);+ worker.postMessage(data, transfer);+ return await reply;+ }++ function collect(target, count) {+ const received = [];+ return new Promise(resolve => {+ target.onmessage = ({ data }) => {+ received.push(data);+ if (received.length === count) resolve(received);+ };+ });+ }++ async function waitForNoWorkers() {+ await waitForCondition(() => internals.workerAgentCount() === 0);+ }++ function kind(port) {+ return internals.messagePortEntanglementKind(port);+ }++ async function testRoundTrips() {+ const worker = new Worker(scriptURL);+ const { port1, port2 } = new MessageChannel();+ println(`before the transfer: ${kind(port1)}`);+ worker.postMessage({ op: "echo" }, [port2]);+ println(`after the transfer: ${kind(port1)}`);++ const count = 500;+ const echoes = collect(port1, count);+ for (let i = 0; i < count; ++i) port1.postMessage(i);+ const received = await echoes;+ println(`echoes in order: ${received.every((value, index) => value === index)}`);+ worker.terminate();+ await waitForNoWorkers();+ }++ async function testDisabledQueue() {+ const worker = new Worker(scriptURL);+ const { port1, port2 } = new MessageChannel();+ await ask(worker, { op: "keep" }, [port2]);+ port1.postMessage("a");+ port1.postMessage("b");+ await timeout(10);+ port1.postMessage("c");++ const messages = collect(worker, 3);+ worker.postMessage({ op: "report" });+ println(`after start: ${(await messages).join(" ")}`);+ worker.terminate();+ await waitForNoWorkers();+ }++ async function testTransferToAnotherThread() {+ const first = new Worker(scriptURL);+ const second = new Worker(scriptURL);+ const { port1, port2 } = new MessageChannel();+ await ask(first, { op: "keep" }, [port2]);+ port1.postMessage(1);+ port1.postMessage(2);++ // NB: These go after the port has left the first worker, and before the second one has it.+ const givenBack = await ask(first, { op: "give back" });+ port1.postMessage(3);+ println(`kind of the port back on this thread: ${kind(givenBack.ports[0])}`);+ await ask(second, { op: "keep" }, [givenBack.ports[0]]);+ port1.postMessage(4);++ const messages = collect(second, 4);+ second.postMessage({ op: "report" });+ println(`after two transfers: ${(await messages).join(" ")}`);+ first.terminate();+ second.terminate();+ await waitForNoWorkers();+ }++ async function testPortInQueuedMessage() {+ const worker = new Worker(scriptURL);+ const { port1, port2 } = new MessageChannel();+ await ask(worker, { op: "keep" }, [port2]);++ const inner = new MessageChannel();+ port1.postMessage("carries a port", [inner.port2]);+ inner.port1.postMessage("through a port");+ println(`a port in a queued message: ${kind(inner.port1)}`);++ const messages = collect(worker, 1);+ worker.postMessage({ op: "report" });+ println(await messages);+ worker.terminate();+ await waitForNoWorkers();+ }++ async function testClose() {+ const worker = new Worker(scriptURL);+ const { port1, port2 } = new MessageChannel();+ await ask(worker, { op: "keep" }, [port2]);++ const lastWords = nextMessage(port1);+ port1.start();+ await ask(worker, { op: "close" });+ println(`from a closed port: ${(await lastWords).data}`);+ port1.postMessage("nobody hears this");+ await timeout(10);+ println(`after the close: ${kind(port1)}`);+ worker.terminate();+ await waitForNoWorkers();+ }++ async function testTerminateWithQueuedMessages() {+ const worker = new Worker(scriptURL);+ const { port1, port2 } = new MessageChannel();+ await ask(worker, { op: "keep" }, [port2]);+ for (let i = 0; i < 100; ++i) port1.postMessage(new ArrayBuffer(1024));+ worker.terminate();+ for (let i = 0; i < 100; ++i) port1.postMessage(i);+ await waitForNoWorkers();+ port1.postMessage("after the end");+ println(`after terminate: ${kind(port1)}`);+ }++ async function testPortLeavesProcess() {+ const reachable = new Promise(resolve => {+ window.onmessage = event => {+ if (event.data === "ready") resolve();+ };+ });+ const remoteURL = new URL(+ await httpTestServer().createEcho("GET", "/worker-message-channel-remote", {+ status: 200,+ headers: { "Content-Type": "text/html" },+ body: `<!DOCTYPE html><script>+ addEventListener("message", ({ ports }) => {+ const port = ports[0];+ port.onmessage = event => port.postMessage("remote got " + event.data);+ });+ parent.postMessage("ready", "*");+ <\/script>`,+ })+ );+ remoteURL.hostname = uniqueLocalhostHostname("message-channel");+ const iframe = document.createElement("iframe");+ iframe.src = remoteURL;+ document.body.appendChild(iframe);+ await reachable;++ // The worker's port goes through this page to the other process. Its peer here has messages under way.+ const worker = new Worker(scriptURL);+ const { port1, port2 } = new MessageChannel();+ await ask(worker, { op: "keep" }, [port2]);+ port1.postMessage("sent early");+ const givenBack = await ask(worker, { op: "give back" });+ port1.postMessage("sent late");+ const replies = collect(port1, 3);+ iframe.contentWindow.postMessage("here", "*", [givenBack.ports[0]]);+ port1.postMessage("sent after it left");+ println((await replies).join(", "));+ println(`peer in another process: ${kind(port1)}`);++ // This port stays with the worker, and its peer leaves from this page, with messages for it.+ const { port1: leavingPort, port2: stayingPort } = new MessageChannel();+ await ask(worker, { op: "keep" }, [stayingPort]);+ await ask(worker, { op: "send", value: "from the worker, early" });+ iframe.contentWindow.postMessage("here", "*", [leavingPort]);+ await ask(worker, { op: "send", value: "from the worker, late" });+ const answers = collect(worker, 2);+ worker.postMessage({ op: "report" });+ println((await answers).join(", "));++ worker.terminate();+ await waitForNoWorkers();+ iframe.remove();+ }++ promiseTest(async () => {+ await testRoundTrips();+ await testDisabledQueue();+ await testTransferToAnotherThread();+ await testPortInQueuedMessage();+ await testClose();+ await testTerminateWithQueuedMessages();+ await testPortLeavesProcess();+ });+</script>