Truly independent web browser
LibWeb: Keep the MessagePort transport with MessagePort
Shannon Booth64b3ac7e3e70
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rsindex ec6cc7b2b5c..d3a20c5bbe0 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs@@ -35,7 +35,6 @@ pub(crate) mod realm_data;pub(crate) mod services;pub(crate) mod setlike;pub(crate) mod structured_data;-pub(crate) mod transport;use core::ptr::NonNull;diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rsindex 118857bed95..0f0373760db 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs@@ -25,8 +25,8 @@ use libjs_rust::api::{Gc, MarkedVec, Object, Realm, Value, Vm};use libwebcommon_rust::html::serialization_records::SerializationType;use crate::bindings::interface::{ConstructedObject, Interface, Ref, implementation_of, wrap};-use crate::bindings::transport::TransportHandle;use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::html::message_port::TransportHandle;use crate::html::structured_serialize::cpp::{ImageBitmapSharedPixels, SharedPixelBuffers, data_clone_error_from_serialization_error,};diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/transport.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/transport.rsdeleted file mode 100644index e5402011614..00000000000--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/transport.rs+++ /dev/null@@ -1,291 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! What LibWeb's C++ IPC transports lend to Rust: the transport that carries the messages of a MessagePort between-//! agents, and the handle of one end of such a transport, which a data holder carries. The Rust bindings hold them as-//! opaque pointers, and reach them through the C ABI of RustBindingsServices.cpp.--use core::any::Any;-use core::ffi::c_void;-use core::ptr::NonNull;--use crate::html::structured_serialize::transfer_data_holder::{- RawAttachment, ReceivePayload, TransferPayload, append_attachments,-};-use crate::html::structured_serialize::transfer_record::{TransferRecord, TransferRecordRef};-use libipc_rust::{Attachment, DecodeError, Decoder, Encoder};-use libjs_rust::api::{MarkedVec, Vm};--unsafe extern "C" {- fn web_structured_serialize_transfer_handle_take(- handle: *mut c_void,- context: *mut c_void,- receive: ReceivePayload,- );- fn web_structured_serialize_transfer_handle_create_transport(- bytes: ak::Span<'_, u8>,- attachments: *const RawAttachment,- 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_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(- transport: *mut c_void,- state: *mut c_void,- steps: unsafe extern "C" fn(*mut c_void),- );- fn web_bindings_message_port_transport_is_open(transport: *mut c_void) -> bool;- fn web_bindings_message_port_transport_close(transport: *mut c_void);- fn web_bindings_message_port_transport_close_after_sending_all_pending_messages(transport: *mut c_void);- fn web_bindings_message_port_transport_send(- transport: *mut c_void,- bytes: ak::Span<'_, u8>,- attachments: *const RawAttachment,- count: usize,- ) -> bool;- fn web_bindings_message_port_transport_read_messages(- transport: *mut c_void,- records: *mut c_void,- append: unsafe extern "C" fn(*mut c_void, ak::Span<'_, u8>, *const RawAttachment, usize) -> bool,- ) -> bool;-}--/// The rights of one end of an IPC transport, which this owns until a data holder carries them to another agent, or a-/// transport takes them.-pub(crate) struct TransportHandle {- attachments: Vec<Attachment>,-}--impl TransportHandle {- /// # Safety- ///- /// `handle` must be a handle that LibWeb hands over.- pub(crate) unsafe fn from_raw(handle: *mut c_void) -> Self {- let mut payload = None;- // SAFETY: The call takes the native handle and fills the lent payload slot.- unsafe {- web_structured_serialize_transfer_handle_take(handle, (&raw mut payload).cast(), TransferPayload::receive);- };- let payload: TransferPayload = payload.expect("C++ hands over the handle's payload");- let mut decoder = Decoder::new(&payload.bytes, payload.attachments);- let handle = Self::decode(&mut decoder).expect("a native handle has the transport's rights");- assert!(decoder.is_at_end() && decoder.remaining_attachments() == 0);- handle- }-- pub(crate) fn encode_into(self, encoder: &mut Encoder) {- append_attachments(encoder, self.attachments);- }-- pub(crate) fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {- let count = if cfg!(target_vendor = "apple") { 2 } else { 1 };- if decoder.remaining_attachments() < count {- return Err(DecodeError::MissingAttachment);- }- let mut attachments = Vec::with_capacity(count);- for index in 0..count {- let attachment = decoder.take_attachment()?;- #[cfg(target_vendor = "apple")]- let attachment = {- use libipc_rust::mach::{- MACH_MSG_TYPE_MOVE_RECEIVE, MACH_MSG_TYPE_MOVE_SEND, MACH_PORT_DEAD, MACH_PORT_NULL,- };- let (port, disposition) = attachment.into_mach_port();- let expected = if index == 0 {- MACH_MSG_TYPE_MOVE_RECEIVE- } else {- MACH_MSG_TYPE_MOVE_SEND- };- if disposition != expected- || port.name() == MACH_PORT_NULL- || (index == 0 && port.name() == MACH_PORT_DEAD)- {- return Err(DecodeError::InvalidValue("invalid transport handle right"));- }- Attachment::from_mach_port(port, disposition)- };- #[cfg(not(target_vendor = "apple"))]- let _ = index;- attachments.push(attachment);- }- 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| {- // SAFETY: The call takes every right, and LibWeb hands over the transport.- unsafe {- MessagePortTransport::from_raw(web_structured_serialize_transfer_handle_create_transport(- bytes,- attachments.as_ptr(),- attachments.len(),- ))- }- })- }-}--/// 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 {- No,- Yes,-}--/// The read hook of a transport: its steps, and the state they run with.-struct ReadHook<S> {- state: 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>>,-}--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))- }- }-- /// # 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.- unsafe {- TransportHandle::from_raw(web_bindings_message_port_transport_release_for_transfer(- self.raw.as_ptr(),- ))- }- }-- /// 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 {- let mut encoder = Encoder::new();- TransferRecord::encode_into(record, vm, &mut encoder).expect("a message record encodes");- let (bytes, attachments) = encoder.finish();- TransferPayload { 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(- self.raw.as_ptr(),- bytes,- attachments.as_ptr(),- attachments.len(),- )- }- })- }-- /// 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 {- unsafe extern "C" fn append(- context: *mut c_void,- bytes: ak::Span<'_, u8>,- attachments: *const RawAttachment,- count: usize,- ) -> bool {- // SAFETY: The read lends its VM, rooted result list and bytes, and hands over every attachment.- let (vm, records) = unsafe { &*context.cast::<(&Vm, &MarkedVec<'_, TransferRecordRef>)>() };- let attachments = unsafe { RawAttachment::take_all(attachments, count) };- let mut decoder = Decoder::new(bytes.as_slice(), attachments);- match TransferRecord::decode(vm, &mut decoder) {- Ok(record) => {- records.push(record);- true- }- Err(error) => {- eprintln!("Failed to decode a MessagePort message: {error:?}");- false- }- }- }- let mut context = (vm, records);- // SAFETY: This owns the transport, and lends the records for the call.- let should_shutdown = unsafe {- web_bindings_message_port_transport_read_messages(self.raw.as_ptr(), (&raw mut context).cast(), append)- };- if should_shutdown {- ShouldShutdown::Yes- } else {- ShouldShutdown::No- }- }-}--impl Drop for MessagePortTransport {- 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()) };- }-}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs b/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rsindex 292d2dc3b7c..1b460caf9e5 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs@@ -9,12 +9,14 @@//! MessagePort, https://html.spec.whatwg.org/multipage/web-messaging.html#message-ports+use core::any::Any;use core::cell::{Cell, RefCell};use core::ffi::c_void;use core::ptr::NonNull;use std::collections::VecDeque;use ak::Utf16String;+use libipc_rust::{Attachment, DecodeError, Decoder, Encoder};use libjs_rust::api::{CellRoot, DeferGc, EmbedderCell, Gc, GcRefCell, GcWeak, MarkedVec, Object, Realm, Trace, Value, Vm,is_host_instance_of,@@ -26,8 +28,10 @@ use crate::bindings::interface::{};use crate::bindings::promise::{TaskSource, queue_a_global_task};use crate::bindings::structured_data::{TransferDataReader, TransferDataWriter, Transferable};-use crate::bindings::transport::{MessagePortTransport, ShouldShutdown};use crate::bindings::{CallContext, Exception, WebIdlResult};+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::{structured_deserialize_with_transfer, structured_serialize_with_transfer};@@ -730,3 +734,270 @@ impl Transferable for MessagePort {Ok(value)}}++unsafe extern "C" {+ fn web_bindings_transport_handle_take(handle: *mut c_void, context: *mut c_void, receive: ReceivePayload);+ fn web_bindings_transport_handle_create_transport(+ bytes: ak::Span<'_, u8>,+ attachments: *const RawAttachment,+ 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_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(+ transport: *mut c_void,+ state: *mut c_void,+ steps: unsafe extern "C" fn(*mut c_void),+ );+ fn web_bindings_message_port_transport_is_open(transport: *mut c_void) -> bool;+ fn web_bindings_message_port_transport_close(transport: *mut c_void);+ fn web_bindings_message_port_transport_close_after_sending_all_pending_messages(transport: *mut c_void);+ fn web_bindings_message_port_transport_send(+ transport: *mut c_void,+ bytes: ak::Span<'_, u8>,+ attachments: *const RawAttachment,+ count: usize,+ ) -> bool;+ fn web_bindings_message_port_transport_read_messages(+ transport: *mut c_void,+ records: *mut c_void,+ append: unsafe extern "C" fn(*mut c_void, ak::Span<'_, u8>, *const RawAttachment, usize) -> bool,+ ) -> bool;+}++/// The rights of one end of an IPC transport, which this owns until a data holder carries them to another agent, or a+/// transport takes them.+pub(crate) struct TransportHandle {+ attachments: Vec<Attachment>,+}++impl TransportHandle {+ /// # Safety+ ///+ /// `handle` must be a handle that LibWeb hands over.+ pub(crate) unsafe fn from_raw(handle: *mut c_void) -> Self {+ let mut payload = None;+ // SAFETY: The call takes the native handle and fills the lent payload slot.+ unsafe {+ web_bindings_transport_handle_take(handle, (&raw mut payload).cast(), TransferPayload::receive);+ };+ let payload: TransferPayload = payload.expect("C++ hands over the handle's payload");+ let mut decoder = Decoder::new(&payload.bytes, payload.attachments);+ let handle = Self::decode(&mut decoder).expect("a native handle has the transport's rights");+ assert!(decoder.is_at_end() && decoder.remaining_attachments() == 0);+ handle+ }++ pub(crate) fn encode_into(self, encoder: &mut Encoder) {+ append_attachments(encoder, self.attachments);+ }++ pub(crate) fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ let count = if cfg!(target_vendor = "apple") { 2 } else { 1 };+ if decoder.remaining_attachments() < count {+ return Err(DecodeError::MissingAttachment);+ }+ let mut attachments = Vec::with_capacity(count);+ for index in 0..count {+ let attachment = decoder.take_attachment()?;+ #[cfg(target_vendor = "apple")]+ let attachment = {+ use libipc_rust::mach::{+ MACH_MSG_TYPE_MOVE_RECEIVE, MACH_MSG_TYPE_MOVE_SEND, MACH_PORT_DEAD, MACH_PORT_NULL,+ };+ let (port, disposition) = attachment.into_mach_port();+ let expected = if index == 0 {+ MACH_MSG_TYPE_MOVE_RECEIVE+ } else {+ MACH_MSG_TYPE_MOVE_SEND+ };+ if disposition != expected+ || port.name() == MACH_PORT_NULL+ || (index == 0 && port.name() == MACH_PORT_DEAD)+ {+ return Err(DecodeError::InvalidValue("invalid transport handle right"));+ }+ Attachment::from_mach_port(port, disposition)+ };+ #[cfg(not(target_vendor = "apple"))]+ let _ = index;+ attachments.push(attachment);+ }+ 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| {+ // SAFETY: The call takes every right, and LibWeb hands over the transport.+ unsafe {+ MessagePortTransport::from_raw(web_bindings_transport_handle_create_transport(+ bytes,+ attachments.as_ptr(),+ attachments.len(),+ ))+ }+ })+ }+}++/// 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 {+ No,+ Yes,+}++/// The read hook of a transport: its steps, and the state they run with.+struct ReadHook<S> {+ state: 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>>,+}++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))+ }+ }++ /// # 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.+ unsafe {+ TransportHandle::from_raw(web_bindings_message_port_transport_release_for_transfer(+ self.raw.as_ptr(),+ ))+ }+ }++ /// 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 {+ let mut encoder = Encoder::new();+ TransferRecord::encode_into(record, vm, &mut encoder).expect("a message record encodes");+ let (bytes, attachments) = encoder.finish();+ TransferPayload { 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(+ self.raw.as_ptr(),+ bytes,+ attachments.as_ptr(),+ attachments.len(),+ )+ }+ })+ }++ /// 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 {+ unsafe extern "C" fn append(+ context: *mut c_void,+ bytes: ak::Span<'_, u8>,+ attachments: *const RawAttachment,+ count: usize,+ ) -> bool {+ // SAFETY: The read lends its VM, rooted result list and bytes, and hands over every attachment.+ let (vm, records) = unsafe { &*context.cast::<(&Vm, &MarkedVec<'_, TransferRecordRef>)>() };+ let attachments = unsafe { RawAttachment::take_all(attachments, count) };+ let mut decoder = Decoder::new(bytes.as_slice(), attachments);+ match TransferRecord::decode(vm, &mut decoder) {+ Ok(record) => {+ records.push(record);+ true+ }+ Err(error) => {+ eprintln!("Failed to decode a MessagePort message: {error:?}");+ false+ }+ }+ }+ let mut context = (vm, records);+ // SAFETY: This owns the transport, and lends the records for the call.+ let should_shutdown = unsafe {+ web_bindings_message_port_transport_read_messages(self.raw.as_ptr(), (&raw mut context).cast(), append)+ };+ if should_shutdown {+ ShouldShutdown::Yes+ } else {+ ShouldShutdown::No+ }+ }+}++impl Drop for MessagePortTransport {+ 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()) };+ }+}diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cppindex b071bd05c01..8af342bca37 100644--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp@@ -4,8 +4,6 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibIPC/Transport.h>-#include <LibIPC/TransportHandle.h>#include <LibJS/HostClassBuilder.h>#include <LibJS/Runtime/HostObject.h>#include <LibJS/Runtime/Realm.h>@@ -112,13 +110,6 @@ void web_bindings_with_temporary_execution_context(void* realm, bool callbacks_ebool web_bindings_object_implements_interface(JSObject* object, u16 interface_name);JSObject* web_bindings_create_dom_exception(void* realm, ReadonlyBytes name, FlatPtr message);bool web_bindings_extract_an_origin(JSObject* object, void* ctx, void (*on_origin)(void*, URL::FFI::FfiOrigin const*));-IPC::Transport* web_bindings_message_port_transport_create_paired(IPC::TransportHandle** out_remote_handle);-void web_bindings_message_port_transport_destroy(IPC::Transport*);-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*);-void web_bindings_message_port_transport_close(IPC::Transport*);-void web_bindings_message_port_transport_close_after_sending_all_pending_messages(IPC::Transport*);void* web_css_wrap_object(void* realm, void* cell);void* web_css_realm_document(void* realm);@@ -286,44 +277,6 @@ bool web_bindings_extract_an_origin(JSObject* object, void* ctx, void (*on_origireturn true;}-IPC::Transport* web_bindings_message_port_transport_create_paired(IPC::TransportHandle** out_remote_handle)-{- auto paired = MUST(IPC::Transport::create_paired());- *out_remote_handle = new IPC::TransportHandle(move(paired.remote_handle));- return paired.local.leak_ptr();-}--void web_bindings_message_port_transport_destroy(IPC::Transport* transport)-{- delete transport;-}--// 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)-{- return new IPC::TransportHandle(MUST(transport->release_for_transfer()));-}--void web_bindings_message_port_transport_set_up_read_hook(IPC::Transport* transport, void* state, void (*steps)(void*))-{- transport->set_up_read_hook([state, steps] { steps(state); });-}--bool web_bindings_message_port_transport_is_open(IPC::Transport* transport)-{- return transport->is_open();-}--void web_bindings_message_port_transport_close(IPC::Transport* transport)-{- transport->close();-}--void web_bindings_message_port_transport_close_after_sending_all_pending_messages(IPC::Transport* transport)-{- transport->close_after_sending_all_pending_messages();-}-JSObject* web_bindings_rejected_promise(void* current_realm, JSValue this_value, JSValue reason){auto& realm = *static_cast<JS::Realm*>(current_realm);diff --git a/Libraries/LibWeb/HTML/MessagePort.cpp b/Libraries/LibWeb/HTML/MessagePort.cppindex 4477a3a3acc..896d901c2d1 100644--- a/Libraries/LibWeb/HTML/MessagePort.cpp+++ b/Libraries/LibWeb/HTML/MessagePort.cpp@@ -6,6 +6,11 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/MemoryStream.h>+#include <LibIPC/Decoder.h>+#include <LibIPC/Encoder.h>+#include <LibIPC/Transport.h>+#include <LibIPC/TransportHandle.h>#include <LibJS/HostClassBuilder.h>#include <LibJS/Runtime/Realm.h>#include <LibJS/Runtime/VM.h>@@ -31,6 +36,19 @@ 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_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*);+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*);+void web_bindings_message_port_transport_close(IPC::Transport*);+void web_bindings_message_port_transport_close_after_sending_all_pending_messages(IPC::Transport*);+bool web_bindings_message_port_transport_send(IPC::Transport*, ReadonlyBytes, TransferAttachment const*, size_t);+bool web_bindings_message_port_transport_read_messages(IPC::Transport*, void*, bool (*)(void*, ReadonlyBytes, TransferAttachment const*, size_t));+void web_bindings_transport_handle_take(IPC::TransportHandle*, void*, void (*)(void*, ReadonlyBytes, TransferAttachment const*, size_t));+IPC::Transport* web_bindings_transport_handle_create_transport(ReadonlyBytes, TransferAttachment const*, size_t);}static JSVM* vm_abi()@@ -113,4 +131,91 @@ void MessagePort::fail_next_transfer_for_testing()web_rust_message_port_fail_next_transfer_for_testing(this);}+IPC::Transport* web_bindings_message_port_transport_create_paired(IPC::TransportHandle** out_remote_handle)+{+ auto paired = MUST(IPC::Transport::create_paired());+ *out_remote_handle = new IPC::TransportHandle(move(paired.remote_handle));+ return paired.local.leak_ptr();+}++void web_bindings_message_port_transport_destroy(IPC::Transport* transport)+{+ delete transport;+}++// 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)+{+ return new IPC::TransportHandle(MUST(transport->release_for_transfer()));+}++void web_bindings_message_port_transport_set_up_read_hook(IPC::Transport* transport, void* state, void (*steps)(void*))+{+ transport->set_up_read_hook([state, steps] { steps(state); });+}++bool web_bindings_message_port_transport_is_open(IPC::Transport* transport)+{+ return transport->is_open();+}++void web_bindings_message_port_transport_close(IPC::Transport* transport)+{+ transport->close();+}++void web_bindings_message_port_transport_close_after_sending_all_pending_messages(IPC::Transport* transport)+{+ transport->close_after_sending_all_pending_messages();+}++void web_bindings_transport_handle_take(IPC::TransportHandle* handle, void* context, void (*receive)(void*, ReadonlyBytes, TransferAttachment const*, size_t))+{+ auto owner = adopt_own(*handle);+ IPC::MessageBuffer buffer;+ IPC::Encoder encoder(buffer);+ MUST(encoder.encode(*owner));+ auto attachments = release_transfer_attachments(buffer.take_attachments());+ receive(context, buffer.data().span(), attachments.data(), attachments.size());+}++IPC::Transport* web_bindings_transport_handle_create_transport(ReadonlyBytes bytes, TransferAttachment const* attachments, size_t count)+{+ FixedMemoryStream stream(bytes);+ Queue<IPC::Attachment> queue;+ for (auto& attachment : adopt_transfer_attachments(attachments, count))+ queue.enqueue(move(attachment));+ IPC::Decoder decoder(stream, queue);+ auto handle = MUST(decoder.decode<IPC::TransportHandle>());+ return MUST(handle.create_transport()).leak_ptr();+}++bool web_bindings_message_port_transport_send(IPC::Transport* transport, ReadonlyBytes bytes, TransferAttachment const* attachments, size_t count)+{+ IPC::MessageDataType data;+ MUST(data.try_append(bytes.data(), bytes.size()));+ IPC::MessageBuffer buffer { move(data), adopt_transfer_attachments(attachments, count) };+ if (auto result = buffer.transfer_message(*transport); result.is_error()) {+ dbgln("Failed to post message: {}", result.error());+ return false;+ }+ return true;+}++bool web_bindings_message_port_transport_read_messages(IPC::Transport* transport, void* context, bool (*receive)(void*, ReadonlyBytes, TransferAttachment const*, size_t))+{+ bool failed_to_decode = false;+ auto should_shutdown = transport->read_as_many_messages_as_possible_without_blocking([&](auto&& message) {+ // The peer is treated as gone after a malformed record. Later messages still release all their attachments.+ if (failed_to_decode)+ return;+ Vector<IPC::Attachment> attachments;+ while (!message.attachments.is_empty())+ attachments.append(message.attachments.dequeue());+ auto raw_attachments = release_transfer_attachments(move(attachments));+ failed_to_decode = !receive(context, message.bytes.bytes(), raw_attachments.data(), raw_attachments.size());+ });+ return failed_to_decode || should_shutdown == IPC::Transport::ShouldShutdown::Yes;+}+}diff --git a/Libraries/LibWeb/HTML/StructuredSerialize.h b/Libraries/LibWeb/HTML/StructuredSerialize.hindex dbf8b90dc0b..c1a46acefd5 100644--- a/Libraries/LibWeb/HTML/StructuredSerialize.h+++ b/Libraries/LibWeb/HTML/StructuredSerialize.h@@ -35,6 +35,15 @@ class HostObject;namespace Web::HTML {+// A Mach port name and its disposition on Apple, and a descriptor elsewhere.+struct TransferAttachment {+ int value;+ u32 disposition;+};++Vector<IPC::Attachment> adopt_transfer_attachments(TransferAttachment const*, size_t count);+Vector<TransferAttachment> release_transfer_attachments(Vector<IPC::Attachment>);+struct StructuredSerializeOptions {GC::RootVector<GC::Ref<JS::Object>> transfer;};diff --git a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cppindex d8f1d1bc5c1..7adb5899818 100644--- a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp+++ b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp@@ -34,14 +34,11 @@using namespace Web;using namespace Web::HTML;-// A Mach port name and its disposition on Apple, and a descriptor elsewhere.-struct TransferAttachment {- int value;- u32 disposition;-};using ReceiveTransferPayload = void (*)(void*, ReadonlyBytes, TransferAttachment const*, size_t);-static Vector<IPC::Attachment> adopt_attachments(TransferAttachment const* raw, size_t count)+namespace Web::HTML {++Vector<IPC::Attachment> adopt_transfer_attachments(TransferAttachment const* raw, size_t count){Vector<IPC::Attachment> attachments;for (size_t i = 0; i < count; ++i) {@@ -60,8 +57,7 @@ static Vector<IPC::Attachment> adopt_attachments(TransferAttachment const* raw,return attachments;}-template<typename Receive>-static auto hand_over_payload(ReadonlyBytes bytes, Vector<IPC::Attachment> attachments, void* context, Receive receive)+Vector<TransferAttachment> release_transfer_attachments(Vector<IPC::Attachment> attachments){Vector<TransferAttachment> raw;for (auto& attachment : attachments) {@@ -72,7 +68,9 @@ static auto hand_over_payload(ReadonlyBytes bytes, Vector<IPC::Attachment> attacraw.append({ attachment.to_fd(), 0 });#endif}- return receive(context, bytes, raw.data(), raw.size());+ return raw;+}+}extern "C" {@@ -96,11 +94,7 @@ void web_structured_serialize_image_bitmap_pixels_destroy(ImageBitmapSharedPixelTransferDataEncoder* web_structured_serialize_transfer_data_holder_create(ReadonlyBytes, TransferAttachment const*, size_t);void web_structured_serialize_transfer_data_holder_take(TransferDataEncoder*, void*, ReceiveTransferPayload);-void web_structured_serialize_transfer_handle_take(IPC::TransportHandle*, void*, ReceiveTransferPayload);-IPC::Transport* web_structured_serialize_transfer_handle_create_transport(ReadonlyBytes, TransferAttachment const*, size_t);bool web_structured_serialize_validate_shared_memory(int, size_t);-bool web_bindings_message_port_transport_send(IPC::Transport*, ReadonlyBytes, TransferAttachment const*, size_t);-bool web_bindings_message_port_transport_read_messages(IPC::Transport*, void*, bool (*)(void*, ReadonlyBytes, TransferAttachment const*, size_t));SerializedTransferRecord* web_structured_serialize_transfer_record_create(ReadonlyBytes, JSObject* const*, size_t, int const*, size_t const*, size_t, TransferDataEncoder* const*, size_t);void web_structured_serialize_transfer_record_destroy(SerializedTransferRecord*);void web_structured_serialize_transfer_record_take(SerializedTransferRecord*, void*, void (*)(void*, ReadonlyBytes, JSObject* const*, size_t, int const*, size_t const*, size_t), void (*)(void*, TransferDataEncoder*));@@ -224,34 +218,15 @@ TransferDataEncoder* web_structured_serialize_transfer_data_holder_create(Readon{IPC::MessageDataType data;MUST(data.try_append(bytes.data(), bytes.size()));- return new TransferDataEncoder(IPC::MessageBuffer { move(data), adopt_attachments(attachments, count) });+ return new TransferDataEncoder(IPC::MessageBuffer { move(data), adopt_transfer_attachments(attachments, count) });}void web_structured_serialize_transfer_data_holder_take(TransferDataEncoder* holder, void* context, ReceiveTransferPayload receive){auto owner = adopt_own(*holder);auto buffer = owner->take_buffer();- hand_over_payload(buffer.data().span(), buffer.take_attachments(), context, receive);-}--void web_structured_serialize_transfer_handle_take(IPC::TransportHandle* handle, void* context, ReceiveTransferPayload receive)-{- auto owner = adopt_own(*handle);- IPC::MessageBuffer buffer;- IPC::Encoder encoder(buffer);- MUST(encoder.encode(*owner));- hand_over_payload(buffer.data().span(), buffer.take_attachments(), context, receive);-}--IPC::Transport* web_structured_serialize_transfer_handle_create_transport(ReadonlyBytes bytes, TransferAttachment const* attachments, size_t count)-{- FixedMemoryStream stream(bytes);- Queue<IPC::Attachment> queue;- for (auto& attachment : adopt_attachments(attachments, count))- queue.enqueue(move(attachment));- IPC::Decoder decoder(stream, queue);- auto handle = MUST(decoder.decode<IPC::TransportHandle>());- return MUST(handle.create_transport()).leak_ptr();+ auto attachments = release_transfer_attachments(buffer.take_attachments());+ receive(context, buffer.data().span(), attachments.data(), attachments.size());}bool web_structured_serialize_validate_shared_memory(int descriptor, size_t size)@@ -265,33 +240,6 @@ bool web_structured_serialize_validate_shared_memory(int descriptor, size_t sizereturn !buffer.value().validate_backing_size().is_error();}-bool web_bindings_message_port_transport_send(IPC::Transport* transport, ReadonlyBytes bytes, TransferAttachment const* attachments, size_t count)-{- IPC::MessageDataType data;- MUST(data.try_append(bytes.data(), bytes.size()));- IPC::MessageBuffer buffer { move(data), adopt_attachments(attachments, count) };- if (auto result = buffer.transfer_message(*transport); result.is_error()) {- dbgln("Failed to post message: {}", result.error());- return false;- }- return true;-}--bool web_bindings_message_port_transport_read_messages(IPC::Transport* transport, void* context, bool (*receive)(void*, ReadonlyBytes, TransferAttachment const*, size_t))-{- bool failed_to_decode = false;- auto should_shutdown = transport->read_as_many_messages_as_possible_without_blocking([&](auto&& message) {- // The peer is treated as gone after a malformed record. Later messages still release all their attachments.- if (failed_to_decode)- return;- Vector<IPC::Attachment> attachments;- while (!message.attachments.is_empty())- attachments.append(message.attachments.dequeue());- failed_to_decode = !hand_over_payload(message.bytes.bytes(), move(attachments), context, receive);- });- return failed_to_decode || should_shutdown == IPC::Transport::ShouldShutdown::Yes;-}-// Takes over the descriptors and the data holders.SerializedTransferRecord* web_structured_serialize_transfer_record_create(ReadonlyBytes data, JSObject* const* shared_array_buffers, size_t shared_array_buffer_count, int const* shared_memory, size_t const* sizes, size_t shared_memory_count, TransferDataEncoder* const* holders, size_t holder_count){