Truly independent web browser
LibJS+LibWeb+LibGC: Keep SharedArrayBuffer memory in its process
Andreas Kling9a54b9044318
diff --git a/Libraries/LibCore/System.cpp b/Libraries/LibCore/System.cppindex cf26ab666a6..9480ba04c54 100644--- a/Libraries/LibCore/System.cpp+++ b/Libraries/LibCore/System.cpp@@ -226,15 +226,6 @@ ErrorOr<void> decommit_memory(void* address, size_t size, MemoryTag tag)return {};}-ErrorOr<void> map_shared_memory_fixed(void* address, size_t size, int fd)-{- auto* ptr = ::mmap(address, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd, 0);- if (ptr == MAP_FAILED)- return Error::from_syscall("mmap"sv, errno);- VERIFY(ptr == address);- return {};-}-ErrorOr<void> release_address_space(void* address, size_t size){if (::munmap(address, size) < 0)diff --git a/Libraries/LibCore/System.h b/Libraries/LibCore/System.hindex 5d10605d13c..e96ab59b150 100644--- a/Libraries/LibCore/System.h+++ b/Libraries/LibCore/System.h@@ -143,7 +143,6 @@ CORE_API ErrorOr<void> decommit_memory(void* address, size_t size, MemoryTag = MCORE_API ErrorOr<void> release_address_space(void* address, size_t size);// Used for placing a SharedArrayBuffer's cross-process shared memory inside the primitive storage cage.-CORE_API ErrorOr<void> map_shared_memory_fixed(void* address, size_t size, int fd);CORE_API ErrorOr<void> close(int fd);CORE_API ErrorOr<int> dup(int source_fd);diff --git a/Libraries/LibCore/SystemWindows.cpp b/Libraries/LibCore/SystemWindows.cppindex c273421ad22..e56aa4dc052 100644--- a/Libraries/LibCore/SystemWindows.cpp+++ b/Libraries/LibCore/SystemWindows.cpp@@ -121,12 +121,6 @@ ErrorOr<void> release_address_space(void* address, size_t size)return {};}-ErrorOr<void> map_shared_memory_fixed(void*, size_t, int)-{- // FIXME: Placing a file-mapping view at a fixed address inside a reservation needs the Windows 10+ placeholder APIs.- return Error::from_errno(ENOTSUP);-}-int getpid(){return GetCurrentProcessId();diff --git a/Libraries/LibGC/CAPI.cpp b/Libraries/LibGC/CAPI.cppindex f7f52f6afe7..bdd563c4044 100644--- a/Libraries/LibGC/CAPI.cpp+++ b/Libraries/LibGC/CAPI.cpp@@ -5,7 +5,6 @@*/#include <AK/StdLibExtras.h>-#include <LibCore/AnonymousBuffer.h>#include <LibCore/System.h>#include <LibGC/BlockAllocator.h>#include <LibGC/CAPI.h>@@ -448,12 +447,6 @@ bool gc_primitive_storage_reserve(size_t size, size_t capacity, bool zero_fill,return store_created_primitive_storage(storage, storage.try_reserve(size, capacity, as_zero_fill_new_bytes(zero_fill), guard_size), out_handle, out_layout);}-bool gc_primitive_storage_adopt_shared_fd(int fd, size_t size, GCPrimitiveStorageHandle* out_handle, GCPrimitiveStorageLayout* out_layout)-{- auto& storage = PrimitiveStorage::the();- return store_created_primitive_storage(storage, storage.try_adopt_shared_fd(fd, size), out_handle, out_layout);-}-bool gc_primitive_storage_resize(GCPrimitiveStorageHandle handle, size_t new_size, bool zero_fill, GCPrimitiveStorageLayout* out_layout){auto& storage = PrimitiveStorage::the();@@ -509,49 +502,4 @@ uint8_t* gc_primitive_storage_data(GCPrimitiveStorageHandle handle){return PrimitiveStorage::the().data(decode_primitive_storage_handle(handle));}--bool gc_shared_memory_create(size_t size, int* out_fd)-{- *out_fd = -1;- auto buffer = Core::AnonymousBuffer::create_with_size(size);- if (buffer.is_error())- return false;- // NB: The buffer closes its descriptor and unmaps its own view of the memory when it goes away; the caller gets a- // duplicate of the descriptor.- auto fd = Core::System::dup(buffer.value().fd());- if (fd.is_error())- return false;- *out_fd = fd.value();- return true;-}--struct GCSharedMemoryViewOutsideCage {- AK_ALLOC_WITH_KMALLOC;-- Core::AnonymousBuffer buffer;-};--GCSharedMemoryViewOutsideCage* gc_shared_memory_view_outside_cage_create(int fd, size_t size)-{- if (size == 0)- return nullptr;- auto duplicate_fd = Core::System::dup(fd);- if (duplicate_fd.is_error())- return nullptr;- // NB: The buffer owns the duplicate from here on, and closes it if mapping fails.- auto buffer = Core::AnonymousBuffer::create_from_anon_fd(duplicate_fd.value(), size);- if (buffer.is_error() || buffer.value().validate_backing_size().is_error())- return nullptr;- return new GCSharedMemoryViewOutsideCage { buffer.release_value() };-}--uint8_t* gc_shared_memory_view_outside_cage_data(GCSharedMemoryViewOutsideCage* view)-{- return view->buffer.data<uint8_t>();-}--void gc_shared_memory_view_outside_cage_destroy(GCSharedMemoryViewOutsideCage* view)-{- delete view;-}}diff --git a/Libraries/LibGC/CAPI.h b/Libraries/LibGC/CAPI.hindex e9f1c7c3a3d..427257df709 100644--- a/Libraries/LibGC/CAPI.h+++ b/Libraries/LibGC/CAPI.h@@ -227,7 +227,6 @@ GC_API bool gc_primitive_storage_reserve(size_t size, size_t capacity, bool zero// Maps the first size bytes of the shared memory object behind fd into the cage. The mapping keeps the memory alive by// itself, so the caller keeps ownership of fd and may close it at any time. Fails if size is 0. Growing the storage// would replace the mapping with private memory, so shared storage keeps its size.-GC_API bool gc_primitive_storage_adopt_shared_fd(int fd, size_t size, GCPrimitiveStorageHandle* out_handle, GCPrimitiveStorageLayout* out_layout);// The resizing functions return false and leave the storage as it was if the handle names no storage or memory runs// out. Within the capacity, the storage stays where it is; beyond it, the bytes move to new storage, which changes the@@ -252,22 +251,6 @@ GC_API size_t gc_primitive_storage_capacity(GCPrimitiveStorageHandle);GC_API size_t gc_primitive_storage_committed_size(GCPrimitiveStorageHandle);GC_API uint8_t* gc_primitive_storage_data(GCPrimitiveStorageHandle);-// Creates a zero-filled shared memory object of size bytes, made the way the C++ runtime makes the memory of a-// fixed-length SharedArrayBuffer: sealed against resizing where the platform supports seals, so that another process-// holding it cannot shrink it under this one. On success, *out_fd is a new close-on-exec descriptor that the caller owns and must-// close, and that can be passed to other processes and to gc_primitive_storage_adopt_shared_fd(). On failure, *out_fd-// is -1.-GC_API bool gc_shared_memory_create(size_t size, int* out_fd);--// Maps the first size bytes of the shared memory object behind fd outside the cage, for a platform where-// gc_primitive_storage_adopt_shared_fd() cannot place the mapping inside it, as on Windows. The view keeps a duplicate-// of fd, so the caller keeps ownership of fd. Returns null if size is 0, the object is smaller than size bytes, or-// mapping fails.-typedef struct GCSharedMemoryViewOutsideCage GCSharedMemoryViewOutsideCage;-GC_API GCSharedMemoryViewOutsideCage* gc_shared_memory_view_outside_cage_create(int fd, size_t size);-GC_API uint8_t* gc_shared_memory_view_outside_cage_data(GCSharedMemoryViewOutsideCage*);-GC_API void gc_shared_memory_view_outside_cage_destroy(GCSharedMemoryViewOutsideCage*);-#ifdef __cplusplus}#endifdiff --git a/Libraries/LibGC/PrimitiveStorage.cpp b/Libraries/LibGC/PrimitiveStorage.cppindex 21e647233f8..e51d40c8165 100644--- a/Libraries/LibGC/PrimitiveStorage.cpp+++ b/Libraries/LibGC/PrimitiveStorage.cpp@@ -200,31 +200,6 @@ ErrorOr<PrimitiveStorage::Allocator::Allocation> PrimitiveStorage::Allocator::al};}-ErrorOr<PrimitiveStorage::Allocator::Allocation> PrimitiveStorage::Allocator::adopt_shared_fd(int fd, size_t size)-{- VERIFY(size > 0);- TRY(ensure_cage());-- auto reservation_size = round_up_to_page(size);- auto offset = TRY(allocate_cage_range(reservation_size));-- // Replace the reserved PROT_NONE pages at this offset with a shared mapping of fd. On teardown, deallocate() runs- // the same decommit path as any large allocation — which re-establishes the PROT_NONE reservation and drops this.- auto map_result = Core::System::map_shared_memory_fixed(m_cage_base + offset, reservation_size, fd);- if (map_result.is_error()) {- release_cage_range(offset, reservation_size);- return map_result.release_error();- }-- return Allocation {- .offset = offset,- .capacity = size,- .reservation_size = reservation_size,- .committed_size = reservation_size,- .small_allocation = {},- };-}-ErrorOr<size_t> PrimitiveStorage::Allocator::allocate_cage_range(size_t reservation_size){VERIFY(m_cage_base);@@ -441,16 +416,6 @@ ErrorOr<PrimitiveStorageHandle> PrimitiveStorage::try_reserve(size_t size, size_return install_allocation(move(allocation), size);}-ErrorOr<PrimitiveStorageHandle> PrimitiveStorage::try_adopt_shared_fd(int fd, size_t size)-{- MutexLocker locker { m_mutex };- if (size == 0)- return Error::from_errno(EINVAL);-- auto allocation = TRY(m_allocator.adopt_shared_fd(fd, size));- return install_allocation(move(allocation), size);-}-PrimitiveStorageHandle PrimitiveStorage::install_allocation(Allocator::Allocation allocation, size_t size){auto handle = allocate_entry(primitive_storage_tag);diff --git a/Libraries/LibGC/PrimitiveStorage.h b/Libraries/LibGC/PrimitiveStorage.hindex 3472571cfb1..c14d6cfc8d9 100644--- a/Libraries/LibGC/PrimitiveStorage.h+++ b/Libraries/LibGC/PrimitiveStorage.h@@ -46,7 +46,6 @@ public:ErrorOr<PrimitiveStorageHandle> try_allocate(size_t size, ZeroFillNewBytes = ZeroFillNewBytes::Yes);ErrorOr<PrimitiveStorageHandle> try_reserve(size_t size, size_t capacity, ZeroFillNewBytes = ZeroFillNewBytes::Yes, size_t guard_size = 0);- ErrorOr<PrimitiveStorageHandle> try_adopt_shared_fd(int fd, size_t size);ErrorOr<void> ensure_cage();@@ -100,7 +99,6 @@ private:};ErrorOr<Allocation> allocate(size_t size, size_t capacity, ZeroFillNewBytes, size_t guard_size, bool force_large);- ErrorOr<Allocation> adopt_shared_fd(int fd, size_t size);ErrorOr<void> resize(Allocation&, size_t old_size, size_t new_size, ZeroFillNewBytes);ErrorOr<Allocation> reallocate(Allocation const&, size_t old_size, size_t new_size, size_t new_capacity, ZeroFillNewBytes, bool force_large);void deallocate(Allocation&);diff --git a/Libraries/LibJS/Runtime/ArrayBuffer.cpp b/Libraries/LibJS/Runtime/ArrayBuffer.cppindex 65c10a7710c..12554d2b56f 100644--- a/Libraries/LibJS/Runtime/ArrayBuffer.cpp+++ b/Libraries/LibJS/Runtime/ArrayBuffer.cpp@@ -50,11 +50,14 @@ GC::Ref<ArrayBuffer> ArrayBuffer::create_over_external_storage(Realm& realm, Datreturn array_buffer_from_abi(js_array_buffer_create_with_external_storage(vm_to_abi(realm.vm()), cell_to_abi<JSRealm>(realm), &storage_for_the_runtime, is_shared == DataBlock::Shared::Yes));}-GC::Ptr<ArrayBuffer> ArrayBuffer::create_over_shared_memory(Realm& realm, int shared_memory_fd, size_t byte_length, u64 shared_object_id)+GC::Ptr<ArrayBuffer> ArrayBuffer::create_from_shared_store(Realm& realm, u64 shared_store_id){- if (shared_memory_fd < 0)- return nullptr;- return cell_from_abi<ArrayBuffer>(js_array_buffer_create_from_shared_memory(vm_to_abi(realm.vm()), cell_to_abi<JSRealm>(realm), shared_memory_fd, byte_length, shared_object_id));+ return cell_from_abi<ArrayBuffer>(js_array_buffer_create_from_shared_store(vm_to_abi(realm.vm()), cell_to_abi<JSRealm>(realm), shared_store_id));+}++u64 ArrayBuffer::shared_store_id() const+{+ return js_array_buffer_shared_store_id(cell_to_abi<JSObject>(const_cast<ArrayBuffer&>(*this)));}GC::Ref<ArrayBuffer> ArrayBuffer::create_detached(Realm& realm)@@ -106,13 +109,6 @@ ErrorOr<ByteBuffer> ArrayBuffer::copy_to_byte_buffer() constreturn ByteBuffer::copy(bytes_from(0));}-u64 ArrayBuffer::shared_object_id() const-{- JSArrayBufferStorage storage;- js_array_buffer_storage(array_buffer_to_abi(*this), &storage);- return storage.shared_memory_object_id;-}-void ArrayBuffer::copy_data_to(ArrayBuffer& destination, size_t source_offset, size_t destination_offset, size_t count) const{auto source_bytes = bytes_from(source_offset);@@ -159,9 +155,9 @@ ArrayBuffer::StorageDescription ArrayBuffer::storage_description_from_abi(JSArraif (storage.external.has_fixed_byte_length)description.external_fixed_byte_length = storage.external.fixed_byte_length;break;- case JS_ARRAY_BUFFER_STORAGE_SHARED_MEMORY:- description.kind = StorageKind::SharedMemory;- description.shared_memory_object_id = storage.shared_memory_object_id;+ case JS_ARRAY_BUFFER_STORAGE_SHARED_STORE:+ description.kind = StorageKind::SharedStore;+ description.handle = primitive_storage_handle_from_abi(storage.handle);break;default:VERIFY_NOT_REACHED();@@ -176,10 +172,6 @@ ArrayBuffer::StorageDescription ArrayBuffer::describe_storage() constjs_array_buffer_storage(buffer, &storage);auto description = storage_description_from_abi(storage);description.is_shared = js_array_buffer_is_shared_array_buffer(buffer) ? DataBlock::Shared::Yes : DataBlock::Shared::No;- if (description.kind == StorageKind::SharedMemory) {- description.shared_memory_fd = js_array_buffer_duplicate_shared_memory(buffer, &description.shared_memory_byte_length);- VERIFY(description.shared_memory_fd >= 0);- }return description;}diff --git a/Libraries/LibJS/Runtime/ArrayBuffer.h b/Libraries/LibJS/Runtime/ArrayBuffer.hindex 700f0593622..83e0a3a27a1 100644--- a/Libraries/LibJS/Runtime/ArrayBuffer.h+++ b/Libraries/LibJS/Runtime/ArrayBuffer.h@@ -10,7 +10,6 @@#include <AK/Optional.h>#include <AK/Span.h>#include <AK/Variant.h>-#include <LibCore/AnonymousBuffer.h>#include <LibGC/PrimitiveStorage.h>#include <LibJS/Export.h>#include <LibJS/Runtime/BigInt.h>@@ -172,41 +171,14 @@ struct DataBlock {GC::Ref<GC::Cell> owner;};- // AD-HOC: Backs a shared, fixed-length Data Block with cross-process shared memory, so a SharedArrayBuffer can be- // genuinely shared (not copied) across agents in different processes. object_id names the shared object- // in every agent that maps it, and is 0 for an object without one. The runtime maps the object into the- // primitive storage cage when a buffer is created over it.+ // AD-HOC: A shared, fixed-length Data Block is a store that the runtime shares between the agents of the process+ // and keeps alive. This describes one.struct SharedBackingStore {- explicit SharedBackingStore(Core::AnonymousBuffer buffer, u64 object_id = 0)- : buffer(move(buffer))- , object_id(object_id)- {- }-- SharedBackingStore(SharedBackingStore&& other)- : buffer(move(other.buffer))- , object_id(exchange(other.object_id, 0))- {- }-- SharedBackingStore& operator=(SharedBackingStore&& other)- {- if (this != &other) {- buffer = move(other.buffer);- object_id = exchange(other.object_id, 0);- }- return *this;- }-- SharedBackingStore(SharedBackingStore const&) = delete;- SharedBackingStore& operator=(SharedBackingStore const&) = delete;-- u8* data() { return buffer.data<u8>(); }- u8 const* data() const { return buffer.data<u8>(); }- size_t size() const { return buffer.size(); }+ u8* data() { return GC::PrimitiveStorage::the().data(handle); }+ u8 const* data() const { return GC::PrimitiveStorage::the().data(handle); }+ size_t size() const { return GC::PrimitiveStorage::the().size(handle); }- Core::AnonymousBuffer buffer;- u64 object_id { 0 };+ GC::PrimitiveStorageHandle handle;};u8* data_at(size_t byte_offset)@@ -284,21 +256,7 @@ struct DataBlock {}bool is_external() const { return byte_buffer.has<ExternalPrimitiveStorage>(); }- bool is_cross_process_shared() const { return byte_buffer.has<SharedBackingStore>(); }-- Optional<Core::AnonymousBuffer> shared_anonymous_buffer() const- {- if (auto const* shared = byte_buffer.get_pointer<SharedBackingStore>())- return shared->buffer;- return {};- }-- u64 shared_object_id() const- {- if (auto const* shared = byte_buffer.get_pointer<SharedBackingStore>())- return shared->object_id;- return 0;- }+ bool is_in_shared_store() const { return byte_buffer.has<SharedBackingStore>(); }Variant<Empty, OwnedBackingStore, ExternalPrimitiveStorage, SharedBackingStore> byte_buffer;Shared is_shared = { Shared::No };@@ -307,7 +265,7 @@ struct DataBlock {// An ArrayBuffer or a SharedArrayBuffer of the Rust runtime, whose data block the runtime keeps.//// The members that make or take a DataBlock are defined in this header, over out-of-line members that describe the-// storage in plain values, because a DataBlock can hold a Core::AnonymousBuffer, and LibJS links LibCore privately.+// storage in plain values.class JS_API ArrayBuffer final : public Object {public:static bool is_engine_class_of(Object const& object) { return object.engine_class_id() == JS_LAYOUT_CLASS_ID_ARRAY_BUFFER; }@@ -315,7 +273,6 @@ public:static ThrowCompletionOr<GC::Ref<ArrayBuffer>> create(Realm&, size_t, DataBlock::Shared = DataBlock::Shared::No);static GC::Ref<ArrayBuffer> create(Realm&, ByteBuffer, DataBlock::Shared = DataBlock::Shared::No);static GC::Ref<ArrayBuffer> create(Realm&, DataBlock);- static GC::Ref<ArrayBuffer> create(Realm&, Core::AnonymousBuffer, u64 shared_object_id);size_t byte_length() const;@@ -325,8 +282,6 @@ public:void copy_to(size_t offset, Bytes destination) const;ErrorOr<ByteBuffer> copy_to_byte_buffer(size_t offset, size_t count) const;ErrorOr<ByteBuffer> copy_to_byte_buffer() const;- Optional<Core::AnonymousBuffer> shared_buffer() const;- u64 shared_object_id() const;template<typename Callback>decltype(auto) with_readonly_bytes(size_t offset, size_t count, Callback callback) const;void copy_data_to(ArrayBuffer& destination, size_t source_offset, size_t destination_offset, size_t count) const;@@ -360,6 +315,12 @@ public:// 25.2.2.2 IsSharedArrayBuffer ( obj ), https://tc39.es/ecma262/#sec-issharedarraybufferbool is_shared_array_buffer() const;+ // The id of the store that agents of this process share, or 0 if this buffer has none.+ u64 shared_store_id() const;++ // A new SharedArrayBuffer over the store that the id names, if this process has it.+ static GC::Ptr<ArrayBuffer> create_from_shared_store(Realm&, u64 shared_store_id);+enum Order {SeqCst,Unordered@@ -429,20 +390,16 @@ private:Detached,Owned,External,- SharedMemory,+ SharedStore,};- // The storage of a data block in plain values. A description of the storage of a buffer comes with a duplicate of- // the descriptor of its shared memory object, which the receiver owns.+ // The storage of a data block in plain values.struct StorageDescription {StorageKind kind { StorageKind::Detached };DataBlock::Shared is_shared { DataBlock::Shared::No };GC::PrimitiveStorageHandle handle;GC::Ptr<GC::Cell> external_owner;Optional<size_t> external_fixed_byte_length;- int shared_memory_fd { -1 };- size_t shared_memory_byte_length { 0 };- u64 shared_memory_object_id { 0 };};enum class OwnedStorageGoesToTheBlock {@@ -457,7 +414,6 @@ private:static GC::Ref<ArrayBuffer> create_taking_over_storage(Realm&, GC::PrimitiveStorageHandle, DataBlock::Shared);static GC::Ref<ArrayBuffer> create_over_external_storage(Realm&, DataBlock::ExternalPrimitiveStorage const&, DataBlock::Shared);- static GC::Ptr<ArrayBuffer> create_over_shared_memory(Realm&, int shared_memory_fd, size_t byte_length, u64 shared_object_id);static GC::Ref<ArrayBuffer> create_detached(Realm&);void set_external_storage(DataBlock::ExternalPrimitiveStorage const&, DataBlock::Shared);};@@ -475,10 +431,8 @@ inline DataBlock ArrayBuffer::data_block_from(StorageDescription const& storage,if (storage.external_fixed_byte_length.has_value())return DataBlock { DataBlock::ExternalPrimitiveStorage { *storage.external_owner, storage.handle, *storage.external_fixed_byte_length }, storage.is_shared };return DataBlock { DataBlock::ExternalPrimitiveStorage { *storage.external_owner, storage.handle }, storage.is_shared };- case StorageKind::SharedMemory: {- auto shared_memory = MUST(Core::AnonymousBuffer::create_from_anon_fd(storage.shared_memory_fd, storage.shared_memory_byte_length));- return DataBlock { DataBlock::SharedBackingStore { move(shared_memory), storage.shared_memory_object_id }, DataBlock::Shared::Yes };- }+ case StorageKind::SharedStore:+ return DataBlock { DataBlock::SharedBackingStore { storage.handle }, DataBlock::Shared::Yes };}VERIFY_NOT_REACHED();}@@ -496,31 +450,12 @@ inline GC::Ref<ArrayBuffer> ArrayBuffer::create(Realm& realm, DataBlock block)[&](DataBlock::ExternalPrimitiveStorage const& external) {return create_over_external_storage(realm, external, block.is_shared);},- [&](DataBlock::SharedBackingStore const& shared) {- VERIFY(block.is_shared == DataBlock::Shared::Yes);- return create(realm, shared.buffer, shared.object_id);+ [&](DataBlock::SharedBackingStore const&) -> GC::Ref<ArrayBuffer> {+ // NB: Only the runtime can share a store with a new buffer.+ VERIFY_NOT_REACHED();});}-inline GC::Ref<ArrayBuffer> ArrayBuffer::create(Realm& realm, Core::AnonymousBuffer shared_memory, u64 shared_object_id)-{- if (auto buffer = create_over_shared_memory(realm, shared_memory.fd(), shared_memory.size(), shared_object_id))- return *buffer;-- // The runtime cannot map the object into the primitive storage cage, where the bytes of every buffer live, so the- // buffer gets a copy of its bytes instead. A buffer of no bytes has none to share.- auto bytes = shared_memory.size() > 0 ? MUST(ByteBuffer::copy(shared_memory.data<u8>(), shared_memory.size())) : ByteBuffer {};- return create(realm, move(bytes), DataBlock::Shared::Yes);-}--inline Optional<Core::AnonymousBuffer> ArrayBuffer::shared_buffer() const-{- auto storage = describe_storage();- if (storage.kind != StorageKind::SharedMemory)- return {};- return MUST(Core::AnonymousBuffer::create_from_anon_fd(storage.shared_memory_fd, storage.shared_memory_byte_length));-}-inline DataBlock const ArrayBuffer::data_block() const{return data_block_from(describe_storage(), OwnedStorageGoesToTheBlock::No);diff --git a/Libraries/LibJS/Runtime/VM.cpp b/Libraries/LibJS/Runtime/VM.cppindex bc2d246dec5..28a3c8049c2 100644--- a/Libraries/LibJS/Runtime/VM.cpp+++ b/Libraries/LibJS/Runtime/VM.cpp@@ -308,11 +308,9 @@ VM::VM(ErrorMessages error_messages){VERIFY(static_cast<void*>(m_engine_storage) == static_cast<void*>(this));- // The embedder's C++ cells live in the VM's heap, and a SharedArrayBuffer of a fixed length lives in memory that- // other processes can map.+ // The embedder's C++ cells live in the VM's heap.JSVmOptions options {.become_thread_default_heap = true,- .shared_memory_shared_array_buffers = true,};VERIFY(js_vm_construct_at(m_engine_storage, sizeof(m_engine_storage), alignof(VM), &options));diff --git a/Libraries/LibJS/Rust/src/api.rs b/Libraries/LibJS/Rust/src/api.rsindex 65a9514d9ea..b2a8e0e5dea 100644--- a/Libraries/LibJS/Rust/src/api.rs+++ b/Libraries/LibJS/Rust/src/api.rs@@ -46,8 +46,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, OutOfMemory,- OwnedBackingStore, Shared as ArrayBufferShared, SharedBackingStore, clone_array_buffer, create_byte_data_block,- detach_array_buffer,+ OwnedBackingStore, Shared as ArrayBufferShared, 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;@@ -86,6 +85,11 @@ pub use crate::runtime::realm::Realm;pub use crate::runtime::regexp_object::{RegExpObject, regexp_create};pub use crate::runtime::set::Set;pub use crate::runtime::set_iterator::SetIterator;+pub use crate::runtime::shared_backing_store::{+ SharedBackingStore, SharedStoreLifeline, duplicate_lifeline_from_raw_descriptor, lifeline_from_raw_descriptor,+ lifeline_into_raw_descriptor,+ pin_stores_for_a_message, release_stores_of_lost_messages,+};pub use crate::runtime::string_object::StringObject;pub use crate::runtime::typed_array::{Kind as TypedArrayKind, TypedArrayBase, TypedArrayWithBufferWitness, create_typed_array,diff --git a/Libraries/LibJS/Rust/src/contrib/test262/agent_object.rs b/Libraries/LibJS/Rust/src/contrib/test262/agent_object.rsindex 0c439102c1c..9cd00d7d99d 100644--- a/Libraries/LibJS/Rust/src/contrib/test262/agent_object.rs+++ b/Libraries/LibJS/Rust/src/contrib/test262/agent_object.rs@@ -26,11 +26,10 @@ use {crate::runtime::array_buffer::{ArrayBuffer, DataBlockStorage},crate::runtime::big_int::{BigInt, SignedBigInteger},crate::runtime::error::ErrorKind,- crate::runtime::error_types::ErrorType,crate::runtime::primitive_string::PrimitiveString,crate::utf16::{Utf16View, utf16_from_wtf8},ak::Utf16String,- std::os::fd::AsFd,+ std::sync::Arc,};#[repr(C)]@@ -134,29 +133,17 @@ impl AgentObject {BroadcastNumber::Number(number.to_number(vm)?.as_f64())};- let shared_memory = shared_array_buffer.with_data_block(|block| match &block.byte_buffer {- DataBlockStorage::Shared(store) => store- .shared_memory()- .try_clone_to_owned()- .ok()- .map(|shared_memory| (shared_memory, store.object_id())),+ let store = shared_array_buffer.with_data_block(|block| match &block.byte_buffer {+ DataBlockStorage::Shared(store) => Some(Arc::clone(store)),_ => None,});- let Some((shared_memory, object_id)) = shared_memory else {+ let Some(store) = store else {return vm.throw_completion_with_message(ErrorKind::TypeError,- "Agents cannot map a SharedArrayBuffer that is not in shared memory".to_string(),+ "Agents cannot share a SharedArrayBuffer that is not in a shared store".to_string(),);};- let byte_length = shared_array_buffer.byte_length();- agents::broadcast(|| {- Ok(Broadcast {- shared_memory: shared_memory.as_fd().try_clone_to_owned()?,- byte_length,- object_id,- number: number.clone(),- })- });+ agents::broadcast(&Broadcast { store, number });Ok(Value::UNDEFINED)}@@ -195,19 +182,7 @@ impl AgentObject {let realm = vm.current_realm().expect("$262.agent.receiveBroadcast() runs in a realm");- let Ok(shared_array_buffer) = ArrayBuffer::create_from_shared_memory(- vm,- realm,- broadcast.shared_memory.as_fd(),- broadcast.byte_length,- broadcast.object_id,- ) else {- return vm.throw_completion(- ErrorKind::RangeError,- ErrorType::NotEnoughMemoryToAllocate,- &[&broadcast.byte_length],- );- };+ let shared_array_buffer = ArrayBuffer::create_from_shared_store(vm, realm, broadcast.store);let number = match broadcast.number {BroadcastNumber::Undefined => Value::UNDEFINED,BroadcastNumber::Number(number) => Value::from_f64(number),diff --git a/Libraries/LibJS/Rust/src/contrib/test262/agents.rs b/Libraries/LibJS/Rust/src/contrib/test262/agents.rsindex 91284502fd7..120c64a04c5 100644--- a/Libraries/LibJS/Rust/src/contrib/test262/agents.rs+++ b/Libraries/LibJS/Rust/src/contrib/test262/agents.rs@@ -14,11 +14,11 @@use std::cell::RefCell;use std::collections::VecDeque;-use std::os::fd::OwnedFd;use std::sync::{Arc, Condvar, Mutex, PoisonError};use std::thread::JoinHandle;use crate::interpreter::vm::Vm;+use crate::runtime::shared_backing_store::SharedBackingStore;/// JS::VM::MINIMUM_THREAD_STACK_SIZE, which the thread of a VM needs.const AGENT_THREAD_STACK_SIZE: usize = 8 * 1024 * 1024;@@ -32,13 +32,10 @@ pub enum BroadcastNumber {BigInt(Vec<u8>),}-/// A broadcast as an agent receives it: the SharedArrayBuffer's shared memory object and what names it, and the-/// number.-#[derive(Debug)]+/// A broadcast as an agent receives it: the store of the SharedArrayBuffer, and the number.+#[derive(Clone)]pub struct Broadcast {- pub shared_memory: OwnedFd,- pub byte_length: usize,- pub object_id: u64,+ pub store: Arc<SharedBackingStore>,pub number: BroadcastNumber,}@@ -174,15 +171,12 @@ impl RunningAgents {Ok(())}- fn broadcast(&mut self, broadcast: impl Fn() -> std::io::Result<Broadcast>) {+ fn broadcast(&mut self, broadcast: &Broadcast) {for agent in &self.agents {// An agent that already exited cannot take the message, and the test cannot expect it to.- let Ok(broadcast) = broadcast() else {- continue;- };agent.agent.update(|state| {if !state.has_finished {- state.broadcasts.push_back(broadcast);+ state.broadcasts.push_back(broadcast.clone());}});}@@ -211,8 +205,9 @@ pub fn start_agent(source: &[u8]) -> Result<(), String> {.map_err(|error| format!("Could not start an agent: {error}"))}-/// $262.agent.broadcast(): hands every running agent what `broadcast` makes for it, and returns once each has it.-pub fn broadcast(broadcast: impl Fn() -> std::io::Result<Broadcast>) {+/// $262.agent.broadcast(): hands a SharedArrayBuffer's store and a number to every running agent, and returns once each+/// has them.+pub fn broadcast(broadcast: &Broadcast) {RUNNING_AGENTS.with_borrow_mut(|running_agents| running_agents.broadcast(broadcast));}diff --git a/Libraries/LibJS/Rust/src/embedding/array_buffer.rs b/Libraries/LibJS/Rust/src/embedding/array_buffer.rsindex ec75bc49571..e531bc2f420 100644--- a/Libraries/LibJS/Rust/src/embedding/array_buffer.rs+++ b/Libraries/LibJS/Rust/src/embedding/array_buffer.rs@@ -11,7 +11,7 @@//! object that agents in other processes map too. Storage handles cross as the GCPrimitiveStorageHandle word of//! LibGC/CAPI.h. Every function here must be called on the thread that runs the VM.-use core::ffi::{c_int, c_void};+use core::ffi::c_void;use core::ptr::NonNull;use crate::embedding::abi_types::{@@ -21,7 +21,6 @@ use crate::embedding::abi_types::{use crate::gc::capi::GC_PRIMITIVE_STORAGE_NULL_HANDLE;use crate::gc::class::{Extends, GcCell};use crate::gc::foreign::ForeignCellSlot;-use crate::gc::shared_memory::{borrowed_from_raw_descriptor, into_raw_descriptor};use crate::layout::cell::Gc;use crate::layout::host_class::{JSCompletion, JSObject, JSVM, JSValue};use crate::layout::object::Object;@@ -35,6 +34,7 @@ use crate::runtime::data_view::{DataView, DataViewWithBufferWitness, get_view_byte_length, is_view_out_of_bounds,make_data_view_with_buffer_witness_record,};+use crate::runtime::shared_backing_store::SharedBackingStore;/// JSArrayBufferStorage.kind of a detached buffer, which has no storage.pub const JS_ARRAY_BUFFER_STORAGE_DETACHED: u8 = 0;@@ -43,7 +43,7 @@ pub const JS_ARRAY_BUFFER_STORAGE_OWNED: u8 = 1;/// JSArrayBufferStorage.kind of storage that a GC cell of the embedder owns.pub const JS_ARRAY_BUFFER_STORAGE_EXTERNAL: u8 = 2;/// JSArrayBufferStorage.kind of a fixed-length SharedArrayBuffer in a shared memory object.-pub const JS_ARRAY_BUFFER_STORAGE_SHARED_MEMORY: u8 = 3;+pub const JS_ARRAY_BUFFER_STORAGE_SHARED_STORE: u8 = 3;/// JS::ArrayBuffer::Order, the order of the read of a SharedArrayBuffer's byte length.pub const JS_ARRAY_BUFFER_ORDER_SEQ_CST: u8 = 0;@@ -92,9 +92,6 @@ pub struct JSArrayBufferStorage {pub handle: u64,/// For JS_ARRAY_BUFFER_STORAGE_EXTERNAL, the owner and the byte length; zero otherwise.pub external: JSExternalPrimitiveStorage,- /// For JS_ARRAY_BUFFER_STORAGE_SHARED_MEMORY, the id that names the shared memory object in every agent, or 0 if it- /// has none; zero otherwise.- pub shared_memory_object_id: u64,}/// The DataView With Buffer Witness Record of the spec, which C++ calls DataViewWithBufferWitness.@@ -263,30 +260,36 @@ pub unsafe extern "C" fn js_array_buffer_create_with_external_storage(object_into_abi(ArrayBuffer::create_from_data_block(vm, realm, block))}-/// ArrayBuffer::create(Realm&, Core::AnonymousBuffer, u64 shared_object_id): a fixed-length SharedArrayBuffer over the-/// first `byte_length` bytes of a shared memory object, which `object_id` names in every agent, as structured-/// deserialization creates it. The embedder keeps owning `shared_memory_fd` and may close it right away, as the buffer-/// keeps a duplicate. Returns null if the object cannot be mapped into the cage, which includes a `byte_length` of 0-/// and an object smaller than `byte_length`. Main thread only.+/// The id of the store of a SharedArrayBuffer, or 0 if it has none.////// # Safety///-/// `vm` and `realm` must be live, and `shared_memory_fd` an open descriptor.+/// `buffer` must be a live ArrayBuffer.#[unsafe(no_mangle)]-pub unsafe extern "C" fn js_array_buffer_create_from_shared_memory(+pub unsafe extern "C" fn js_array_buffer_shared_store_id(buffer: *mut JSObject) -> u64 {+ // SAFETY: The caller passes a live ArrayBuffer.+ let buffer = unsafe { array_buffer_from_abi(buffer) };+ buffer.with_data_block(|data_block| match &data_block.byte_buffer {+ DataBlockStorage::Shared(store) => store.id(),+ _ => 0,+ })+}++/// A new SharedArrayBuffer in the realm over the store of this process that `id` names, or null if there is none.+///+/// # Safety+///+/// `vm` and `realm` must be live.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn js_array_buffer_create_from_shared_store(vm: *mut JSVM,realm: *mut JSRealm,- shared_memory_fd: c_int,- byte_length: usize,- object_id: u64,+ id: u64,) -> *mut JSObject {// SAFETY: The caller passes a live VM and realm.let (vm, realm) = unsafe { (vm_from_abi(vm), cell_from_abi(realm)) };- assert!(shared_memory_fd >= 0, "the embedder passes an open descriptor");- // SAFETY: The caller guarantees that the descriptor stays open for the duration of the call.- let shared_memory = unsafe { borrowed_from_raw_descriptor(shared_memory_fd) };optional_object_into_abi(- ArrayBuffer::create_from_shared_memory(vm, realm, shared_memory, byte_length, object_id).ok(),+ SharedBackingStore::with_id(id).map(|store| ArrayBuffer::create_from_shared_store(vm, realm, store)),)}@@ -336,7 +339,6 @@ pub unsafe extern "C" fn js_array_buffer_storage(buffer: *mut JSObject, out: *mufixed_byte_length: 0,has_fixed_byte_length: false,},- shared_memory_object_id: 0,};buffer.with_data_block(|block| match &block.byte_buffer {DataBlockStorage::Empty => {}@@ -355,47 +357,14 @@ pub unsafe extern "C" fn js_array_buffer_storage(buffer: *mut JSObject, out: *mu};}DataBlockStorage::Shared(shared) => {- storage.kind = JS_ARRAY_BUFFER_STORAGE_SHARED_MEMORY;+ storage.kind = JS_ARRAY_BUFFER_STORAGE_SHARED_STORE;storage.handle = shared.handle();- storage.shared_memory_object_id = shared.object_id();}});// SAFETY: The caller passes a valid out parameter.unsafe { out.write(storage) };}-/// A new descriptor of the shared memory object behind a buffer of kind JS_ARRAY_BUFFER_STORAGE_SHARED_MEMORY, which-/// the caller owns and has to close, with the byte length of the buffer in `out_byte_length`. This is what the-/// embedder sends another agent, along with the id from js_array_buffer_storage(). Returns -1 for any other buffer, or-/// when no descriptor is left. Main thread only.-///-/// # Safety-///-/// `buffer` must be a live ArrayBuffer, and `out_byte_length` valid for writes.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn js_array_buffer_duplicate_shared_memory(- buffer: *mut JSObject,- out_byte_length: *mut usize,-) -> c_int {- assert!(!out_byte_length.is_null(), "the embedder passes an out parameter");- // SAFETY: The caller passes a live buffer.- let buffer = unsafe { array_buffer_from_abi(buffer) };- let duplicate = buffer.with_data_block(|block| match &block.byte_buffer {- DataBlockStorage::Shared(shared) => shared- .shared_memory()- .try_clone_to_owned()- .ok()- .map(|descriptor| (descriptor, shared.size())),- _ => None,- });- let Some((descriptor, byte_length)) = duplicate else {- return -1;- };- // SAFETY: The caller passes a valid out parameter.- unsafe { out_byte_length.write(byte_length) };- into_raw_descriptor(descriptor)-}-/// [[ArrayBufferByteLength]], which is 0 for a detached buffer. Main thread only.////// # Safety@@ -526,7 +495,6 @@ pub unsafe extern "C" fn js_array_buffer_detach_and_take_storage(fixed_byte_length: 0,has_fixed_byte_length: false,},- shared_memory_object_id: 0,};match block.byte_buffer {DataBlockStorage::Empty => {}diff --git a/Libraries/LibJS/Rust/src/embedding/vm.rs b/Libraries/LibJS/Rust/src/embedding/vm.rsindex d59f00a69a2..e48ca15b8a6 100644--- a/Libraries/LibJS/Rust/src/embedding/vm.rs+++ b/Libraries/LibJS/Rust/src/embedding/vm.rs@@ -50,15 +50,12 @@ pub struct JSVmOptions {/// Makes the VM's heap the one GC::Heap::the() returns on this thread, so that C++ cells of the embedder are/// allocated from it.pub become_thread_default_heap: bool,- /// Backs SharedArrayBuffers with shared memory, which other processes can map.- pub shared_memory_shared_array_buffers: bool,}impl From<JSVmOptions> for VmOptions {fn from(options: JSVmOptions) -> Self {Self {become_thread_default_heap: options.become_thread_default_heap,- shared_memory_shared_array_buffers: options.shared_memory_shared_array_buffers,}}}diff --git a/Libraries/LibJS/Rust/src/gc/capi.rs b/Libraries/LibJS/Rust/src/gc/capi.rsindex 78088469619..323fbff6fe1 100644--- a/Libraries/LibJS/Rust/src/gc/capi.rs+++ b/Libraries/LibJS/Rust/src/gc/capi.rs@@ -6,7 +6,7 @@//! Declarations of Libraries/LibGC/CAPI.h.-use core::ffi::{c_char, c_int, c_void};+use core::ffi::{c_char, c_void};use super::class::CellTypeInfo;@@ -38,11 +38,6 @@ pub struct GCWeakImpl {_private: [u8; 0],}-#[repr(C)]-pub struct GCSharedMemoryViewOutsideCage {- _private: [u8; 0],-}-pub const GC_COLLECTION_TYPE_COLLECT_GARBAGE: i32 = 0;pub const GC_COLLECTION_TYPE_COLLECT_EVERYTHING: i32 = 1;@@ -163,12 +158,6 @@ unsafe extern "C" {out_handle: *mut GCPrimitiveStorageHandle,out_layout: *mut GCPrimitiveStorageLayout,) -> bool;- pub fn gc_primitive_storage_adopt_shared_fd(- fd: c_int,- size: usize,- out_handle: *mut GCPrimitiveStorageHandle,- out_layout: *mut GCPrimitiveStorageLayout,- ) -> bool;pub fn gc_primitive_storage_resize(handle: GCPrimitiveStorageHandle,new_size: usize,@@ -195,11 +184,6 @@ unsafe extern "C" {pub safe fn gc_primitive_storage_capacity(handle: GCPrimitiveStorageHandle) -> usize;pub safe fn gc_primitive_storage_committed_size(handle: GCPrimitiveStorageHandle) -> usize;pub fn gc_primitive_storage_data(handle: GCPrimitiveStorageHandle) -> *mut u8;-- pub fn gc_shared_memory_create(size: usize, out_fd: *mut c_int) -> bool;- pub fn gc_shared_memory_view_outside_cage_create(fd: c_int, size: usize) -> *mut GCSharedMemoryViewOutsideCage;- pub fn gc_shared_memory_view_outside_cage_data(view: *mut GCSharedMemoryViewOutsideCage) -> *mut u8;- pub fn gc_shared_memory_view_outside_cage_destroy(view: *mut GCSharedMemoryViewOutsideCage);}// On Windows, a variable that a DLL exports is only reachable through the DLL's import table, which the reference hasdiff --git a/Libraries/LibJS/Rust/src/gc/primitive_storage.rs b/Libraries/LibJS/Rust/src/gc/primitive_storage.rsindex 1ffd0a670a0..be37bd968e1 100644--- a/Libraries/LibJS/Rust/src/gc/primitive_storage.rs+++ b/Libraries/LibJS/Rust/src/gc/primitive_storage.rs@@ -16,7 +16,6 @@ use super::capi::{self, GC_PRIMITIVE_STORAGE_INVALID_OFFSET, GC_PRIMITIVE_STORAGE_NULL_HANDLE, GCPrimitiveStorageHandle,GCPrimitiveStorageLayout,};-use super::shared_memory::{BorrowedSharedMemory, OwnedSharedMemory, owned_from_raw_descriptor, raw_descriptor};/// GC::PrimitiveStorage::invalid_offset, the offset of storage that does not exist.pub const INVALID_OFFSET: usize = GC_PRIMITIVE_STORAGE_INVALID_OFFSET;@@ -124,25 +123,6 @@ impl OwnedPrimitiveStorage {Self::from_creation(created, handle, layout)}- /// PrimitiveStorage::try_adopt_shared_fd(): maps the first `size` bytes of a shared memory object into the cage.- /// The mapping keeps the memory alive by itself. Such storage must never be resized, since that would replace the- /// shared mapping with private memory.- pub fn adopt_shared_memory(shared_memory: BorrowedSharedMemory<'_>, size: usize) -> Result<Self, OutOfMemory> {- let mut handle = GC_PRIMITIVE_STORAGE_NULL_HANDLE;- let mut layout = LAYOUT_OF_NO_STORAGE;- // SAFETY: The descriptor is open for the duration of the call, which maps it without taking ownership, and the- // handle and the layout are valid places for the results.- let created = unsafe {- capi::gc_primitive_storage_adopt_shared_fd(- raw_descriptor(shared_memory),- size,- &raw mut handle,- &raw mut layout,- )- };- Self::from_creation(created, handle, layout)- }-pub fn handle(&self) -> GCPrimitiveStorageHandle {self.handle.get()}@@ -280,15 +260,3 @@ impl ForeignPrimitiveStorage {}}}--/// gc_shared_memory_create(): a zero-filled shared memory object of `size` bytes that other processes can map, sealed-/// against resizing where the platform can seal it. The descriptor closes when the result is dropped.-pub fn create_shared_memory(size: usize) -> Result<OwnedSharedMemory, OutOfMemory> {- let mut descriptor = -1;- // SAFETY: The descriptor is a valid place for the result.- if !unsafe { capi::gc_shared_memory_create(size, &raw mut descriptor) } {- return Err(OutOfMemory);- }- // SAFETY: On success, the caller owns the new descriptor.- Ok(unsafe { owned_from_raw_descriptor(descriptor) })-}diff --git a/Libraries/LibJS/Rust/src/gc/shared_memory.rs b/Libraries/LibJS/Rust/src/gc/shared_memory.rsindex 825ebb733a3..d52e02b632c 100644--- a/Libraries/LibJS/Rust/src/gc/shared_memory.rs+++ b/Libraries/LibJS/Rust/src/gc/shared_memory.rs@@ -4,14 +4,10 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The descriptor of a shared memory object, as LibGC's C interface and Core::AnonymousBuffer pass it as an int: a-//! file descriptor, or on Windows a HANDLE that AK's to_fd() narrowed.+//! The descriptor of a shared memory object, as Core::AnonymousBuffer passes it as an int: a file descriptor, or on+//! Windows a HANDLE that AK's to_fd() narrowed.use core::ffi::c_int;-use core::ptr::NonNull;--use super::capi;-use super::primitive_storage::OutOfMemory;#[cfg(unix)]pub type OwnedSharedMemory = std::os::fd::OwnedFd;@@ -107,37 +103,3 @@ pub unsafe fn borrowed_from_raw_descriptor<'descriptor>(descriptor: c_int) -> Bounsafe { BorrowedSharedMemory::borrow_raw(handle_from_descriptor(descriptor)) }}}--/// gc_shared_memory_view_outside_cage_create(): the first `size` bytes of a shared memory object, mapped outside the-/// cage on a platform that cannot map it into the cage. The view unmaps the bytes when it is dropped.-pub struct SharedMemoryViewOutsideCage {- view: NonNull<capi::GCSharedMemoryViewOutsideCage>,- data: *mut u8,- size: usize,-}--impl SharedMemoryViewOutsideCage {- pub fn map(shared_memory: BorrowedSharedMemory<'_>, size: usize) -> Result<Self, OutOfMemory> {- // SAFETY: The descriptor is open for the duration of the call, which duplicates it.- let view = unsafe { capi::gc_shared_memory_view_outside_cage_create(raw_descriptor(shared_memory), size) };- let view = NonNull::new(view).ok_or(OutOfMemory)?;- // SAFETY: The view is live.- let data = unsafe { capi::gc_shared_memory_view_outside_cage_data(view.as_ptr()) };- Ok(Self { view, data, size })- }-- pub fn data(&self) -> *mut u8 {- self.data- }-- pub fn size(&self) -> usize {- self.size- }-}--impl Drop for SharedMemoryViewOutsideCage {- fn drop(&mut self) {- // SAFETY: The view is live, and nothing uses it after this.- unsafe { capi::gc_shared_memory_view_outside_cage_destroy(self.view.as_ptr()) };- }-}diff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rsindex bd65489edea..c5bfc7a38b5 100644--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs@@ -184,8 +184,6 @@ pub struct VmOptions {/// Makes the VM's heap the one GC::Heap::the() returns on this thread, so that the embedder's C++ cells are/// allocated from it.pub become_thread_default_heap: bool,- /// Backs SharedArrayBuffers with shared memory, which other processes can map.- pub shared_memory_shared_array_buffers: bool,}/// An execution context stack that VM::save_execution_context_stack() set aside, with the TypeErrorRealmScope thatdiff --git a/Libraries/LibJS/Rust/src/runtime/array_buffer.rs b/Libraries/LibJS/Rust/src/runtime/array_buffer.rsindex 874cd7b7c4f..9376ceb61e7 100644--- a/Libraries/LibJS/Rust/src/runtime/array_buffer.rs+++ b/Libraries/LibJS/Rust/src/runtime/array_buffer.rs@@ -12,6 +12,7 @@ use core::ops::Deref;use core::ptr::NonNull;use core::sync::atomic::{AtomicU8, AtomicU16, AtomicU32, AtomicU64, Ordering};use core::time::Duration;+use std::sync::Arc;use libjs_runtime_macros::Trace;use num_bigint::BigInt as NumBigInt;@@ -21,15 +22,13 @@ use crate::gc::class::{ExternalMemorySize, Finalize, GcCell, define_cell};use crate::gc::foreign::ForeignCellSlot;use crate::gc::gc_ref_cell::GcRefCell;use crate::gc::heap::Heap;-use crate::gc::primitive_storage::{ForeignPrimitiveStorage, OwnedPrimitiveStorage, create_shared_memory};-use crate::gc::shared_memory::{AsSharedMemory, BorrowedSharedMemory, OwnedSharedMemory, SharedMemoryViewOutsideCage};+use crate::gc::primitive_storage::{ForeignPrimitiveStorage, OwnedPrimitiveStorage};use crate::gc::visitor::{Trace, Visitor};use crate::gc::weak::GcWeak;use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;use crate::layout::object::Object;use crate::layout::value::Value;-use crate::random::get_random_u64;use crate::runtime::abstract_operations::ordinary_create_from_constructor_of;use crate::runtime::big_int::BigInt;use crate::runtime::completion::{Must, ThrowCompletionOr};@@ -40,6 +39,7 @@ use crate::runtime::intrinsics::Intrinsics;use crate::runtime::math_object::round_to_binary16;use crate::runtime::object::MayInterfereWithIndexedPropertyAccess;use crate::runtime::realm::Realm;+use crate::runtime::shared_backing_store::SharedBackingStore;use crate::runtime::typed_array::TypedArrayBase;use crate::runtime::value::same_value;use crate::runtime::value_conversions;@@ -291,130 +291,6 @@ impl ExternalPrimitiveStorage {}}-/// The id of a new shared memory object is drawn at random, as it has to stay unique across processes that never-/// coordinate. Zero means that a block has no id.-fn mint_shared_object_id() -> u64 {- loop {- let id = get_random_u64();- if id != 0 {- return id;- }- }-}--/// DataBlock::SharedBackingStore: the bytes of a fixed-length Shared Data Block in a shared memory object, which agents-/// in other processes map too. The block keeps a descriptor of the object to hand it on, and the id that names the-/// object in every agent, since one object that is mapped twice has two addresses.-pub struct SharedBackingStore {- shared_memory: OwnedSharedMemory,- object_id: u64,- mapping: SharedMemoryMapping,-}--/// Like every other backing store, shared memory is mapped into the cage, so that an out-of-bounds access through the-/// buffer is masked back into it. When the cage cannot take the mapping, as on Windows, which cannot place one inside-/// it, the object is mapped outside of it instead, where the views of the buffer reach the bytes through the slow path.-enum SharedMemoryMapping {- InCage(OwnedPrimitiveStorage),- OutsideCage(SharedMemoryViewOutsideCage),-}--impl SharedMemoryMapping {- fn map(shared_memory: BorrowedSharedMemory<'_>, size: usize) -> Result<Self, OutOfMemory> {- if let Ok(storage) = OwnedPrimitiveStorage::adopt_shared_memory(shared_memory, size) {- return Ok(Self::InCage(storage));- }- let view = SharedMemoryViewOutsideCage::map(shared_memory, size)?;- Ok(Self::OutsideCage(view))- }-}--/// Whether the shared memory object has at least `size` bytes, as accessing a mapping beyond the end of its object-/// raises SIGBUS. A Windows section is not a file, so it has no size to ask for, but MapViewOfFile() refuses a view-/// that extends past its end.-fn shared_memory_object_has_at_least(shared_memory: &std::fs::File, size: usize) -> bool {- #[cfg(unix)]- {- shared_memory- .metadata()- .is_ok_and(|metadata| metadata.len() >= size as u64)- }- #[cfg(windows)]- {- let _ = (shared_memory, size);- true- }-}--impl SharedBackingStore {- /// A new zero-filled shared memory object of `size` bytes, named by a new id.- pub fn create(size: usize) -> Result<Self, OutOfMemory> {- let shared_memory = create_shared_memory(size)?;- let mapping = SharedMemoryMapping::map(shared_memory.as_shared_memory(), size)?;- Ok(Self {- shared_memory,- object_id: mint_shared_object_id(),- mapping,- })- }-- /// The first `size` bytes of a shared memory object that another agent made and `object_id` names. The store keeps- /// a duplicate of the descriptor. Fails if `size` is 0 or the object is smaller than that.- pub fn adopt(shared_memory: BorrowedSharedMemory<'_>, size: usize, object_id: u64) -> Result<Self, OutOfMemory> {- let shared_memory = std::fs::File::from(shared_memory.try_clone_to_owned().map_err(|_| OutOfMemory)?);- if !shared_memory_object_has_at_least(&shared_memory, size) {- return Err(OutOfMemory);- }- let mapping = SharedMemoryMapping::map(shared_memory.as_shared_memory(), size)?;- Ok(Self {- shared_memory: shared_memory.into(),- object_id,- mapping,- })- }-- pub fn shared_memory(&self) -> BorrowedSharedMemory<'_> {- self.shared_memory.as_shared_memory()- }-- pub fn object_id(&self) -> u64 {- self.object_id- }-- /// The handle of the storage in the cage, or the null handle for a mapping outside of it.- pub fn handle(&self) -> GCPrimitiveStorageHandle {- match &self.mapping {- SharedMemoryMapping::InCage(storage) => storage.handle(),- SharedMemoryMapping::OutsideCage(_) => GC_PRIMITIVE_STORAGE_NULL_HANDLE,- }- }-- pub fn size(&self) -> usize {- match &self.mapping {- SharedMemoryMapping::InCage(storage) => storage.size(),- SharedMemoryMapping::OutsideCage(view) => view.size(),- }- }-- fn data(&self) -> *mut u8 {- match &self.mapping {- SharedMemoryMapping::InCage(storage) => storage.data(),- SharedMemoryMapping::OutsideCage(view) => view.data(),- }- }-- fn offset(&self) -> usize {- match &self.mapping {- SharedMemoryMapping::InCage(storage) => storage.offset(),- SharedMemoryMapping::OutsideCage(_) => INVALID_DATA_OFFSET,- }- }-- fn is_caged(&self) -> bool {- matches!(self.mapping, SharedMemoryMapping::InCage(_))- }-}-/// Copies `count` bytes; the ranges may overlap.////// # Safety@@ -434,7 +310,7 @@ pub enum DataBlockStorage {Empty,Owned(OwnedBackingStore),External(ExternalPrimitiveStorage),- Shared(SharedBackingStore),+ Shared(Arc<SharedBackingStore>),}// 6.2.9 Data Blocks, https://tc39.es/ecma262/#sec-data-blocks@@ -467,8 +343,8 @@ impl DataBlock {}}- /// A Shared Data Block in shared memory.- pub fn shared_memory(store: SharedBackingStore) -> Self {+ /// A Shared Data Block in the store, which the agents of the process share.+ pub fn shared(store: Arc<SharedBackingStore>) -> Self {Self {byte_buffer: DataBlockStorage::Shared(store),is_shared: Shared::Yes,@@ -685,14 +561,12 @@ impl DataBlock {}}- /// Whether the bytes are in the cage. Owned storage always is, as the runtime fails to create a block rather than- /// fall back to memory outside of it, shared memory is unless the platform cannot map it there, and external- /// storage is while its handle names storage.+ /// Whether the bytes are in the cage. Owned and shared storage always are, as the runtime fails to create a block+ /// rather than fall back to memory outside of it, and external storage is while its handle names storage.pub fn is_caged(&self) -> bool {match &self.byte_buffer {DataBlockStorage::Empty => false,- DataBlockStorage::Owned(_) => true,- DataBlockStorage::Shared(store) => store.is_caged(),+ DataBlockStorage::Owned(_) | DataBlockStorage::Shared(_) => true,DataBlockStorage::External(storage) => storage.storage.is_valid(),}}@@ -710,33 +584,16 @@ impl DataBlock {matches!(self.byte_buffer, DataBlockStorage::External(_))}- /// Whether the bytes are in shared memory, which an agent in another process may write at any time, so that a- /// typed array must not cache their offset for the interpreter's plain loads and stores.- pub fn is_cross_process_shared(&self) -> bool {+ /// Whether the bytes are in a shared store, which an agent on another thread may write at any time, so that a typed+ /// array must not cache their offset for the interpreter's plain loads and stores.+ pub fn is_in_shared_store(&self) -> bool {matches!(self.byte_buffer, DataBlockStorage::Shared(_))}- /// The id of the shared memory object, or 0 for a block that is not in shared memory.- pub fn shared_object_id(&self) -> u64 {- match &self.byte_buffer {- DataBlockStorage::Shared(store) => store.object_id(),- _ => 0,- }- }-pub fn shares_storage_with(&self, other: &DataBlock) -> bool {if matches!(self.byte_buffer, DataBlockStorage::Empty) || matches!(other.byte_buffer, DataBlockStorage::Empty) {return false;}- // NB: One shared memory object can be mapped at several addresses, so blocks in shared memory are compared by- // the id of the object, and one without an id matches nothing.- if let DataBlockStorage::Shared(store) = &self.byte_buffer {- return matches!(&other.byte_buffer, DataBlockStorage::Shared(other_store)- if store.object_id() != 0 && store.object_id() == other_store.object_id());- }- if matches!(other.byte_buffer, DataBlockStorage::Shared(_)) {- return false;- }// NB: Two blocks of zero bytes share the storage they do not have.core::ptr::eq(self.data(), other.data())}@@ -1017,17 +874,10 @@ impl ArrayBuffer {array_buffer}- /// ArrayBuffer::create(Realm&, Core::AnonymousBuffer, u64 shared_object_id): a fixed-length SharedArrayBuffer over- /// `size` bytes of a shared memory object that another agent made, as structured deserialization creates it.- pub fn create_from_shared_memory(- vm: &Vm,- realm: Gc<Realm>,- shared_memory: BorrowedSharedMemory<'_>,- size: usize,- object_id: u64,- ) -> Result<Gc<ArrayBuffer>, OutOfMemory> {- let store = SharedBackingStore::adopt(shared_memory, size, object_id)?;- Ok(Self::create_from_data_block(vm, realm, DataBlock::shared_memory(store)))+ /// A fixed-length SharedArrayBuffer over a store that another agent of this process made, as structured+ /// deserialization creates it.+ pub fn create_from_shared_store(vm: &Vm, realm: Gc<Realm>, store: Arc<SharedBackingStore>) -> Gc<ArrayBuffer> {+ Self::create_from_data_block(vm, realm, DataBlock::shared(store))}pub fn byte_length(&self) -> usize {@@ -1331,16 +1181,15 @@ impl ArrayBuffer {pub fn can_cache_typed_array_view_data_offset(&self) -> bool {let data_block = self.data_block.borrow();- // NB: The views of a fixed-length Shared Data Block backed by shared memory stay on the atomic slow path.- // Unless the VM was asked for shared memory, the runtime owns such a block instead, and its views take the- // same path.- let stands_in_for_shared_memory =+ // NB: The views of a fixed-length Shared Data Block in a shared store stay on the atomic slow path, and so do+ // those of such a block that the runtime owns instead, as a clone of one that lost its store does.+ let stands_in_for_shared_store =matches!(data_block.byte_buffer, DataBlockStorage::Owned(_)) && data_block.is_shared == Shared::Yes;!matches!(data_block.byte_buffer, DataBlockStorage::Empty)&& self.is_fixed_length()&& data_block.is_caged()- && !data_block.is_cross_process_shared()- && !stands_in_for_shared_memory+ && !data_block.is_in_shared_store()+ && !stands_in_for_shared_store}// 25.2.2.2 IsSharedArrayBuffer ( obj ), https://tc39.es/ecma262/#sec-issharedarraybuffer@@ -1636,16 +1485,12 @@ fn create_shared_byte_data_block(vm: &Vm, size: usize, capacity: Option<usize>)let capacity = capacity.unwrap_or(size);- // AD-HOC: A fixed-length shared Data Block is backed by cross-process shared memory (Core::AnonymousBuffer) — so- // that the SharedArrayBuffer is genuinely shared across agents in different processes, rather than copied.- // Fresh anonymous shared memory is zero-filled by the OS. A growable shared Data Block (capacity > size)- // uses process-local storage, so a growable SharedArrayBuffer crosses a process boundary as a copy.- // NB: Only a VM whose embedder has agents in other processes asks for shared memory. Otherwise, the fixed-length- // block is owned by the runtime, like a growable one.+ // AD-HOC: A fixed-length shared Data Block is a store that the agents of the process share, so that the+ // SharedArrayBuffer is genuinely shared with agents on other threads, rather than copied. A growable shared+ // Data Block (capacity > size) is owned by its heap, so a growable SharedArrayBuffer reaches another thread+ // as a copy.if capacity == size && size > 0 {- // AD-HOC: Cap the shared allocation — so one SharedArrayBuffer can't reserve an absurd amount of address space- // in every agent that maps it. Chromium caps its shared-memory regions at INT_MAX; match that (the fd- // transport also carries the size as a u32).+ // AD-HOC: Cap the shared allocation, as Chromium caps its shared regions at INT_MAX.if size > i32::MAX as usize {return vm.throw_completion(ErrorKind::RangeError,@@ -1654,14 +1499,7 @@ fn create_shared_byte_data_block(vm: &Vm, size: usize, capacity: Option<usize>));}- let block = allocate_or_retry_after_gc(vm.heap(), || {- if vm.options().shared_memory_shared_array_buffers {- // Mint the id that will name this object for as long as it exists — in this agent and every agent it- // reaches.- return Ok(DataBlock::shared_memory(SharedBackingStore::create(size)?));- }- Ok(DataBlock::new(OwnedBackingStore::create_zeroed(size)?, Shared::Yes))- });+ let block = allocate_or_retry_after_gc(vm.heap(), || Ok(DataBlock::shared(SharedBackingStore::create(size)?)));let Ok(block) = block else {return vm.throw_completion(ErrorKind::RangeError, ErrorType::NotEnoughMemoryToAllocate, &[&size]);};diff --git a/Libraries/LibJS/Rust/src/runtime/mod.rs b/Libraries/LibJS/Rust/src/runtime/mod.rsindex ee51d26d0b9..103421ad5c4 100644--- a/Libraries/LibJS/Rust/src/runtime/mod.rs+++ b/Libraries/LibJS/Rust/src/runtime/mod.rs@@ -161,6 +161,7 @@ pub mod set_prototype;pub mod shape;pub mod shared_array_buffer_constructor;pub mod shared_array_buffer_prototype;+pub mod shared_backing_store;pub mod shared_function_instance_data;pub mod source_text_module;pub mod special_property_cache;diff --git a/Libraries/LibJS/Rust/src/runtime/shared_backing_store.rs b/Libraries/LibJS/Rust/src/runtime/shared_backing_store.rsnew file mode 100644index 00000000000..1d95957b8dd--- /dev/null+++ b/Libraries/LibJS/Rust/src/runtime/shared_backing_store.rs@@ -0,0 +1,210 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The bytes of the fixed-length SharedArrayBuffers of a process, and how a message finds them in another agent of the+//! process.+//!+//! A SharedArrayBuffer never leaves its agent cluster, and an agent cluster never leaves its process, so these bytes are+//! ordinary memory of the process: there is one mapping, at one address, for every agent. A message names a store by its+//! id. The id gives nothing to the process of a receiver that is not this one, which is where a message goes that+//! deserialization then rejects.+//!+//! A message can wait in a socket for a long time, and every agent may drop its buffer meanwhile. So a message holds a+//! lifeline: the read end of a pipe that the sender's process keeps the store for. The kernel keeps track of where that+//! read end is, as it does for any descriptor in flight, so it does not matter whether the message is delivered to one+//! receiver, to many, to a process that has no use for it, or to nobody.++use core::ffi::c_int;+use std::collections::HashMap;+use std::sync::{Arc, LazyLock, Mutex, PoisonError, Weak};++use crate::gc::capi::GCPrimitiveStorageHandle;+use crate::gc::primitive_storage::{OutOfMemory, OwnedPrimitiveStorage, ZeroFillNewBytes};+use crate::random::get_random_u64;++/// DataBlock::SharedBackingStore: the bytes of a fixed-length Shared Data Block, which every agent of the process that+/// has the block shares. The last agent to drop it frees the bytes.+pub struct SharedBackingStore {+ storage: OwnedPrimitiveStorage,+ id: u64,+}++// SAFETY: LibGC's primitive storage takes a lock, the storage is never resized, and what agents do to the bytes goes+// through atomics.+unsafe impl Send for SharedBackingStore {}+// SAFETY: As above.+unsafe impl Sync for SharedBackingStore {}++type StoresById = HashMap<u64, Weak<SharedBackingStore>>;++fn stores_by_id() -> std::sync::MutexGuard<'static, StoresById> {+ static STORES_BY_ID: LazyLock<Mutex<StoresById>> = LazyLock::new(Mutex::default);+ STORES_BY_ID.lock().unwrap_or_else(PoisonError::into_inner)+}++impl SharedBackingStore {+ /// A new zero-filled store of `size` bytes.+ pub fn create(size: usize) -> Result<Arc<Self>, OutOfMemory> {+ let storage = OwnedPrimitiveStorage::allocate(size, ZeroFillNewBytes::Yes)?;+ let mut stores = stores_by_id();+ // NB: An id that a message carries should not be guessable, as a message can come from another process.+ let mut id = get_random_u64();+ while id == 0 || stores.contains_key(&id) {+ id = get_random_u64();+ }+ let store = Arc::new(Self { storage, id });+ stores.insert(id, Arc::downgrade(&store));+ Ok(store)+ }++ /// The store of this process that `id` names, if there is one.+ pub fn with_id(id: u64) -> Option<Arc<Self>> {+ stores_by_id().get(&id)?.upgrade()+ }++ pub fn id(&self) -> u64 {+ self.id+ }++ pub fn handle(&self) -> GCPrimitiveStorageHandle {+ self.storage.handle()+ }++ pub fn size(&self) -> usize {+ self.storage.size()+ }++ pub(crate) fn data(&self) -> *mut u8 {+ self.storage.data()+ }++ pub(crate) fn offset(&self) -> usize {+ self.storage.offset()+ }+}++impl Drop for SharedBackingStore {+ fn drop(&mut self) {+ stores_by_id().remove(&self.id);+ }+}++/// The read end of the pipe of a message.+#[cfg(unix)]+pub type SharedStoreLifeline = std::os::fd::OwnedFd;+#[cfg(windows)]+pub type SharedStoreLifeline = std::os::windows::io::OwnedHandle;++/// The lifeline as the descriptor that LibIPC and C++ pass around, which the caller then owns.+pub fn lifeline_into_raw_descriptor(lifeline: SharedStoreLifeline) -> c_int {+ #[cfg(unix)]+ {+ std::os::fd::IntoRawFd::into_raw_fd(lifeline)+ }+ #[cfg(windows)]+ {+ // AK's to_fd() keeps the low 32 bits, which hold every value a kernel handle can have.+ std::os::windows::io::IntoRawHandle::into_raw_handle(lifeline) as isize as c_int+ }+}++/// The lifeline behind a descriptor of LibIPC.+///+/// # Safety+///+/// `descriptor` must be open, and owned by nothing else.+pub unsafe fn lifeline_from_raw_descriptor(descriptor: c_int) -> SharedStoreLifeline {+ // SAFETY: As the caller guarantees.+ unsafe { crate::gc::shared_memory::owned_from_raw_descriptor(descriptor) }+}++/// A duplicate of the lifeline behind a descriptor of LibIPC, if the system has a descriptor left.+///+/// # Safety+///+/// `descriptor` must stay open for the call.+pub unsafe fn duplicate_lifeline_from_raw_descriptor(descriptor: c_int) -> std::io::Result<SharedStoreLifeline> {+ #[cfg(unix)]+ {+ // SAFETY: As the caller guarantees.+ unsafe { std::os::fd::BorrowedFd::borrow_raw(descriptor) }.try_clone_to_owned()+ }+ #[cfg(windows)]+ {+ // SAFETY: As the caller guarantees. AK's to_handle() sign-extends the int.+ unsafe {+ std::os::windows::io::BorrowedHandle::borrow_raw(descriptor as isize as std::os::windows::io::RawHandle)+ }+ .try_clone_to_owned()+ }+}++/// Stores that a message keeps alive, until the last duplicate of its lifeline is closed.+struct PinnedStores {+ /// The write end of the pipe, which only ever reports that the read end is gone.+ // NB: Windows does not poll it yet, see take_pins_nothing_holds().+ #[cfg_attr(windows, allow(dead_code))]+ write_end: std::io::PipeWriter,+ /// NB: Only dropped for what it keeps alive.+ _stores: Vec<Arc<SharedBackingStore>>,+}++fn pinned_stores() -> std::sync::MutexGuard<'static, Vec<PinnedStores>> {+ static PINNED_STORES: Mutex<Vec<PinnedStores>> = Mutex::new(Vec::new());+ PINNED_STORES.lock().unwrap_or_else(PoisonError::into_inner)+}++#[cfg(unix)]+fn take_pins_nothing_holds(pins: &mut Vec<PinnedStores>) -> Vec<PinnedStores> {+ use std::os::fd::AsRawFd;++ let mut poll_descriptors: Vec<libc::pollfd> = pins+ .iter()+ .map(|pin| libc::pollfd {+ fd: pin.write_end.as_raw_fd(),+ events: 0,+ revents: 0,+ })+ .collect();+ // SAFETY: The array is valid for its length, and the call does not block.+ let result = unsafe { libc::poll(poll_descriptors.as_mut_ptr(), poll_descriptors.len() as libc::nfds_t, 0) };+ if result <= 0 {+ return Vec::new();+ }+ let mut poll_descriptors = poll_descriptors.into_iter();+ pins.extract_if(.., |_| {+ poll_descriptors+ .next()+ .is_some_and(|descriptor| descriptor.revents & (libc::POLLERR | libc::POLLHUP) != 0)+ })+ .collect()+}++// FIXME: Find out on Windows when a pipe has lost its reader. Until then, the stores of a message stay for as long as+// the process does.+#[cfg(windows)]+fn take_pins_nothing_holds(_: &mut Vec<PinnedStores>) -> Vec<PinnedStores> {+ Vec::new()+}++/// Lets go of the stores of the messages that are gone. A message that is destroyed in this process calls this. One that+/// another process destroys gets noticed the next time a message goes out or is destroyed here.+pub fn release_stores_of_lost_messages() {+ let released = take_pins_nothing_holds(&mut pinned_stores());+ // NB: A store that goes takes other locks.+ drop(released);+}++/// A new lifeline that keeps `stores` for as long as it, or a duplicate of it, is open anywhere.+pub fn pin_stores_for_a_message(stores: Vec<Arc<SharedBackingStore>>) -> std::io::Result<SharedStoreLifeline> {+ release_stores_of_lost_messages();+ let (read_end, write_end) = std::io::pipe()?;+ pinned_stores().push(PinnedStores {+ write_end,+ _stores: stores,+ });+ Ok(read_end.into())+}diff --git a/Libraries/LibJS/Rust/src/utilities/test262_runner.rs b/Libraries/LibJS/Rust/src/utilities/test262_runner.rsindex 7a7e6ca2e27..c3695a8037e 100644--- a/Libraries/LibJS/Rust/src/utilities/test262_runner.rs+++ b/Libraries/LibJS/Rust/src/utilities/test262_runner.rs@@ -597,12 +597,8 @@ fn run_program(vm: &Vm, program: ScriptOrModuleProgram) -> Result<(), TestError>.map_err(|throw| describe_thrown_value(vm, throw.value()))}-/// A VM whose SharedArrayBuffers agents can map, as broadcasting one hands its shared memory to them.fn create_vm() -> Box<Vm> {- Vm::create_with(VmOptions {- shared_memory_shared_array_buffers: true,- ..VmOptions::default()- })+ Vm::create_with(VmOptions::default())}fn run_test(diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rs b/Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rsindex d15262f430b..919169edfc5 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rs@@ -44,9 +44,7 @@ unsafe extern "C" {realm: *mut c_void,channel_name: usize,serialized_message: ak::Span<'_, u8>,- shared_memory: *const c_int,- shared_memory_sizes: *const usize,- shared_memory_count: usize,+ shared_store_lifeline: c_int,);}@@ -250,9 +248,8 @@ impl BroadcastChannel {}// 3. Let serialized be StructuredSerialize(message). Rethrow any exceptions.- // AD-HOC: This message reaches agents in other processes through the browser process — so a shared-memory-backed- // SharedArrayBuffer travels beside the record, by file descriptor, and every receiver references the same- // [[ArrayBufferData]] rather than a copy.+ // AD-HOC: This message reaches agents through the browser process, also those in this process, which then reference+ // the same [[ArrayBufferData]] rather than a copy.let serialized = structured_serialize_for_message(cx.vm(), cx.realm(), message)?;// 4. Let sourceOrigin be this's relevant settings object's origin.@@ -271,17 +268,14 @@ impl BroadcastChannel {// Steps 6-9.Self::deliver_message_locally(cx.vm(), message, Some(*this));- let (shared_memory, shared_memory_sizes) = message.serialized.duplicate_shared_memory();// SAFETY: The realm is live, the name and the bytes are lent for the call, and the call takes over the- // duplicated descriptors.+ // duplicated descriptor.unsafe {web_html_broadcast_channel_post_message_to_other_processes(this.realm.as_ptr().cast(),message.channel_name.raw_identity(),ak::Span::new(&message.serialized.bytes),- shared_memory.as_ptr(),- shared_memory_sizes.as_ptr(),- shared_memory.len(),+ message.serialized.duplicate_shared_store_lifeline(),);}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rsindex 6483d06b148..6b023abcfb8 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs@@ -436,8 +436,7 @@ pub unsafe extern "C" fn web_rust_shut_down_agent(vm: *mut c_void) {/// # Safety////// `vm` must be the live VM, the origins and the bytes lent, `channel_name` an owned AK::Utf16String, and-/// `shared_memory` and `shared_memory_sizes` arrays of `shared_memory_count` descriptors that are open for the call and-/// their sizes.+/// `shared_store_lifeline` a descriptor that is open for the call, or negative.#[unsafe(no_mangle)]pub unsafe extern "C" fn web_rust_broadcast_channel_deliver_message_locally(vm: *mut c_void,@@ -445,12 +444,10 @@ pub unsafe extern "C" fn web_rust_broadcast_channel_deliver_message_locally(channel_name: usize,source_origin: *const FfiOrigin,serialized_message: ak::Span<'_, u8>,- shared_memory: *const c_int,- shared_memory_sizes: *const usize,- shared_memory_count: usize,+ shared_store_lifeline: c_int,) {- // SAFETY: The caller passes the live VM, lends the origins and the descriptors, and hands over the name.- let (vm, storage_key, channel_name, source_origin, shared_memory, shared_memory_sizes) = unsafe {+ // SAFETY: The caller passes the live VM, lends the origins and the descriptor, and hands over the name.+ let (vm, storage_key, channel_name, source_origin) = unsafe {(&*vm.cast::<Vm>(),StorageKey {@@ -458,22 +455,15 @@ pub unsafe extern "C" fn web_rust_broadcast_channel_deliver_message_locally(},Utf16String::from_raw_owned(channel_name),(*source_origin).to_origin(),- ak::slice_from_raw_parts(shared_memory, shared_memory_count),- ak::slice_from_raw_parts(shared_memory_sizes, shared_memory_count),)};let message = BROADCAST_CHANNEL_MESSAGE_CLASS.allocate(vm, |defer_gc| BroadcastChannelMessage {storage_key,channel_name,source_origin,- // SAFETY: The caller keeps the descriptors open for the call.+ // SAFETY: The caller keeps the descriptor open for the call.serialized: unsafe {- MessageRecord::received(- defer_gc,- serialized_message.as_slice(),- shared_memory,- shared_memory_sizes,- )+ MessageRecord::received(defer_gc, serialized_message.as_slice(), &[], &[], shared_store_lifeline)},});BroadcastChannel::deliver_message_locally(vm, message, None);diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rsindex b19ccd06965..cf9aff62885 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs@@ -14,7 +14,10 @@ use core::marker::PhantomData;use core::mem::ManuallyDrop;use core::ptr::NonNull;-use libjs_rust::api::{ArrayBuffer, AsSharedMemory, Gc, Object, RawNativeFunctionResult, Realm, Value, raw_descriptor};+use libjs_rust::api::{+ ArrayBuffer, AsSharedMemory, Gc, Object, RawNativeFunctionResult, Realm, Value, raw_descriptor,+ release_stores_of_lost_messages,+};use crate::bindings::{Exception, WebIdlResult};use crate::html::structured_serialize::message_record::SharedMemory;@@ -316,6 +319,7 @@ impl Drop for OwnedSerializedTransferRecord {fn drop(&mut self) {// SAFETY: This owns the record.unsafe { web_structured_serialize_transfer_record_destroy(self.0.0.as_ptr()) };+ release_stores_of_lost_messages();}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/message_record.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/message_record.rsindex f65879c8df4..97077ca217d 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/message_record.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/message_record.rs@@ -5,14 +5,15 @@*///! The record of a message that may reach agents in other processes, which Rust owns: the bytes of the values, the-//! SharedArrayBuffers that agents in this process share, and the shared memory that agents in other processes map.+//! SharedArrayBuffers that agents in this agent's realms share, the lifeline of the stores that the bytes name, and the+//! shared memory that hands the pixels of ImageBitmaps over.//! C++ sees the record only when it is sent to or received from other processes.use core::ffi::c_int;use libjs_rust::api::{- ArrayBuffer, AsSharedMemory, DeferGc, Gc, OwnedSharedMemory, Trace, borrowed_from_raw_descriptor,- into_raw_descriptor,+ ArrayBuffer, DeferGc, Gc, OwnedSharedMemory, SharedStoreLifeline, Trace, borrowed_from_raw_descriptor,+ duplicate_lifeline_from_raw_descriptor, lifeline_into_raw_descriptor, release_stores_of_lost_messages,};pub(crate) struct SharedMemory {@@ -40,21 +41,29 @@ impl SharedMemory {pub(crate) struct MessageRecord {#[gc(untraced)]pub(crate) bytes: Vec<u8>,- /// The same-process side table, by index from the bytes.+ /// The same-agent side table, by index from the bytes.pub(crate) shared_array_buffers: Vec<Gc<ArrayBuffer>>,- /// The shared memory of the SharedArrayBuffers, by index from the bytes.+ /// The shared memory of ImageBitmap pixels, by index from the data holders.#[gc(untraced)]pub(crate) shared_memory: Vec<SharedMemory>,+ #[gc(untraced)]+ pub(crate) shared_store_lifeline: Option<SharedStoreLifeline>,}impl MessageRecord {- /// A record that another process sent, for the caller to allocate a cell with under the deferral. A descriptor that- /// cannot be duplicated leaves out the shared memory from it on, which deserializing then throws for.+ /// A record that another process sent, for the caller to allocate a cell with under the deferral. A lifeline that+ /// cannot be duplicated is left out, so that the stores it would keep may be gone, which deserializing throws for.////// # Safety///- /// Each descriptor must stay open for the call.- pub(crate) unsafe fn received(_: &DeferGc<'_>, bytes: &[u8], descriptors: &[c_int], sizes: &[usize]) -> Self {+ /// Each descriptor must stay open for the call, and so must the one of the lifeline, if it is not negative.+ pub(crate) unsafe fn received(+ _: &DeferGc<'_>,+ bytes: &[u8],+ descriptors: &[c_int],+ sizes: &[usize],+ shared_store_lifeline: c_int,+ ) -> Self {let shared_memory = descriptors.iter().zip(sizes)@@ -65,18 +74,27 @@ impl MessageRecord {bytes: bytes.to_vec(),shared_array_buffers: Vec::new(),shared_memory,+ // SAFETY: The caller keeps the descriptor open.+ shared_store_lifeline: (shared_store_lifeline >= 0)+ .then(|| unsafe { duplicate_lifeline_from_raw_descriptor(shared_store_lifeline) }.ok())+ .flatten(),}}- /// Duplicates of the descriptors of the shared memory, which the caller owns, and their sizes, for sending the- /// record to other processes.- pub(crate) fn duplicate_shared_memory(&self) -> (Vec<c_int>, Vec<usize>) {- self.shared_memory- .iter()- .map_while(|shared_memory| {- let descriptor = shared_memory.descriptor.as_shared_memory().try_clone_to_owned().ok()?;- Some((into_raw_descriptor(descriptor), shared_memory.size))- })- .unzip()+ /// A duplicate of the descriptor of the lifeline, which the caller owns, or a negative value for no lifeline, for+ /// sending the record to other processes.+ pub(crate) fn duplicate_shared_store_lifeline(&self) -> c_int {+ self.shared_store_lifeline+ .as_ref()+ .and_then(|lifeline| lifeline.try_clone().ok())+ .map_or(-1, lifeline_into_raw_descriptor)+ }+}++impl Drop for MessageRecord {+ fn drop(&mut self) {+ if self.shared_store_lifeline.take().is_some() {+ release_stores_of_lost_messages();+ }}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rsindex 4b6f147c01d..e81b4a7b88b 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs@@ -475,24 +475,21 @@ fn serialize_array_buffer(} else {// 3. Otherwise, set serialized to { [[Type]]: "SharedArrayBuffer", [[ArrayBufferData]]: value.[[ArrayBufferData]],// [[ArrayBufferByteLength]]: value.[[ArrayBufferByteLength]] }.- // To share (rather than copy) [[ArrayBufferData]] with a same-process target, stash the source buffer in the- // record's side table and encode its index. A record that crosses a process boundary arrives with an empty- // side table — and shares through the file-descriptor side list below instead, or falls back to a byte copy.+ // To share (rather than copy) [[ArrayBufferData]] with a target in the same agent, stash the source buffer in+ // the record's side table and encode its index. A record that leaves the agent arrives with an empty side+ // table, and names the store below instead, or falls back to a byte copy.data_holder.encode_u8(ValueTag::SharedArrayBuffer as u8);serialize_agent_cluster(data_holder, allow_shared_array_buffers)?;data_holder.encode_u32(data_holder.add_shared_array_buffer(array_buffer));- // AD-HOC: When backed by cross-process shared memory and a side list is available (the messaging path),- // transfer the buffer by appending it to shared_buffers, and encoding its index. That lets the file- // descriptor survive structured clone, whose main record is bytes-only, so an agent in another- // process references the same [[ArrayBufferData]]. Without a side list (e.g., serialization for- // storage) or a shared backing (e.g., a zero-length buffer), fall back to copying the bytes.- let shared_buffer_index = data_holder.append_shared_memory_of(array_buffer);- data_holder.encode_bool(shared_buffer_index.is_some());- if let Some(index) = shared_buffer_index {- data_holder.encode_u32(index);- // Carried beside the index — so the receiving agent can tell this object apart from any other, even- // when it maps this same one twice, from two separate messages.- data_holder.encode_u64(array_buffer.with_data_block(|data_block| data_block.shared_object_id()));+ // AD-HOC: On the messaging path, a buffer in a shared store goes by the id of the store, so that an agent on+ // another thread of this process references the same [[ArrayBufferData]]. The bytes never leave this+ // process: a receiver in another one is not in the agent cluster, and only gets the id. Without the+ // messaging path (e.g., serialization for storage) or a store (e.g., a zero-length buffer), fall back+ // to copying the bytes.+ let shared_store_id = data_holder.name_store_of(array_buffer);+ data_holder.encode_bool(shared_store_id.is_some());+ if let Some(id) = shared_store_id {+ data_holder.encode_u64(id);} else {data_holder.encode_bytes(&array_buffer.copy_all_to_byte_buffer());}@@ -1285,15 +1282,11 @@ impl Deserializer<'_, '_, '_> {let side_table_index = self.serialized.decode_u32()?;- // 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.- let is_shared_backed = self.serialized.decode_bool()?;- if is_shared_backed {- let index = self.serialized.decode_u32()?;- let shared_object_id = self.serialized.decode_u64()?;- value = self- .serialized- .array_buffer_from_shared_memory(vm, index, shared_object_id)?;+ // AD-HOC: A record on the messaging path names the store, which this agent shares with the sender.+ let has_shared_store = self.serialized.decode_bool()?;+ if has_shared_store {+ let id = self.serialized.decode_u64()?;+ value = self.serialized.array_buffer_from_shared_store(vm, id)?;break 'shared_array_buffer;}@@ -1307,8 +1300,8 @@ impl Deserializer<'_, '_, '_> {break 'shared_array_buffer;}- // A buffer with no cross-process shared memory to share (a zero-length one, e.g.) whose record crossed a- // process boundary arrives with an empty side table — so it's reconstructed from the byte copy.+ // A buffer with no store to share (a zero-length one, e.g.) whose record left the agent arrives with an+ // empty side table, so it's reconstructed from the byte copy.value = Value::from_object(array_buffer_from_bytes(vm, realm, bytes, ArrayBufferShared::Yes)?);}@@ -1732,8 +1725,8 @@ pub(crate) fn structured_serialize_with_transfer(}// 3. Let serialized be ? StructuredSerializeInternal(value, false, memory).- // 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.+ // NB: The record may leave the process, so it is a message record, which names the stores of its SharedArrayBuffers.+ // The data holders share the pixels of ImageBitmaps through its shared memory.let serialized = StructuredSerializeWriter::new_for_message(vm);structured_serialize_internal(vm,@@ -1745,6 +1738,10 @@ pub(crate) fn structured_serialize_with_transfer(AllowSharedArrayBuffers::CrossOriginIsolatedOnly,)?;+ serialized+ .pin_named_stores()+ .map_err(|_| data_clone_error("Cannot share SharedArrayBuffer"))?;+// 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, pixels_shared_memory) =@@ -1989,8 +1986,8 @@ pub(crate) fn structured_deserialize_with_transfer_internal(}// https://html.spec.whatwg.org/multipage/structured-data.html#structuredserialize-// AD-HOC: For a message that reaches agents in other processes, whose shared-memory-backed SharedArrayBuffers are handed-// over beside it. The caller finishes the writer into a MessageRecord.+// AD-HOC: For a message that reaches agents in other processes, which names the stores of its SharedArrayBuffers. The+// caller finishes the writer into a MessageRecord.pub(crate) fn structured_serialize_for_message(vm: &Vm,realm: Gc<Realm>,@@ -2009,6 +2006,9 @@ pub(crate) fn structured_serialize_for_message(&memory,AllowSharedArrayBuffers::CrossOriginIsolatedOnly,)?;+ serialized+ .pin_named_stores()+ .map_err(|_| data_clone_error("Cannot share SharedArrayBuffer"))?;Ok(serialized)}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rsindex 3ae535cebb7..ea3558de561 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs@@ -15,11 +15,12 @@use core::ffi::c_void;use core::ptr::NonNull;+use std::sync::Arc;use ak::Utf16String;use libjs_rust::api::{- ArrayBuffer, ArrayBufferShared, AsSharedMemory, BigInt, DataBlock, DataBlockStorage, ExternalPrimitiveStorage,- ForeignCellSlot, GC_PRIMITIVE_STORAGE_NULL_HANDLE, Gc, Realm, SharedBackingStore, Value, Vm,+ 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};@@ -193,31 +194,15 @@ impl<'a> StructuredSerializeReader<'a> {)))}- pub(crate) fn array_buffer_from_shared_memory(- &self,- vm: &Vm,- index: u32,- shared_object_id: u64,- ) -> WebIdlResult<Value> {- let shared_memory = match self.shared_array_buffers {- SharedArrayBuffers::None | SharedArrayBuffers::Lent(_) => &[],- 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 over the store that `id` names. A store is only found in the process of the agent that+ /// sent the message, as its bytes do not leave that process.+ pub(crate) fn array_buffer_from_shared_store(&self, vm: &Vm, id: u64) -> WebIdlResult<Value> {+ let store = SharedBackingStore::with_id(id).ok_or_else(|| {+ data_clone_error_from_serialization_error(self.realm, "SharedArrayBuffer is out of reach")+ })?;+ Ok(Value::from_object(ArrayBuffer::create_from_shared_store(+ vm, self.realm, store,+ )))}/// A new SharedArrayBuffer that shares the storage of the buffer at the index of the record's same-process side@@ -267,14 +252,9 @@ fn array_buffer_sharing_storage_with(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)- }+ // AD-HOC: A fixed-length shared block is aliased by referencing the same store, so that the clone can itself be+ // shared with an agent on another thread.+ DataBlockStorage::Shared(store) => Some(DataBlock::shared(Arc::clone(store))),DataBlockStorage::Owned(owned) => {// Zero-length buffers have no backing storage to share.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 e2035b0167c..c011efaf0a3 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@@ -13,6 +13,7 @@ use core::ptr::NonNull;use libjs_rust::api::{ArrayBuffer, DeferGc, EmbedderCell, EmbedderClass, EmbedderValue, Gc, GcRefCell, Trace, Vm, into_raw_descriptor,+ lifeline_into_raw_descriptor,};use super::cpp::{OwnedSerializedTransferRecord, SerializedTransferRecord, objects_into_abi};@@ -20,7 +21,7 @@ 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};+use libjs_rust::api::{AsSharedMemory, lifeline_from_raw_descriptor, owned_from_raw_descriptor, raw_descriptor};unsafe extern "C" {fn web_structured_serialize_validate_shared_memory(descriptor: c_int, size: usize) -> bool;@@ -31,6 +32,7 @@ unsafe extern "C" {descriptors: *const c_int,sizes: *const usize,shared_memory_count: usize,+ shared_store_lifeline: c_int,holders: *const *mut c_void,holder_count: usize,) -> *mut c_void;@@ -45,11 +47,23 @@ unsafe extern "C" {*const c_int,*const usize,usize,+ c_int,),append_holder: unsafe extern "C" fn(*mut c_void, *mut c_void),);}+/// The descriptor as what the record encodes, which takes it over.+fn file_from_raw_descriptor(raw: c_int) -> File {+ #[cfg(unix)]+ // SAFETY: The caller hands the descriptor over.+ let descriptor = unsafe { std::os::fd::FromRawFd::from_raw_fd(raw) };+ #[cfg(windows)]+ // SAFETY: The caller hands the descriptor over.+ let descriptor = unsafe { libipc_rust::transport_windows::OwnedDescriptor::from_raw(raw) };+ File(descriptor)+}+#[derive(Trace)]#[gc(crate = libjs_rust)]pub(crate) struct TransferRecord {@@ -85,13 +99,16 @@ impl TransferRecord {pub(crate) fn into_cpp(record: TransferRecordRef, vm: &Vm) -> OwnedSerializedTransferRecord {DeferGc::scope(vm, |_defer_gc| {- let message = record.serialized.replace(None).expect("a record is handed over once");+ let mut message = record.serialized.replace(None).expect("a record is handed over once");let buffers = objects_into_abi(&message.shared_array_buffers);- let (descriptors, sizes): (Vec<_>, Vec<_>) = message- .shared_memory+ let (descriptors, sizes): (Vec<_>, Vec<_>) = core::mem::take(&mut message.shared_memory).into_iter().map(|memory| (into_raw_descriptor(memory.descriptor), memory.size)).unzip();+ let shared_store_lifeline = message+ .shared_store_lifeline+ .take()+ .map_or(-1, lifeline_into_raw_descriptor);let holders: Vec<_> = record.data_holders.borrow_mut()@@ -108,6 +125,7 @@ impl TransferRecord {descriptors.as_ptr(),sizes.as_ptr(),descriptors.len(),+ shared_store_lifeline,holders.as_ptr(),holders.len(),))@@ -118,20 +136,20 @@ 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");+ let mut message = record.serialized.replace(None).expect("a record is handed over once");encoder.encode(message.bytes.as_slice())?;let holders = core::mem::take(&mut *record.data_holders.borrow_mut());encoder.encode_owned(holders)?;encoder.encode_size(message.shared_memory.len())?;- for memory in message.shared_memory {+ for memory in core::mem::take(&mut 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))?;+ encoder.encode_owned(file_from_raw_descriptor(into_raw_descriptor(memory.descriptor)))?;+ }+ let shared_store_lifeline = message.shared_store_lifeline.take();+ encoder.encode(&shared_store_lifeline.is_some())?;+ if let Some(lifeline) = shared_store_lifeline {+ encoder.encode_owned(file_from_raw_descriptor(lifeline_into_raw_descriptor(lifeline)))?;}Ok(())})@@ -175,12 +193,25 @@ impl TransferRecord {shared_memory.push(memory);}}+ let shared_store_lifeline = decoder+ .decode::<bool>()?+ .then(|| decoder.decode::<File>())+ .transpose()?+ .map(|File(descriptor)| {+ #[cfg(unix)]+ let raw = std::os::fd::IntoRawFd::into_raw_fd(descriptor);+ #[cfg(windows)]+ let raw = descriptor.into_raw();+ // SAFETY: File hands its descriptor over to the lifeline.+ unsafe { lifeline_from_raw_descriptor(raw) }+ });Ok(Self::create(vm,|_| MessageRecord {bytes,shared_array_buffers: Vec::new(),shared_memory,+ shared_store_lifeline,},holders,))@@ -201,28 +232,33 @@ impl TransferRecord {descriptors: *const c_int,sizes: *const usize,shared_memory_count: usize,+ shared_store_lifeline: c_int,) {// SAFETY: from_cpp() lends the state under its allocation's deferral, and C++ lends every input slice.let received = unsafe { &mut *context.cast::<Received<'_>>() };- received.message = Some(MessageRecord {- shared_array_buffers: unsafe { ak::slice_from_raw_parts(buffers, buffer_count) }- .iter()- .map(|&buffer| {- // SAFETY: C++ lends live ArrayBuffers while the collector is deferred.- unsafe {- Gc::from_non_null(NonNull::new(buffer.cast::<ArrayBuffer>()).expect("C++ lends a buffer"))- }- })- .collect(),- ..unsafe {- MessageRecord::received(- received.defer_gc,- bytes.as_slice(),- ak::slice_from_raw_parts(descriptors, shared_memory_count),- ak::slice_from_raw_parts(sizes, shared_memory_count),- )- }- });+ #[cfg_attr(+ ladybird_gc_lints,+ expect(gc_container_on_stack, reason = "the collector is deferred while C++ lends them")+ )]+ let mut message = unsafe {+ MessageRecord::received(+ received.defer_gc,+ bytes.as_slice(),+ ak::slice_from_raw_parts(descriptors, shared_memory_count),+ ak::slice_from_raw_parts(sizes, shared_memory_count),+ shared_store_lifeline,+ )+ };+ message.shared_array_buffers = unsafe { ak::slice_from_raw_parts(buffers, buffer_count) }+ .iter()+ .map(|&buffer| {+ // SAFETY: C++ lends live ArrayBuffers while the collector is deferred.+ unsafe {+ Gc::from_non_null(NonNull::new(buffer.cast::<ArrayBuffer>()).expect("C++ lends a buffer"))+ }+ })+ .collect();+ received.message = Some(message);}unsafe extern "C" fn append(context: *mut c_void, holder: *mut c_void) {diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rsindex e0c1d192dd5..3051f820dc4 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rs@@ -14,9 +14,13 @@//! C++ record when it finishes, or to a MessageRecord that Rust keeps.use core::cell::RefCell;+use std::sync::Arc;use ak::{Utf16String, Utf16StringUnits};-use libjs_rust::api::{ArrayBuffer, BigInt, DataBlockStorage, DeferGc, Gc, MarkedVec, Vm};+use libjs_rust::api::{+ ArrayBuffer, BigInt, DataBlockStorage, DeferGc, Gc, MarkedVec, SharedBackingStore, SharedStoreLifeline, Vm,+ pin_stores_for_a_message,+};use libwebcommon_rust::html::serialization_records::{RecordEncoder, SerializationType};use crate::html::structured_serialize::cpp::{IPCSerializationRecord, StorageSerializationRecord};@@ -31,6 +35,9 @@ pub(crate) struct StructuredSerializeWriter<'vm> {shared_array_buffers: MarkedVec<'vm, Gc<ArrayBuffer>>,/// The shared memory that a MessageRecord, which may reach agents in other processes, hands over beside its bytes.shared_memory: Option<RefCell<Vec<SharedMemory>>>,+ /// The stores that a message names, which only a record that may reach an agent on another thread has.+ stores_of_message: Option<RefCell<Vec<Arc<SharedBackingStore>>>>,+ shared_store_lifeline: RefCell<Option<SharedStoreLifeline>>,}impl<'vm> StructuredSerializeWriter<'vm> {@@ -39,13 +46,17 @@ impl<'vm> StructuredSerializeWriter<'vm> {encoder: RefCell::new(RecordEncoder::new(serialization_type)),shared_array_buffers: MarkedVec::new(vm),shared_memory: None,+ stores_of_message: None,+ shared_store_lifeline: RefCell::new(None),}}- /// The writer of a MessageRecord.+ /// The writer of a message, which agents on other threads may receive, and which names the stores of its+ /// SharedArrayBuffers.pub(crate) fn new_for_message(vm: &'vm Vm) -> Self {Self {shared_memory: Some(RefCell::new(Vec::new())),+ stores_of_message: Some(RefCell::new(Vec::new())),..Self::new(vm, SerializationType::Ipc)}}@@ -164,18 +175,26 @@ impl<'vm> StructuredSerializeWriter<'vm> {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> {- 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(),- }),+ /// Has the message keep the store of the SharedArrayBuffer alive, and returns the id that names the store, if the+ /// buffer has one, and the record is a message.+ pub(crate) fn name_store_of(&self, array_buffer: Gc<ArrayBuffer>) -> Option<u64> {+ let stores = self.stores_of_message.as_ref()?;+ let store = array_buffer.with_data_block(|data_block| match &data_block.byte_buffer {+ DataBlockStorage::Shared(store) => Some(Arc::clone(store)),_ => None,})?;- Some(self.append_shared_memory(shared_memory))+ let id = store.id();+ stores.borrow_mut().push(store);+ Some(id)+ }++ /// Gives the message its lifeline, if it names stores. Fails if the system has no descriptors left.+ pub(crate) fn pin_named_stores(&self) -> std::io::Result<()> {+ let stores = self.stores_of_message.as_ref().map(RefCell::take).unwrap_or_default();+ if !stores.is_empty() {+ *self.shared_store_lifeline.borrow_mut() = Some(pin_stores_for_a_message(stores)?);+ }+ Ok(())}/// Sets the IPC record that C++ lends to what the writer wrote.@@ -190,6 +209,7 @@ impl<'vm> StructuredSerializeWriter<'vm> {assert_eq!(self.serialization_type(), SerializationType::Ipc);let shared_memory = self.shared_memory.expect("the writer is a message's");MessageRecord {+ shared_store_lifeline: self.shared_store_lifeline.take(),bytes: self.encoder.into_inner().into_bytes(),shared_array_buffers: self.shared_array_buffers.values().to_vec(),shared_memory: shared_memory.into_inner(),diff --git a/Libraries/LibWeb/HTML/BroadcastChannel.cpp b/Libraries/LibWeb/HTML/BroadcastChannel.cppindex 7821a73a6e8..5c74197cf57 100644--- a/Libraries/LibWeb/HTML/BroadcastChannel.cpp+++ b/Libraries/LibWeb/HTML/BroadcastChannel.cpp@@ -28,10 +28,10 @@ extern "C" {void web_html_broadcast_channel_relevant_settings_object_origin(void* realm, void* ctx, void (*on_origin)(void*, URL::FFI::FfiOrigin const*));void web_html_broadcast_channel_set_strongly_referenced(void* realm, DOM::EventTarget*, bool strongly_referenced);-void web_html_broadcast_channel_post_message_to_other_processes(void* realm, FlatPtr channel_name, ReadonlyBytes serialized_message, int const* shared_memory, size_t const* shared_memory_sizes, size_t shared_memory_count);+void web_html_broadcast_channel_post_message_to_other_processes(void* realm, FlatPtr channel_name, ReadonlyBytes serialized_message, int shared_store_lifeline);// Defined on the Rust side.-void web_rust_broadcast_channel_deliver_message_locally(JSVM*, URL::FFI::FfiOrigin const* storage_key_origin, FlatPtr channel_name, URL::FFI::FfiOrigin const* source_origin, ReadonlyBytes serialized_message, int const* shared_memory, size_t const* shared_memory_sizes, size_t shared_memory_count);+void web_rust_broadcast_channel_deliver_message_locally(JSVM*, URL::FFI::FfiOrigin const* storage_key_origin, FlatPtr channel_name, URL::FFI::FfiOrigin const* source_origin, ReadonlyBytes serialized_message, int shared_store_lifeline);}static JS::Object& global_object_of(void* realm)@@ -55,42 +55,28 @@ void web_html_broadcast_channel_set_strongly_referenced(void* realm, DOM::EventTglobal_scope.remove_strong_reference_to_broadcast_channel(*event_target);}-void web_html_broadcast_channel_post_message_to_other_processes(void* realm, FlatPtr channel_name, ReadonlyBytes serialized_message, int const* shared_memory, size_t const* shared_memory_sizes, size_t shared_memory_count)+void web_html_broadcast_channel_post_message_to_other_processes(void* realm, FlatPtr channel_name, ReadonlyBytes serialized_message, int shared_store_lifeline){auto& js_realm = *static_cast<JS::Realm*>(realm);auto name = Utf16String::from_raw(channel_name);- Vector<Core::AnonymousBuffer> shared_buffers;- shared_buffers.ensure_capacity(shared_memory_count);- for (size_t i = 0; i < shared_memory_count; ++i)- shared_buffers.unchecked_append(MUST(Core::AnonymousBuffer::create_from_anon_fd(shared_memory[i], shared_memory_sizes[i])));-// NB: The UI process forwards the message to the other processes hosting an environment with its storage key, and// each delivers it to its own BroadcastChannel objects.PostedBroadcastChannelMessage posted_message {.environment_id = principal_realm_settings_object(js_realm).id,.channel_name = Utf16FlyString::from_utf16(name.utf16_view()),.serialized_message = create_ipc_serialization_record(serialized_message, {}),- .shared_buffers = move(shared_buffers),+ .shared_store_lifeline = SharedStoreLifeline::adopting_fd(shared_store_lifeline),};Bindings::principal_host_defined_page(js_realm).client().page_did_post_broadcast_channel_message(posted_message);}void deliver_broadcast_channel_message_locally(BroadcastChannelMessage message){- Vector<int> shared_memory;- Vector<size_t> shared_memory_sizes;- shared_memory.ensure_capacity(message.shared_buffers.size());- shared_memory_sizes.ensure_capacity(message.shared_buffers.size());- for (auto const& shared_buffer : message.shared_buffers) {- shared_memory.unchecked_append(shared_buffer.fd());- shared_memory_sizes.unchecked_append(shared_buffer.size());- }-auto channel_name = Utf16String::from_utf16(message.channel_name.view());URL::RustIntegration::lend_origin_to_ffi(message.storage_key.origin, [&](URL::FFI::FfiOrigin const& storage_key_origin) {URL::RustIntegration::lend_origin_to_ffi(message.source_origin, [&](URL::FFI::FfiOrigin const& source_origin) {- web_rust_broadcast_channel_deliver_message_locally(JS::HostABI::vm_to_abi(JS::VM::the()), &storage_key_origin, move(channel_name).into_raw(), &source_origin, message.serialized_message.data.span(), shared_memory.data(), shared_memory_sizes.data(), shared_memory.size());+ web_rust_broadcast_channel_deliver_message_locally(JS::HostABI::vm_to_abi(JS::VM::the()), &storage_key_origin, move(channel_name).into_raw(), &source_origin, message.serialized_message.data.span(), message.shared_store_lifeline.fd());});});}diff --git a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cppindex 7adb5899818..a1ea1f24f11 100644--- a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp+++ b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp@@ -95,9 +95,9 @@ void web_structured_serialize_image_bitmap_pixels_destroy(ImageBitmapSharedPixelTransferDataEncoder* web_structured_serialize_transfer_data_holder_create(ReadonlyBytes, TransferAttachment const*, size_t);void web_structured_serialize_transfer_data_holder_take(TransferDataEncoder*, void*, ReceiveTransferPayload);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);+SerializedTransferRecord* web_structured_serialize_transfer_record_create(ReadonlyBytes, JSObject* const*, size_t, int const*, size_t const*, size_t, int, 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*));+void web_structured_serialize_transfer_record_take(SerializedTransferRecord*, void*, void (*)(void*, ReadonlyBytes, JSObject* const*, size_t, int const*, size_t const*, size_t, int), void (*)(void*, 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*);@@ -241,12 +241,13 @@ bool web_structured_serialize_validate_shared_memory(int descriptor, size_t size}// Takes over the descriptors and the data holders.-SerializedTransferRecord* web_structured_serialize_transfer_record_create(ReadonlyBytes data, JSObject* const* shared_array_buffers, size_t shared_array_buffer_count, int const* shared_memory, size_t const* sizes, size_t shared_memory_count, TransferDataEncoder* const* holders, size_t holder_count)+SerializedTransferRecord* web_structured_serialize_transfer_record_create(ReadonlyBytes data, JSObject* const* shared_array_buffers, size_t shared_array_buffer_count, int const* shared_memory, size_t const* sizes, size_t shared_memory_count, int shared_store_lifeline, TransferDataEncoder* const* holders, size_t holder_count){auto* record = new SerializedTransferRecord;record->serialized = create_ipc_serialization_record(data, shared_array_buffers_from_abi(shared_array_buffers, shared_array_buffer_count));for (size_t i = 0; i < shared_memory_count; ++i)record->shared_buffers.append(MUST(Core::AnonymousBuffer::create_from_anon_fd(shared_memory[i], sizes[i])));+ record->shared_store_lifeline = SharedStoreLifeline::adopting_fd(shared_store_lifeline);for (size_t i = 0; i < holder_count; ++i) {record->transfer_data_holders.append(move(*holders[i]));delete holders[i];@@ -260,7 +261,7 @@ void web_structured_serialize_transfer_record_destroy(SerializedTransferRecord*}// Rust roots the SharedArrayBuffers before this returns.-void web_structured_serialize_transfer_record_take(SerializedTransferRecord* record, void* context, void (*receive)(void*, ReadonlyBytes, JSObject* const*, size_t, int const*, size_t const*, size_t), void (*append_holder)(void*, TransferDataEncoder*))+void web_structured_serialize_transfer_record_take(SerializedTransferRecord* record, void* context, void (*receive)(void*, ReadonlyBytes, JSObject* const*, size_t, int const*, size_t const*, size_t, int), void (*append_holder)(void*, TransferDataEncoder*)){Vector<JSObject*> buffers;for (auto const& buffer : same_process_shared_array_buffers(record->serialized))@@ -271,7 +272,7 @@ void web_structured_serialize_transfer_record_take(SerializedTransferRecord* recdescriptors.append(buffer.fd());sizes.append(buffer.size());}- receive(context, record->serialized.data.span(), buffers.data(), buffers.size(), descriptors.data(), sizes.data(), descriptors.size());+ receive(context, record->serialized.data.span(), buffers.data(), buffers.size(), descriptors.data(), sizes.data(), descriptors.size(), record->shared_store_lifeline.fd());for (auto& holder : record->transfer_data_holders)append_holder(context, new TransferDataEncoder(move(holder)));record->shared_buffers.clear();diff --git a/Libraries/LibWebCommon/HTML/BroadcastChannelMessage.cpp b/Libraries/LibWebCommon/HTML/BroadcastChannelMessage.cppindex 659e9faf5f7..4c3a3abd453 100644--- a/Libraries/LibWebCommon/HTML/BroadcastChannelMessage.cpp+++ b/Libraries/LibWebCommon/HTML/BroadcastChannelMessage.cpp@@ -18,7 +18,7 @@ ErrorOr<void> encode(Encoder& encoder, Web::HTML::BroadcastChannelMessage const&TRY(encoder.encode(message.channel_name));TRY(encoder.encode(message.source_origin));TRY(encoder.encode(message.serialized_message));- TRY(encoder.encode(message.shared_buffers));+ TRY(encoder.encode(message.shared_store_lifeline));return {};}@@ -29,14 +29,14 @@ ErrorOr<Web::HTML::BroadcastChannelMessage> decode(Decoder& decoder)auto channel_name = TRY(decoder.decode<Utf16FlyString>());auto source_origin = TRY(decoder.decode<URL::Origin>());auto serialized_message = TRY(decoder.decode<Web::HTML::IPCSerializationRecord>());- auto shared_buffers = TRY(decoder.decode<Vector<Core::AnonymousBuffer>>());+ auto shared_store_lifeline = TRY(decoder.decode<Web::HTML::SharedStoreLifeline>());return Web::HTML::BroadcastChannelMessage {.storage_key = move(storage_key),.channel_name = move(channel_name),.source_origin = move(source_origin),.serialized_message = move(serialized_message),- .shared_buffers = move(shared_buffers),+ .shared_store_lifeline = move(shared_store_lifeline),};}@@ -46,7 +46,7 @@ ErrorOr<void> encode(Encoder& encoder, Web::HTML::PostedBroadcastChannelMessageTRY(encoder.encode(message.environment_id));TRY(encoder.encode(message.channel_name));TRY(encoder.encode(message.serialized_message));- TRY(encoder.encode(message.shared_buffers));+ TRY(encoder.encode(message.shared_store_lifeline));return {};}@@ -56,13 +56,13 @@ ErrorOr<Web::HTML::PostedBroadcastChannelMessage> decode(Decoder& decoder)auto environment_id = TRY(decoder.decode<Web::HTML::EnvironmentId>());auto channel_name = TRY(decoder.decode<Utf16FlyString>());auto serialized_message = TRY(decoder.decode<Web::HTML::IPCSerializationRecord>());- auto shared_buffers = TRY(decoder.decode<Vector<Core::AnonymousBuffer>>());+ auto shared_store_lifeline = TRY(decoder.decode<Web::HTML::SharedStoreLifeline>());return Web::HTML::PostedBroadcastChannelMessage {.environment_id = move(environment_id),.channel_name = move(channel_name),.serialized_message = move(serialized_message),- .shared_buffers = move(shared_buffers),+ .shared_store_lifeline = move(shared_store_lifeline),};}diff --git a/Libraries/LibWebCommon/HTML/BroadcastChannelMessage.h b/Libraries/LibWebCommon/HTML/BroadcastChannelMessage.hindex 9c772e218a9..bfc2905d152 100644--- a/Libraries/LibWebCommon/HTML/BroadcastChannelMessage.h+++ b/Libraries/LibWebCommon/HTML/BroadcastChannelMessage.h@@ -24,17 +24,14 @@ struct WEBCOMMON_API BroadcastChannelMessage {Utf16FlyString channel_name;URL::Origin source_origin;IPCSerializationRecord serialized_message;- // AD-HOC: Cross-process shared memory backing the SharedArrayBuffers in serialized_message, by file descriptor- // — referenced by index from the record, whose bytes can't carry one. So the browser process's fan-out- // hands every receiving process the same memory. See SerializedTransferRecord.- Vector<Core::AnonymousBuffer> shared_buffers;+ SharedStoreLifeline shared_store_lifeline;};struct WEBCOMMON_API PostedBroadcastChannelMessage {EnvironmentId environment_id;Utf16FlyString channel_name;IPCSerializationRecord serialized_message;- Vector<Core::AnonymousBuffer> shared_buffers;+ SharedStoreLifeline shared_store_lifeline;};}diff --git a/Libraries/LibWebCommon/HTML/SerializationRecords.cpp b/Libraries/LibWebCommon/HTML/SerializationRecords.cppindex 4bf13979441..395ada76378 100644--- a/Libraries/LibWebCommon/HTML/SerializationRecords.cpp+++ b/Libraries/LibWebCommon/HTML/SerializationRecords.cpp@@ -16,6 +16,18 @@ namespace Web::HTML {SameProcessSerializationSideTable::~SameProcessSerializationSideTable() = default;+SharedStoreLifeline SharedStoreLifeline::adopting_fd(int fd)+{+ if (fd < 0)+ return {};+ return { IPC::File::adopt_fd(fd) };+}++int SharedStoreLifeline::fd() const+{+ return file.has_value() ? file->fd() : -1;+}+void append_storage_format_prologue(ByteBuffer& data){data.append(storage_format_magic.data(), storage_format_magic.size());@@ -136,6 +148,7 @@ ErrorOr<void> encode(Encoder& encoder, Web::HTML::SerializedTransferRecord constTRY(encoder.encode(record.serialized));TRY(encoder.encode(record.transfer_data_holders));TRY(encoder.encode(record.shared_buffers));+ TRY(encoder.encode(record.shared_store_lifeline));return {};}@@ -145,8 +158,27 @@ ErrorOr<Web::HTML::SerializedTransferRecord> decode(Decoder& decoder)auto serialized = TRY(decoder.decode<Web::HTML::IPCSerializationRecord>());auto transfer_data_holders = TRY(decoder.decode<Vector<Web::HTML::TransferDataEncoder>>());auto shared_buffers = TRY(decoder.decode<Vector<Core::AnonymousBuffer>>());+ auto shared_store_lifeline = TRY(decoder.decode<Web::HTML::SharedStoreLifeline>());++ return Web::HTML::SerializedTransferRecord { move(serialized), move(transfer_data_holders), move(shared_buffers), move(shared_store_lifeline) };+}- return Web::HTML::SerializedTransferRecord { move(serialized), move(transfer_data_holders), move(shared_buffers) };+template<>+ErrorOr<void> encode(Encoder& encoder, Web::HTML::SharedStoreLifeline const& lifeline)+{+ // NB: A record may go out more than once, so what goes out is a duplicate.+ TRY(encoder.encode(lifeline.file.has_value()));+ if (lifeline.file.has_value())+ TRY(encoder.encode(TRY(File::clone_fd(lifeline.file->fd()))));+ return {};+}++template<>+ErrorOr<Web::HTML::SharedStoreLifeline> decode(Decoder& decoder)+{+ if (!TRY(decoder.decode<bool>()))+ return Web::HTML::SharedStoreLifeline {};+ return Web::HTML::SharedStoreLifeline { TRY(decoder.decode<File>()) };}}diff --git a/Libraries/LibWebCommon/HTML/SerializationRecords.h b/Libraries/LibWebCommon/HTML/SerializationRecords.hindex b8a467c95a5..c134379269e 100644--- a/Libraries/LibWebCommon/HTML/SerializationRecords.h+++ b/Libraries/LibWebCommon/HTML/SerializationRecords.h@@ -11,11 +11,13 @@#include <AK/Array.h>#include <AK/ByteBuffer.h>+#include <AK/Optional.h>#include <AK/RefCounted.h>#include <AK/RefPtr.h>#include <AK/Vector.h>#include <LibCore/AnonymousBuffer.h>#include <LibIPC/Encoder.h>+#include <LibIPC/File.h>#include <LibIPC/Forward.h>#include <LibIPC/Message.h>#include <LibWebCommon/Export.h>@@ -136,21 +138,37 @@ private:IPC::Encoder m_encoder;};+// AD-HOC: What keeps the SharedArrayBuffer stores that a message names alive while the message is on its way, for as+// long as this or a copy of it in any process is open. It gives no access to the stores, whose bytes never leave+// their process. See shared_backing_store.rs in LibJS.+struct WEBCOMMON_API SharedStoreLifeline {+ static SharedStoreLifeline adopting_fd(int fd);++ int fd() const;++ Optional<IPC::File> file;+};+struct SerializedTransferRecord {AK_ALLOC_WITH_KMALLOC;IPCSerializationRecord serialized;Vector<TransferDataEncoder> transfer_data_holders;- // AD-HOC: Cross-process shared memory backing serialized SharedArrayBuffers — referenced by index from the main- // record (whose bytes can't carry file descriptors). Unlike the record's same-process side table, this one- // is IPC-encoded, so it reaches an agent in another process.+ // AD-HOC: Shared memory that hands the pixels of transferred ImageBitmaps over, by index from the data holders.Vector<Core::AnonymousBuffer> shared_buffers;+ SharedStoreLifeline shared_store_lifeline;};}namespace IPC {+template<>+WEBCOMMON_API ErrorOr<void> encode(Encoder&, Web::HTML::SharedStoreLifeline const&);++template<>+WEBCOMMON_API ErrorOr<Web::HTML::SharedStoreLifeline> decode(Decoder&);+template<>WEBCOMMON_API ErrorOr<void> encode(Encoder&, Web::HTML::IPCSerializationRecord const&);diff --git a/Libraries/LibWebView/WorkerProcessManager.cpp b/Libraries/LibWebView/WorkerProcessManager.cppindex ae53949bfff..1106d92ad26 100644--- a/Libraries/LibWebView/WorkerProcessManager.cpp+++ b/Libraries/LibWebView/WorkerProcessManager.cpp@@ -518,7 +518,7 @@ void WorkerProcessManager::post_broadcast_channel_message(Web::HTML::PostedBroad.channel_name = move(posted_message.channel_name),.source_origin = source_settings.origin(),.serialized_message = move(posted_message.serialized_message),- .shared_buffers = move(posted_message.shared_buffers),+ .shared_store_lifeline = move(posted_message.shared_store_lifeline),};WebContentClient::for_each_client([&](auto& client) {diff --git a/Tests/LibJS/TestVMThreads.cpp b/Tests/LibJS/TestVMThreads.cppindex ade0239d627..1c314d30ea9 100644--- a/Tests/LibJS/TestVMThreads.cpp+++ b/Tests/LibJS/TestVMThreads.cpp@@ -11,7 +11,6 @@#include <AK/Time.h>#include <AK/Utf16String.h>#include <AK/Vector.h>-#include <LibCore/AnonymousBuffer.h>#include <LibCore/Environment.h>#include <LibCore/System.h>#include <LibGC/BlockAllocator.h>@@ -358,8 +357,17 @@ static constexpr i32 RESULT_TIMED_OUT = 3;class SharedMemoryScripts {public:SharedMemoryScripts()- : m_memory(MUST(Core::AnonymousBuffer::create_with_size(4096))){+ // NB: The agent that created the memory keeps it for the test, as the others come and go.+ auto owner = Threading::Thread::construct("VMThreadTestOwner"sv, [this] {+ own_memory();+ return static_cast<intptr_t>(0);+ });+ owner->set_stack_size(JS::VM::MINIMUM_THREAD_STACK_SIZE);+ owner->start();+ m_threads.append(move(owner));+ while (!m_words.load())+ MUST(Core::System::sleep_ms(1));}~SharedMemoryScripts()@@ -369,7 +377,7 @@ public:MUST(thread->join());}- // Runs a script on a VM and thread of its own, which each map the memory again, like another process would.+ // Runs a script on a VM and thread of its own, which shares the memory as a worker's agent would.void start(ByteString source, Optional<size_t> index = {}){auto thread = Threading::Thread::construct("VMThreadTest"sv, [this, source = move(source), index] {@@ -431,9 +439,28 @@ public:return m_did_throw[index] && !has_result(index);}- AK::Atomic<i32>& word(size_t index) { return reinterpret_cast<AK::Atomic<i32>*>(m_memory.data<i32>())[index]; }+ AK::Atomic<i32>& word(size_t index) { return m_words.load()[index]; }private:+ void own_memory()+ {+ auto vm = JS::VM::create();+ vm->heap().set_incremental_sweep_enabled(false);+ auto root_execution_context = JS::create_simple_execution_context<JS::GlobalObject>(*vm);+ auto& realm = *root_execution_context->realm;++ auto source_text = "new SharedArrayBuffer(4096)"_utf16;+ auto script = JS::Script::parse(source_text.utf16_view(), realm);+ VERIFY(!script.is_error());+ auto& buffer = as<JS::ArrayBuffer>(vm->run(script.value()).value().as_object());+ EXPECT_NE(buffer.shared_store_id(), 0u);+ m_shared_store_id = buffer.shared_store_id();+ m_words = reinterpret_cast<AK::Atomic<i32>*>(const_cast<u8*>(buffer.data_at(0)));++ while (!m_may_destroy_vms)+ MUST(Core::System::sleep_ms(1));+ }+void run(ByteString const& source, Optional<size_t> index){auto vm = JS::VM::create();@@ -441,9 +468,8 @@ private:auto root_execution_context = JS::create_simple_execution_context<JS::GlobalObject>(*vm);auto& realm = *root_execution_context->realm;- auto memory = MUST(Core::AnonymousBuffer::create_from_anon_fd(MUST(Core::System::dup(m_memory.fd())), m_memory.size()));- auto buffer = JS::ArrayBuffer::create(realm, move(memory), 1);- EXPECT(buffer->shared_buffer().has_value());+ auto buffer = JS::ArrayBuffer::create_from_shared_store(realm, m_shared_store_id.load());+ VERIFY(buffer);MUST(realm.global_object().set(JS::PropertyKey { "memory"_utf16_fly_string }, buffer, JS::Object::ShouldThrowExceptions::Yes));auto text = ByteString::formatted("const words = new Int32Array(memory); {}", source);@@ -465,7 +491,8 @@ private:static constexpr size_t MAX_WAITER_COUNT = 8;- Core::AnonymousBuffer m_memory;+ AK::Atomic<u64> m_shared_store_id { 0 };+ AK::Atomic<AK::Atomic<i32>*> m_words { nullptr };Vector<NonnullRefPtr<Threading::Thread>> m_threads;Array<AK::Atomic<JS::VM*>, MAX_WAITER_COUNT> m_vms;Array<AK::Atomic<bool>, MAX_WAITER_COUNT> m_did_throw;diff --git a/Tests/LibWeb/TestStructuredSerializeSharedArrayBuffer.cpp b/Tests/LibWeb/TestStructuredSerializeSharedArrayBuffer.cppindex c05f36a3d9d..ebc74adb95f 100644--- a/Tests/LibWeb/TestStructuredSerializeSharedArrayBuffer.cpp+++ b/Tests/LibWeb/TestStructuredSerializeSharedArrayBuffer.cpp@@ -48,9 +48,9 @@ static GC::Ref<JS::ArrayBuffer> make_shared_array_buffer(JS::Realm& realm, Readoreturn buffer;}-// The SharedArrayBuffer constructor's path: A fixed-length shared Data Block is backed by cross-process shared memory,-// unlike the process-local storage that ArrayBuffer::create(Realm&, size_t, Shared) allocates above.-static GC::Ref<JS::ArrayBuffer> make_shared_memory_backed_array_buffer(JS::Realm& realm, ReadonlyBytes contents)+// The SharedArrayBuffer constructor's path: A fixed-length shared Data Block is a store that agents on other threads can+// share, unlike the storage of one buffer that ArrayBuffer::create(Realm&, size_t, Shared) allocates above.+static GC::Ref<JS::ArrayBuffer> make_array_buffer_in_shared_store(JS::Realm& realm, ReadonlyBytes contents){Web::HTML::TemporaryExecutionContext execution_context { realm };auto& buffer = as<JS::ArrayBuffer>(*MUST(JS::construct(realm.vm(), *realm.intrinsics().shared_array_buffer_constructor(), JS::Value(contents.size()))));@@ -121,22 +121,20 @@ TEST_CASE(same_process_clone_aliases_the_backing_store)EXPECT_EQ(source_contents[1], static_cast<u8>('C'));}-TEST_CASE(shared_memory_backed_clone_references_the_same_shared_object)+TEST_CASE(clone_in_a_shared_store_references_the_same_store){- auto source = make_shared_memory_backed_array_buffer(source_realm(), "shared memory"sv.bytes());- EXPECT(source->shared_buffer().has_value());+ auto source = make_array_buffer_in_shared_store(source_realm(), "shared store"sv.bytes());+ EXPECT(source->data_block().is_in_shared_store());auto& clone = as_array_buffer(deserialize(serialize_same_agent(JS::Value { source.ptr() }), target_realm()));EXPECT(clone.is_shared_array_buffer());EXPECT_EQ(clone.byte_length(), source->byte_length());EXPECT(&clone != source.ptr());- // The clone references the source's shared object, rather than a process-local alias of it — so it can itself- // be shared with an agent in another process.- auto clone_shared_memory = clone.shared_buffer();- EXPECT(clone_shared_memory.has_value());- clone_shared_memory->data<u8>()[2] = static_cast<u8>('M');- EXPECT_EQ(contents_of(*source)[2], static_cast<u8>('M'));+ // The clone references the source's store, rather than a local alias of the buffer, so it can itself be shared with+ // an agent on another thread.+ EXPECT(clone.data_block().is_in_shared_store());+ EXPECT_EQ(clone.data_at(0), source->data_at(0));source->overwrite(0, "S", 1);auto clone_contents = contents_of(clone);diff --git a/Tests/LibWeb/Text/expected/shared-array-buffer-kept-alive-by-message.txt b/Tests/LibWeb/Text/expected/shared-array-buffer-kept-alive-by-message.txtnew file mode 100644index 00000000000..c62750fbd9b--- /dev/null+++ b/Tests/LibWeb/Text/expected/shared-array-buffer-kept-alive-by-message.txt@@ -0,0 +1,2 @@+received a SharedArrayBuffer: true+value: 42diff --git a/Tests/LibWeb/Text/input/shared-array-buffer-kept-alive-by-message.html b/Tests/LibWeb/Text/input/shared-array-buffer-kept-alive-by-message.htmlnew file mode 100644index 00000000000..549c7aeb37a--- /dev/null+++ b/Tests/LibWeb/Text/input/shared-array-buffer-kept-alive-by-message.html@@ -0,0 +1,37 @@+<!DOCTYPE html>+<script type="worker">+ const channel = new BroadcastChannel("kept-alive");+ self.onmessage = () => {+ const view = new Int32Array(new SharedArrayBuffer(4096));+ view[0] = 42;+ channel.postMessage(view.buffer);+ self.close();+ };+ postMessage("ready");+</script>+<script src="include.js"></script>+<script>+ // A message on its way may be the only thing that still has the memory of a SharedArrayBuffer: here, the only agent+ // that had the buffer is gone before this thread gets to read the message.+ asyncTest((done) => {+ const receiver = new BroadcastChannel("kept-alive");+ receiver.onmessage = (e) => {+ println(`received a SharedArrayBuffer: ${e.data instanceof SharedArrayBuffer}`);+ println(`value: ${new Int32Array(e.data)[0]}`);+ done();+ };+ receiver.onmessageerror = () => {+ println("messageerror");+ done();+ };++ const workerSource = document.querySelector("[type=worker]").innerText;+ const worker = new Worker(URL.createObjectURL(new Blob([workerSource], { type: "text/javascript" })));+ worker.onmessage = () => {+ worker.postMessage("go");+ // NB: The worker closes itself once it posted the buffer, and its agent counts as gone once it shut down.+ const start = performance.now();+ while (internals.workerAgentCount() !== 0 && performance.now() - start < 5000);+ };+ });+</script>diff --git a/Tests/LibWeb/Text/input/shared-array-buffer-kept-alive-by-message.html.headers b/Tests/LibWeb/Text/input/shared-array-buffer-kept-alive-by-message.html.headersnew file mode 100644index 00000000000..63b60e490f4--- /dev/null+++ b/Tests/LibWeb/Text/input/shared-array-buffer-kept-alive-by-message.html.headers@@ -0,0 +1,2 @@+Cross-Origin-Opener-Policy: same-origin+Cross-Origin-Embedder-Policy: require-corp