Skip to content

Truly independent web browser

LibWeb: Serialize transfers into Rust message records

Shannon Boothf480807adbb0
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs
index 95fdd064318..755e3d95949 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs
@@ -9,15 +9,16 @@
//! bytes over to and the deserializations read the bytes of, the registry of serializable interfaces, the platform
//! objects, and the side tables that SharedArrayBuffers are shared through.
-use core::ffi::c_void;
+use core::ffi::{c_int, c_void};
use core::marker::PhantomData;
use core::mem::ManuallyDrop;
use core::ptr::NonNull;
-use libjs_rust::api::{ArrayBuffer, Gc, Object, RawNativeFunctionResult, Realm, Value};
+use libjs_rust::api::{ArrayBuffer, DeferGc, Gc, Object, RawNativeFunctionResult, Realm, Value, into_raw_descriptor};
use crate::bindings::structured_data::{SerializationReader, SerializationWriter};
use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::html::structured_serialize::message_record::{MessageRecord, SharedMemory};
use crate::html::structured_serialize::transfer_data_holder::TransferDataHolder;
unsafe extern "C" {
@@ -37,23 +38,12 @@ unsafe extern "C" {
identifier: ak::Span<'_, u8>,
interface_name: &mut u16,
) -> bool;
- fn web_structured_serialize_shared_buffers_append_shared_memory(
- shared_buffers: *mut c_void,
- array_buffer: *mut c_void,
- index: &mut u32,
- ) -> bool;
fn web_structured_serialize_ipc_record_data(record: *const c_void, data: &mut ak::Span<'static, u8>);
fn web_structured_serialize_ipc_record_shared_array_buffer(
record: *const c_void,
side_table_index: u32,
) -> *mut c_void;
- fn web_structured_serialize_shared_buffers_shared_array_buffer(
- shared_buffers: *mut c_void,
- realm: *mut c_void,
- index: u32,
- shared_object_id: u64,
- ) -> RawNativeFunctionResult;
fn web_structured_serialize_data_clone_error_from_serialization_error(
realm: *mut c_void,
message: ak::Span<'_, u8>,
@@ -82,9 +72,11 @@ unsafe extern "C" {
) -> RawNativeFunctionResult;
fn web_structured_serialize_gather_image_bitmap_pixels(
- shared_buffers: *mut c_void,
transfer_list: *const *mut c_void,
count: usize,
+ buffer_index: u32,
+ shared_memory: &mut c_int,
+ size: &mut usize,
) -> *mut c_void;
fn web_structured_serialize_image_bitmap_pixels_destroy(image_bitmap_pixels: *mut c_void);
@@ -97,9 +89,18 @@ unsafe extern "C" {
record: *mut c_void,
data: ak::Span<'_, u8>,
shared_array_buffers: *const *mut c_void,
- count: usize,
+ shared_array_buffer_count: usize,
+ shared_memory: *const c_int,
+ shared_memory_sizes: *const usize,
+ shared_memory_count: usize,
+ );
+ fn web_structured_serialize_transfer_record_shared_memory_count(record: *mut c_void) -> usize;
+ fn web_structured_serialize_transfer_record_shared_memory(
+ record: *mut c_void,
+ index: usize,
+ shared_memory: &mut c_int,
+ size: &mut usize,
);
- fn web_structured_serialize_transfer_record_shared_buffers(record: *mut c_void) -> *mut c_void;
fn web_structured_serialize_transfer_record_append_data_holder(record: *mut c_void, data_holder: *mut c_void);
fn web_structured_serialize_transfer_record_data_holder_count(record: *mut c_void) -> usize;
fn web_structured_serialize_transfer_record_take_data_holder(record: *mut c_void, index: usize) -> *mut c_void;
@@ -241,64 +242,33 @@ impl<'a> ReceivedIPCSerializationRecord<'a> {
}
}
-/// The side list of the cross-process shared memory that a record on the messaging path shares its SharedArrayBuffers
-/// through: a Vector<Core::AnonymousBuffer> that C++ lends.
-#[derive(Clone, Copy)]
-pub(crate) struct SharedBuffers(NonNull<c_void>);
-
-impl SharedBuffers {
- /// # Safety
- ///
- /// `shared_buffers` must be a list that C++ lends while this is used.
- pub(crate) unsafe fn from_raw(shared_buffers: *mut c_void) -> Self {
- Self(NonNull::new(shared_buffers).expect("C++ lends a list"))
+/// AD-HOC: Gathers the pixels of the ImageBitmaps of the transfer list in one buffer of shared memory, whose index in
+/// the shared memory of the record of the transfer is the buffer index. Without it, as when there is not enough
+/// memory for it, the pixels travel inline.
+pub(crate) fn gather_image_bitmap_pixels(
+ transfer_list: &[Gc<Object>],
+ buffer_index: u32,
+) -> (ImageBitmapSharedPixels, Option<SharedMemory>) {
+ let transfer_list = objects_into_abi(transfer_list);
+ let (mut descriptor, mut size) = (0, 0);
+ // SAFETY: The objects are live, and the call writes to the locals.
+ let pixels = ImageBitmapSharedPixels(NonNull::new(unsafe {
+ web_structured_serialize_gather_image_bitmap_pixels(
+ transfer_list.as_ptr(),
+ transfer_list.len(),
+ buffer_index,
+ &mut descriptor,
+ &mut size,
+ )
+ }));
+ if pixels.0.is_none() {
+ return (pixels, None);
}
-
- /// Appends the cross-process shared memory of the SharedArrayBuffer to the list, and returns its index there, if
- /// the buffer is backed by some.
- pub(crate) fn append_shared_memory_of(self, array_buffer: Gc<ArrayBuffer>) -> Option<u32> {
- let mut index = 0;
- // SAFETY: The list is lent, and the buffer is live.
- unsafe {
- web_structured_serialize_shared_buffers_append_shared_memory(
- self.0.as_ptr(),
- object_into_abi(array_buffer),
- &mut index,
- )
- }
- .then_some(index)
- }
-
- /// A new SharedArrayBuffer in the realm over the cross-process shared memory at the index of the list.
- pub(crate) fn shared_array_buffer(
- self,
- realm: Gc<Realm>,
- index: u32,
- shared_object_id: u64,
- ) -> WebIdlResult<Value> {
- // SAFETY: The list is lent, and the realm is live.
- completion(unsafe {
- web_structured_serialize_shared_buffers_shared_array_buffer(
- self.0.as_ptr(),
- realm.as_ptr().cast(),
- index,
- shared_object_id,
- )
- })
- }
-
- /// Gathers the pixels of the ImageBitmaps of the transfer list in one buffer of shared memory, which the list
- /// holds.
- pub(crate) fn gather_image_bitmap_pixels(self, transfer_list: &[Gc<Object>]) -> ImageBitmapSharedPixels {
- let transfer_list = objects_into_abi(transfer_list);
- // SAFETY: The list is lent, and the objects are live.
- ImageBitmapSharedPixels(NonNull::new(unsafe {
- web_structured_serialize_gather_image_bitmap_pixels(
- self.0.as_ptr(),
- transfer_list.as_ptr(),
- transfer_list.len(),
- )
- }))
+ // SAFETY: The pixels keep the descriptor open.
+ match unsafe { SharedMemory::duplicate(descriptor, size) } {
+ Some(shared_memory) => (pixels, Some(shared_memory)),
+ // NB: Without a descriptor for the record, the pixels travel inline.
+ None => (ImageBitmapSharedPixels(None), None),
}
}
@@ -502,25 +472,52 @@ impl SerializedTransferRecord {
self.0.as_ptr()
}
- /// Sets the record's [[Serialized]] to the bytes, with the SharedArrayBuffers of its same-process side table.
- pub(crate) fn set_serialized(self, data: &[u8], shared_array_buffers: &[Gc<ArrayBuffer>]) {
- let shared_array_buffers = objects_into_abi(shared_array_buffers);
- // SAFETY: The record is lent, the call borrows the bytes, and the buffers are live.
+ /// Sets the record's [[Serialized]] to the message record, with its same-process side table and the shared memory
+ /// of the transfer, which C++ takes over. Its SharedArrayBuffers are rooted once the record has them, so the
+ /// caller hands it over under the deferral that it was finished under.
+ pub(crate) fn set_serialized(self, _: &DeferGc<'_>, serialized: MessageRecord) {
+ let shared_array_buffers = objects_into_abi(&serialized.shared_array_buffers);
+ let (shared_memory, shared_memory_sizes): (Vec<c_int>, Vec<usize>) = serialized
+ .shared_memory
+ .into_iter()
+ .map(|shared_memory| (into_raw_descriptor(shared_memory.descriptor), shared_memory.size))
+ .unzip();
+ // SAFETY: The record is lent, the call borrows the bytes, the buffers are live, and it takes over the
+ // descriptors.
unsafe {
web_structured_serialize_transfer_record_set_serialized(
self.0.as_ptr(),
- ak::Span::new(data),
+ ak::Span::new(&serialized.bytes),
shared_array_buffers.as_ptr(),
shared_array_buffers.len(),
+ shared_memory.as_ptr(),
+ shared_memory_sizes.as_ptr(),
+ shared_memory.len(),
);
}
}
- /// The cross-process shared memory of the record, which its [[Serialized]] and its data holders share
- /// SharedArrayBuffers and the pixels of ImageBitmaps through.
- pub(crate) fn shared_buffers(self) -> SharedBuffers {
- // SAFETY: The record is lent, and so is its list.
- unsafe { SharedBuffers::from_raw(web_structured_serialize_transfer_record_shared_buffers(self.0.as_ptr())) }
+ /// Duplicates of the shared memory of the record, which its [[Serialized]] and its data holders share
+ /// SharedArrayBuffers and the pixels of ImageBitmaps through. A descriptor that cannot be duplicated leaves out the
+ /// shared memory from it on, which deserializing then throws for.
+ pub(crate) fn shared_memory(self) -> Vec<SharedMemory> {
+ // SAFETY: The record is lent.
+ let count = unsafe { web_structured_serialize_transfer_record_shared_memory_count(self.0.as_ptr()) };
+ (0..count)
+ .map_while(|index| {
+ let (mut descriptor, mut size) = (0, 0);
+ // SAFETY: The record is lent, and it keeps the descriptor open.
+ unsafe {
+ web_structured_serialize_transfer_record_shared_memory(
+ self.0.as_ptr(),
+ index,
+ &mut descriptor,
+ &mut size,
+ );
+ SharedMemory::duplicate(descriptor, size)
+ }
+ })
+ .collect()
}
/// Appends the data holder to the record's [[TransferDataHolders]].
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/exports.rs
index e6369c6e4b9..b602ea967b9 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/exports.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/exports.rs
@@ -137,7 +137,7 @@ pub unsafe extern "C" fn web_rust_structured_deserialize(
let cx = CallContext::new(vm, target_realm);
// SAFETY: The caller lends the record.
let record = unsafe { ReceivedIPCSerializationRecord::from_raw(record) };
- let serialized = StructuredSerializeReader::new_ipc(target_realm, record, None);
+ let serialized = StructuredSerializeReader::new_ipc(target_realm, record, &[]);
let memory = DeserializationMemory::new(vm);
completion(&cx, structured_deserialize_internal(&cx, &serialized, &memory, false))
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/message_record.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/message_record.rs
index 98eea76f2ba..f65879c8df4 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/message_record.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/message_record.rs
@@ -20,6 +20,21 @@ pub(crate) struct SharedMemory {
pub(crate) size: usize,
}
+impl SharedMemory {
+ /// A duplicate of a descriptor that C++ lends, unless it cannot be duplicated.
+ ///
+ /// # Safety
+ ///
+ /// The descriptor must stay open for the call.
+ pub(crate) unsafe fn duplicate(descriptor: c_int, size: usize) -> Option<Self> {
+ // SAFETY: The caller keeps the descriptor open.
+ let descriptor = unsafe { borrowed_from_raw_descriptor(descriptor) }
+ .try_clone_to_owned()
+ .ok()?;
+ Some(Self { descriptor, size })
+ }
+}
+
#[derive(Trace)]
#[gc(crate = libjs_rust)]
pub(crate) struct MessageRecord {
@@ -43,13 +58,8 @@ impl MessageRecord {
let shared_memory = descriptors
.iter()
.zip(sizes)
- .map_while(|(&descriptor, &size)| {
- // SAFETY: The caller keeps the descriptor open.
- let descriptor = unsafe { borrowed_from_raw_descriptor(descriptor) }
- .try_clone_to_owned()
- .ok()?;
- Some(SharedMemory { descriptor, size })
- })
+ // SAFETY: The caller keeps the descriptors open.
+ .map_while(|(&descriptor, &size)| unsafe { SharedMemory::duplicate(descriptor, size) })
.collect();
Self {
bytes: bytes.to_vec(),
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs
index ba16c9d73bc..d760121f4f7 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs
@@ -23,8 +23,8 @@ pub(crate) mod writer;
use ak::Utf16String;
use libjs_rust::api::{
Array, ArrayBuffer, ArrayBufferOrder, ArrayBufferShared, BigIntObject, BooleanObject, ByteLength, DataView, Date,
- ErrorKind, ErrorType as JsErrorType, Gc, Map, MarkedVec, Must, NumberObject, Object, PrimitiveString, PropertyKey,
- PropertyKind, Realm, RegExpObject, Set, StringObject, TypedArrayBase, TypedArrayKind, Value, Vm,
+ DeferGc, ErrorKind, ErrorType as JsErrorType, Gc, Map, MarkedVec, Must, NumberObject, Object, PrimitiveString,
+ PropertyKey, PropertyKind, Realm, RegExpObject, Set, StringObject, TypedArrayBase, TypedArrayKind, Value, Vm,
create_byte_data_block, detach_array_buffer, is_typed_array_out_of_bounds, is_view_out_of_bounds,
length_of_array_like, make_data_view_with_buffer_witness_record, make_typed_array_with_buffer_witness_record,
regexp_create,
@@ -43,8 +43,9 @@ use crate::html::offscreen_canvas;
use crate::html::structured_serialize::cpp::{
OwnedSerializedTransferRecord, SerializableSteps, SerializedTransferRecord, current_settings_object_agent_cluster,
current_settings_object_cross_origin_isolated_capability, data_clone_error_from_serialization_error,
- deserialize_rust_platform_object, is_exposed, is_platform_object, realm_agent_cluster, serializable_interface_name,
- serializable_interface_storage_identifier, serializable_payload_version, serializable_steps, serialization_steps,
+ deserialize_rust_platform_object, gather_image_bitmap_pixels, is_exposed, is_platform_object, realm_agent_cluster,
+ serializable_interface_name, serializable_interface_storage_identifier, serializable_payload_version,
+ serializable_steps, serialization_steps,
};
use crate::html::structured_serialize::memory::{DeserializationMemory, SerializationMemory};
use crate::html::structured_serialize::message_record::MessageRecord;
@@ -1722,14 +1723,12 @@ pub(crate) fn structured_serialize_with_transfer(
memory.set(transferable_value, memory.size());
}
- // NB: The record of the result holds the shared memory that serialized and the data holders share through.
let result = OwnedSerializedTransferRecord::new();
- let shared_buffers = result.record().shared_buffers();
// 3. Let serialized be ? StructuredSerializeInternal(value, false, memory).
- // NB: The record may cross a process boundary, so it is an IPC record, with the memory of its SharedArrayBuffers
- // shared on the side.
- let serialized = StructuredSerializeWriter::new_with_shared_buffers(vm, shared_buffers);
+ // NB: The record may cross a process boundary, so it is a message record, with the memory of its SharedArrayBuffers
+ // shared on the side. The data holders share the pixels of ImageBitmaps through the same list.
+ let serialized = StructuredSerializeWriter::new_for_message(vm);
structured_serialize_internal(
vm,
Some(cx.realm()),
@@ -1742,7 +1741,11 @@ pub(crate) fn structured_serialize_with_transfer(
// AD-HOC: Gather the pixels of the transferred ImageBitmaps in one buffer of shared memory. Without it, as when there
// is not enough memory for it, the pixels travel inline.
- let image_bitmap_pixels = shared_buffers.gather_image_bitmap_pixels(transfer_list);
+ let (image_bitmap_pixels, pixels_shared_memory) =
+ gather_image_bitmap_pixels(transfer_list, serialized.next_shared_memory_index());
+ if let Some(shared_memory) = pixels_shared_memory {
+ serialized.append_shared_memory(shared_memory);
+ }
// 4. Let transferDataHolders be a new empty List.
// NB: The record of the result holds the list.
@@ -1825,7 +1828,11 @@ pub(crate) fn structured_serialize_with_transfer(
}
// 6. Let result be { [[Serialized]]: serialized, [[TransferDataHolders]]: transferDataHolders, [[InterfaceNames]]: an empty ordered set, [[AgentCluster]]: null }.
- serialized.finish_transfer_record(result.record());
+ DeferGc::scope(vm, |defer_gc| {
+ result
+ .record()
+ .set_serialized(defer_gc, serialized.finish_message_record(defer_gc));
+ });
// FIXME: 7. For each object → record of memory:
// 1. If object is a platform object, then append record.[[Type]] to result.[[InterfaceNames]].
@@ -1881,11 +1888,12 @@ pub(crate) fn structured_deserialize_with_transfer<'vm>(
}
// 6. Let deserialized be ? StructuredDeserialize(serializeWithTransferResult.[[Serialized]], targetRealm, memory).
+ let shared_memory = serialize_with_transfer_result.shared_memory();
let serialized = StructuredSerializeReader::new_ipc(
target_realm,
// SAFETY: The caller lends the record for the deserialization.
unsafe { serialize_with_transfer_result.serialized() },
- Some(serialize_with_transfer_result.shared_buffers()),
+ &shared_memory,
);
let deserialized = with_temporary_execution_context(target_realm, || {
structured_deserialize_internal(cx, &serialized, &memory, false)
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs
index adf5275b5ad..d0ba0bed2cd 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs
@@ -25,16 +25,17 @@ use libwebcommon_rust::html::serialization_records::{DecodeError, DecodedString,
use crate::bindings::WebIdlResult;
use crate::html::structured_serialize::cpp::{
- ReceivedIPCSerializationRecord, SharedBuffers, data_clone_error_from_serialization_error, is_ipc_interface,
+ ReceivedIPCSerializationRecord, data_clone_error_from_serialization_error, is_ipc_interface,
serializable_interface_name_from_storage_identifier,
};
-use crate::html::structured_serialize::message_record::MessageRecord;
+use crate::html::structured_serialize::message_record::{MessageRecord, SharedMemory};
/// Where the record keeps the SharedArrayBuffers that it shares.
#[derive(Clone, Copy)]
enum SharedArrayBuffers<'a> {
None,
- Lent(ReceivedIPCSerializationRecord<'a>, Option<SharedBuffers>),
+ /// The side table of a record that C++ lends, and the shared memory that it was handed over with, if any.
+ Lent(ReceivedIPCSerializationRecord<'a>, &'a [SharedMemory]),
Message(&'a MessageRecord),
}
@@ -48,12 +49,12 @@ impl<'a> StructuredSerializeReader<'a> {
pub(crate) fn new_ipc(
realm: Gc<Realm>,
record: ReceivedIPCSerializationRecord<'a>,
- shared_buffers: Option<SharedBuffers>,
+ shared_memory: &'a [SharedMemory],
) -> Self {
Self {
decoder: RecordDecoder::new(SerializationType::Ipc, record.data()).expect("an IPC record has no prologue"),
realm,
- shared_array_buffers: SharedArrayBuffers::Lent(record, shared_buffers),
+ shared_array_buffers: SharedArrayBuffers::Lent(record, shared_memory),
}
}
@@ -200,31 +201,26 @@ impl<'a> StructuredSerializeReader<'a> {
index: u32,
shared_object_id: u64,
) -> WebIdlResult<Value> {
- let index_out_of_range =
- || data_clone_error_from_serialization_error(self.realm, "SharedArrayBuffer side-list index out of range");
- match self.shared_array_buffers {
- SharedArrayBuffers::Lent(_, Some(shared_buffers)) => {
- shared_buffers.shared_array_buffer(self.realm, index, shared_object_id)
- }
- SharedArrayBuffers::Message(record) => {
- let shared_memory = record
- .shared_memory
- .get(index as usize)
- .ok_or_else(index_out_of_range)?;
- let array_buffer = ArrayBuffer::create_from_shared_memory(
- vm,
- self.realm,
- shared_memory.descriptor.as_shared_memory(),
- shared_memory.size,
- shared_object_id,
- )
- .map_err(|_| {
- data_clone_error_from_serialization_error(self.realm, "Unable to map SharedArrayBuffer memory")
- })?;
- Ok(Value::from_object(array_buffer))
- }
- SharedArrayBuffers::None | SharedArrayBuffers::Lent(_, None) => Err(index_out_of_range()),
- }
+ let shared_memory = match self.shared_array_buffers {
+ SharedArrayBuffers::None => &[],
+ SharedArrayBuffers::Lent(_, shared_memory) => shared_memory,
+ SharedArrayBuffers::Message(record) => record.shared_memory.as_slice(),
+ };
+ let Some(shared_memory) = shared_memory.get(index as usize) else {
+ return Err(data_clone_error_from_serialization_error(
+ self.realm,
+ "SharedArrayBuffer side-list index out of range",
+ ));
+ };
+ let array_buffer = ArrayBuffer::create_from_shared_memory(
+ vm,
+ self.realm,
+ shared_memory.descriptor.as_shared_memory(),
+ shared_memory.size,
+ shared_object_id,
+ )
+ .map_err(|_| data_clone_error_from_serialization_error(self.realm, "Unable to map SharedArrayBuffer memory"))?;
+ Ok(Value::from_object(array_buffer))
}
/// A new SharedArrayBuffer that shares the storage of the buffer at the index of the record's same-process side
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rs
index a636c21c6a7..e1f817bc86a 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rs
@@ -20,25 +20,18 @@ use libjs_rust::api::{ArrayBuffer, BigInt, DataBlockStorage, DeferGc, Gc, Marked
use libwebcommon_rust::html::serialization_records::{RecordEncoder, SerializationType};
use crate::html::structured_serialize::cpp::{
- IPCSerializationRecord, SerializedTransferRecord, SharedBuffers, StorageSerializationRecord,
- serializable_interface_storage_identifier,
+ IPCSerializationRecord, StorageSerializationRecord, serializable_interface_storage_identifier,
};
use crate::html::structured_serialize::message_record::{MessageRecord, SharedMemory};
-/// Where a record that reaches agents in other processes hands the shared memory of its SharedArrayBuffers over.
-enum CrossProcessSharedMemory {
- None,
- Lent(SharedBuffers),
- Owned(RefCell<Vec<SharedMemory>>),
-}
-
/// The record of a structured serialization, which the serialization writes its values to.
pub(crate) struct StructuredSerializeWriter<'vm> {
encoder: RefCell<RecordEncoder>,
/// The SharedArrayBuffers that an IPC record shares with a deserialization in the same process, by their index in
/// this same-process side table.
shared_array_buffers: MarkedVec<'vm, Gc<ArrayBuffer>>,
- shared_memory: CrossProcessSharedMemory,
+ /// The shared memory that a MessageRecord, which may reach agents in other processes, hands over beside its bytes.
+ shared_memory: Option<RefCell<Vec<SharedMemory>>>,
}
impl<'vm> StructuredSerializeWriter<'vm> {
@@ -46,22 +39,14 @@ impl<'vm> StructuredSerializeWriter<'vm> {
Self {
encoder: RefCell::new(RecordEncoder::new(serialization_type)),
shared_array_buffers: MarkedVec::new(vm),
- shared_memory: CrossProcessSharedMemory::None,
- }
- }
-
- /// The writer of an IPC record whose SharedArrayBuffers share their cross-process shared memory through the list.
- pub(crate) fn new_with_shared_buffers(vm: &'vm Vm, shared_buffers: SharedBuffers) -> Self {
- Self {
- shared_memory: CrossProcessSharedMemory::Lent(shared_buffers),
- ..Self::new(vm, SerializationType::Ipc)
+ shared_memory: None,
}
}
/// The writer of a MessageRecord.
pub(crate) fn new_for_message(vm: &'vm Vm) -> Self {
Self {
- shared_memory: CrossProcessSharedMemory::Owned(RefCell::new(Vec::new())),
+ shared_memory: Some(RefCell::new(Vec::new())),
..Self::new(vm, SerializationType::Ipc)
}
}
@@ -158,27 +143,40 @@ impl<'vm> StructuredSerializeWriter<'vm> {
index
}
+ /// Hands the shared memory over beside the record, and returns its index there.
+ pub(crate) fn append_shared_memory(&self, shared_memory: SharedMemory) -> u32 {
+ let mut list = self
+ .shared_memory
+ .as_ref()
+ .expect("the record hands shared memory over")
+ .borrow_mut();
+ let index = u32::try_from(list.len()).expect("a record shares fewer than 2^32 buffers");
+ list.push(shared_memory);
+ index
+ }
+
+ /// The index that the next shared memory handed over beside the record gets.
+ pub(crate) fn next_shared_memory_index(&self) -> u32 {
+ let list = self
+ .shared_memory
+ .as_ref()
+ .expect("the record hands shared memory over")
+ .borrow();
+ u32::try_from(list.len()).expect("a record shares fewer than 2^32 buffers")
+ }
+
/// Hands the cross-process shared memory of the SharedArrayBuffer over beside the record, and returns its index
/// there, if the buffer is backed by some, and the record reaches agents in other processes.
pub(crate) fn append_shared_memory_of(&self, array_buffer: Gc<ArrayBuffer>) -> Option<u32> {
- let shared_memory = match &self.shared_memory {
- CrossProcessSharedMemory::None => return None,
- CrossProcessSharedMemory::Lent(shared_buffers) => {
- return shared_buffers.append_shared_memory_of(array_buffer);
- }
- CrossProcessSharedMemory::Owned(shared_memory) => shared_memory,
- };
- let descriptor = array_buffer.with_data_block(|data_block| match &data_block.byte_buffer {
+ self.shared_memory.as_ref()?;
+ let shared_memory = array_buffer.with_data_block(|data_block| match &data_block.byte_buffer {
DataBlockStorage::Shared(store) => Some(SharedMemory {
descriptor: store.shared_memory().try_clone_to_owned().ok()?,
size: store.size(),
}),
_ => None,
})?;
- let mut shared_memory = shared_memory.borrow_mut();
- let index = u32::try_from(shared_memory.len()).expect("a record shares fewer than 2^32 buffers");
- shared_memory.push(descriptor);
- Some(index)
+ Some(self.append_shared_memory(shared_memory))
}
/// Sets the IPC record that C++ lends to what the writer wrote.
@@ -191,9 +189,7 @@ impl<'vm> StructuredSerializeWriter<'vm> {
/// allocates under the deferral.
pub(crate) fn finish_message_record(self, _: &DeferGc<'_>) -> MessageRecord {
assert_eq!(self.serialization_type(), SerializationType::Ipc);
- let CrossProcessSharedMemory::Owned(shared_memory) = self.shared_memory else {
- unreachable!("the writer is a message's");
- };
+ let shared_memory = self.shared_memory.expect("the writer is a message's");
MessageRecord {
bytes: self.encoder.into_inner().into_bytes(),
shared_array_buffers: self.shared_array_buffers.values().to_vec(),
@@ -220,10 +216,4 @@ impl<'vm> StructuredSerializeWriter<'vm> {
);
record.set(self.encoder.borrow().bytes());
}
-
- /// Sets the [[Serialized]] of the record of a transfer to what the writer wrote.
- pub(crate) fn finish_transfer_record(self, record: SerializedTransferRecord) {
- assert_eq!(self.serialization_type(), SerializationType::Ipc);
- record.set_serialized(self.encoder.borrow().bytes(), &self.shared_array_buffers.values());
- }
}
diff --git a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
index b842984fa71..a759f944e2d 100644
--- a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
+++ b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
@@ -46,11 +46,9 @@ void web_structured_serialize_set_storage_record(StorageSerializationRecord*, Re
bool web_structured_serialize_interface_storage_identifier(u16 interface_name, ReadonlyBytes* identifier);
bool web_structured_serialize_is_ipc_interface(u16 interface_name);
bool web_structured_serialize_interface_name_from_storage_identifier(ReadonlyBytes identifier, u16* interface_name);
-bool web_structured_serialize_shared_buffers_append_shared_memory(Vector<Core::AnonymousBuffer>*, JSObject* array_buffer, u32* index);
void web_structured_serialize_ipc_record_data(IPCSerializationRecord const*, ReadonlyBytes* data);
JSObject* web_structured_serialize_ipc_record_shared_array_buffer(IPCSerializationRecord const*, u32 side_table_index);
-JSCompletion web_structured_serialize_shared_buffers_shared_array_buffer(Vector<Core::AnonymousBuffer> const*, void* realm, u32 index, u64 shared_object_id);
JSCompletion web_structured_serialize_data_clone_error_from_serialization_error(void* realm, ReadonlyBytes message);
u64 web_structured_serialize_serializable_payload_version();
@@ -66,7 +64,7 @@ bool web_structured_serialize_is_exposed(u16 interface_name, void* realm);
u8 web_structured_serialize_serializable_steps(u16 interface_name);
JSCompletion web_structured_serialize_deserialize_rust_platform_object(u16 interface_name, void* realm, void* serialized);
-ImageBitmapSharedPixels* web_structured_serialize_gather_image_bitmap_pixels(Vector<Core::AnonymousBuffer>*, JSObject* const* transfer_list, size_t count);
+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();
@@ -74,8 +72,9 @@ void web_structured_serialize_transfer_data_holder_append(TransferDataEncoder*,
void web_structured_serialize_transfer_data_holder_destroy(TransferDataEncoder*);
SerializedTransferRecord* web_structured_serialize_transfer_record_create();
void web_structured_serialize_transfer_record_destroy(SerializedTransferRecord*);
-void web_structured_serialize_transfer_record_set_serialized(SerializedTransferRecord*, ReadonlyBytes data, JSObject* const* shared_array_buffers, size_t count);
-Vector<Core::AnonymousBuffer>* web_structured_serialize_transfer_record_shared_buffers(SerializedTransferRecord*);
+void web_structured_serialize_transfer_record_set_serialized(SerializedTransferRecord*, ReadonlyBytes data, JSObject* const* shared_array_buffers, size_t shared_array_buffer_count, int const* shared_memory, size_t const* shared_memory_sizes, size_t shared_memory_count);
+size_t web_structured_serialize_transfer_record_shared_memory_count(SerializedTransferRecord*);
+void web_structured_serialize_transfer_record_shared_memory(SerializedTransferRecord*, size_t index, int* shared_memory, size_t* size);
void web_structured_serialize_transfer_record_append_data_holder(SerializedTransferRecord*, TransferDataEncoder*);
size_t web_structured_serialize_transfer_record_data_holder_count(SerializedTransferRecord*);
TransferDataDecoder* web_structured_serialize_transfer_record_take_data_holder(SerializedTransferRecord*, size_t index);
@@ -153,33 +152,11 @@ bool web_structured_serialize_interface_name_from_storage_identifier(ReadonlyByt
return false;
}
-// AD-HOC: A SharedArrayBuffer backed by cross-process shared memory shares it through the side list of a record on the
-// messaging path, which hands it over by file descriptor.
-bool web_structured_serialize_shared_buffers_append_shared_memory(Vector<Core::AnonymousBuffer>* shared_buffers, JSObject* array_buffer, u32* index)
-{
- auto shared_buffer = array_buffer_from_abi(array_buffer).shared_buffer();
- if (!shared_buffer.has_value())
- return false;
- *index = static_cast<u32>(shared_buffers->size());
- shared_buffers->append(shared_buffer.release_value());
- return true;
-}
-
void web_structured_serialize_ipc_record_data(IPCSerializationRecord const* record, ReadonlyBytes* data)
{
*data = record->data.span();
}
-// AD-HOC: When the backing was transferred as cross-process shared memory, map it from the side list by index — so
-// both agents reference the same bytes.
-JSCompletion web_structured_serialize_shared_buffers_shared_array_buffer(Vector<Core::AnonymousBuffer> const* shared_buffers, void* realm, u32 index, u64 shared_object_id)
-{
- auto& js_realm = realm_from_abi(realm);
- if (index >= shared_buffers->size())
- return Bindings::completion_to_abi(js_realm, WebIDL::ExceptionOr<JS::Value> { data_clone_error_from_serialization_error(js_realm, AK::Error::from_string_literal("SharedArrayBuffer side-list index out of range")) });
- return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<JS::Value> { JS::ArrayBuffer::create(js_realm, shared_buffers->at(index), shared_object_id) });
-}
-
JSObject* web_structured_serialize_ipc_record_shared_array_buffer(IPCSerializationRecord const* record, u32 side_table_index)
{
auto shared_array_buffers = same_process_shared_array_buffers(*record);
@@ -277,7 +254,7 @@ JSCompletion web_structured_serialize_deserialize_rust_platform_object(u16 inter
// AD-HOC: Gather the pixels of the transferred ImageBitmaps in one buffer of shared memory. Without it, as when there
// is not enough memory for it, the pixels travel inline.
-ImageBitmapSharedPixels* web_structured_serialize_gather_image_bitmap_pixels(Vector<Core::AnonymousBuffer>* shared_buffers, JSObject* const* transfer_list, size_t count)
+ImageBitmapSharedPixels* web_structured_serialize_gather_image_bitmap_pixels(JSObject* const* transfer_list, size_t count, u32 buffer_index, int* shared_memory, size_t* size)
{
Checked<size_t> image_bitmap_pixels_size = 0;
for (size_t i = 0; i < count; ++i) {
@@ -289,8 +266,9 @@ ImageBitmapSharedPixels* web_structured_serialize_gather_image_bitmap_pixels(Vec
auto buffer = Core::AnonymousBuffer::create_with_size(image_bitmap_pixels_size.value());
if (buffer.is_error())
return nullptr;
- auto* image_bitmap_pixels = new ImageBitmapSharedPixels { .buffer = buffer.release_value(), .buffer_index = static_cast<u32>(shared_buffers->size()) };
- shared_buffers->append(image_bitmap_pixels->buffer);
+ auto* image_bitmap_pixels = new ImageBitmapSharedPixels { .buffer = buffer.release_value(), .buffer_index = buffer_index };
+ *shared_memory = image_bitmap_pixels->buffer.fd();
+ *size = image_bitmap_pixels->buffer.size();
return image_bitmap_pixels;
}
@@ -324,14 +302,24 @@ void web_structured_serialize_transfer_record_destroy(SerializedTransferRecord*
delete record;
}
-void web_structured_serialize_transfer_record_set_serialized(SerializedTransferRecord* record, ReadonlyBytes data, JSObject* const* shared_array_buffers, size_t count)
+// The record's [[Serialized]], with the shared memory of the transfer, whose descriptors it takes over.
+void web_structured_serialize_transfer_record_set_serialized(SerializedTransferRecord* record, ReadonlyBytes data, JSObject* const* shared_array_buffers, size_t shared_array_buffer_count, int const* shared_memory, size_t const* shared_memory_sizes, size_t shared_memory_count)
+{
+ record->serialized = create_ipc_serialization_record(data, shared_array_buffers_from_abi(shared_array_buffers, shared_array_buffer_count));
+ record->shared_buffers.ensure_capacity(shared_memory_count);
+ for (size_t i = 0; i < shared_memory_count; ++i)
+ record->shared_buffers.unchecked_append(MUST(Core::AnonymousBuffer::create_from_anon_fd(shared_memory[i], shared_memory_sizes[i])));
+}
+
+size_t web_structured_serialize_transfer_record_shared_memory_count(SerializedTransferRecord* record)
{
- record->serialized = create_ipc_serialization_record(data, shared_array_buffers_from_abi(shared_array_buffers, count));
+ return record->shared_buffers.size();
}
-Vector<Core::AnonymousBuffer>* web_structured_serialize_transfer_record_shared_buffers(SerializedTransferRecord* record)
+void web_structured_serialize_transfer_record_shared_memory(SerializedTransferRecord* record, size_t index, int* shared_memory, size_t* size)
{
- return &record->shared_buffers;
+ *shared_memory = record->shared_buffers[index].fd();
+ *size = record->shared_buffers[index].size();
}
void web_structured_serialize_transfer_record_append_data_holder(SerializedTransferRecord* record, TransferDataEncoder* data_holder)