Truly independent web browser
LibWeb: Own transfer payloads and attachments in Rust
Shannon Booth18cd7fa9a469
diff --git a/Libraries/LibJS/Rust/src/api.rs b/Libraries/LibJS/Rust/src/api.rsindex 80d94c8a774..ada14baba6a 100644--- a/Libraries/LibJS/Rust/src/api.rs+++ b/Libraries/LibJS/Rust/src/api.rs@@ -21,7 +21,8 @@ pub use crate::gc::foreign::ForeignCellSlot;pub use crate::gc::gc_ref_cell::{GcRefCell, GcRefMut};pub use crate::gc::root::{CellRoot, MarkedVec, Root};pub use crate::gc::shared_memory::{- AsSharedMemory, OwnedSharedMemory, borrowed_from_raw_descriptor, into_raw_descriptor, raw_descriptor,+ AsSharedMemory, OwnedSharedMemory, borrowed_from_raw_descriptor, into_raw_descriptor, owned_from_raw_descriptor,+ raw_descriptor,};pub use crate::gc::visitor::{Trace, Visitor};pub use crate::gc::weak::GcWeak;diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rsindex 4b255965305..118857bed95 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs@@ -10,7 +10,7 @@//!//! The algorithms of crate::html::structured_serialize call the steps of such an interface directly through the//! generated Rust dispatch. Those steps write and read the record of the algorithm.-//! The algorithms run the transfer steps and the transfer-receiving steps themselves, which write and read the C+++//! The algorithms run the transfer steps and the transfer-receiving steps themselves, which write and read the Rust//! data holders of the transfer. Unlike an object of an interface implemented in C++, which is created before its//! deserialization steps fill it in, an object of an interface implemented in Rust is what its deserialization steps//! and its transfer-receiving steps return.@@ -21,18 +21,17 @@ use core::ptr::NonNull;use ak::Utf16String;use libipc_rust::{Decode, DecodeError, Decoder, Encode};-use libjs_rust::api::{Gc, MarkedVec, Object, RawNativeFunctionResult, Realm, Value, Vm};+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::structured_serialize::cpp::{- ImageBitmapSharedPixels, OwnedSerializedTransferRecord, SharedPixelBuffers, TransferDataDecoder,- data_clone_error_from_serialization_error,+ ImageBitmapSharedPixels, SharedPixelBuffers, data_clone_error_from_serialization_error,};use crate::html::structured_serialize::reader::StructuredSerializeReader;-use crate::html::structured_serialize::transfer_data_holder::TransferDataHolder;+use crate::html::structured_serialize::transfer_data_holder::{TransferDataHolder, TransferPayload};use crate::html::structured_serialize::transfer_record::{TransferRecord, TransferRecordRef};use crate::html::structured_serialize::writer::StructuredSerializeWriter;use crate::html::structured_serialize::{@@ -40,25 +39,6 @@ use crate::html::structured_serialize::{structured_deserialize_with_transfer_internal, structured_serialize_with_transfer,};-unsafe extern "C" {- fn web_bindings_transfer_data_encode_records(data_holder: *mut c_void, records: *const *mut c_void, count: usize);- fn web_bindings_transfer_data_encode_transport_handle(data_holder: *mut c_void, handle: *mut c_void);- fn web_bindings_transfer_data_extend(data_holder: *mut c_void, holder: *mut c_void);- fn web_bindings_transfer_data_decode_records(- data_holder: *mut c_void,- realm: *mut c_void,- offset: &mut usize,- records: *mut c_void,- append: unsafe extern "C" fn(*mut c_void, *mut c_void),- ) -> RawNativeFunctionResult;- fn web_bindings_transfer_data_decode_transport_handle(- data_holder: *mut c_void,- realm: *mut c_void,- offset: &mut usize,- out_handle: &mut *mut c_void,- ) -> RawNativeFunctionResult;-}-/// The record of a structured serialization, which the serialization steps of an object write to, and the serialization/// that the sub-serializations of the steps run in.pub(crate) struct SerializationWriter<'a, 'memory> {@@ -284,27 +264,21 @@ impl<'a> TransferDataWriter<'a> {/// Writes the records of structured serializations with transfer, as a list.pub(crate) fn write_records(&mut self, cx: &CallContext, records: &[TransferRecordRef]) {- let carriers: Vec<_> = records- .iter()- .map(|&record| TransferRecord::into_cpp(record, cx.vm()))- .collect();- let records: Vec<*mut c_void> = carriers.iter().map(|record| record.record().as_raw()).collect();- // SAFETY: The carrier is live, and the call borrows the records.- unsafe {- web_bindings_transfer_data_encode_records(- self.data_holder.carrier().as_raw(),- records.as_ptr(),- records.len(),- );- }+ self.data_holder.with_encoder(|encoder| {+ encoder.encode_size(records.len())?;+ for &record in records {+ TransferRecord::encode_into(record, cx.vm(), encoder)?;+ }+ Ok(())+ });}/// 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) {- // SAFETY: The carrier is live, and the call borrows the handle.- unsafe {- web_bindings_transfer_data_encode_transport_handle(self.data_holder.carrier().as_raw(), handle.as_raw());- }+ 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@@ -312,8 +286,7 @@ impl<'a> TransferDataWriter<'a> {pub(crate) fn write_transferred_value(&mut self, cx: &CallContext, value: Value) -> WebIdlResult<()> {let record = structured_serialize_with_transfer(cx, value, &[value.as_object()])?;for holder in record.data_holders.borrow_mut().drain(..) {- // SAFETY: The outer carrier is live, and the call takes the nested holder.- unsafe { web_bindings_transfer_data_extend(self.data_holder.carrier().as_raw(), holder.into_raw()) };+ self.data_holder.extend(holder);}TransferRecord::discard(record);Ok(())@@ -321,44 +294,30 @@ impl<'a> TransferDataWriter<'a> {}/// The data holder of a received object, which its transfer-receiving steps read from, in the realm that the object is-/// created in. Rust reads its bytes, which an HTML::TransferDataDecoder that C++ lends holds, and C++ decodes the values-/// that have attachments at the offset that Rust has read to. What the steps read that the data holder does not hold-/// throws a "DataCloneError" DOMException.+/// created in. What the steps read that the data holder does not hold throws a "DataCloneError" DOMException.pub(crate) struct TransferDataReader<'a> {- decoder: TransferDataDecoder,- bytes: &'a [u8],- offset: usize,+ decoder: Decoder<'a>,realm: Gc<Realm>,shared_pixels: Option<&'a SharedPixelBuffers<'a>>,}impl<'a> TransferDataReader<'a> {- /// # Safety- ///- /// `decoder` must be lent for `'a`.- pub(crate) unsafe fn new(decoder: TransferDataDecoder, realm: Gc<Realm>) -> Self {+ pub(crate) fn new(payload: &'a mut TransferPayload, realm: Gc<Realm>) -> Self {Self {- decoder,- // SAFETY: The caller lends the decoder for 'a.- bytes: unsafe { decoder.bytes() },- offset: 0,+ decoder: Decoder::new(&payload.bytes, core::mem::take(&mut payload.attachments)),realm,shared_pixels: None,}}- /// # Safety- ///- /// The decoder must be lent for 'a, alongside the shared pixel context.- pub(crate) unsafe fn with_shared_pixels(- decoder: TransferDataDecoder,+ pub(crate) fn with_shared_pixels(+ payload: &'a mut TransferPayload,realm: Gc<Realm>,shared_pixels: &'a SharedPixelBuffers<'a>,) -> Self {- // SAFETY: The caller lends the decoder for 'a.Self {shared_pixels: Some(shared_pixels),- ..unsafe { Self::new(decoder, realm) }+ ..Self::new(payload, realm)}}@@ -373,17 +332,10 @@ impl<'a> TransferDataReader<'a> {self.realm}- /// The data holder as the C ABI of an interface's C++ class takes it.- pub(crate) fn as_raw(&self) -> *mut c_void {- self.decoder.as_raw()- }-fn decoded<T>(&mut self, read: impl FnOnce(&mut Decoder<'a>) -> Result<T, DecodeError>) -> WebIdlResult<T> {- let mut decoder = Decoder::new(&self.bytes[self.offset..], []);- let value = read(&mut decoder)- .map_err(|_| data_clone_error_from_serialization_error(self.realm, "Unable to decode transfer data"))?;- self.offset = self.bytes.len() - decoder.remaining_bytes();- Ok(value)+ read(&mut self.decoder).map_err(|error| {+ data_clone_error_from_serialization_error(self.realm, &format!("Unable to decode transfer data: {error:?}"))+ })}pub(crate) fn read<T: Decode>(&mut self) -> WebIdlResult<T> {@@ -404,43 +356,26 @@ impl<'a> TransferDataReader<'a> {/// Reads what TransferDataWriter::write_records() writes.pub(crate) fn read_records<'vm>(&mut self, vm: &'vm Vm) -> WebIdlResult<MarkedVec<'vm, TransferRecordRef>> {- unsafe extern "C" fn append(context: *mut c_void, record: *mut c_void) {- // SAFETY: read_records() lends its VM and rooted list; C++ hands the carrier over.- let (vm, records) = unsafe { &*context.cast::<(&Vm, &MarkedVec<'_, TransferRecordRef>)>() };- let carrier = unsafe { OwnedSerializedTransferRecord::from_raw(record) };- records.push(TransferRecord::from_cpp(vm, carrier.record()));- }let records = MarkedVec::new(vm);- let mut context = (vm, &records);- // SAFETY: The decoder, realm, context and rooted list live for the call.- unsafe {- web_bindings_transfer_data_decode_records(- self.as_raw(),- self.realm.as_ptr().cast(),- &mut self.offset,- (&raw mut context).cast(),- append,- )+ let result = self.decoded(|decoder| {+ let count = decoder.decode_size()?;+ for _ in 0..count {+ records.push(TransferRecord::decode(vm, decoder)?);+ }+ Ok(())+ });+ if let Err(exception) = result {+ for &record in records.values().iter() {+ TransferRecord::discard(record);+ }+ return Err(exception);}- .into_completion()?;Ok(records)}/// Reads what TransferDataWriter::write_transport_handle() writes.pub(crate) fn read_transport_handle(&mut self) -> WebIdlResult<TransportHandle> {- let mut handle = core::ptr::null_mut();- // SAFETY: The data holder is lent for the steps, and the realm is live.- unsafe {- web_bindings_transfer_data_decode_transport_handle(- self.as_raw(),- self.realm.as_ptr().cast(),- &mut self.offset,- &mut handle,- )- }- .into_completion()?;- // SAFETY: LibWeb hands over the handle it read.- Ok(unsafe { TransportHandle::from_raw(handle) })+ self.decoded(TransportHandle::decode)}/// ! StructuredDeserializeWithTransfer(dataHolder, the current Realm).[[Deserialized]] for whatdiff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/transport.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/transport.rsindex e963e8a48e7..58649ab0aad 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/transport.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/transport.rs@@ -13,12 +13,24 @@ use core::ffi::c_void;use core::ptr::NonNull;use crate::html::structured_serialize::cpp::OwnedSerializedTransferRecord;+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_bindings_transport_handle_destroy(handle: *mut c_void);- fn web_bindings_transport_handle_create_transport(handle: *mut c_void) -> *mut c_void;+ 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;@@ -38,33 +50,83 @@ unsafe extern "C" {) -> bool;}-/// A handle to one end of an IPC transport that this owns: an IPC::TransportHandle, which holds the rights of that end-/// until a data holder carries them to another agent, or a transport takes them.-pub(crate) struct TransportHandle(NonNull<c_void>);+/// 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 {- Self(NonNull::new(handle).expect("LibWeb hands over a handle"))+ 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 as_raw(&self) -> *mut c_void {- self.0.as_ptr()+ pub(crate) fn encode_into(self, encoder: &mut Encoder) {+ append_attachments(encoder, 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 {- // SAFETY: This owns the handle, and LibWeb hands over the transport.- unsafe { MessagePortTransport::from_raw(web_bindings_transport_handle_create_transport(self.0.as_ptr())) }+ 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 })}-}-impl Drop for TransportHandle {- fn drop(&mut self) {- // SAFETY: This owns the handle.- unsafe { web_bindings_transport_handle_destroy(self.0.as_ptr()) };+ /// 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(),+ ))+ }+ })}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rsindex 7347e850418..68e67ace2f2 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs@@ -34,9 +34,8 @@ use crate::bindings::interface::{Interface, Ref, cell_from_abi, cell_into_abi, ruse crate::bindings::structured_data::{TransferDataReader, TransferDataWriter, Transferable};use crate::dom::event::EventInit;use crate::html::structured_serialize::cpp::SerializedTransferRecord;-use crate::html::structured_serialize::cpp::TransferDataDecoder;use crate::html::structured_serialize::message_record::MessageRecord;-use crate::html::structured_serialize::transfer_data_holder::TransferDataHolder;+use crate::html::structured_serialize::transfer_data_holder::{TransferDataHolder, TransferPayload};use crate::html::structured_serialize::transfer_record::TransferRecord;use crate::storage_api::storage_area_mirror::StorageEndpointType;use crate::storage_api::storage_bottle::{obtain_a_local_storage_bottle_map, obtain_a_session_storage_bottle_map};@@ -372,7 +371,7 @@ 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.into_carrier().into_raw();+ *out_data_holder = data_holder.finish().into_cpp();}RawNativeFunctionResult::from_completion(result@@ -386,19 +385,17 @@ pub unsafe extern "C" fn web_rust_message_port_transfer_steps(////// # Safety///-/// `vm` must be the live VM, `realm` a live realm, and `data_holder` an HTML::TransferDataDecoder that C++ lends for-/// the call.+/// `vm` must be the live VM, `realm` a live realm, and `data_holder` an HTML::TransferDataEncoder that C++ hands over.#[unsafe(no_mangle)]pub unsafe extern "C" fn web_rust_message_port_transfer_receiving_steps(vm: *mut c_void,realm: *mut c_void,data_holder: *mut c_void,) -> RawNativeFunctionResult {- // SAFETY: The caller passes the live VM and a live realm, and lends the data holder for the call.- let ((vm, realm), decoder) = unsafe { (realm_arguments(vm, realm), TransferDataDecoder::from_raw(data_holder)) };+ // SAFETY: The caller passes the live VM and a live realm, and hands over the data holder.+ let ((vm, realm), mut payload) = unsafe { (realm_arguments(vm, realm), TransferPayload::from_cpp(data_holder)) };let mut cx = CallContext::new(vm, realm);- // SAFETY: The caller lends the data holder for the call.- let mut data_holder = unsafe { TransferDataReader::new(decoder, realm) };+ let mut data_holder = TransferDataReader::new(&mut payload, realm);let result = MessagePort::transfer_receiving_steps(&mut cx, &mut data_holder);RawNativeFunctionResult::from_completion(resultdiff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rsindex 59108c9cd34..b19ccd06965 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs@@ -55,11 +55,7 @@ unsafe extern "C" {) -> *mut c_void;fn web_structured_serialize_image_bitmap_pixels_destroy(image_bitmap_pixels: *mut c_void);- fn web_structured_serialize_transfer_data_holder_create() -> *mut c_void;- fn web_structured_serialize_transfer_data_holder_append(data_holder: *mut c_void, bytes: ak::Span<'_, u8>);- fn web_structured_serialize_transfer_data_holder_destroy(data_holder: *mut c_void);fn web_structured_serialize_transfer_record_destroy(record: *mut c_void);- fn web_structured_serialize_transfer_data_decoder_create(data_holder: *mut c_void) -> *mut c_void;fn web_structured_serialize_shared_pixels_create(descriptors: *const c_int,sizes: *const usize,@@ -67,8 +63,6 @@ unsafe extern "C" {) -> *mut c_void;fn web_structured_serialize_shared_pixels_destroy(buffers: *mut c_void);fn web_structured_serialize_transferred_values_append(transferred_values: *mut c_void, value: *mut c_void);- fn web_structured_serialize_transfer_data_decoder_bytes(decoder: *const c_void, bytes: &mut ak::Span<'static, u8>);- fn web_structured_serialize_transfer_data_decoder_destroy(decoder: *mut c_void);}fn object_into_abi<T>(object: Gc<T>) -> *mut c_void {@@ -278,54 +272,6 @@ impl Drop for ImageBitmapSharedPixels {}}-/// The C++ carrier of a data holder that this owns: an HTML::TransferDataEncoder, which the record of a transfer and-/// IPC carry, and which C++ encodes the values that have attachments into.-pub(crate) struct TransferDataCarrier(NonNull<c_void>);--impl TransferDataCarrier {- pub(crate) fn new() -> Self {- // SAFETY: LibWeb returns a new carrier, which this owns.- Self(- NonNull::new(unsafe { web_structured_serialize_transfer_data_holder_create() }).expect("LibWeb creates it"),- )- }-- /// # Safety- ///- /// The carrier must be handed over by C++.- pub(crate) unsafe fn from_raw(carrier: *mut c_void) -> Self {- Self(NonNull::new(carrier).expect("C++ hands over a carrier"))- }-- pub(crate) fn into_decoder(self) -> Option<OwnedTransferDataDecoder> {- // SAFETY: The call takes the carrier, including when it is empty.- NonNull::new(unsafe { web_structured_serialize_transfer_data_decoder_create(self.into_raw()) })- .map(|decoder| OwnedTransferDataDecoder(TransferDataDecoder(decoder)))- }-- pub(crate) fn as_raw(&self) -> *mut c_void {- self.0.as_ptr()- }-- /// Appends bytes that are already in IPC's encoding.- pub(crate) fn append(&self, bytes: &[u8]) {- // SAFETY: This owns the carrier, and the call borrows the bytes.- unsafe { web_structured_serialize_transfer_data_holder_append(self.0.as_ptr(), ak::Span::new(bytes)) };- }-- /// Hands the carrier over to LibWeb's C++ code, which owns it from then on.- pub(crate) fn into_raw(self) -> *mut c_void {- ManuallyDrop::new(self).0.as_ptr()- }-}--impl Drop for TransferDataCarrier {- fn drop(&mut self) {- // SAFETY: This owns the carrier.- unsafe { web_structured_serialize_transfer_data_holder_destroy(self.0.as_ptr()) };- }-}-/// An HTML::SerializedTransferRecord that C++ lends.#[derive(Clone, Copy)]pub(crate) struct SerializedTransferRecord(NonNull<c_void>);@@ -392,51 +338,6 @@ impl TransferredValues {}}-/// The decoder of a received data holder: an HTML::TransferDataDecoder that C++ lends.-#[derive(Clone, Copy)]-pub(crate) struct TransferDataDecoder(NonNull<c_void>);--impl TransferDataDecoder {- /// # Safety- ///- /// `decoder` must be a decoder that C++ lends while this is used.- pub(crate) unsafe fn from_raw(decoder: *mut c_void) -> Self {- Self(NonNull::new(decoder).expect("C++ lends a decoder"))- }-- pub(crate) fn as_raw(self) -> *mut c_void {- self.0.as_ptr()- }-- /// The bytes of the data holder, which it lends for as long as it is lent.- ///- /// # Safety- ///- /// The decoder must be lent for `'a`.- pub(crate) unsafe fn bytes<'a>(self) -> &'a [u8] {- let mut bytes = ak::Span::default();- // SAFETY: The decoder is lent for 'a, and its bytes with it.- unsafe { web_structured_serialize_transfer_data_decoder_bytes(self.0.as_ptr(), &mut bytes) };- bytes.as_slice()- }-}--/// A decoder of a received data holder that this owns.-pub(crate) struct OwnedTransferDataDecoder(TransferDataDecoder);--impl OwnedTransferDataDecoder {- pub(crate) fn decoder(&self) -> TransferDataDecoder {- self.0- }-}--impl Drop for OwnedTransferDataDecoder {- fn drop(&mut self) {- // SAFETY: This owns the decoder.- unsafe { web_structured_serialize_transfer_data_decoder_destroy(self.0.0.as_ptr()) };- }-}-/// The shared memory that the ImageBitmaps of a record share their pixels through, mapped when one needs it.pub(crate) struct SharedPixelBuffers<'a> {memory: &'a [SharedMemory],diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rsindex 1d18c624472..9d8b3323cd0 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs@@ -1829,7 +1829,7 @@ pub(crate) fn structured_serialize_with_transfer(}// 6. Append dataHolder to transferDataHolders.- transfer_data_holders.push(data_holder.into_carrier());+ transfer_data_holders.push(data_holder.finish());}// 6. Let result be { [[Serialized]]: serialized, [[TransferDataHolders]]: transferDataHolders, [[InterfaceNames]]: an empty ordered set, [[AgentCluster]]: null }.@@ -1881,14 +1881,13 @@ pub(crate) fn structured_deserialize_with_transfer<'vm>(// 5. For each transferDataHolder of serializeWithTransferResult.[[TransferDataHolders]]:let transfer_data_holders = core::mem::take(&mut *serialize_with_transfer_result.data_holders.borrow_mut());- for transfer_data_holder in transfer_data_holders {+ for mut transfer_data_holder in transfer_data_holders {// NB: The transfer writes no empty data holder.- let decoder = transfer_data_holder- .into_decoder()- .ok_or_else(|| data_clone_error("Empty transfer data holder"))?;- // SAFETY: The decoder lives for the loop body.+ if transfer_data_holder.bytes.is_empty() {+ return Err(data_clone_error("Empty transfer data holder"));+ }let mut data_holder =- unsafe { TransferDataReader::with_shared_pixels(decoder.decoder(), target_realm, &shared_pixels) };+ TransferDataReader::with_shared_pixels(&mut transfer_data_holder, target_realm, &shared_pixels);// 1. Let value be an uninitialized value.let value = structured_deserialize_with_transfer_internal(cx, &mut data_holder)?;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 6ae23a4293d..d26cd39d176 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@@ -4,48 +4,225 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The data holder of a transferred value, in the encoding of IPC, which only IPC carries. Rust writes its bytes. The-//! values that have attachments, like the end of a transport or the records of messages, C++ encodes into the holder's-//! carrier, after the bytes before them.+//! The data holders of the transfer steps and the transfer-receiving steps,+//! https://html.spec.whatwg.org/multipage/structured-data.html#transferable-objectsuse core::cell::RefCell;+use core::ffi::{c_int, c_void};+use libipc_rust::{Attachment, Decode, DecodeError, Decoder, Encode, EncodeError, Encoder};-use libipc_rust::{Encode, Encoder};+#[repr(C)]+pub(crate) struct RawAttachment {+ value: c_int,+ disposition: u32,+}++impl RawAttachment {+ /// # Safety+ ///+ /// The raw attachment must hand over one owned descriptor or Mach right.+ unsafe fn into_attachment(self) -> Attachment {+ #[cfg(target_vendor = "apple")]+ {+ use libipc_rust::mach::{+ MACH_MSG_TYPE_MAKE_SEND, MACH_MSG_TYPE_MAKE_SEND_ONCE, MACH_MSG_TYPE_MOVE_RECEIVE,+ MACH_MSG_TYPE_MOVE_SEND_ONCE, MachPort, PortRight,+ };+ let right = match self.disposition {+ MACH_MSG_TYPE_MOVE_RECEIVE | MACH_MSG_TYPE_MAKE_SEND | MACH_MSG_TYPE_MAKE_SEND_ONCE => {+ PortRight::Receive+ }+ MACH_MSG_TYPE_MOVE_SEND_ONCE => PortRight::SendOnce,+ _ => PortRight::Send,+ };+ Attachment::from_mach_port(MachPort::adopt(self.value as u32, right), self.disposition)+ }+ #[cfg(all(unix, not(target_vendor = "apple")))]+ {+ use std::os::fd::FromRawFd;+ Attachment::from(unsafe { std::os::fd::OwnedFd::from_raw_fd(self.value) })+ }+ #[cfg(windows)]+ {+ Attachment::from_descriptor(unsafe {+ libipc_rust::transport_windows::OwnedDescriptor::from_raw(self.value)+ })+ }+ }++ /// # Safety+ ///+ /// `raw` must point to `count` raw attachments, each of which hands over its descriptor or Mach right.+ pub(crate) unsafe fn take_all(raw: *const Self, count: usize) -> Vec<Attachment> {+ // SAFETY: The caller lends the raw attachments and hands over what each one names.+ unsafe { ak::slice_from_raw_parts(raw, count) }+ .iter()+ .map(|attachment| {+ let owned = Self {+ value: attachment.value,+ disposition: attachment.disposition,+ };+ unsafe { owned.into_attachment() }+ })+ .collect()+ }++ pub(crate) fn from_attachment(attachment: Attachment) -> Self {+ #[cfg(target_vendor = "apple")]+ {+ let (port, disposition) = attachment.into_mach_port();+ Self {+ value: core::mem::ManuallyDrop::new(port).name() as c_int,+ disposition,+ }+ }+ #[cfg(all(unix, not(target_vendor = "apple")))]+ {+ use std::os::fd::IntoRawFd;+ Self {+ value: attachment+ .into_fd()+ .expect("a Unix attachment is a descriptor")+ .into_raw_fd(),+ disposition: 0,+ }+ }+ #[cfg(windows)]+ {+ Self {+ value: attachment.into_descriptor().into_raw(),+ disposition: 0,+ }+ }+ }+}++pub(crate) type ReceivePayload = unsafe extern "C" fn(*mut c_void, ak::Span<'_, u8>, *const RawAttachment, usize);++unsafe extern "C" {+ fn web_structured_serialize_transfer_data_holder_create(+ bytes: ak::Span<'_, u8>,+ attachments: *const RawAttachment,+ count: usize,+ ) -> *mut c_void;+ fn web_structured_serialize_transfer_data_holder_take(+ holder: *mut c_void,+ context: *mut c_void,+ receive: ReceivePayload,+ );+}++pub(crate) fn append_attachments(encoder: &mut Encoder, attachments: Vec<Attachment>) {+ for attachment in attachments {+ encoder.append_attachment(attachment);+ }+}++pub(crate) struct TransferPayload {+ pub(crate) bytes: Vec<u8>,+ pub(crate) attachments: Vec<Attachment>,+}++impl TransferPayload {+ pub(crate) fn into_cpp(self) -> *mut c_void {+ self.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())+ }+ })+ }-use crate::html::structured_serialize::cpp::TransferDataCarrier;+ /// # Safety+ ///+ /// C++ must hand over the holder and its attachments.+ pub(crate) unsafe fn from_cpp(holder: *mut c_void) -> Self {+ 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")+ }++ pub(crate) unsafe extern "C" fn receive(+ context: *mut c_void,+ bytes: ak::Span<'_, u8>,+ attachments: *const RawAttachment,+ count: usize,+ ) {+ // 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,+ });+ };+ }-pub(crate) struct TransferDataHolder {- /// The bytes since the carrier last took them.- bytes: RefCell<Encoder>,- carrier: TransferDataCarrier,+ pub(crate) fn with_raw<R>(self, steps: impl FnOnce(ak::Span<'_, u8>, &[RawAttachment]) -> R) -> R {+ let attachments: Vec<_> = self+ .attachments+ .into_iter()+ .map(RawAttachment::from_attachment)+ .collect();+ steps(ak::Span::new(&self.bytes), &attachments)+ }}+impl Encode for TransferPayload {+ fn encode(&self, _: &mut Encoder) -> Result<(), EncodeError> {+ Err(EncodeError::InvalidValue(+ "a transfer payload must move its attachments",+ ))+ }++ fn encode_owned(self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ encoder.encode(self.bytes.as_slice())?;+ encoder.encode_size(self.attachments.len())?;+ append_attachments(encoder, self.attachments);+ Ok(())+ }+}++impl Decode for TransferPayload {+ const MIN_ENCODED_SIZE: usize = 8;++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ let bytes = decoder.decode::<Vec<u8>>()?;+ let count = decoder.decode::<u32>()? as usize;+ if count > decoder.remaining_attachments() {+ return Err(DecodeError::MissingAttachment);+ }+ let attachments = (0..count)+ .map(|_| decoder.take_attachment())+ .collect::<Result<_, _>>()?;+ Ok(Self { bytes, attachments })+ }+}++pub(crate) struct TransferDataHolder(RefCell<Encoder>);+impl TransferDataHolder {pub(crate) fn new() -> Self {- Self {- bytes: RefCell::new(Encoder::new()),- carrier: TransferDataCarrier::new(),- }+ Self(RefCell::new(Encoder::new()))}pub(crate) fn encode<T: Encode + ?Sized>(&self, value: &T) {- self.bytes- .borrow_mut()- .encode(value)- .expect("a data holder encodes what it is given");+ self.with_encoder(|encoder| encoder.encode(value));+ }++ 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");}- /// The carrier, with the bytes so far, for C++ to encode a value that has attachments into.- pub(crate) fn carrier(&self) -> &TransferDataCarrier {- let (bytes, attachments) = core::mem::take(&mut *self.bytes.borrow_mut()).finish();- debug_assert!(attachments.is_empty(), "C++ encodes the values that have attachments");- self.carrier.append(&bytes);- &self.carrier+ pub(crate) fn extend(&self, payload: TransferPayload) {+ let mut encoder = self.0.borrow_mut();+ encoder.append_bytes(&payload.bytes);+ append_attachments(&mut encoder, payload.attachments);}- /// The carrier, with every byte of the holder, which C++ takes over.- pub(crate) fn into_carrier(self) -> TransferDataCarrier {- self.carrier();- self.carrier+ pub(crate) fn finish(self) -> TransferPayload {+ let (bytes, attachments) = self.0.into_inner().finish();+ TransferPayload { bytes, attachments }}}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 23f20b5f251..e2035b0167c 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@@ -15,10 +15,15 @@ use libjs_rust::api::{ArrayBuffer, DeferGc, EmbedderCell, EmbedderClass, EmbedderValue, Gc, GcRefCell, Trace, Vm, into_raw_descriptor,};-use super::cpp::{OwnedSerializedTransferRecord, SerializedTransferRecord, TransferDataCarrier, objects_into_abi};-use super::message_record::MessageRecord;+use super::cpp::{OwnedSerializedTransferRecord, SerializedTransferRecord, objects_into_abi};+use super::message_record::{MessageRecord, SharedMemory};+use super::transfer_data_holder::TransferPayload;+use libipc_rust::wire::File;+use libipc_rust::{DecodeError, Decoder, EncodeError, Encoder};+use libjs_rust::api::{AsSharedMemory, owned_from_raw_descriptor, raw_descriptor};unsafe extern "C" {+ fn web_structured_serialize_validate_shared_memory(descriptor: c_int, size: usize) -> bool;fn web_structured_serialize_transfer_record_create(bytes: ak::Span<'_, u8>,array_buffers: *const *mut c_void,@@ -50,7 +55,7 @@ unsafe extern "C" {pub(crate) struct TransferRecord {pub(crate) serialized: GcRefCell<Option<MessageRecord>>,#[gc(untraced)]- pub(crate) data_holders: RefCell<Vec<TransferDataCarrier>>,+ pub(crate) data_holders: RefCell<Vec<TransferPayload>>,}static TRANSFER_RECORD_CLASS: EmbedderClass<TransferRecord> = EmbedderClass::new("SerializedTransferRecord");@@ -70,7 +75,7 @@ impl TransferRecord {pub(crate) fn create(vm: &Vm,build: impl FnOnce(&DeferGc<'_>) -> MessageRecord,- data_holders: Vec<TransferDataCarrier>,+ data_holders: Vec<TransferPayload>,) -> TransferRecordRef {TRANSFER_RECORD_CLASS.allocate(vm, |defer_gc| Self {serialized: GcRefCell::new(Some(build(defer_gc))),@@ -91,7 +96,7 @@ impl TransferRecord {.data_holders.borrow_mut().drain(..)- .map(TransferDataCarrier::into_raw)+ .map(TransferPayload::into_cpp).collect();// SAFETY: The call borrows bytes and live buffers, and takes every descriptor and holder. GC remains// deferred until the C++ carrier roots the buffer aliases.@@ -110,11 +115,82 @@ impl TransferRecord {})}+ /// The IPC encoding of a SerializedTransferRecord, without its same-process SharedArrayBuffers.+ pub(crate) fn encode_into(record: TransferRecordRef, vm: &Vm, encoder: &mut Encoder) -> Result<(), EncodeError> {+ DeferGc::scope(vm, |_| {+ let 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 message.shared_memory {+ encoder.encode(&true)?;+ encoder.encode(&(memory.size as u64))?;+ let raw = into_raw_descriptor(memory.descriptor);+ #[cfg(unix)]+ let descriptor = unsafe { std::os::fd::FromRawFd::from_raw_fd(raw) };+ #[cfg(windows)]+ let descriptor = unsafe { libipc_rust::transport_windows::OwnedDescriptor::from_raw(raw) };+ encoder.encode_owned(File(descriptor))?;+ }+ 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);+ }+ }+ Ok(Self::create(+ vm,+ |_| MessageRecord {+ bytes,+ shared_array_buffers: Vec::new(),+ shared_memory,+ },+ holders,+ ))+ }+pub(crate) fn from_cpp(vm: &Vm, record: SerializedTransferRecord) -> TransferRecordRef {struct Received<'a> {defer_gc: &'a DeferGc<'a>,message: Option<MessageRecord>,- holders: Vec<TransferDataCarrier>,+ holders: Vec<TransferPayload>,}unsafe extern "C" fn receive(@@ -154,7 +230,7 @@ impl TransferRecord {unsafe {(*context.cast::<Received<'_>>()).holders- .push(TransferDataCarrier::from_raw(holder));+ .push(TransferPayload::from_cpp(holder));};}diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cppindex 76a9ab8f39d..75b61c06e90 100644--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp@@ -112,13 +112,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*));-void web_bindings_transfer_data_encode_records(HTML::TransferDataEncoder*, HTML::SerializedTransferRecord const* const*, size_t count);-void web_bindings_transfer_data_encode_transport_handle(HTML::TransferDataEncoder*, IPC::TransportHandle const*);-void web_bindings_transfer_data_extend(HTML::TransferDataEncoder*, HTML::TransferDataEncoder*);-JSCompletion web_bindings_transfer_data_decode_records(HTML::TransferDataDecoder*, void* realm, size_t* offset, void* records, void (*append)(void*, HTML::SerializedTransferRecord*));-JSCompletion web_bindings_transfer_data_decode_transport_handle(HTML::TransferDataDecoder*, void* realm, size_t* offset, IPC::TransportHandle** out_handle);-void web_bindings_transport_handle_destroy(IPC::TransportHandle*);-IPC::Transport* web_bindings_transport_handle_create_transport(IPC::TransportHandle*);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*);@@ -295,58 +288,6 @@ bool web_bindings_extract_an_origin(JSObject* object, void* ctx, void (*on_origireturn true;}-// Writes the records as a Vector of them is encoded, which web_bindings_transfer_data_decode_records() and C++ read.-void web_bindings_transfer_data_encode_records(HTML::TransferDataEncoder* data_holder, HTML::SerializedTransferRecord const* const* records, size_t count)-{- MUST(data_holder->encode_size(count));- for (size_t i = 0; i < count; ++i)- MUST(data_holder->encode(*records[i]));-}--void web_bindings_transfer_data_encode_transport_handle(HTML::TransferDataEncoder* data_holder, IPC::TransportHandle const* handle)-{- MUST(data_holder->encode(*handle));-}--void web_bindings_transfer_data_extend(HTML::TransferDataEncoder* data_holder, HTML::TransferDataEncoder* holder)-{- data_holder->extend(*adopt_own(*holder));-}--// Reads what web_bindings_transfer_data_encode_records() writes, and hands each record over.-JSCompletion web_bindings_transfer_data_decode_records(HTML::TransferDataDecoder* data_holder, void* realm, size_t* offset, void* records, void (*append)(void*, HTML::SerializedTransferRecord*))-{- auto& js_realm = *static_cast<JS::Realm*>(realm);- auto decoded = data_holder->decode_at<Vector<HTML::SerializedTransferRecord>>(*offset);- if (decoded.is_error())- return completion_to_abi(js_realm, HTML::data_clone_error_from_serialization_error(js_realm, decoded.release_error()));- for (auto& record : decoded.value())- append(records, new HTML::SerializedTransferRecord(move(record)));- return completion_to_abi(js_realm, JS::js_undefined());-}--// Reads a transport handle, and hands it over.-JSCompletion web_bindings_transfer_data_decode_transport_handle(HTML::TransferDataDecoder* data_holder, void* realm, size_t* offset, IPC::TransportHandle** out_handle)-{- auto& js_realm = *static_cast<JS::Realm*>(realm);- auto handle = data_holder->decode_at<IPC::TransportHandle>(*offset);- if (handle.is_error())- return completion_to_abi(js_realm, HTML::data_clone_error_from_serialization_error(js_realm, handle.release_error()));- *out_handle = new IPC::TransportHandle(handle.release_value());- return completion_to_abi(js_realm, JS::js_undefined());-}--void web_bindings_transport_handle_destroy(IPC::TransportHandle* handle)-{- delete handle;-}--// The transport of the end whose rights the handle holds, which it gives up, handed over.-IPC::Transport* web_bindings_transport_handle_create_transport(IPC::TransportHandle* handle)-{- return MUST(handle->create_transport()).leak_ptr();-}-IPC::Transport* web_bindings_message_port_transport_create_paired(IPC::TransportHandle** out_remote_handle){auto paired = MUST(IPC::Transport::create_paired());diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.hindex 256ed4f463f..7ebbe4f33de 100644--- a/Libraries/LibWeb/Forward.h+++ b/Libraries/LibWeb/Forward.h@@ -813,7 +813,6 @@ class Timer;class TimeRanges;class ToggleEvent;class TrackEvent;-class TransferDataDecoder;class UserActivation;class UserScrollGestureHold;class ValidityState;diff --git a/Libraries/LibWeb/HTML/MessagePort.cpp b/Libraries/LibWeb/HTML/MessagePort.cppindex ba20313455e..4477a3a3acc 100644--- a/Libraries/LibWeb/HTML/MessagePort.cpp+++ b/Libraries/LibWeb/HTML/MessagePort.cpp@@ -30,7 +30,7 @@ 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_receiving_steps(JSVM*, void* realm, TransferDataDecoder*);+JSCompletion web_rust_message_port_transfer_receiving_steps(JSVM*, void* realm, TransferDataEncoder*);}static JSVM* vm_abi()@@ -43,9 +43,9 @@ GC::Ref<MessagePort> MessagePort::create(JS::Realm& realm)return GC::Ref { *static_cast<MessagePort*>(web_rust_message_port_create(vm_abi(), &realm)) };}-GC::Ref<MessagePort> MessagePort::create_from_transfer(JS::Realm& realm, TransferDataDecoder& data_holder)+GC::Ref<MessagePort> MessagePort::create_from_transfer(JS::Realm& realm, TransferDataEncoder&& data_holder){- auto wrapper = MUST(JS::HostABI::completion_from_abi<JS::Value>(web_rust_message_port_transfer_receiving_steps(vm_abi(), &realm, &data_holder)));+ auto wrapper = MUST(JS::HostABI::completion_from_abi<JS::Value>(web_rust_message_port_transfer_receiving_steps(vm_abi(), &realm, new TransferDataEncoder(move(data_holder)))));return *Bindings::impl_from<MessagePort>(&wrapper.as_object());}diff --git a/Libraries/LibWeb/HTML/MessagePort.h b/Libraries/LibWeb/HTML/MessagePort.hindex 4a016770ef5..83b23880788 100644--- a/Libraries/LibWeb/HTML/MessagePort.h+++ b/Libraries/LibWeb/HTML/MessagePort.h@@ -27,7 +27,7 @@ public:[[nodiscard]] static GC::Ref<MessagePort> create(JS::Realm&);// https://html.spec.whatwg.org/multipage/web-messaging.html#message-ports:transfer-receiving-steps- [[nodiscard]] static GC::Ref<MessagePort> create_from_transfer(JS::Realm&, TransferDataDecoder&);+ [[nodiscard]] static GC::Ref<MessagePort> create_from_transfer(JS::Realm&, TransferDataEncoder&&);static void disentangle_ports_of_realm(JS::Realm&);diff --git a/Libraries/LibWeb/HTML/StructuredSerialize.cpp b/Libraries/LibWeb/HTML/StructuredSerialize.cppindex b71d08b4936..9db4b8fac92 100644--- a/Libraries/LibWeb/HTML/StructuredSerialize.cpp+++ b/Libraries/LibWeb/HTML/StructuredSerialize.cpp@@ -133,15 +133,6 @@ WebIDL::ExceptionOr<JS::Value> structured_deserialize(JS::VM& vm, StorageSerialireturn TRY(JS::HostABI::completion_from_abi<JS::Value>(web_rust_structured_deserialize_for_storage(JS::HostABI::vm_to_abi(vm), &target_realm, serialized.data.bytes())));}-TransferDataDecoder::TransferDataDecoder(TransferDataEncoder&& data_holder)- : m_buffer(data_holder.take_buffer())- , m_stream(m_buffer.data().span())- , m_decoder(m_stream, m_attachments)-{- for (auto& attachment : m_buffer.take_attachments())- m_attachments.enqueue(move(attachment));-}-Vector<SerializableRegistryEntry> serializable_storage_registry(){Vector<SerializableRegistryEntry> entries;diff --git a/Libraries/LibWeb/HTML/StructuredSerialize.h b/Libraries/LibWeb/HTML/StructuredSerialize.hindex 321e038e1c1..dbf8b90dc0b 100644--- a/Libraries/LibWeb/HTML/StructuredSerialize.h+++ b/Libraries/LibWeb/HTML/StructuredSerialize.h@@ -35,35 +35,6 @@ class HostObject;namespace Web::HTML {-// A received data holder, whose bytes Rust reads. The values that have attachments C++ decodes for it, at the offset-// that Rust has read to.-class WEB_API TransferDataDecoder {- AK_ALLOC_WITH_KMALLOC;--public:- explicit TransferDataDecoder(TransferDataEncoder&&);-- ReadonlyBytes bytes() const { return m_buffer.data().span(); }-- // Decodes a value at the offset, and sets the offset to the end of the value.- template<typename T>- ErrorOr<T> decode_at(size_t& offset)- {- TRY(m_stream.seek(offset, SeekMode::SetPosition));- auto value = TRY(m_decoder.decode<T>());- offset = TRY(m_stream.tell());- return value;- }--private:- IPC::MessageBuffer m_buffer;-- FixedMemoryStream m_stream;- Queue<IPC::Attachment> m_attachments;-- IPC::Decoder m_decoder;-};-struct StructuredSerializeOptions {GC::RootVector<GC::Ref<JS::Object>> transfer;};@@ -105,15 +76,6 @@ struct SerializableRegistryEntry {WEB_API Vector<SerializableRegistryEntry> serializable_storage_registry();-template<typename T>-WebIDL::ExceptionOr<void> encode_or_throw_data_clone_error(JS::Realm& realm, TransferDataEncoder& encoder, T const& value)-{- auto result = encoder.encode(value);- if (result.is_error())- return data_clone_error_from_serialization_error(realm, result.release_error());- return {};-}-WEB_API WebIDL::ExceptionOr<SerializedTransferRecord> structured_serialize_with_transfer(JS::Realm&, JS::Value, ReadonlySpan<GC::Ref<JS::Object>> transfer_list);WEB_API WebIDL::ExceptionOr<DeserializedTransferRecord> structured_deserialize_with_transfer(SerializedTransferRecord&, JS::Realm&);diff --git a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cppindex f6199dd8a92..33ee5cdf449 100644--- a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp+++ b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp@@ -12,6 +12,8 @@#include <LibCore/AnonymousBuffer.h>#include <LibGC/RootVector.h>#include <LibIPC/File.h>+#include <LibIPC/Transport.h>+#include <LibIPC/TransportHandle.h>#include <LibJS/HostClassBuilder.h>#include <LibJS/Runtime/ArrayBuffer.h>#include <LibJS/Runtime/Realm.h>@@ -32,6 +34,46 @@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)+{+ Vector<IPC::Attachment> attachments;+ for (size_t i = 0; i < count; ++i) {+#if defined(AK_OS_MACOS) || defined(AK_OS_IOS)+ auto disposition = static_cast<Core::MachPort::MessageRight>(raw[i].disposition);+ auto right = Core::MachPort::PortRight::Send;+ if (disposition == Core::MachPort::MessageRight::MoveReceive || disposition == Core::MachPort::MessageRight::MakeSend || disposition == Core::MachPort::MessageRight::MakeSendOnce)+ right = Core::MachPort::PortRight::Receive;+ else if (disposition == Core::MachPort::MessageRight::MoveSendOnce)+ right = Core::MachPort::PortRight::SendOnce;+ attachments.append(IPC::Attachment::from_mach_port(Core::MachPort::adopt_right(static_cast<mach_port_t>(raw[i].value), right), disposition));+#else+ attachments.append(IPC::Attachment::from_fd(raw[i].value));+#endif+ }+ return attachments;+}++static void hand_over_payload(ReadonlyBytes bytes, Vector<IPC::Attachment> attachments, void* context, ReceiveTransferPayload receive)+{+ Vector<TransferAttachment> raw;+ for (auto& attachment : attachments) {+#if defined(AK_OS_MACOS) || defined(AK_OS_IOS)+ auto disposition = to_underlying(attachment.message_right());+ raw.append({ static_cast<int>(attachment.release_mach_port().release()), disposition });+#else+ raw.append({ attachment.to_fd(), 0 });+#endif+ }+ receive(context, bytes, raw.data(), raw.size());+}+extern "C" {void web_structured_serialize_set_ipc_record(IPCSerializationRecord*, ReadonlyBytes data, JSObject* const* shared_array_buffers, size_t count);@@ -51,18 +93,17 @@ bool web_structured_serialize_is_exposed(u16 interface_name, void* realm);ImageBitmapSharedPixels* web_structured_serialize_gather_image_bitmap_pixels(JSObject* const* transfer_list, size_t count, u32 buffer_index, int* shared_memory, size_t* size);void web_structured_serialize_image_bitmap_pixels_destroy(ImageBitmapSharedPixels*);-TransferDataEncoder* web_structured_serialize_transfer_data_holder_create();-void web_structured_serialize_transfer_data_holder_append(TransferDataEncoder*, ReadonlyBytes);-void web_structured_serialize_transfer_data_holder_destroy(TransferDataEncoder*);+TransferDataEncoder* 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);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*));-TransferDataDecoder* web_structured_serialize_transfer_data_decoder_create(TransferDataEncoder*);Vector<Core::AnonymousBuffer>* web_structured_serialize_shared_pixels_create(int const*, size_t const*, size_t);void web_structured_serialize_shared_pixels_destroy(Vector<Core::AnonymousBuffer>*);void web_structured_serialize_transferred_values_append(Vector<GC::Root<JS::Object>>*, JSObject*);-void web_structured_serialize_transfer_data_decoder_bytes(TransferDataDecoder const*, ReadonlyBytes* bytes);-void web_structured_serialize_transfer_data_decoder_destroy(TransferDataDecoder*);}static JS::Realm& realm_from_abi(void* realm)@@ -176,19 +217,49 @@ void web_structured_serialize_image_bitmap_pixels_destroy(ImageBitmapSharedPixeldelete image_bitmap_pixels;}-TransferDataEncoder* web_structured_serialize_transfer_data_holder_create()+TransferDataEncoder* web_structured_serialize_transfer_data_holder_create(ReadonlyBytes bytes, TransferAttachment const* attachments, size_t count){- return new TransferDataEncoder;+ IPC::MessageDataType data;+ MUST(data.try_append(bytes.data(), bytes.size()));+ return new TransferDataEncoder(IPC::MessageBuffer { move(data), adopt_attachments(attachments, count) });}-void web_structured_serialize_transfer_data_holder_append(TransferDataEncoder* data_holder, ReadonlyBytes bytes)+void web_structured_serialize_transfer_data_holder_take(TransferDataEncoder* holder, void* context, ReceiveTransferPayload receive){- MUST(data_holder->append(bytes));+ 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_data_holder_destroy(TransferDataEncoder* data_holder)+void web_structured_serialize_transfer_handle_take(IPC::TransportHandle* handle, void* context, ReceiveTransferPayload receive){- delete data_holder;+ 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();+}++bool web_structured_serialize_validate_shared_memory(int descriptor, size_t size)+{+ auto file = IPC::File::clone_fd(descriptor);+ if (file.is_error())+ return false;+ auto buffer = Core::AnonymousBuffer::create_from_anon_fd(file.release_value().take_fd(), size);+ if (buffer.is_error())+ return false;+ return !buffer.value().validate_backing_size().is_error();}// Takes over the descriptors and the data holders.@@ -228,14 +299,6 @@ void web_structured_serialize_transfer_record_take(SerializedTransferRecord* recrecord->shared_buffers.clear();}-TransferDataDecoder* web_structured_serialize_transfer_data_decoder_create(TransferDataEncoder* holder)-{- auto carrier = adopt_own(*holder);- if (carrier->buffer().data().is_empty())- return nullptr;- return new TransferDataDecoder(move(*carrier));-}-Vector<Core::AnonymousBuffer>* web_structured_serialize_shared_pixels_create(int const* descriptors, size_t const* sizes, size_t count){Vector<Core::AnonymousBuffer> buffers;@@ -260,13 +323,3 @@ void web_structured_serialize_transferred_values_append(Vector<GC::Root<JS::Obje{transferred_values->append(GC::make_root(*JS::HostABI::object_from_abi(value)));}--void web_structured_serialize_transfer_data_decoder_bytes(TransferDataDecoder const* decoder, ReadonlyBytes* bytes)-{- *bytes = decoder->bytes();-}--void web_structured_serialize_transfer_data_decoder_destroy(TransferDataDecoder* decoder)-{- delete decoder;-}diff --git a/Libraries/LibWebCommon/HTML/SerializationRecords.cpp b/Libraries/LibWebCommon/HTML/SerializationRecords.cppindex 3103655650b..4bf13979441 100644--- a/Libraries/LibWebCommon/HTML/SerializationRecords.cpp+++ b/Libraries/LibWebCommon/HTML/SerializationRecords.cpp@@ -64,11 +64,6 @@ IPC::MessageBuffer TransferDataEncoder::take_buffer() constreturn move(m_buffer);}-void TransferDataEncoder::extend(TransferDataEncoder const& data_holder)-{- MUST(m_buffer.extend(data_holder.take_buffer()));-}-}namespace IPC {diff --git a/Libraries/LibWebCommon/HTML/SerializationRecords.h b/Libraries/LibWebCommon/HTML/SerializationRecords.hindex 37f03677813..b8a467c95a5 100644--- a/Libraries/LibWebCommon/HTML/SerializationRecords.h+++ b/Libraries/LibWebCommon/HTML/SerializationRecords.h@@ -127,22 +127,6 @@ public:return m_encoder.encode(value);}- // The size of a list, as the encoding of a Vector begins.- ErrorOr<void> encode_size(size_t size)- {- VERIFY(!m_buffer_has_been_taken);- return m_encoder.encode_size(size);- }-- // Bytes that are already in the encoding, which the Rust data holders write.- ErrorOr<void> append(ReadonlyBytes bytes)- {- VERIFY(!m_buffer_has_been_taken);- return m_encoder.append(bytes.data(), bytes.size());- }-- void extend(TransferDataEncoder const&);-IPC::MessageBuffer const& buffer() const;IPC::MessageBuffer take_buffer() const;diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex fa89022ecbe..8aac45d81e3 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -61,7 +61,7 @@ ALLOWED_REALM_MENTIONS = {"FileAPI": (2, 9, "Blob glue still creates streams and buffers in selected realms"),"HTML": (63,- 169,+ 168,"HTML algorithms still contain structured serialization, including canvas, navigation transfer/reconstruction, worker/worklet, and event realm use, and cross-origin Window/Location property functions are created in the current realm; window postMessage glue supplies principal realms and routes remote messages; ""the C++ glue of the Rust structured serialization creates platform objects and SharedArrayBuffers in a given realm; ""the C++ glue of the Rust Storage and StorageEvent creates them in a given realm",diff --git a/Services/WebWorker/WorkerHost.cpp b/Services/WebWorker/WorkerHost.cppindex f4d8c9c60a2..c71f8329540 100644--- a/Services/WebWorker/WorkerHost.cpp+++ b/Services/WebWorker/WorkerHost.cpp@@ -267,8 +267,7 @@ void WorkerHost::run(GC::Ref<Web::Page> page, Web::HTML::TransferDataEncoder mes// (step 5) to connect_shared_worker_impl. Each connecting page gets its own pair// since the connect event fires once per owner, not once at worker startup.if (!is_shared) {- Web::HTML::TransferDataDecoder decoder { move(message_port_data) };- inside_port = Web::HTML::MessagePort::create_from_transfer(realm, decoder);+ inside_port = Web::HTML::MessagePort::create_from_transfer(realm, move(message_port_data));// 1. Set inside port's message event target to worker global scope.inside_port->set_message_event_target(*worker_global_scope);@@ -378,8 +377,7 @@ void WorkerHost::connect_shared_worker_impl(Web::HTML::TransferDataEncoder messa// 11.5.5. Let insidePort be a new MessagePort in insideSettings's realm.// 11.5.6. Entangle outsidePort and insidePort.auto& realm = m_inside_settings->realm();- Web::HTML::TransferDataDecoder decoder { move(message_port_data) };- auto inside_port = Web::HTML::MessagePort::create_from_transfer(realm, decoder);+ auto inside_port = Web::HTML::MessagePort::create_from_transfer(realm, move(message_port_data));// 11.5.7. Queue a global task on the DOM manipulation task source given workerGlobalScope to// fire an event named connect at workerGlobalScope, using MessageEvent, with the data