Skip to content

Truly independent web browser

LibWeb: Share SharedArrayBuffer storage within a process from Rust

Shannon Booth04c67994019d
diff --git a/Libraries/LibJS/Rust/src/api.rs b/Libraries/LibJS/Rust/src/api.rs
index caef7457f30..45369464805 100644
--- a/Libraries/LibJS/Rust/src/api.rs
+++ b/Libraries/LibJS/Rust/src/api.rs
@@ -13,6 +13,7 @@ pub use crate::embedding::abi_types::{completion_into_abi, object_from_abi, vm_f
pub use crate::embedding::host::host_function::HostFunction;
pub use crate::embedding::host::host_module::{HostModule, host_class_of as host_module_class_of};
pub use crate::embedding::host::host_object::{HostObject, host_class_of, host_data_of, is_host_instance_of};
+pub use crate::gc::capi::GC_PRIMITIVE_STORAGE_NULL_HANDLE;
pub use crate::gc::class::ExternalMemorySize;
pub use crate::gc::defer_gc::DeferGc;
pub use crate::gc::embedder_cell::{EmbedderCell, EmbedderClass, EmbedderValue};
@@ -41,7 +42,7 @@ pub use crate::runtime::agent::agent_can_suspend;
pub use crate::runtime::array::Array;
pub use crate::runtime::array_buffer::{
ArrayBuffer, DataBlock, DataBlockStorage, ExternalPrimitiveStorage, Order as ArrayBufferOrder,
- Shared as ArrayBufferShared, clone_array_buffer, create_byte_data_block, detach_array_buffer,
+ Shared as ArrayBufferShared, SharedBackingStore, clone_array_buffer, create_byte_data_block, detach_array_buffer,
};
pub use crate::runtime::big_int::BigInt;
pub use crate::runtime::big_int_object::BigIntObject;
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 291683afbab..a7d64e53c4f 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs
@@ -44,10 +44,7 @@ unsafe extern "C" {
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,
- realm: *mut c_void,
side_table_index: u32,
- byte_length: usize,
- preserve_growability: bool,
) -> *mut c_void;
fn web_structured_serialize_shared_buffers_shared_array_buffer(
shared_buffers: *mut c_void,
@@ -293,25 +290,20 @@ impl<'a> ReceivedIPCSerializationRecord<'a> {
data.as_slice()
}
- /// A new SharedArrayBuffer in the realm that shares the storage of the buffer at the index of the record's
- /// same-process side table, if there is such a buffer, and its storage can be shared.
- pub(crate) fn shared_array_buffer(
- self,
- realm: Gc<Realm>,
- side_table_index: u32,
- byte_length: usize,
- preserve_growability: bool,
- ) -> Option<Gc<Object>> {
- // SAFETY: The record is lent, and the realm is live. LibWeb returns a live object or null.
- unsafe {
+ /// The SharedArrayBuffer at the index of the record's same-process side table, if there is one.
+ pub(crate) fn shared_array_buffer(self, side_table_index: u32) -> Option<Gc<ArrayBuffer>> {
+ // SAFETY: The record is lent. LibWeb returns a live object or null.
+ let object = unsafe {
object_from_abi(web_structured_serialize_ipc_record_shared_array_buffer(
self.raw.as_ptr(),
- realm.as_ptr().cast(),
side_table_index,
- byte_length,
- preserve_growability,
))
- }
+ }?;
+ Some(
+ object
+ .downcast::<ArrayBuffer>()
+ .expect("the side table holds ArrayBuffers"),
+ )
}
}
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 d14b5845392..79cdd9c3c4f 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs
@@ -1148,7 +1148,7 @@ impl Deserializer<'_, '_, '_> {
if let Some(array_buffer) =
self.serialized
- .array_buffer_sharing_side_table_entry(side_table_index, bytes.len(), false)
+ .array_buffer_sharing_side_table_entry(vm, side_table_index, bytes.len(), false)
{
value = Value::from_object(array_buffer);
break 'shared_array_buffer;
@@ -1179,12 +1179,9 @@ impl Deserializer<'_, '_, '_> {
if let Some(array_buffer) =
self.serialized
- .array_buffer_sharing_side_table_entry(side_table_index, bytes.len(), true)
+ .array_buffer_sharing_side_table_entry(vm, side_table_index, bytes.len(), true)
{
- let data = array_buffer
- .downcast::<ArrayBuffer>()
- .expect("the side table holds ArrayBuffers");
- data.set_max_byte_length(max_byte_length);
+ array_buffer.set_max_byte_length(max_byte_length);
value = Value::from_object(array_buffer);
break 'growable_shared_array_buffer;
}
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 cb5cbf1edac..5f8ad866f7b 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs
@@ -13,8 +13,14 @@
//! beside them. What the deserialization reads that the record does not hold throws a "DataCloneError" DOMException in
//! the realm that it creates its values in.
+use core::ffi::c_void;
+use core::ptr::NonNull;
+
use ak::Utf16String;
-use libjs_rust::api::{BigInt, Gc, Object, Realm, Value, Vm};
+use libjs_rust::api::{
+ ArrayBuffer, ArrayBufferShared, BigInt, DataBlock, DataBlockStorage, ExternalPrimitiveStorage, ForeignCellSlot,
+ GC_PRIMITIVE_STORAGE_NULL_HANDLE, Gc, Realm, SharedBackingStore, Value, Vm,
+};
use libwebcommon_rust::html::serialization_records::{DecodeError, DecodedString, RecordDecoder, SerializationType};
use crate::bindings::WebIdlResult;
@@ -184,13 +190,73 @@ impl<'a> StructuredSerializeReader<'a> {
shared_buffers.shared_array_buffer(self.realm, index, shared_object_id)
}
+ /// A new SharedArrayBuffer that shares the storage of the buffer at the index of the record's same-process side
+ /// table, if there is such a buffer, and its storage can be shared.
pub(crate) fn array_buffer_sharing_side_table_entry(
&self,
+ vm: &Vm,
side_table_index: u32,
byte_length: usize,
preserve_growability: bool,
- ) -> Option<Gc<Object>> {
- self.ipc_record?
- .shared_array_buffer(self.realm, side_table_index, byte_length, preserve_growability)
+ ) -> Option<Gc<ArrayBuffer>> {
+ let source_buffer = self.ipc_record?.shared_array_buffer(side_table_index)?;
+ array_buffer_sharing_storage_with(vm, self.realm, source_buffer, byte_length, preserve_growability)
}
}
+
+fn foreign_cell_slot(cell: NonNull<c_void>) -> ForeignCellSlot {
+ let slot = ForeignCellSlot::empty();
+ // SAFETY: The cell is a live cell of the heap, which the slot then keeps alive.
+ unsafe { slot.set(Some(cell)) };
+ slot
+}
+
+// Returns None when the source storage cannot be aliased, allowing the caller to copy it.
+fn array_buffer_sharing_storage_with(
+ vm: &Vm,
+ realm: Gc<Realm>,
+ source_buffer: Gc<ArrayBuffer>,
+ byte_length: usize,
+ preserve_growability: bool,
+) -> Option<Gc<ArrayBuffer>> {
+ assert!(source_buffer.is_shared_array_buffer());
+ let fixed_byte_length = (!preserve_growability).then_some(byte_length);
+ let data_block = source_buffer.with_data_block(|source_block| match &source_block.byte_buffer {
+ // Flatten alias chains to the actual owner. Keep this buffer's byte length because the owner's
+ // storage may be larger (for example, a fixed-length view of growable WebAssembly.Memory).
+ DataBlockStorage::External(external) => Some(DataBlock::external(
+ ExternalPrimitiveStorage::new(
+ foreign_cell_slot(external.owner()),
+ external.handle(),
+ fixed_byte_length,
+ ),
+ ArrayBufferShared::Yes,
+ )),
+
+ // AD-HOC: A fixed-length shared block backed by cross-process shared memory is aliased by referencing the same
+ // shared object — so the clone shares its bytes, and can itself be shared with an agent in another
+ // process.
+ DataBlockStorage::Shared(store) => {
+ SharedBackingStore::adopt(store.shared_memory(), store.size(), store.object_id())
+ .ok()
+ .map(DataBlock::shared_memory)
+ }
+
+ DataBlockStorage::Owned(owned) => {
+ // Zero-length buffers have no backing storage to share.
+ if owned.handle() == GC_PRIMITIVE_STORAGE_NULL_HANDLE {
+ return None;
+ }
+ // SAFETY: The source buffer is a live cell.
+ let owner = unsafe { NonNull::new_unchecked(source_buffer.as_ptr().cast()) };
+ Some(DataBlock::external(
+ ExternalPrimitiveStorage::new(foreign_cell_slot(owner), owned.handle(), fixed_byte_length),
+ ArrayBufferShared::Yes,
+ ))
+ }
+
+ // A detached block has no storage to share.
+ DataBlockStorage::Empty => None,
+ })?;
+ Some(ArrayBuffer::create_from_data_block(vm, realm, data_block))
+}
diff --git a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
index 4b268bbf540..1f6f8285e5f 100644
--- a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
+++ b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
@@ -52,7 +52,7 @@ bool web_structured_serialize_interface_name_from_storage_identifier(ReadonlyByt
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*, void* realm, u32 side_table_index, size_t byte_length, bool preserve_growability);
+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);
size_t web_structured_serialize_byte_buffer_size(ByteBuffer*);
JSObject* web_structured_serialize_array_buffer_from_byte_buffer(void* realm, ByteBuffer*, bool shared);
@@ -215,49 +215,12 @@ JSCompletion web_structured_serialize_shared_buffers_shared_array_buffer(Vector<
return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<JS::Value> { JS::ArrayBuffer::create(js_realm, shared_buffers->at(index), shared_object_id) });
}
-// Returns no value when the source storage cannot be aliased, allowing the caller to copy it.
-static Optional<JS::DataBlock> data_block_sharing_storage_with(JS::ArrayBuffer& source_buffer, size_t byte_length, bool preserve_growability = false)
-{
- VERIFY(source_buffer.is_shared_array_buffer());
- auto const& source_block = source_buffer.data_block();
-
- // Flatten alias chains to the actual owner. Keep this buffer's byte length because the owner's
- // storage may be larger (for example, a fixed-length view of growable WebAssembly.Memory).
- if (auto const* external = source_block.byte_buffer.get_pointer<JS::DataBlock::ExternalPrimitiveStorage>()) {
- if (preserve_growability)
- return JS::DataBlock { JS::DataBlock::ExternalPrimitiveStorage { external->owner, external->handle }, JS::DataBlock::Shared::Yes };
- return JS::DataBlock { JS::DataBlock::ExternalPrimitiveStorage { external->owner, external->handle, byte_length }, JS::DataBlock::Shared::Yes };
- }
-
- // AD-HOC: A fixed-length shared block backed by cross-process shared memory is aliased by referencing the same
- // shared object — so the clone shares its bytes, and can itself be shared with an agent in another process.
- if (auto const* shared = source_block.byte_buffer.get_pointer<JS::DataBlock::SharedBackingStore>())
- return JS::DataBlock { JS::DataBlock::SharedBackingStore { shared->buffer, shared->object_id }, JS::DataBlock::Shared::Yes };
-
- if (auto const* owned = source_block.byte_buffer.get_pointer<JS::DataBlock::OwnedBackingStore>()) {
- // Zero-length buffers have no backing storage to share.
- if (!owned->handle().is_valid())
- return {};
- if (preserve_growability)
- return JS::DataBlock { JS::DataBlock::ExternalPrimitiveStorage { GC::Ref<GC::Cell> { source_buffer }, owned->handle() }, JS::DataBlock::Shared::Yes };
- return JS::DataBlock { JS::DataBlock::ExternalPrimitiveStorage { GC::Ref<GC::Cell> { source_buffer }, owned->handle(), byte_length }, JS::DataBlock::Shared::Yes };
- }
-
- // A detached block has no storage to share.
- return {};
-}
-
-// A new SharedArrayBuffer that shares the storage of the buffer at the index of the record's same-process side table,
-// or null if there is no such buffer, or its storage cannot be shared.
-JSObject* web_structured_serialize_ipc_record_shared_array_buffer(IPCSerializationRecord const* record, void* realm, u32 side_table_index, size_t byte_length, bool preserve_growability)
+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);
if (side_table_index >= shared_array_buffers.size())
return nullptr;
- auto data_block = data_block_sharing_storage_with(*shared_array_buffers[side_table_index], byte_length, preserve_growability);
- if (!data_block.has_value())
- return nullptr;
- return JS::HostABI::object_to_abi(JS::ArrayBuffer::create(realm_from_abi(realm), data_block.release_value()).ptr());
+ return JS::HostABI::object_to_abi(shared_array_buffers[side_table_index].ptr());
}
JSCompletion web_structured_serialize_data_clone_error_from_serialization_error(void* realm, ReadonlyBytes message)