Skip to content

Truly independent web browser

LibWeb: Own structured serialization transfer records from Rust

Shannon Booth933620bb7f1c
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs
index b2b5eb6f537..35e5d010a49 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs
@@ -19,6 +19,8 @@ use libjs_rust::api::{ArrayBuffer, ArrayBufferShared, Gc, Object, RawNativeFunct
use crate::bindings::{CallContext, Exception, WebIdlResult};
unsafe extern "C" {
+ fn web_structured_serialize_writer_create_for_transfer() -> *mut c_void;
+ fn web_structured_serialize_writer_destroy(writer: *mut c_void);
fn web_structured_serialize_writer_type(writer: *mut c_void) -> u8;
fn web_structured_serialize_writer_encode_u8(writer: *mut c_void, value: u8);
fn web_structured_serialize_writer_encode_bool(writer: *mut c_void, value: bool);
@@ -203,6 +205,9 @@ unsafe extern "C" {
fn web_structured_serialize_transfer_data_holder_encode_bytes(data_holder: *mut c_void, bytes: ak::Span<'_, u8>);
fn web_structured_serialize_transfer_data_holder_encode_size(data_holder: *mut c_void, value: usize);
fn web_structured_serialize_transfer_data_holder_destroy(data_holder: *mut c_void);
+ fn web_structured_serialize_transfer_record_create() -> *mut c_void;
+ fn web_structured_serialize_transfer_record_destroy(record: *mut c_void);
+ fn web_structured_serialize_transfer_record_set_serialized(record: *mut c_void, writer: *mut c_void);
fn web_structured_serialize_transfer_record_append_data_holder(record: *mut c_void, data_holder: *mut c_void);
fn web_structured_serialize_transfer_record_data_holder_count(record: *mut c_void) -> usize;
fn web_structured_serialize_transfer_record_take_data_holder(record: *mut c_void, index: usize) -> *mut c_void;
@@ -423,6 +428,28 @@ impl StructuredSerializeWriter {
}
}
+/// A writer that this owns, of the [[Serialized]] of a transfer: an IPC record, since the transfer may cross a process
+/// boundary, with the shared memory of its SharedArrayBuffers on the side.
+pub(crate) struct OwnedStructuredSerializeWriter(StructuredSerializeWriter);
+
+impl OwnedStructuredSerializeWriter {
+ pub(crate) fn new_for_transfer() -> Self {
+ // SAFETY: LibWeb returns a new writer, which this owns.
+ Self(unsafe { StructuredSerializeWriter::from_raw(web_structured_serialize_writer_create_for_transfer()) })
+ }
+
+ pub(crate) fn writer(&self) -> StructuredSerializeWriter {
+ self.0
+ }
+}
+
+impl Drop for OwnedStructuredSerializeWriter {
+ fn drop(&mut self) {
+ // SAFETY: This owns the writer.
+ unsafe { web_structured_serialize_writer_destroy(self.0.as_raw()) };
+ }
+}
+
/// The record that a structured deserialization reads: an HTML::StructuredSerializeReader that C++ lends. What it
/// reads that the record does not hold throws a "DataCloneError" DOMException in the realm.
#[derive(Clone, Copy)]
@@ -987,6 +1014,13 @@ impl SerializedTransferRecord {
Self(NonNull::new(record).expect("C++ lends a record"))
}
+ /// Sets the record's [[Serialized]] to what the writer wrote, with the shared memory of the SharedArrayBuffers it
+ /// shared.
+ pub(crate) fn set_serialized(self, writer: StructuredSerializeWriter) {
+ // SAFETY: The record and the writer are lent.
+ unsafe { web_structured_serialize_transfer_record_set_serialized(self.0.as_ptr(), writer.as_raw()) };
+ }
+
/// Appends the data holder to the record's [[TransferDataHolders]].
pub(crate) fn append_data_holder(self, data_holder: TransferDataHolder) {
let data_holder = core::mem::ManuallyDrop::new(data_holder);
@@ -1024,6 +1058,33 @@ impl SerializedTransferRecord {
}
}
+/// A record of a structured serialization with transfer that this owns.
+pub(crate) struct OwnedSerializedTransferRecord(SerializedTransferRecord);
+
+impl OwnedSerializedTransferRecord {
+ pub(crate) fn new() -> Self {
+ // SAFETY: LibWeb returns a new record, which this owns.
+ Self(unsafe { SerializedTransferRecord::from_raw(web_structured_serialize_transfer_record_create()) })
+ }
+
+ pub(crate) fn record(&self) -> SerializedTransferRecord {
+ self.0
+ }
+
+ /// Hands the record over to LibWeb's C++ code, which owns it from then on.
+ pub(crate) fn into_raw(self) -> *mut c_void {
+ let record = ManuallyDrop::new(self);
+ record.0.0.as_ptr()
+ }
+}
+
+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()) };
+ }
+}
+
/// The list of transferred values of a structured deserialization with transfer: a Vector<GC::Root<JS::Object>> that
/// C++ lends.
#[derive(Clone, Copy)]
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/exports.rs
index b2b93094823..330b3cec548 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/exports.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/exports.rs
@@ -104,34 +104,25 @@ pub unsafe extern "C" fn web_rust_structured_deserialize_internal(
completion(&cx, result)
}
-/// StructuredSerializeWithTransfer in the realm, which writes [[Serialized]] with the writer, and appends
-/// [[TransferDataHolders]] to the record.
+/// StructuredSerializeWithTransfer in the realm, whose record the caller owns.
///
/// # Safety
///
-/// The pointers must be the VM, a live realm, a writer and a record that C++ lends, and `count` live objects. The
-/// value must be live.
+/// The pointers must be the VM, a live realm, and `count` live objects. The value must be live.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn web_rust_structured_serialize_with_transfer(
vm: *mut c_void,
realm: *mut c_void,
- serialized: *mut c_void,
- record: *mut c_void,
value: u64,
transfer_list: *const *mut c_void,
count: usize,
+ out_record: &mut *mut c_void,
) -> RawNativeFunctionResult {
// SAFETY: The caller passes the VM and a live realm.
let (vm, realm) = unsafe { realm_arguments(vm, realm) };
let cx = CallContext::new(vm, realm);
- // SAFETY: The caller lends the writer and the record, and passes a live value.
- let (serialized, record, value) = unsafe {
- (
- StructuredSerializeWriter::from_raw(serialized),
- SerializedTransferRecord::from_raw(record),
- Value::from_raw(value),
- )
- };
+ // SAFETY: The caller passes a live value.
+ let value = unsafe { Value::from_raw(value) };
let transfer_list_values = MarkedVec::with_capacity(vm, count);
for index in 0..count {
// SAFETY: The caller passes `count` live objects.
@@ -139,8 +130,14 @@ pub unsafe extern "C" fn web_rust_structured_serialize_with_transfer(
Gc::from_non_null(NonNull::new((*transfer_list.add(index)).cast::<Object>()).expect("C++ passes objects"))
});
}
- let result = structured_serialize_with_transfer(&cx, serialized, record, value, &transfer_list_values.values());
- completion(&cx, result.map(|()| Value::UNDEFINED))
+ let result = structured_serialize_with_transfer(&cx, value, &transfer_list_values.values());
+ completion(
+ &cx,
+ result.map(|record| {
+ *out_record = record.into_raw();
+ Value::UNDEFINED
+ }),
+ )
}
/// StructuredDeserializeWithTransfer in the realm, which returns [[Deserialized]], and appends [[TransferredValues]] to
@@ -166,8 +163,16 @@ pub unsafe extern "C" fn web_rust_structured_deserialize_with_transfer(
TransferredValues::from_raw(transferred_values),
)
};
- let result = structured_deserialize_with_transfer(&cx, record, transferred_values);
- completion(&cx, result)
+ let result = structured_deserialize_with_transfer(&cx, record);
+ completion(
+ &cx,
+ result.map(|deserialize_record| {
+ for value in deserialize_record.transferred_values.values().iter() {
+ transferred_values.append(*value);
+ }
+ deserialize_record.deserialized
+ }),
+ )
}
/// The value that one data holder of a transfer holds, in the realm.
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs
index cc60db2b785..936428c603d 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs
@@ -29,15 +29,15 @@ use libjs_rust::api::{
use crate::bindings::{CallContext, Exception, WebIdlResult};
use crate::html::structured_serialize::cpp::{
- DeserializationMemory, OwnedDeserializationMemory, SerializationMemory, SerializationType,
- SerializedTransferRecord, StructuredSerializeReader, StructuredSerializeWriter, TransferDataDecoder,
- TransferDataHolder, TransferredValues, create_serialized_platform_object, create_transferred_platform_object,
- current_settings_object_agent_cluster, current_settings_object_cross_origin_isolated_capability,
- data_clone_error_from_serialization_error, deserialization_steps, deserialize_rust_platform_object, is_exposed,
- is_platform_object, is_transferable, is_transferable_interface_exposed, realm_agent_cluster,
- serializable_interface_is_implemented_in_rust, serializable_interface_name, serializable_payload_version,
- serialization_steps, transfer_steps, transferable_is_detached, transferable_primary_interface,
- transferable_set_detached,
+ DeserializationMemory, OwnedDeserializationMemory, OwnedSerializedTransferRecord, OwnedStructuredSerializeWriter,
+ SerializationMemory, SerializationType, SerializedTransferRecord, StructuredSerializeReader,
+ StructuredSerializeWriter, TransferDataDecoder, TransferDataHolder, create_serialized_platform_object,
+ create_transferred_platform_object, current_settings_object_agent_cluster,
+ current_settings_object_cross_origin_isolated_capability, data_clone_error_from_serialization_error,
+ deserialization_steps, deserialize_rust_platform_object, is_exposed, is_platform_object, is_transferable,
+ is_transferable_interface_exposed, realm_agent_cluster, serializable_interface_is_implemented_in_rust,
+ serializable_interface_name, serializable_payload_version, serialization_steps, transfer_steps,
+ transferable_is_detached, transferable_primary_interface, transferable_set_detached,
};
/// HTML::ValueTag, the tags of the values of a record, which are part of the stable storage serialization format.
@@ -1475,15 +1475,12 @@ impl Deserializer<'_, '_> {
// https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializewithtransfer
pub(crate) fn structured_serialize_with_transfer(
cx: &CallContext,
- serialized_writer: StructuredSerializeWriter,
- record: SerializedTransferRecord,
value: Value,
transfer_list: &[Gc<Object>],
-) -> WebIdlResult<()> {
+) -> WebIdlResult<OwnedSerializedTransferRecord> {
let vm = cx.vm();
// 1. Let memory be an empty map.
- // NB: C++ creates the writer, and makes the record of what this returns.
let memory = cpp::OwnedSerializationMemory::new();
// 2. For each transferable of transferList:
@@ -1513,10 +1510,13 @@ 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 an IPC record, with the memory of its SharedArrayBuffers
+ // shared on the side.
+ let serialized = OwnedStructuredSerializeWriter::new_for_transfer();
structured_serialize_internal(
vm,
Some(cx.realm()),
- serialized_writer,
+ serialized.writer(),
value,
false,
memory.memory(),
@@ -1525,10 +1525,11 @@ pub(crate) fn structured_serialize_with_transfer(
// AD-HOC: Gather the pixels of the transferred ImageBitmaps in one buffer of shared memory. Without it, as when there
// is not enough memory for it, the pixels travel inline.
- let image_bitmap_pixels = serialized_writer.gather_image_bitmap_pixels(transfer_list);
+ let image_bitmap_pixels = serialized.writer().gather_image_bitmap_pixels(transfer_list);
// 4. Let transferDataHolders be a new empty List.
- // NB: The data holders are appended to the record that C++ returns.
+ // NB: The record of the result holds the list.
+ let result = OwnedSerializedTransferRecord::new();
// 5. For each transferable of transferList:
for transferable in transfer_list {
@@ -1601,23 +1602,34 @@ pub(crate) fn structured_serialize_with_transfer(
}
// 6. Append dataHolder to transferDataHolders.
- record.append_data_holder(data_holder);
+ result.record().append_data_holder(data_holder);
}
// 6. Let result be { [[Serialized]]: serialized, [[TransferDataHolders]]: transferDataHolders, [[InterfaceNames]]: an empty ordered set, [[AgentCluster]]: null }.
+ result.record().set_serialized(serialized.writer());
+
// FIXME: 7. For each object → record of memory:
// 1. If object is a platform object, then append record.[[Type]] to result.[[InterfaceNames]].
// 2. If record.[[AgentCluster]] is not null, then restrict result to the same agent cluster.
+
// 8. Return result.
- Ok(())
+ Ok(result)
+}
+
+/// The record that StructuredDeserializeWithTransfer returns,
+/// https://html.spec.whatwg.org/multipage/structured-data.html#structureddeserializewithtransfer
+pub(crate) struct DeserializedTransferRecord<'vm> {
+ /// [[Deserialized]], the deserialized value.
+ pub(crate) deserialized: Value,
+ /// [[TransferredValues]], the transferred objects in the order of their data holders.
+ pub(crate) transferred_values: MarkedVec<'vm, Gc<Object>>,
}
// https://html.spec.whatwg.org/multipage/structured-data.html#structureddeserializewithtransfer
-pub(crate) fn structured_deserialize_with_transfer(
- cx: &CallContext,
+pub(crate) fn structured_deserialize_with_transfer<'vm>(
+ cx: &CallContext<'vm>,
serialize_with_transfer_result: SerializedTransferRecord,
- transferred_values: TransferredValues,
-) -> WebIdlResult<Value> {
+) -> WebIdlResult<DeserializedTransferRecord<'vm>> {
let target_realm = cx.realm();
// 1. Let memory be an empty map.
@@ -1628,7 +1640,7 @@ pub(crate) fn structured_deserialize_with_transfer(
// 1. If the interface identified by interfaceName is not exposed in targetRealm, then throw a "DataCloneError" DOMException.
// 4. Let transferredValues be a new empty List.
- // NB: C++ lends the list that it returns.
+ let transferred_values = MarkedVec::new(cx.vm());
// 5. For each transferDataHolder of serializeWithTransferResult.[[TransferDataHolders]]:
for index in 0..serialize_with_transfer_result.data_holder_count() {
@@ -1643,7 +1655,7 @@ pub(crate) fn structured_deserialize_with_transfer(
memory.memory().append(value);
// 6. Append value to transferredValues.
- transferred_values.append(value.as_object());
+ transferred_values.push(value.as_object());
}
// 6. Let deserialized be ? StructuredDeserialize(serializeWithTransferResult.[[Serialized]], targetRealm, memory).
@@ -1654,7 +1666,10 @@ pub(crate) fn structured_deserialize_with_transfer(
serialize_with_transfer_result.clear_shared_buffers();
// 7. Return { [[Deserialized]]: deserialized, [[TransferredValues]]: transferredValues }.
- Ok(deserialized)
+ Ok(DeserializedTransferRecord {
+ deserialized,
+ transferred_values,
+ })
}
// AD-HOC: This non-standard overload is meant to extract just one transferrable value from a serialized transfer record.
diff --git a/Libraries/LibWeb/HTML/StructuredSerialize.cpp b/Libraries/LibWeb/HTML/StructuredSerialize.cpp
index 7c9dea1effb..2d0e1c590ad 100644
--- a/Libraries/LibWeb/HTML/StructuredSerialize.cpp
+++ b/Libraries/LibWeb/HTML/StructuredSerialize.cpp
@@ -1105,7 +1105,7 @@ WebIDL::Exception data_clone_error_from_serialization_error(JS::Realm& realm, AK
extern "C" {
JSCompletion web_rust_structured_serialize_internal(JSVM*, StructuredSerializeWriter*, JSValue, bool for_storage, SerializationMemory*, u8 allow_shared_array_buffers);
JSCompletion web_rust_structured_deserialize_internal(JSVM*, void* target_realm, StructuredSerializeReader*, DeserializationMemory*, bool check_fully_consumed);
-JSCompletion web_rust_structured_serialize_with_transfer(JSVM*, void* realm, StructuredSerializeWriter*, SerializedTransferRecord*, JSValue, JSObject* const* transfer_list, size_t count);
+JSCompletion web_rust_structured_serialize_with_transfer(JSVM*, void* realm, JSValue, JSObject* const* transfer_list, size_t count, SerializedTransferRecord** out_record);
JSCompletion web_rust_structured_deserialize_with_transfer(JSVM*, void* target_realm, SerializedTransferRecord*, Vector<GC::Root<JS::Object>>* transferred_values);
JSCompletion web_rust_structured_deserialize_with_transfer_internal(JSVM*, void* target_realm, TransferDataDecoder*);
}
@@ -1113,20 +1113,16 @@ JSCompletion web_rust_structured_deserialize_with_transfer_internal(JSVM*, void*
// https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializewithtransfer
WebIDL::ExceptionOr<SerializedTransferRecord> structured_serialize_with_transfer(JS::Realm& realm, JS::Value value, ReadonlySpan<GC::Ref<JS::Object>> transfer_list)
{
- auto serialized_writer = StructuredSerializeWriter::create_ipc();
- serialized_writer.enable_shared_buffers();
- SerializedTransferRecord record;
-
Vector<JSObject*> transfer_list_abi;
transfer_list_abi.ensure_capacity(transfer_list.size());
for (auto const& transferable : transfer_list)
transfer_list_abi.unchecked_append(JS::HostABI::object_to_abi(transferable.ptr()));
- TRY(JS::HostABI::completion_from_abi<JS::Value>(web_rust_structured_serialize_with_transfer(JS::HostABI::vm_to_abi(realm.vm()), &realm, &serialized_writer, &record, JS::HostABI::value_to_abi(value), transfer_list_abi.data(), transfer_list_abi.size())));
-
- record.serialized = serialized_writer.take_ipc_record();
- record.shared_buffers = serialized_writer.take_shared_buffers();
- return record;
+ // NB: Rust creates the record, and hands it over with the result.
+ SerializedTransferRecord* record = nullptr;
+ TRY(JS::HostABI::completion_from_abi<JS::Value>(web_rust_structured_serialize_with_transfer(JS::HostABI::vm_to_abi(realm.vm()), &realm, JS::HostABI::value_to_abi(value), transfer_list_abi.data(), transfer_list_abi.size(), &record)));
+ auto owned_record = adopt_own(*record);
+ return move(*owned_record);
}
// https://html.spec.whatwg.org/multipage/structured-data.html#structureddeserializewithtransfer
diff --git a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
index c8ea9ee448e..5d0d361f5f4 100644
--- a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
+++ b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
@@ -40,6 +40,8 @@ using namespace Web::HTML;
extern "C" {
+StructuredSerializeWriter* web_structured_serialize_writer_create_for_transfer();
+void web_structured_serialize_writer_destroy(StructuredSerializeWriter*);
u8 web_structured_serialize_writer_type(StructuredSerializeWriter*);
void web_structured_serialize_writer_encode_u8(StructuredSerializeWriter*, u8);
void web_structured_serialize_writer_encode_bool(StructuredSerializeWriter*, bool);
@@ -119,6 +121,9 @@ void web_structured_serialize_transfer_data_holder_encode_u8(TransferDataEncoder
void web_structured_serialize_transfer_data_holder_encode_bytes(TransferDataEncoder*, ReadonlyBytes);
void web_structured_serialize_transfer_data_holder_encode_size(TransferDataEncoder*, size_t);
void web_structured_serialize_transfer_data_holder_destroy(TransferDataEncoder*);
+SerializedTransferRecord* web_structured_serialize_transfer_record_create();
+void web_structured_serialize_transfer_record_destroy(SerializedTransferRecord*);
+void web_structured_serialize_transfer_record_set_serialized(SerializedTransferRecord*, StructuredSerializeWriter*);
void web_structured_serialize_transfer_record_append_data_holder(SerializedTransferRecord*, TransferDataEncoder*);
size_t web_structured_serialize_transfer_record_data_holder_count(SerializedTransferRecord*);
TransferDataDecoder* web_structured_serialize_transfer_record_take_data_holder(SerializedTransferRecord*, size_t index);
@@ -168,6 +173,20 @@ static JS::ArrayBuffer& array_buffer_from_abi(JSObject* array_buffer)
return as<JS::ArrayBuffer>(*JS::HostABI::object_from_abi(array_buffer));
}
+// The writer of the [[Serialized]] of a transfer: an IPC record, since the transfer may cross a process boundary, with
+// the shared memory of its SharedArrayBuffers on the side.
+StructuredSerializeWriter* web_structured_serialize_writer_create_for_transfer()
+{
+ auto* writer = new StructuredSerializeWriter(StructuredSerializeWriter::create_ipc());
+ writer->enable_shared_buffers();
+ return writer;
+}
+
+void web_structured_serialize_writer_destroy(StructuredSerializeWriter* writer)
+{
+ delete writer;
+}
+
u8 web_structured_serialize_writer_type(StructuredSerializeWriter* writer)
{
return to_underlying(writer->type());
@@ -675,6 +694,23 @@ void web_structured_serialize_transfer_data_holder_destroy(TransferDataEncoder*
delete data_holder;
}
+SerializedTransferRecord* web_structured_serialize_transfer_record_create()
+{
+ return new SerializedTransferRecord;
+}
+
+void web_structured_serialize_transfer_record_destroy(SerializedTransferRecord* record)
+{
+ delete record;
+}
+
+// Sets the record's [[Serialized]] to what the writer wrote, with the shared memory of the SharedArrayBuffers it shared.
+void web_structured_serialize_transfer_record_set_serialized(SerializedTransferRecord* record, StructuredSerializeWriter* writer)
+{
+ record->serialized = writer->take_ipc_record();
+ record->shared_buffers = writer->take_shared_buffers();
+}
+
void web_structured_serialize_transfer_record_append_data_holder(SerializedTransferRecord* record, TransferDataEncoder* data_holder)
{
record->transfer_data_holders.append(move(*data_holder));
diff --git a/Libraries/LibWebCommon/HTML/SerializationRecords.h b/Libraries/LibWebCommon/HTML/SerializationRecords.h
index ef572cdd869..64fe9beec0f 100644
--- a/Libraries/LibWebCommon/HTML/SerializationRecords.h
+++ b/Libraries/LibWebCommon/HTML/SerializationRecords.h
@@ -142,6 +142,8 @@ private:
};
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