Skip to content

Truly independent web browser

LibJS+LibWeb: Write structured serialization records in Rust

Shannon Booth7e9c9cf1b413
diff --git a/Libraries/LibJS/Rust/src/runtime/big_int.rs b/Libraries/LibJS/Rust/src/runtime/big_int.rs
index 47201e914c9..35a58b792b8 100644
--- a/Libraries/LibJS/Rust/src/runtime/big_int.rs
+++ b/Libraries/LibJS/Rust/src/runtime/big_int.rs
@@ -6,6 +6,7 @@
use ak::Utf16String;
use libjs_runtime_macros::Trace;
+use num_bigint::Sign;
use num_traits::FromPrimitive;
use crate::gc::class::{GcCell, define_cell};
@@ -52,6 +53,18 @@ impl BigInt {
&self.big_integer
}
+ pub fn is_negative(&self) -> bool {
+ self.big_integer.sign() == Sign::Minus
+ }
+
+ /// The magnitude of the value, big-endian and without leading zeros, which has no bytes for zero.
+ pub fn magnitude_to_bytes_be(&self) -> Vec<u8> {
+ if self.big_integer.sign() == Sign::NoSign {
+ return Vec::new();
+ }
+ self.big_integer.magnitude().to_bytes_be()
+ }
+
/// The value, if it is an integer in the range of u64.
pub fn to_u64_if_exact(&self) -> Option<u64> {
u64::try_from(&self.big_integer).ok()
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs
index 5ba8759619e..060e341a21b 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs
@@ -8,9 +8,10 @@
//! https://html.spec.whatwg.org/multipage/structured-data.html#serializable-objects and
//! https://html.spec.whatwg.org/multipage/structured-data.html#transferable-objects
//!
-//! StructuredSerialize of LibWeb's C++ runs the algorithms, and runs the steps of such an interface through the entry
-//! points that the generated bindings of the interface define, which call the functions here. The steps read and
-//! write the records of the serialization through what C++ lends them; the structs that it lends are in
+//! The algorithms of crate::html::structured_serialize run the steps of such an interface through LibWeb's C++, which
+//! dispatches to the entry points that the generated bindings of the interface define, which call the functions here.
+//! The serialization steps write to the record of the serialization, which the algorithms pass through C++ to them.
+//! The other steps read and write what C++ lends them; the structs that it lends are in
//! Libraries/LibWeb/Bindings/RustSerialization.h. Unlike an object of an interface implemented in C++, which is
//! created before its deserialization steps fill it in, an object of an interface implemented in Rust is what its
//! deserialization steps and its transfer-receiving steps return.
@@ -27,22 +28,13 @@ use crate::bindings::interface::{ConstructedObject, Interface, Ref, cell_from_ab
use crate::bindings::transport::TransportHandle;
use crate::bindings::{CallContext, WebIdlResult};
use crate::html::structured_serialize::cpp::{OwnedSerializedTransferRecord, TransferDataDecoder};
+use crate::html::structured_serialize::writer::StructuredSerializeWriter;
use crate::html::structured_serialize::{
- structured_deserialize_with_transfer_internal, structured_serialize_with_transfer,
+ Serializer, encode_serializable_object_header, structured_deserialize_with_transfer_internal,
+ structured_serialize_with_transfer,
};
unsafe extern "C" {
- fn web_bindings_serialize_value(serialized: *mut c_void, value: u64) -> RawNativeFunctionResult;
- fn web_bindings_serialize_u8(serialized: *mut c_void, value: u8);
- fn web_bindings_serialize_i32(serialized: *mut c_void, value: i32);
- fn web_bindings_serialize_u32(serialized: *mut c_void, value: u32);
- fn web_bindings_serialize_u64(serialized: *mut c_void, value: u64);
- fn web_bindings_serialize_f64(serialized: *mut c_void, value: f64);
- fn web_bindings_serialize_bool(serialized: *mut c_void, value: bool);
- fn web_bindings_serialize_i64(serialized: *mut c_void, value: i64);
- fn web_bindings_serialize_optional_u64(serialized: *mut c_void, has_value: bool, value: u64);
- fn web_bindings_serialize_utf16_string(serialized: *mut c_void, string: usize);
- fn web_bindings_serialize_bytes(serialized: *mut c_void, bytes: ak::Span<'_, u8>);
fn web_bindings_deserialize_value(serialized: *mut c_void) -> RawNativeFunctionResult;
fn web_bindings_deserialize_is_for_storage(serialized: *mut c_void) -> bool;
fn web_bindings_deserialize_u8(serialized: *mut c_void, out_value: &mut u8) -> RawNativeFunctionResult;
@@ -66,7 +58,6 @@ unsafe extern "C" {
serialized: *mut c_void,
out_string: &mut usize,
) -> RawNativeFunctionResult;
- fn web_bindings_serialize_inline_object_header(serialized: *mut c_void, interface_name: u16);
fn web_bindings_deserialize_inline_object_header(
serialized: *mut c_void,
interface_name: u16,
@@ -98,75 +89,65 @@ unsafe extern "C" {
fn web_bindings_transfer_data_decoder(data_holder: *mut c_void) -> *mut c_void;
}
-/// The record of a structured serialization, which the serialization steps of an object write to: a
-/// Web::Bindings::RustSerializationWriter that C++ lends for the steps.
-pub(crate) struct SerializationWriter<'a> {
- raw: NonNull<c_void>,
- _lent: PhantomData<&'a mut c_void>,
+/// The record of a structured serialization, which the serialization steps of an object write to, and the serialization
+/// that the sub-serializations of the steps run in.
+pub(crate) struct SerializationWriter<'a, 'memory> {
+ serializer: &'a Serializer<'a, 'a, 'memory>,
}
-impl SerializationWriter<'_> {
- /// The writer as the C ABI of an interface's C++ class takes it, for what only C++ encodes.
- pub(crate) fn as_raw(&mut self) -> *mut c_void {
- self.raw.as_ptr()
+impl<'a, 'memory> SerializationWriter<'a, 'memory> {
+ pub(crate) fn new(serializer: &'a Serializer<'a, 'a, 'memory>) -> Self {
+ Self { serializer }
+ }
+
+ fn serialized(&self) -> &StructuredSerializeWriter<'memory> {
+ self.serializer.serialized()
}
/// Sets a field of the serialized form to the sub-serialization of the value,
/// https://html.spec.whatwg.org/multipage/structured-data.html#sub-serialization
pub(crate) fn write_value(&mut self, value: Value) -> WebIdlResult<()> {
- // SAFETY: The writer is lent for the steps, and the value is live while they run.
- unsafe { web_bindings_serialize_value(self.raw.as_ptr(), value.to_raw()) }.into_completion()?;
- Ok(())
+ self.serializer.serialize(value)
}
pub(crate) fn write_u8(&mut self, value: u8) {
- // SAFETY: The writer is lent for the steps.
- unsafe { web_bindings_serialize_u8(self.raw.as_ptr(), value) };
+ self.serialized().encode_u8(value);
}
pub(crate) fn write_i32(&mut self, value: i32) {
- // SAFETY: The writer is lent for the steps.
- unsafe { web_bindings_serialize_i32(self.raw.as_ptr(), value) };
+ self.serialized().encode_i32(value);
}
pub(crate) fn write_u32(&mut self, value: u32) {
- // SAFETY: The writer is lent for the steps.
- unsafe { web_bindings_serialize_u32(self.raw.as_ptr(), value) };
+ self.serialized().encode_u32(value);
}
pub(crate) fn write_u64(&mut self, value: u64) {
- // SAFETY: The writer is lent for the steps.
- unsafe { web_bindings_serialize_u64(self.raw.as_ptr(), value) };
+ self.serialized().encode_u64(value);
}
pub(crate) fn write_f64(&mut self, value: f64) {
- // SAFETY: The writer is lent for the steps.
- unsafe { web_bindings_serialize_f64(self.raw.as_ptr(), value) };
+ self.serialized().encode_f64(value);
}
pub(crate) fn write_bool(&mut self, value: bool) {
- // SAFETY: The writer is lent for the steps.
- unsafe { web_bindings_serialize_bool(self.raw.as_ptr(), value) };
+ self.serialized().encode_bool(value);
}
pub(crate) fn write_i64(&mut self, value: i64) {
- // SAFETY: The writer is lent for the steps.
- unsafe { web_bindings_serialize_i64(self.raw.as_ptr(), value) };
+ self.serialized().encode_i64(value);
}
pub(crate) fn write_optional_u64(&mut self, value: Option<u64>) {
- // SAFETY: The writer is lent for the steps.
- unsafe { web_bindings_serialize_optional_u64(self.raw.as_ptr(), value.is_some(), value.unwrap_or(0)) };
+ self.serialized().encode_optional_u64(value);
}
pub(crate) fn write_utf16_string(&mut self, string: &Utf16String) {
- // SAFETY: The writer is lent for the steps, and the call borrows the string.
- unsafe { web_bindings_serialize_utf16_string(self.raw.as_ptr(), string.raw_identity()) };
+ self.serialized().encode_utf16_string(string);
}
pub(crate) fn write_bytes(&mut self, bytes: &[u8]) {
- // SAFETY: The writer is lent for the steps, and the call borrows the bytes.
- unsafe { web_bindings_serialize_bytes(self.raw.as_ptr(), ak::Span::new(bytes)) };
+ self.serialized().encode_bytes(bytes);
}
/// Writes the record of a serializable object in place, as StructuredSerializeInternal writes it, but without
@@ -178,8 +159,7 @@ impl SerializationWriter<'_> {
object: &T,
for_storage: bool,
) -> WebIdlResult<()> {
- // SAFETY: The writer is lent for the steps.
- unsafe { web_bindings_serialize_inline_object_header(self.raw.as_ptr(), T::INTERFACE_NAME) };
+ encode_serializable_object_header(self.serialized(), T::INTERFACE_NAME);
object.serialization_steps(cx, self, for_storage)
}
}
@@ -446,7 +426,8 @@ fn wrap_new_object<T: Interface>(cx: &CallContext, object: impl ConstructedObjec
///
/// # Safety
///
-/// The pointers must be the VM, a live realm, the live cell of an object of `T`, and a writer that C++ lends.
+/// The pointers must be the VM, a live realm, the live cell of an object of `T`, and the SerializationWriter that
+/// crate::html::structured_serialize lends through C++.
pub(crate) unsafe fn serialization_steps<T: Serializable>(
vm: *mut c_void,
realm: *mut c_void,
@@ -457,11 +438,9 @@ pub(crate) unsafe fn serialization_steps<T: Serializable>(
// SAFETY: The caller passes the VM, a live realm and a live cell of an object of T.
let ((vm, realm), object) = unsafe { (realm_arguments(vm, realm), cell_from_abi::<T>(cell)) };
let mut cx = CallContext::new(vm, realm);
- let mut serialized = SerializationWriter {
- raw: NonNull::new(serialized).expect("C++ lends a writer"),
- _lent: PhantomData,
- };
- let result = object.serialization_steps(&mut cx, &mut serialized, for_storage);
+ // SAFETY: The caller passes the writer that the serialization lends for the steps.
+ let serialized = unsafe { &mut *serialized.cast::<SerializationWriter<'_, '_>>() };
+ let result = object.serialization_steps(&mut cx, serialized, for_storage);
completion(&cx, result.map(|()| Value::UNDEFINED))
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs
index f4ff3cee4da..78171feb17a 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs
@@ -14,11 +14,11 @@ use core::ptr::NonNull;
use ak::Utf16String;
use libjs_rust::api::{Gc, Object, RawNativeFunctionResult, Realm};
+use libwebcommon_rust::html::serialization_records::SerializationType;
use crate::bindings::{Exception, WebIdlResult};
-use crate::html::structured_serialize::cpp::{
- DecodedBytes, SerializationType, StructuredSerializeReader, StructuredSerializeWriter,
-};
+use crate::html::structured_serialize::cpp::{DecodedBytes, StructuredSerializeReader};
+use crate::html::structured_serialize::writer::StructuredSerializeWriter;
/// The fields of a CryptoKey, as Libraries/LibWeb/Crypto/CryptoKey.cpp hands them over and creates a key from. A key
/// that it hands over owns its strings for the receiver, and borrows its bytes from the key for the call.
@@ -98,7 +98,7 @@ fn data_clone_error(message: &[u8]) -> Exception {
Exception::Dom("DataCloneError", Utf16String::from_ascii(message))
}
-fn encode_identifier(serialized: StructuredSerializeWriter, identifier: &[u8]) {
+fn encode_identifier(serialized: &StructuredSerializeWriter, identifier: &[u8]) {
serialized.encode_utf16_string(&Utf16String::from_ascii(identifier));
}
@@ -117,18 +117,23 @@ fn decode_identifier(
}
/// Runs the serialization steps of the CryptoKey, given the record.
-pub(crate) fn serialization_steps(key: Gc<Object>, serialized: StructuredSerializeWriter) {
+pub(crate) fn serialization_steps(key: Gc<Object>, serialized: &StructuredSerializeWriter) {
unsafe extern "C" fn steps(state: *mut c_void, fields: *const RawFields<'_>) {
// SAFETY: The state is the writer that serialization_steps() lends, and the fields live for the call.
- let (serialized, fields) = unsafe { (*state.cast::<StructuredSerializeWriter>(), &*fields) };
+ let (serialized, fields) = unsafe { (&*state.cast::<StructuredSerializeWriter>(), &*fields) };
write_fields(serialized, fields);
}
- let mut state = serialized;
- // SAFETY: The object is a live CryptoKey, and the state lives for the call.
- unsafe { web_crypto_key_with_fields(key.as_ptr().cast(), (&raw mut state).cast(), steps) };
+ // SAFETY: The object is a live CryptoKey, and the writer lives for the call.
+ unsafe {
+ web_crypto_key_with_fields(
+ key.as_ptr().cast(),
+ core::ptr::from_ref(serialized).cast_mut().cast(),
+ steps,
+ );
+ }
}
-fn write_fields(serialized: StructuredSerializeWriter, value: &RawFields<'_>) {
+fn write_fields(serialized: &StructuredSerializeWriter, value: &RawFields<'_>) {
let for_storage = serialized.serialization_type() == SerializationType::Storage;
// SAFETY: LibWeb hands over the strings.
let (algorithm_name, hash, named_curve) = unsafe {
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 2b2e4e2a878..d7b28498bf3 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs
@@ -5,9 +5,9 @@
*/
//! What structured serialization asks of LibWeb's C++ code, which implements it in
-//! Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp: the records that the serializations write and read,
-//! which the serialization steps of the interfaces implemented in C++ write and read as well, the memories of the
-//! serializations, the platform objects, and the side tables that SharedArrayBuffers are shared through.
+//! Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp: the C++ records that the serializations hand their
+//! bytes over to, the records that the deserializations read, the platform objects, and the side tables that
+//! SharedArrayBuffers are shared through.
use core::ffi::c_void;
use core::mem::ManuallyDrop;
@@ -15,37 +15,29 @@ use core::ptr::NonNull;
use ak::Utf16String;
use libjs_rust::api::{ArrayBuffer, ArrayBufferShared, Gc, Object, RawNativeFunctionResult, Realm, Value};
+use libwebcommon_rust::html::serialization_records::SerializationType;
+use crate::bindings::structured_data::SerializationWriter;
use crate::bindings::{CallContext, Exception, WebIdlResult};
-use crate::html::structured_serialize::memory::{DeserializationMemory, SerializationMemory};
+use crate::html::structured_serialize::memory::DeserializationMemory;
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);
- fn web_structured_serialize_writer_encode_i32(writer: *mut c_void, value: i32);
- fn web_structured_serialize_writer_encode_u16(writer: *mut c_void, value: u16);
- fn web_structured_serialize_writer_encode_u32(writer: *mut c_void, value: u32);
- fn web_structured_serialize_writer_encode_u64(writer: *mut c_void, value: u64);
- fn web_structured_serialize_writer_encode_f64(writer: *mut c_void, value: f64);
- fn web_structured_serialize_writer_encode_utf16_string(writer: *mut c_void, string: usize);
- fn web_structured_serialize_writer_encode_optional_utf16_string(
- writer: *mut c_void,
- has_value: bool,
- string: usize,
+ fn web_structured_serialize_set_ipc_record(
+ record: *mut c_void,
+ data: ak::Span<'_, u8>,
+ shared_array_buffers: *const *mut c_void,
+ count: usize,
+ );
+ fn web_structured_serialize_set_storage_record(record: *mut c_void, data: ak::Span<'_, u8>);
+ fn web_structured_serialize_interface_storage_identifier(
+ interface_name: u16,
+ identifier: &mut ak::Span<'static, u8>,
);
- fn web_structured_serialize_writer_encode_bytes(writer: *mut c_void, bytes: ak::Span<'_, u8>);
- fn web_structured_serialize_writer_encode_interface_name(writer: *mut c_void, interface_name: u16);
- fn web_structured_serialize_writer_encode_big_int(writer: *mut c_void, big_int: u64);
- fn web_structured_serialize_writer_add_shared_array_buffer(writer: *mut c_void, array_buffer: *mut c_void) -> u32;
- fn web_structured_serialize_writer_can_share_array_buffer_memory(
- writer: *mut c_void,
+ fn web_structured_serialize_shared_buffers_append_shared_memory(
+ shared_buffers: *mut c_void,
array_buffer: *mut c_void,
+ index: &mut u32,
) -> bool;
- fn web_structured_serialize_writer_shared_buffer_count(writer: *mut c_void) -> u32;
- fn web_structured_serialize_writer_append_shared_buffer(writer: *mut c_void, array_buffer: *mut c_void);
fn web_structured_serialize_reader_type(reader: *mut c_void) -> u8;
fn web_structured_serialize_reader_is_at_end(reader: *mut c_void) -> bool;
@@ -151,9 +143,8 @@ unsafe extern "C" {
fn web_structured_serialize_serialization_steps(
realm: *mut c_void,
object: *mut c_void,
- writer: *mut c_void,
+ serialized: *mut c_void,
for_storage: bool,
- memory: *mut c_void,
) -> RawNativeFunctionResult;
fn web_structured_serialize_is_exposed(interface_name: u16, realm: *mut c_void) -> bool;
fn web_structured_serialize_serializable_steps(interface_name: u16) -> u8;
@@ -181,7 +172,7 @@ unsafe extern "C" {
decoder: *mut c_void,
) -> RawNativeFunctionResult;
fn web_structured_serialize_gather_image_bitmap_pixels(
- writer: *mut c_void,
+ shared_buffers: *mut c_void,
transfer_list: *const *mut c_void,
count: usize,
) -> *mut c_void;
@@ -194,7 +185,13 @@ unsafe extern "C" {
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_set_serialized(
+ record: *mut c_void,
+ data: ak::Span<'_, u8>,
+ shared_array_buffers: *const *mut c_void,
+ count: usize,
+ );
+ fn web_structured_serialize_transfer_record_shared_buffers(record: *mut c_void) -> *mut c_void;
fn web_structured_serialize_transfer_record_append_data_holder(record: *mut c_void, data_holder: *mut c_void);
fn web_structured_serialize_transfer_record_data_holder_count(record: *mut c_void) -> usize;
fn web_structured_serialize_transfer_record_take_data_holder(record: *mut c_void, index: usize) -> *mut c_void;
@@ -223,20 +220,11 @@ unsafe extern "C" {
fn web_structured_serialize_transfer_data_decoder_destroy(decoder: *mut c_void);
}
-/// HTML::SerializationType.
-#[derive(Clone, Copy, PartialEq, Eq)]
-pub(crate) enum SerializationType {
- Ipc,
- Storage,
-}
-
-impl SerializationType {
- fn from_abi(value: u8) -> Self {
- match value {
- 0 => Self::Ipc,
- 1 => Self::Storage,
- _ => unreachable!("LibWeb has no other serialization type"),
- }
+fn serialization_type_from_abi(value: u8) -> SerializationType {
+ match value {
+ 0 => SerializationType::Ipc,
+ 1 => SerializationType::Storage,
+ _ => unreachable!("LibWeb has no other serialization type"),
}
}
@@ -296,136 +284,98 @@ impl Drop for DecodedBytes {
}
}
-/// The record that a structured serialization writes: an HTML::StructuredSerializeWriter that C++ lends.
-#[derive(Clone, Copy)]
-pub(crate) struct StructuredSerializeWriter(NonNull<c_void>);
+/// The values of an array of objects, as the C ABI takes them.
+fn objects_into_abi<T>(objects: &[Gc<T>]) -> Vec<*mut c_void> {
+ objects.iter().map(|object| object_into_abi(*object)).collect()
+}
-impl StructuredSerializeWriter {
+/// An HTML::IPCSerializationRecord that C++ lends for a serialization to set.
+pub(crate) struct IPCSerializationRecord(NonNull<c_void>);
+
+impl IPCSerializationRecord {
/// # Safety
///
- /// `writer` must be a writer that C++ lends while this is used.
- pub(crate) unsafe fn from_raw(writer: *mut c_void) -> Self {
- Self(NonNull::new(writer).expect("C++ lends a writer"))
- }
-
- pub(crate) fn as_raw(self) -> *mut c_void {
- self.0.as_ptr()
- }
-
- pub(crate) fn serialization_type(self) -> SerializationType {
- // SAFETY: The writer is lent.
- SerializationType::from_abi(unsafe { web_structured_serialize_writer_type(self.as_raw()) })
- }
-
- pub(crate) fn encode_u8(self, value: u8) {
- // SAFETY: The writer is lent.
- unsafe { web_structured_serialize_writer_encode_u8(self.as_raw(), value) };
- }
-
- pub(crate) fn encode_bool(self, value: bool) {
- // SAFETY: The writer is lent.
- unsafe { web_structured_serialize_writer_encode_bool(self.as_raw(), value) };
- }
-
- pub(crate) fn encode_i32(self, value: i32) {
- // SAFETY: The writer is lent.
- unsafe { web_structured_serialize_writer_encode_i32(self.as_raw(), value) };
- }
-
- pub(crate) fn encode_u16(self, value: u16) {
- // SAFETY: The writer is lent.
- unsafe { web_structured_serialize_writer_encode_u16(self.as_raw(), value) };
- }
-
- pub(crate) fn encode_u32(self, value: u32) {
- // SAFETY: The writer is lent.
- unsafe { web_structured_serialize_writer_encode_u32(self.as_raw(), value) };
- }
-
- pub(crate) fn encode_u64(self, value: u64) {
- // SAFETY: The writer is lent.
- unsafe { web_structured_serialize_writer_encode_u64(self.as_raw(), value) };
- }
-
- pub(crate) fn encode_f64(self, value: f64) {
- // SAFETY: The writer is lent.
- unsafe { web_structured_serialize_writer_encode_f64(self.as_raw(), value) };
- }
-
- /// An Optional<double>, as HTML::StructuredSerializeWriter encodes one: whether it has a value, then the value.
- pub(crate) fn encode_optional_f64(self, value: Option<f64>) {
- self.encode_bool(value.is_some());
- if let Some(value) = value {
- self.encode_f64(value);
- }
- }
-
- pub(crate) fn encode_utf16_string(self, string: &Utf16String) {
- // SAFETY: The writer is lent, and the call borrows the string.
- unsafe { web_structured_serialize_writer_encode_utf16_string(self.as_raw(), string.raw_identity()) };
+ /// `record` must be a record that C++ lends while this is used.
+ pub(crate) unsafe fn from_raw(record: *mut c_void) -> Self {
+ Self(NonNull::new(record).expect("C++ lends a record"))
}
- pub(crate) fn encode_optional_utf16_string(self, string: Option<&Utf16String>) {
- // SAFETY: The writer is lent, and the call borrows the string.
+ /// Sets the record to the bytes, with the SharedArrayBuffers of its same-process side table.
+ pub(crate) fn set(self, data: &[u8], shared_array_buffers: &[Gc<ArrayBuffer>]) {
+ let shared_array_buffers = objects_into_abi(shared_array_buffers);
+ // SAFETY: The record is lent, the call borrows the bytes, and the buffers are live.
unsafe {
- web_structured_serialize_writer_encode_optional_utf16_string(
- self.as_raw(),
- string.is_some(),
- string.map_or(0, Utf16String::raw_identity),
+ web_structured_serialize_set_ipc_record(
+ self.0.as_ptr(),
+ ak::Span::new(data),
+ shared_array_buffers.as_ptr(),
+ shared_array_buffers.len(),
);
}
}
+}
- pub(crate) fn encode_bytes(self, bytes: &[u8]) {
- // SAFETY: The writer is lent, and the call borrows the bytes.
- unsafe { web_structured_serialize_writer_encode_bytes(self.as_raw(), ak::Span::new(bytes)) };
- }
+/// An HTML::StorageSerializationRecord that C++ lends for a serialization to set.
+pub(crate) struct StorageSerializationRecord(NonNull<c_void>);
- /// Bindings::InterfaceName, which a storage record holds as the identifier of the interface.
- pub(crate) fn encode_interface_name(self, interface_name: u16) {
- // SAFETY: The writer is lent.
- unsafe { web_structured_serialize_writer_encode_interface_name(self.as_raw(), interface_name) };
+impl StorageSerializationRecord {
+ /// # Safety
+ ///
+ /// `record` must be a record that C++ lends while this is used.
+ pub(crate) unsafe fn from_raw(record: *mut c_void) -> Self {
+ Self(NonNull::new(record).expect("C++ lends a record"))
}
- /// The value of a BigInt, as encode_signed_big_integer() writes it.
- pub(crate) fn encode_big_int(self, big_int: Value) {
- // SAFETY: The writer is lent, and the BigInt is live.
- unsafe { web_structured_serialize_writer_encode_big_int(self.as_raw(), big_int.to_raw()) };
+ pub(crate) fn set(self, data: &[u8]) {
+ // SAFETY: The record is lent, and the call borrows the bytes.
+ unsafe { web_structured_serialize_set_storage_record(self.0.as_ptr(), ak::Span::new(data)) };
}
+}
- /// Puts the SharedArrayBuffer in the record's same-process side table, and returns its index there.
- pub(crate) fn add_shared_array_buffer(self, array_buffer: Gc<ArrayBuffer>) -> u32 {
- // SAFETY: The writer is lent, and the buffer is live.
- unsafe { web_structured_serialize_writer_add_shared_array_buffer(self.as_raw(), object_into_abi(array_buffer)) }
- }
+/// The identifier of the serializable interface that a storage record holds, from LibWeb's registry of them.
+pub(crate) fn serializable_interface_storage_identifier(interface_name: u16) -> &'static [u8] {
+ let mut identifier = ak::Span::default();
+ // SAFETY: The call writes a span of static storage to the local.
+ unsafe { web_structured_serialize_interface_storage_identifier(interface_name, &mut identifier) };
+ identifier.as_slice()
+}
- /// Whether the SharedArrayBuffer is backed by cross-process shared memory, and the writer has a side list for it.
- pub(crate) fn can_share_array_buffer_memory(self, array_buffer: Gc<ArrayBuffer>) -> bool {
- // SAFETY: The writer is lent, and the buffer is live.
- unsafe {
- web_structured_serialize_writer_can_share_array_buffer_memory(self.as_raw(), object_into_abi(array_buffer))
- }
- }
+/// The side list of the cross-process shared memory that a record on the messaging path shares its SharedArrayBuffers
+/// through: a Vector<Core::AnonymousBuffer> that C++ lends.
+#[derive(Clone, Copy)]
+pub(crate) struct SharedBuffers(NonNull<c_void>);
- pub(crate) fn shared_buffer_count(self) -> u32 {
- // SAFETY: The writer is lent.
- unsafe { web_structured_serialize_writer_shared_buffer_count(self.as_raw()) }
+impl SharedBuffers {
+ /// # Safety
+ ///
+ /// `shared_buffers` must be a list that C++ lends while this is used.
+ pub(crate) unsafe fn from_raw(shared_buffers: *mut c_void) -> Self {
+ Self(NonNull::new(shared_buffers).expect("C++ lends a list"))
}
- /// Appends the cross-process shared memory of the SharedArrayBuffer to the writer's side list.
- pub(crate) fn append_shared_buffer(self, array_buffer: Gc<ArrayBuffer>) {
- // SAFETY: The writer is lent, and the buffer is live.
- unsafe { web_structured_serialize_writer_append_shared_buffer(self.as_raw(), object_into_abi(array_buffer)) };
+ /// Appends the cross-process shared memory of the SharedArrayBuffer to the list, and returns its index there, if
+ /// the buffer is backed by some.
+ pub(crate) fn append_shared_memory_of(self, array_buffer: Gc<ArrayBuffer>) -> Option<u32> {
+ let mut index = 0;
+ // SAFETY: The list is lent, and the buffer is live.
+ unsafe {
+ web_structured_serialize_shared_buffers_append_shared_memory(
+ self.0.as_ptr(),
+ object_into_abi(array_buffer),
+ &mut index,
+ )
+ }
+ .then_some(index)
}
- /// Gathers the pixels of the ImageBitmaps of the transfer list in one buffer of shared memory, which the writer's
- /// side list holds.
+ /// Gathers the pixels of the ImageBitmaps of the transfer list in one buffer of shared memory, which the list
+ /// holds.
pub(crate) fn gather_image_bitmap_pixels(self, transfer_list: &[Gc<Object>]) -> ImageBitmapSharedPixels {
- let transfer_list: Vec<*mut c_void> = transfer_list.iter().map(|object| object_into_abi(*object)).collect();
- // SAFETY: The writer is lent, and the objects are live.
+ let transfer_list = objects_into_abi(transfer_list);
+ // SAFETY: The list is lent, and the objects are live.
ImageBitmapSharedPixels(NonNull::new(unsafe {
web_structured_serialize_gather_image_bitmap_pixels(
- self.as_raw(),
+ self.0.as_ptr(),
transfer_list.as_ptr(),
transfer_list.len(),
)
@@ -433,28 +383,6 @@ 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)]
@@ -484,7 +412,7 @@ impl StructuredSerializeReader {
pub(crate) fn serialization_type(self) -> SerializationType {
// SAFETY: The reader is lent.
- SerializationType::from_abi(unsafe { web_structured_serialize_reader_type(self.as_raw()) })
+ serialization_type_from_abi(unsafe { web_structured_serialize_reader_type(self.as_raw()) })
}
pub(crate) fn is_at_end(self) -> bool {
@@ -712,22 +640,21 @@ pub(crate) fn serializable_interface_name(object: Gc<Object>) -> Option<u16> {
.then_some(interface_name)
}
-/// The serialization steps of the primary interface of the serializable platform object.
+/// The serialization steps of the primary interface of the serializable platform object, which C++ runs through the
+/// bindings of the interface, given the writer, which it passes on.
pub(crate) fn serialization_steps(
cx: &CallContext,
object: Gc<Object>,
- serialized: StructuredSerializeWriter,
+ serialized: &mut SerializationWriter,
for_storage: bool,
- memory: &SerializationMemory,
) -> WebIdlResult<()> {
- // SAFETY: The realm and the object are live, and the writer and the memory are lent.
+ // SAFETY: The realm and the object are live, and the writer is lent for the call.
completion(unsafe {
web_structured_serialize_serialization_steps(
cx.realm().as_ptr().cast(),
object_into_abi(object),
- serialized.as_raw(),
+ core::ptr::from_mut(serialized).cast(),
for_storage,
- memory.as_abi(),
)
})?;
Ok(())
@@ -908,11 +835,25 @@ impl SerializedTransferRecord {
self.0.as_ptr()
}
- /// 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()) };
+ /// Sets the record's [[Serialized]] to the bytes, with the SharedArrayBuffers of its same-process side table.
+ pub(crate) fn set_serialized(self, data: &[u8], shared_array_buffers: &[Gc<ArrayBuffer>]) {
+ let shared_array_buffers = objects_into_abi(shared_array_buffers);
+ // SAFETY: The record is lent, the call borrows the bytes, and the buffers are live.
+ unsafe {
+ web_structured_serialize_transfer_record_set_serialized(
+ self.0.as_ptr(),
+ ak::Span::new(data),
+ shared_array_buffers.as_ptr(),
+ shared_array_buffers.len(),
+ );
+ }
+ }
+
+ /// The cross-process shared memory of the record, which its [[Serialized]] and its data holders share
+ /// SharedArrayBuffers and the pixels of ImageBitmaps through.
+ pub(crate) fn shared_buffers(self) -> SharedBuffers {
+ // SAFETY: The record is lent, and so is its list.
+ unsafe { SharedBuffers::from_raw(web_structured_serialize_transfer_record_shared_buffers(self.0.as_ptr())) }
}
/// Appends the data holder to the record's [[TransferDataHolders]].
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/exports.rs
index ff16d9fece3..eab7f8aad0d 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/exports.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/exports.rs
@@ -11,14 +11,16 @@ use core::ffi::c_void;
use core::ptr::NonNull;
use libjs_rust::api::{Gc, MarkedVec, Object, RawNativeFunctionResult, ThrowCompletionOr, Value, Vm};
+use libwebcommon_rust::html::serialization_records::SerializationType;
use crate::bindings::interface::realm_arguments;
use crate::bindings::{CallContext, WebIdlResult};
use crate::html::structured_serialize::cpp::{
- SerializedTransferRecord, StructuredSerializeReader, StructuredSerializeWriter, TransferDataDecoder,
- TransferredValues,
+ IPCSerializationRecord, SerializedTransferRecord, SharedBuffers, StorageSerializationRecord,
+ StructuredSerializeReader, TransferDataDecoder, TransferredValues,
};
use crate::html::structured_serialize::memory::{DeserializationMemory, SerializationMemory};
+use crate::html::structured_serialize::writer::StructuredSerializeWriter;
use crate::html::structured_serialize::{
AllowSharedArrayBuffers, structured_deserialize_internal, structured_deserialize_with_transfer,
structured_deserialize_with_transfer_internal, structured_serialize_internal, structured_serialize_with_transfer,
@@ -30,54 +32,99 @@ fn completion(cx: &CallContext, result: WebIdlResult<Value>) -> RawNativeFunctio
RawNativeFunctionResult::from_completion(result)
}
-/// StructuredSerializeInternal, which runs in the current realm.
+/// StructuredSerializeInternal(value, forStorage) in the current realm, with a new memory.
+fn structured_serialize_in_current_realm<'vm>(
+ vm: &'vm Vm,
+ serialized: &StructuredSerializeWriter<'vm>,
+ value: Value,
+ for_storage: bool,
+ allow_shared_array_buffers: AllowSharedArrayBuffers,
+) -> Result<(), RawNativeFunctionResult> {
+ let memory = SerializationMemory::new(vm);
+ // NB: Code outside of any script serializes values too, with no current realm. An object's exception is created in
+ // its realm then; a Symbol throws too, but only script serializes one.
+ let realm = vm
+ .current_realm()
+ .or_else(|| value.is_object().then(|| value.as_object().shape().realm()));
+ structured_serialize_internal(
+ vm,
+ realm,
+ serialized,
+ value,
+ for_storage,
+ &memory,
+ allow_shared_array_buffers,
+ )
+ .map_err(|exception| {
+ let cx = CallContext::new(vm, realm.expect("what throws has a realm"));
+ completion(&cx, Err(exception))
+ })
+}
+
+/// StructuredSerialize, which runs in the current realm, and sets the record. The record shares the cross-process
+/// shared memory of SharedArrayBuffers through the list, if there is one.
///
/// # Safety
///
-/// The pointers must be the VM, a writer that C++ lends, and the memory of the serialization that a serialization step
-/// serializes a value of, or null for a new one. The value must be live.
+/// The pointers must be the VM, a list that C++ lends or null, and a record that C++ lends. The value must be live.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_rust_structured_serialize_internal(
+pub unsafe extern "C" fn web_rust_structured_serialize(
vm: *mut c_void,
- serialized: *mut c_void,
value: u64,
- for_storage: bool,
- memory: *mut c_void,
allow_shared_array_buffers: u8,
+ shared_buffers: *mut c_void,
+ record: *mut c_void,
) -> RawNativeFunctionResult {
// SAFETY: The caller passes the VM.
let vm = unsafe { &*vm.cast::<Vm>() };
- // SAFETY: The caller lends the writer, and passes a live value.
- let (serialized, value) = unsafe { (StructuredSerializeWriter::from_raw(serialized), Value::from_raw(value)) };
- let new_memory;
- let memory = if memory.is_null() {
- new_memory = SerializationMemory::new(vm);
- &new_memory
+ // SAFETY: The caller passes a live value, and lends the list and the record.
+ let (value, record) = unsafe { (Value::from_raw(value), IPCSerializationRecord::from_raw(record)) };
+ let serialized = if shared_buffers.is_null() {
+ StructuredSerializeWriter::new(vm, SerializationType::Ipc)
} else {
- // SAFETY: The caller passes the memory of the serialization that it runs in.
- unsafe { SerializationMemory::from_abi(memory) }
+ // SAFETY: The caller lends the list.
+ StructuredSerializeWriter::new_with_shared_buffers(vm, unsafe { SharedBuffers::from_raw(shared_buffers) })
};
- // NB: Code outside of any script serializes values too, with no current realm. An object's exception is created in
- // its realm then; a Symbol throws too, but only script serializes one.
- let realm = vm
- .current_realm()
- .or_else(|| value.is_object().then(|| value.as_object().shape().realm()));
- let result = structured_serialize_internal(
+ if let Err(result) = structured_serialize_in_current_realm(
vm,
- realm,
- serialized,
+ &serialized,
value,
- for_storage,
- memory,
+ false,
AllowSharedArrayBuffers::from_abi(allow_shared_array_buffers),
- );
- match result {
- Ok(()) => RawNativeFunctionResult::from_completion(Ok(Value::UNDEFINED)),
- Err(exception) => {
- let cx = CallContext::new(vm, realm.expect("what throws has a realm"));
- completion(&cx, Err(exception))
- }
+ ) {
+ return result;
+ }
+ serialized.finish_ipc_record(record);
+ RawNativeFunctionResult::from_completion(Ok(Value::UNDEFINED))
+}
+
+/// StructuredSerializeForStorage, which runs in the current realm, and sets the record.
+///
+/// # Safety
+///
+/// The pointers must be the VM and a record that C++ lends. The value must be live.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_structured_serialize_for_storage(
+ vm: *mut c_void,
+ value: u64,
+ record: *mut c_void,
+) -> RawNativeFunctionResult {
+ // SAFETY: The caller passes the VM.
+ let vm = unsafe { &*vm.cast::<Vm>() };
+ // SAFETY: The caller passes a live value, and lends the record.
+ let (value, record) = unsafe { (Value::from_raw(value), StorageSerializationRecord::from_raw(record)) };
+ let serialized = StructuredSerializeWriter::new(vm, SerializationType::Storage);
+ if let Err(result) = structured_serialize_in_current_realm(
+ vm,
+ &serialized,
+ value,
+ true,
+ AllowSharedArrayBuffers::CrossOriginIsolatedOnly,
+ ) {
+ return result;
}
+ serialized.finish_storage_record(record);
+ RawNativeFunctionResult::from_completion(Ok(Value::UNDEFINED))
}
/// StructuredDeserialize in the realm, which throws a "DataCloneError" DOMException for a storage record with bytes
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/memory.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/memory.rs
index 8ebdabd3197..552e6c5c4aa 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/memory.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/memory.rs
@@ -4,8 +4,9 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! The memories of structured serializations and deserializations, which C++ only passes on, as opaque pointers, to
-//! the serializations of the values that the serialization steps of a platform object hold.
+//! The memories of structured serializations and deserializations. C++ only passes the memory of a deserialization
+//! on, as an opaque pointer, to the deserializations of the values that the deserialization steps of a platform object
+//! hold.
use core::cell::RefCell;
use core::ffi::c_void;
@@ -26,20 +27,6 @@ impl<'vm> SerializationMemory<'vm> {
}
}
- /// The memory that C++ passes on.
- ///
- /// # Safety
- ///
- /// `memory` must be a memory that Rust lent to C++ for the call that passes it back.
- pub(crate) unsafe fn from_abi<'a>(memory: *mut c_void) -> &'a Self {
- // SAFETY: The caller passes a memory that outlives the call.
- unsafe { &*memory.cast::<Self>() }
- }
-
- pub(crate) fn as_abi(&self) -> *mut c_void {
- core::ptr::from_ref(self).cast_mut().cast()
- }
-
pub(crate) fn get(&self, value: Value) -> Option<u32> {
self.positions.borrow().get(&value.to_raw()).copied()
}
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 e011c7d0a38..98cb7d28589 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs
@@ -10,13 +10,13 @@
//! Safe passing of structured data, https://html.spec.whatwg.org/multipage/structured-data.html
//!
-//! The algorithms run here. The records they write and read stay LibWeb's C++ HTML::StructuredSerializeWriter and
-//! HTML::StructuredSerializeReader, which the serialization steps of the interfaces implemented in C++ write and read
-//! as well (cpp.rs).
+//! The algorithms run here, and write their records through writer.rs. The records that they read stay LibWeb's C++
+//! HTML::StructuredSerializeReader (cpp.rs).
pub(crate) mod cpp;
pub(crate) mod exports;
pub(crate) mod memory;
+pub(crate) mod writer;
use ak::Utf16String;
use libjs_rust::api::{
@@ -27,13 +27,14 @@ use libjs_rust::api::{
length_of_array_like, make_data_view_with_buffer_witness_record, make_typed_array_with_buffer_witness_record,
regexp_create,
};
+use libwebcommon_rust::html::serialization_records::SerializationType;
+use crate::bindings::structured_data::SerializationWriter;
use crate::bindings::{CallContext, Exception, WebIdlResult};
use crate::crypto::crypto_key;
use crate::html::structured_serialize::cpp::{
- OwnedSerializedTransferRecord, OwnedStructuredSerializeWriter, SerializableSteps, SerializationType,
- SerializedTransferRecord, StructuredSerializeReader, StructuredSerializeWriter, TransferDataDecoder,
- TransferDataHolder, create_transferred_platform_object, current_settings_object_agent_cluster,
+ OwnedSerializedTransferRecord, SerializableSteps, SerializedTransferRecord, StructuredSerializeReader,
+ TransferDataDecoder, TransferDataHolder, create_transferred_platform_object, current_settings_object_agent_cluster,
current_settings_object_cross_origin_isolated_capability, data_clone_error_from_serialization_error,
deserialize_rust_platform_object, is_exposed, is_platform_object, is_transferable,
is_transferable_interface_exposed, realm_agent_cluster, serializable_interface_name, serializable_payload_version,
@@ -41,6 +42,7 @@ use crate::html::structured_serialize::cpp::{
transferable_set_detached,
};
use crate::html::structured_serialize::memory::{DeserializationMemory, SerializationMemory};
+use crate::html::structured_serialize::writer::StructuredSerializeWriter;
use crate::webidl::dom_exception::{self, DOMExceptionFields};
use crate::webidl::quota_exceeded_error::{self, QuotaExceededErrorFields};
@@ -188,7 +190,7 @@ fn error_kind_of(error_type: ErrorType) -> ErrorKind {
}
/// An IPC record holds an error type as its index, and a storage record as its name.
-fn encode_error_type(serialized: StructuredSerializeWriter, error_type: ErrorType) {
+fn encode_error_type(serialized: &StructuredSerializeWriter, error_type: ErrorType) {
if serialized.serialization_type() == SerializationType::Ipc {
serialized.encode_u8(error_type as u8);
} else {
@@ -273,7 +275,7 @@ impl AllowSharedArrayBuffers {
// the target realm's against — so the buffer never leaves the cluster it was created in. A SameAgentAlways clone never
// leaves its agent, and names no cluster.
fn serialize_agent_cluster(
- data_holder: StructuredSerializeWriter,
+ data_holder: &StructuredSerializeWriter,
allow_shared_array_buffers: AllowSharedArrayBuffers,
) -> WebIdlResult<()> {
if allow_shared_array_buffers == AllowSharedArrayBuffers::SameAgentAlways {
@@ -294,7 +296,7 @@ fn serialize_agent_cluster(
// https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal
fn serialize_array_buffer(
vm: &Vm,
- data_holder: StructuredSerializeWriter,
+ data_holder: &StructuredSerializeWriter,
array_buffer: Gc<ArrayBuffer>,
for_storage: bool,
allow_shared_array_buffers: AllowSharedArrayBuffers,
@@ -344,14 +346,15 @@ fn serialize_array_buffer(
// 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 can_share = data_holder.can_share_array_buffer_memory(array_buffer);
- data_holder.encode_bool(can_share);
- if can_share {
- data_holder.encode_u32(data_holder.shared_buffer_count());
+ let shared_buffer_index = data_holder
+ .shared_buffers()
+ .and_then(|shared_buffers| shared_buffers.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()));
- data_holder.append_shared_buffer(array_buffer);
} else {
data_holder.encode_bytes(&array_buffer.copy_all_to_byte_buffer());
}
@@ -405,7 +408,7 @@ enum ViewType {
DataView(Gc<DataView>),
}
-fn serialize_byte_length(data_holder: StructuredSerializeWriter, byte_length: ByteLength) {
+fn serialize_byte_length(data_holder: &StructuredSerializeWriter, byte_length: ByteLength) {
assert!(!byte_length.is_detached());
data_holder.encode_bool(byte_length.is_auto());
@@ -415,13 +418,13 @@ fn serialize_byte_length(data_holder: StructuredSerializeWriter, byte_length: By
}
// https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal
-fn serialize_viewed_array_buffer(
+fn serialize_viewed_array_buffer<'memory>(
vm: &Vm,
realm: Option<Gc<Realm>>,
- data_holder: StructuredSerializeWriter,
+ data_holder: &StructuredSerializeWriter<'memory>,
view: ViewType,
for_storage: bool,
- memory: &SerializationMemory,
+ memory: &SerializationMemory<'memory>,
allow_shared_array_buffers: AllowSharedArrayBuffers,
) -> WebIdlResult<()> {
// 15. Otherwise, if value has a [[ViewedArrayBuffer]] internal slot:
@@ -507,19 +510,24 @@ fn serialize_viewed_array_buffer(
// Serializing and deserializing are each two passes:
// 1. Fill up the memory with all the values, but without translating references
// 2. Translate all the references into the appropriate form
-struct Serializer<'a, 'vm, 'memory> {
+pub(crate) struct Serializer<'a, 'vm, 'memory> {
vm: &'vm Vm,
// NB: The current realm, which a serialization outside of any script has none of.
realm: Option<Gc<Realm>>,
- serialized: StructuredSerializeWriter,
+ serialized: &'a StructuredSerializeWriter<'memory>,
memory: &'a SerializationMemory<'memory>, // JS value -> index
for_storage: bool,
allow_shared_array_buffers: AllowSharedArrayBuffers,
}
-impl Serializer<'_, '_, '_> {
+impl<'memory> Serializer<'_, '_, 'memory> {
+ /// The record that the serialization writes.
+ pub(crate) fn serialized(&self) -> &StructuredSerializeWriter<'memory> {
+ self.serialized
+ }
+
// https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal
- fn serialize(&self, value: Value) -> WebIdlResult<()> {
+ pub(crate) fn serialize(&self, value: Value) -> WebIdlResult<()> {
let vm = self.vm;
if vm.did_reach_stack_space_limit() {
return Err(call_stack_size_exceeded(vm));
@@ -561,7 +569,7 @@ impl Serializer<'_, '_, '_> {
serialized.encode_f64(value.as_f64());
} else if value.is_bigint() {
self.encode_tag(ValueTag::BigIntPrimitive);
- serialized.encode_big_int(value);
+ serialized.encode_big_int(value.as_bigint());
} else if value.is_string() {
self.encode_tag(ValueTag::StringPrimitive);
serialized.encode_utf16_string(&value.as_string().utf16_string());
@@ -596,7 +604,7 @@ impl Serializer<'_, '_, '_> {
// 10. Otherwise, if value has a [[BigIntData]] internal slot, then set serialized to { [[Type]]: "BigInt", [[BigIntData]]: value.[[BigIntData]] }.
else if let Some(big_int_object) = object.downcast::<BigIntObject>() {
self.encode_tag(ValueTag::BigIntObject);
- serialized.encode_big_int(Value::from_bigint(big_int_object.bigint()));
+ serialized.encode_big_int(big_int_object.bigint());
}
// 11. Otherwise, if value has a [[StringData]] internal slot, then set serialized to { [[Type]]: "String", [[StringData]]: value.[[StringData]] }.
else if let Some(string_object) = object.downcast::<StringObject>() {
@@ -737,11 +745,7 @@ impl Serializer<'_, '_, '_> {
// 2. Let typeString be the identifier of the primary interface of value.
// 3. Set serialized to { [[Type]]: typeString }.
- self.encode_tag(ValueTag::SerializableObject);
- serialized.encode_interface_name(interface_name);
- if self.for_storage {
- serialized.encode_u64(serializable_payload_version());
- }
+ encode_serializable_object_header(serialized, interface_name);
// FIXME: 4. If value's primary interface is decorated with [SameAgentCluster], then set sameAgentCluster to true.
@@ -860,9 +864,8 @@ impl Serializer<'_, '_, '_> {
serialization_steps(
&CallContext::new(vm, realm),
object,
- serialized,
+ &mut SerializationWriter::new(self),
self.for_storage,
- self.memory,
)?;
}
}
@@ -910,6 +913,14 @@ impl Serializer<'_, '_, '_> {
}
}
+pub(crate) fn encode_serializable_object_header(serialized: &StructuredSerializeWriter, interface_name: u16) {
+ serialized.encode_u8(ValueTag::SerializableObject as u8);
+ serialized.encode_interface_name(interface_name);
+ if serialized.serialization_type() == SerializationType::Storage {
+ serialized.encode_u64(serializable_payload_version());
+ }
+}
+
struct Deserializer<'a, 'vm, 'memory> {
cx: &'a CallContext<'vm>,
serialized: StructuredSerializeReader,
@@ -1526,14 +1537,18 @@ pub(crate) fn structured_serialize_with_transfer(
memory.set(transferable_value, memory.size());
}
+ // NB: The record of the result holds the shared memory that serialized and the data holders share through.
+ let result = OwnedSerializedTransferRecord::new();
+ let shared_buffers = result.record().shared_buffers();
+
// 3. Let serialized be ? StructuredSerializeInternal(value, false, memory).
// NB: The record may cross a process boundary, so it is an IPC record, with the memory of its SharedArrayBuffers
// shared on the side.
- let serialized = OwnedStructuredSerializeWriter::new_for_transfer();
+ let serialized = StructuredSerializeWriter::new_with_shared_buffers(vm, shared_buffers);
structured_serialize_internal(
vm,
Some(cx.realm()),
- serialized.writer(),
+ &serialized,
value,
false,
&memory,
@@ -1542,11 +1557,10 @@ 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 = shared_buffers.gather_image_bitmap_pixels(transfer_list);
// 4. Let transferDataHolders be a new empty List.
// NB: The record of the result holds the list.
- let result = OwnedSerializedTransferRecord::new();
// 5. For each transferable of transferList:
for transferable in transfer_list {
@@ -1623,7 +1637,7 @@ pub(crate) fn structured_serialize_with_transfer(
}
// 6. Let result be { [[Serialized]]: serialized, [[TransferDataHolders]]: transferDataHolders, [[InterfaceNames]]: an empty ordered set, [[AgentCluster]]: null }.
- result.record().set_serialized(serialized.writer());
+ serialized.finish_transfer_record(result.record());
// FIXME: 7. For each object → record of memory:
// 1. If object is a platform object, then append record.[[Type]] to result.[[InterfaceNames]].
@@ -1751,13 +1765,13 @@ pub(crate) fn structured_deserialize_with_transfer_internal(
}
// https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal
-pub(crate) fn structured_serialize_internal(
+pub(crate) fn structured_serialize_internal<'memory>(
vm: &Vm,
realm: Option<Gc<Realm>>,
- serialized: StructuredSerializeWriter,
+ serialized: &StructuredSerializeWriter<'memory>,
value: Value,
for_storage: bool,
- memory: &SerializationMemory,
+ memory: &SerializationMemory<'memory>,
allow_shared_array_buffers: AllowSharedArrayBuffers,
) -> WebIdlResult<()> {
let serializer = Serializer {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rs
new file mode 100644
index 00000000000..30b5bc3a996
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rs
@@ -0,0 +1,171 @@
+/*
+ * Copyright (c) 2022, Daniel Ehrenberg <[email protected]>
+ * Copyright (c) 2022, Andrew Kaster <[email protected]>
+ * Copyright (c) 2023-2024, Kenneth Myhra <[email protected]>
+ * Copyright (c) 2023, Idan Horowitz <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The record that a structured serialization writes: the bytes of the values in the format of the record
+//! (libwebcommon_rust::html::serialization_records), and the SharedArrayBuffers that the record shares beside them.
+//! C++ code and the UI process carry records without reading them, so a writer hands what it wrote over to LibWeb's
+//! C++ record when it finishes.
+
+use core::cell::RefCell;
+
+use ak::{Utf16String, Utf16StringUnits};
+use libjs_rust::api::{ArrayBuffer, BigInt, Gc, MarkedVec, Vm};
+use libwebcommon_rust::html::serialization_records::{RecordEncoder, SerializationType};
+
+use crate::html::structured_serialize::cpp::{
+ IPCSerializationRecord, SerializedTransferRecord, SharedBuffers, StorageSerializationRecord,
+ serializable_interface_storage_identifier,
+};
+
+/// The record of a structured serialization, which the serialization writes its values to.
+pub(crate) struct StructuredSerializeWriter<'vm> {
+ encoder: RefCell<RecordEncoder>,
+ /// The SharedArrayBuffers that an IPC record shares with a deserialization in the same process, by their index in
+ /// this same-process side table.
+ shared_array_buffers: MarkedVec<'vm, Gc<ArrayBuffer>>,
+ shared_buffers: Option<SharedBuffers>,
+}
+
+impl<'vm> StructuredSerializeWriter<'vm> {
+ pub(crate) fn new(vm: &'vm Vm, serialization_type: SerializationType) -> Self {
+ Self {
+ encoder: RefCell::new(RecordEncoder::new(serialization_type)),
+ shared_array_buffers: MarkedVec::new(vm),
+ shared_buffers: None,
+ }
+ }
+
+ /// The writer of an IPC record whose SharedArrayBuffers share their cross-process shared memory through the list.
+ pub(crate) fn new_with_shared_buffers(vm: &'vm Vm, shared_buffers: SharedBuffers) -> Self {
+ Self {
+ shared_buffers: Some(shared_buffers),
+ ..Self::new(vm, SerializationType::Ipc)
+ }
+ }
+
+ pub(crate) fn serialization_type(&self) -> SerializationType {
+ self.encoder.borrow().serialization_type()
+ }
+
+ pub(crate) fn encode_u8(&self, value: u8) {
+ self.encoder.borrow_mut().encode_u8(value);
+ }
+
+ pub(crate) fn encode_bool(&self, value: bool) {
+ self.encoder.borrow_mut().encode_bool(value);
+ }
+
+ pub(crate) fn encode_i32(&self, value: i32) {
+ self.encoder.borrow_mut().encode_i32(value);
+ }
+
+ pub(crate) fn encode_u16(&self, value: u16) {
+ self.encoder.borrow_mut().encode_u16(value);
+ }
+
+ pub(crate) fn encode_u32(&self, value: u32) {
+ self.encoder.borrow_mut().encode_u32(value);
+ }
+
+ pub(crate) fn encode_u64(&self, value: u64) {
+ self.encoder.borrow_mut().encode_u64(value);
+ }
+
+ pub(crate) fn encode_i64(&self, value: i64) {
+ self.encoder.borrow_mut().encode_i64(value);
+ }
+
+ pub(crate) fn encode_f64(&self, value: f64) {
+ self.encoder.borrow_mut().encode_f64(value);
+ }
+
+ pub(crate) fn encode_optional_f64(&self, value: Option<f64>) {
+ self.encode_bool(value.is_some());
+ if let Some(value) = value {
+ self.encode_f64(value);
+ }
+ }
+
+ pub(crate) fn encode_optional_u64(&self, value: Option<u64>) {
+ self.encode_bool(value.is_some());
+ if let Some(value) = value {
+ self.encode_u64(value);
+ }
+ }
+
+ pub(crate) fn encode_utf16_string(&self, string: &Utf16String) {
+ self.encoder.borrow_mut().encode_utf16_string(string.as_units());
+ }
+
+ pub(crate) fn encode_optional_utf16_string(&self, string: Option<&Utf16String>) {
+ self.encode_bool(string.is_some());
+ if let Some(string) = string {
+ self.encode_utf16_string(string);
+ }
+ }
+
+ pub(crate) fn encode_bytes(&self, bytes: &[u8]) {
+ self.encoder.borrow_mut().encode_bytes(bytes);
+ }
+
+ /// Bindings::InterfaceName, which a storage record holds as the identifier of the interface.
+ pub(crate) fn encode_interface_name(&self, interface_name: u16) {
+ match self.serialization_type() {
+ SerializationType::Ipc => self.encode_u16(interface_name),
+ SerializationType::Storage => {
+ let identifier = serializable_interface_storage_identifier(interface_name);
+ self.encoder
+ .borrow_mut()
+ .encode_utf16_string(Utf16StringUnits::Ascii(identifier));
+ }
+ }
+ }
+
+ pub(crate) fn encode_big_int(&self, big_int: Gc<BigInt>) {
+ self.encoder
+ .borrow_mut()
+ .encode_big_int(big_int.is_negative(), &big_int.magnitude_to_bytes_be());
+ }
+
+ /// Puts the SharedArrayBuffer in the record's same-process side table, and returns its index there.
+ pub(crate) fn add_shared_array_buffer(&self, array_buffer: Gc<ArrayBuffer>) -> u32 {
+ let index = u32::try_from(self.shared_array_buffers.len()).expect("a record shares fewer than 2^32 buffers");
+ self.shared_array_buffers.push(array_buffer);
+ index
+ }
+
+ /// The side list that the record shares the cross-process shared memory of its SharedArrayBuffers through, if it
+ /// has one.
+ pub(crate) fn shared_buffers(&self) -> Option<SharedBuffers> {
+ self.shared_buffers
+ }
+
+ /// Sets the IPC record that C++ lends to what the writer wrote.
+ pub(crate) fn finish_ipc_record(self, record: IPCSerializationRecord) {
+ assert_eq!(self.serialization_type(), SerializationType::Ipc);
+ record.set(self.encoder.borrow().bytes(), &self.shared_array_buffers.values());
+ }
+
+ /// Sets the storage record that C++ lends to what the writer wrote.
+ pub(crate) fn finish_storage_record(self, record: StorageSerializationRecord) {
+ assert_eq!(self.serialization_type(), SerializationType::Storage);
+ assert!(
+ self.shared_array_buffers.is_empty(),
+ "a storage record shares no SharedArrayBuffer"
+ );
+ record.set(self.encoder.borrow().bytes());
+ }
+
+ /// Sets the [[Serialized]] of the record of a transfer to what the writer wrote.
+ pub(crate) fn finish_transfer_record(self, record: SerializedTransferRecord) {
+ assert_eq!(self.serialization_type(), SerializationType::Ipc);
+ record.set_serialized(self.encoder.borrow().bytes(), &self.shared_array_buffers.values());
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/webidl/dom_exception.rs b/Libraries/LibWeb/Bindings/Rust/src/webidl/dom_exception.rs
index 8a747d2d33f..d36aeaf7670 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/webidl/dom_exception.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/webidl/dom_exception.rs
@@ -15,7 +15,8 @@ use ak::Utf16String;
use libjs_rust::api::{Gc, Object, Realm};
use crate::bindings::WebIdlResult;
-use crate::html::structured_serialize::cpp::{StructuredSerializeReader, StructuredSerializeWriter};
+use crate::html::structured_serialize::cpp::StructuredSerializeReader;
+use crate::html::structured_serialize::writer::StructuredSerializeWriter;
unsafe extern "C" {
fn web_dom_exception_name_and_message(exception: *mut c_void, name: &mut usize, message: &mut usize);
@@ -59,7 +60,7 @@ pub(crate) fn create(realm: Gc<Realm>, fields: &DOMExceptionFields) -> Gc<Object
}
// https://webidl.spec.whatwg.org/#idl-DOMException
-pub(crate) fn serialization_steps(value: &DOMExceptionFields, serialized: StructuredSerializeWriter) {
+pub(crate) fn serialization_steps(value: &DOMExceptionFields, serialized: &StructuredSerializeWriter) {
// 1. Set serialized.[[Name]] to value’s name.
serialized.encode_utf16_string(&value.name);
diff --git a/Libraries/LibWeb/Bindings/Rust/src/webidl/quota_exceeded_error.rs b/Libraries/LibWeb/Bindings/Rust/src/webidl/quota_exceeded_error.rs
index 359a6b63a7c..a1dc29c42d4 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/webidl/quota_exceeded_error.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/webidl/quota_exceeded_error.rs
@@ -15,7 +15,8 @@ use libjs_rust::api::{Gc, Object, Realm};
use super::dom_exception::{self, DOMExceptionFields};
use crate::bindings::WebIdlResult;
-use crate::html::structured_serialize::cpp::{StructuredSerializeReader, StructuredSerializeWriter};
+use crate::html::structured_serialize::cpp::StructuredSerializeReader;
+use crate::html::structured_serialize::writer::StructuredSerializeWriter;
unsafe extern "C" {
fn web_quota_exceeded_error_quota_and_requested(
@@ -85,7 +86,7 @@ pub(crate) fn create(realm: Gc<Realm>, fields: &QuotaExceededErrorFields) -> Gc<
}
// https://webidl.spec.whatwg.org/#ref-for-quotaexceedederror⑦
-pub(crate) fn serialization_steps(value: &QuotaExceededErrorFields, serialized: StructuredSerializeWriter) {
+pub(crate) fn serialization_steps(value: &QuotaExceededErrorFields, serialized: &StructuredSerializeWriter) {
// 1. Run the DOMException serialization steps given value and serialized.
dom_exception::serialization_steps(&value.dom_exception, serialized);
diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
index d1ad267bf41..fa1bf31bc2a 100644
--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
@@ -130,17 +130,6 @@ void web_bindings_with_temporary_execution_context(void* realm, bool callbacks_e
bool web_bindings_object_implements_interface(JSObject* object, u16 interface_name);
JSObject* web_bindings_create_dom_exception(void* realm, ReadonlyBytes name, FlatPtr message);
bool web_bindings_extract_an_origin(JSObject* object, void* ctx, void (*on_origin)(void*, URL::FFI::FfiOrigin const*));
-JSCompletion web_bindings_serialize_value(RustSerializationWriter*, JSValue);
-void web_bindings_serialize_u8(RustSerializationWriter*, u8);
-void web_bindings_serialize_i32(RustSerializationWriter*, i32);
-void web_bindings_serialize_u32(RustSerializationWriter*, u32);
-void web_bindings_serialize_u64(RustSerializationWriter*, u64);
-void web_bindings_serialize_f64(RustSerializationWriter*, double);
-void web_bindings_serialize_bool(RustSerializationWriter*, bool);
-void web_bindings_serialize_i64(RustSerializationWriter*, i64);
-void web_bindings_serialize_optional_u64(RustSerializationWriter*, bool has_value, u64);
-void web_bindings_serialize_utf16_string(RustSerializationWriter*, FlatPtr string);
-void web_bindings_serialize_bytes(RustSerializationWriter*, ReadonlyBytes);
JSCompletion web_bindings_deserialize_value(RustSerializationReader*);
bool web_bindings_deserialize_is_for_storage(RustSerializationReader*);
JSCompletion web_bindings_deserialize_u8(RustSerializationReader*, u8* out_value);
@@ -153,7 +142,6 @@ JSCompletion web_bindings_deserialize_i64(RustSerializationReader*, i64* out_val
JSCompletion web_bindings_deserialize_optional_u64(RustSerializationReader*, bool* out_has_value, u64* out_value);
JSCompletion web_bindings_deserialize_bytes(RustSerializationReader*, void* bytes, void (*append)(void*, u8 const*, size_t));
JSCompletion web_bindings_deserialize_utf16_string(RustSerializationReader*, FlatPtr* out_string);
-void web_bindings_serialize_inline_object_header(RustSerializationWriter*, u16 interface_name);
JSCompletion web_bindings_deserialize_inline_object_header(RustSerializationReader*, u16 interface_name);
JSCompletion web_bindings_transfer_data_encode_bool(RustTransferDataWriter*, bool);
JSCompletion web_bindings_transfer_data_encode_records(RustTransferDataWriter*, HTML::SerializedTransferRecord const* const*, size_t count);
@@ -241,66 +229,6 @@ bool web_bindings_extract_an_origin(JSObject* object, void* ctx, void (*on_origi
return true;
}
-// StructuredSerializeInternal of a value that the serialized form of an object of an interface implemented in Rust
-// holds, https://html.spec.whatwg.org/multipage/structured-data.html#sub-serialization
-JSCompletion web_bindings_serialize_value(RustSerializationWriter* writer, JSValue value)
-{
- auto result = HTML::structured_serialize_internal(writer->realm->vm(), writer->serialized, JS::HostABI::value_from_abi(value), writer->for_storage, writer->memory);
- if (result.is_exception())
- return completion_to_abi(writer->realm, result.exception());
- return completion_to_abi(writer->realm, JS::js_undefined());
-}
-
-void web_bindings_serialize_u8(RustSerializationWriter* writer, u8 value)
-{
- writer->serialized.encode(value);
-}
-
-void web_bindings_serialize_i32(RustSerializationWriter* writer, i32 value)
-{
- writer->serialized.encode(value);
-}
-
-void web_bindings_serialize_u32(RustSerializationWriter* writer, u32 value)
-{
- writer->serialized.encode(value);
-}
-
-void web_bindings_serialize_u64(RustSerializationWriter* writer, u64 value)
-{
- writer->serialized.encode(value);
-}
-
-void web_bindings_serialize_f64(RustSerializationWriter* writer, double value)
-{
- writer->serialized.encode(value);
-}
-
-void web_bindings_serialize_bool(RustSerializationWriter* writer, bool value)
-{
- writer->serialized.encode(value);
-}
-
-void web_bindings_serialize_i64(RustSerializationWriter* writer, i64 value)
-{
- writer->serialized.encode(value);
-}
-
-void web_bindings_serialize_optional_u64(RustSerializationWriter* writer, bool has_value, u64 value)
-{
- writer->serialized.encode(has_value ? Optional<u64> { value } : Optional<u64> {});
-}
-
-void web_bindings_serialize_utf16_string(RustSerializationWriter* writer, FlatPtr string)
-{
- writer->serialized.encode(Utf16String::from_raw(string));
-}
-
-void web_bindings_serialize_bytes(RustSerializationWriter* writer, ReadonlyBytes bytes)
-{
- writer->serialized.encode(bytes);
-}
-
// StructuredDeserialize of a value that the serialized form of an object holds, https://html.spec.whatwg.org/multipage/structured-data.html#sub-deserialization
JSCompletion web_bindings_deserialize_value(RustSerializationReader* reader)
{
@@ -373,18 +301,8 @@ JSCompletion web_bindings_deserialize_utf16_string(RustSerializationReader* read
return result;
}
-// The record of a serializable object of the interface as StructuredSerializeInternal starts it, for an object that
-// steps serialize in place, without a position in the memory of the serialization.
-void web_bindings_serialize_inline_object_header(RustSerializationWriter* writer, u16 interface_name)
-{
- writer->serialized.encode(to_underlying(HTML::ValueTag::SerializableObject));
- writer->serialized.encode(static_cast<InterfaceName>(interface_name));
- if (writer->serialized.type() == HTML::SerializationType::Storage)
- writer->serialized.encode(HTML::serializable_payload_version);
-}
-
-// Reads what web_bindings_serialize_inline_object_header() writes, and throws a "DataCloneError" DOMException if it is
-// not the start of the record of a serializable object of the interface.
+// Reads the start of the record of a serializable object of the interface, as StructuredSerializeInternal writes it for
+// an object that steps serialize in place, and throws a "DataCloneError" DOMException if it is not.
JSCompletion web_bindings_deserialize_inline_object_header(RustSerializationReader* reader, u16 interface_name)
{
auto result = [&]() -> WebIDL::ExceptionOr<JS::Value> {
diff --git a/Libraries/LibWeb/Bindings/RustSerialization.h b/Libraries/LibWeb/Bindings/RustSerialization.h
index d77f1a0748b..ae789c94db9 100644
--- a/Libraries/LibWeb/Bindings/RustSerialization.h
+++ b/Libraries/LibWeb/Bindings/RustSerialization.h
@@ -21,19 +21,10 @@ struct ImageBitmapSharedPixels;
namespace Web::Bindings {
-// What the steps of a serializable or transferable interface implemented in Rust read and write, which the Rust bindings
-// hold as opaque pointers (Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs). They read and write through
-// the C ABI of RustBindingsServices.cpp, and through that of the C++ class of their interface for what only C++
-// encodes.
-
-// The record of a structured serialization, and its memory, which the sub-serializations of the steps use. What they
-// throw is created in the realm of the serialized object.
-struct RustSerializationWriter {
- GC::Ref<JS::Realm> realm;
- HTML::StructuredSerializeWriter& serialized;
- bool for_storage { false };
- HTML::SerializationMemory* memory { nullptr };
-};
+// What the steps of a serializable or transferable interface implemented in Rust read and write, other than the record
+// of a serialization, which is Rust's own. The Rust bindings hold them as opaque pointers
+// (Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs). They read and write through the C ABI of
+// RustBindingsServices.cpp, and through that of the C++ class of their interface for what only C++ encodes.
// The record of a structured deserialization, and its memory, in the realm that the deserialization creates its values
// in.
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index 5598eb2ac99..c489eb1d6bb 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -801,7 +801,6 @@ class SharedWorker;
class SharedWorkerGlobalScope;
class Storage;
class StructuredSerializeReader;
-class StructuredSerializeWriter;
class SubmitEvent;
class TextTrack;
class TextTrackCue;
diff --git a/Libraries/LibWeb/HTML/StructuredSerialize.cpp b/Libraries/LibWeb/HTML/StructuredSerialize.cpp
index cf9a1643028..34492845491 100644
--- a/Libraries/LibWeb/HTML/StructuredSerialize.cpp
+++ b/Libraries/LibWeb/HTML/StructuredSerialize.cpp
@@ -265,31 +265,6 @@ static ErrorOr<Gfx::AlphaType> storage_identifier_to_alpha_type(StringView ident
return Error::from_string_literal("Unknown structured serialize alpha type");
}
-class StructuredSerializeDataEncoder {
-public:
- AK_ALLOC_WITH_KMALLOC;
-
- virtual ~StructuredSerializeDataEncoder() = default;
-
- virtual SerializationType type() const = 0;
-
- virtual void encode(bool) = 0;
- virtual void encode(u8) = 0;
- virtual void encode(u16) = 0;
- virtual void encode(i32) = 0;
- virtual void encode(u32) = 0;
- virtual void encode(i64) = 0;
- virtual void encode(u64) = 0;
- virtual void encode(double) = 0;
- virtual void encode(Utf16String const&) = 0;
- virtual void encode(ByteBuffer const&) = 0;
- virtual void encode(ReadonlyBytes) = 0;
-
- virtual void append(IPCSerializationRecord&&) { VERIFY_NOT_REACHED(); }
- virtual IPCSerializationRecord take_ipc_record() { VERIFY_NOT_REACHED(); }
- virtual StorageSerializationRecord take_storage_record() { VERIFY_NOT_REACHED(); }
-};
-
class StructuredSerializeDataDecoder {
public:
AK_ALLOC_WITH_KMALLOC;
@@ -313,36 +288,6 @@ public:
virtual ErrorOr<void> decode(ByteBuffer&) = 0;
};
-class IPCStructuredSerializeDataEncoder final : public StructuredSerializeDataEncoder {
-public:
- virtual SerializationType type() const override { return SerializationType::IPC; }
-
- virtual void encode(bool value) override { MUST(m_encoder.encode(value)); }
- virtual void encode(u8 value) override { MUST(m_encoder.encode(value)); }
- virtual void encode(u16 value) override { MUST(m_encoder.encode(value)); }
- virtual void encode(i32 value) override { MUST(m_encoder.encode(value)); }
- virtual void encode(u32 value) override { MUST(m_encoder.encode(value)); }
- virtual void encode(i64 value) override { MUST(m_encoder.encode(value)); }
- virtual void encode(u64 value) override { MUST(m_encoder.encode(value)); }
- virtual void encode(double value) override { MUST(m_encoder.encode(value)); }
- virtual void encode(Utf16String const& value) override { MUST(m_encoder.encode(value)); }
- virtual void encode(ByteBuffer const& value) override { MUST(m_encoder.encode(value)); }
- virtual void encode(ReadonlyBytes value) override { MUST(m_encoder.encode(value)); }
-
- virtual void append(IPCSerializationRecord&& record) override
- {
- m_encoder.append(move(record));
- }
-
- virtual IPCSerializationRecord take_ipc_record() override
- {
- return IPCSerializationRecord { m_encoder.take_buffer().take_data() };
- }
-
-private:
- TransferDataEncoder m_encoder;
-};
-
class IPCStructuredSerializeDataDecoder final : public StructuredSerializeDataDecoder {
public:
explicit IPCStructuredSerializeDataDecoder(IPCSerializationRecord const& record)
@@ -383,79 +328,6 @@ private:
TransferDataDecoder m_decoder;
};
-class StorageStructuredSerializeDataEncoder final : public StructuredSerializeDataEncoder {
-public:
- StorageStructuredSerializeDataEncoder()
- {
- append_storage_format_prologue(m_data);
- }
-
- virtual SerializationType type() const override { return SerializationType::Storage; }
-
- virtual void encode(bool value) override { encode(static_cast<u8>(value ? 1 : 0)); }
-
- virtual void encode(u8 value) override { m_data.append(value); }
-
- virtual void encode(u16 value) override { append_leb128(value); }
-
- virtual void encode(u32 value) override { append_leb128(value); }
-
- virtual void encode(i32 value) override { append_leb128(value); }
-
- virtual void encode(u64 value) override { append_leb128(value); }
-
- virtual void encode(i64 value) override { append_leb128(value); }
-
- virtual void encode(double value) override { append_little_endian(bit_cast<u64>(value)); }
-
- virtual void encode(Utf16String const& string) override
- {
- auto view = string.utf16_view();
- auto length = view.length_in_code_units();
- encode((static_cast<u64>(length) << 1) | (view.has_ascii_storage() ? 1u : 0u));
- if (view.has_ascii_storage()) {
- m_data.append(view.bytes());
- } else if constexpr (AK::HostIsLittleEndian) {
- m_data.append(reinterpret_cast<u8 const*>(view.utf16_span().data()), length * sizeof(char16_t));
- } else {
- for (char16_t code_unit : view.utf16_span())
- append_little_endian(static_cast<u16>(code_unit));
- }
- }
-
- virtual void encode(ByteBuffer const& buffer) override
- {
- encode(buffer.bytes());
- }
-
- virtual void encode(ReadonlyBytes bytes) override
- {
- encode(static_cast<u64>(bytes.size()));
- m_data.append(bytes.data(), bytes.size());
- }
-
- virtual StorageSerializationRecord take_storage_record() override
- {
- return StorageSerializationRecord { move(m_data) };
- }
-
-private:
- template<typename T>
- void append_leb128(T value)
- {
- LEB128<T>::append_to(m_data, value);
- }
-
- template<typename T>
- void append_little_endian(T value)
- {
- AK::LittleEndian<T> const little_endian { value };
- m_data.append(reinterpret_cast<u8 const*>(&little_endian), sizeof(little_endian));
- }
-
- ByteBuffer m_data;
-};
-
class StorageStructuredSerializeDataDecoder final : public StructuredSerializeDataDecoder {
public:
explicit StorageStructuredSerializeDataDecoder(StorageSerializationRecord const& record)
@@ -620,141 +492,6 @@ private:
Optional<AK::Error> m_error;
};
-StructuredSerializeWriter StructuredSerializeWriter::create_ipc()
-{
- return StructuredSerializeWriter { make<IPCStructuredSerializeDataEncoder>() };
-}
-
-StructuredSerializeWriter StructuredSerializeWriter::create_storage()
-{
- return StructuredSerializeWriter { make<StorageStructuredSerializeDataEncoder>() };
-}
-
-StructuredSerializeWriter::StructuredSerializeWriter(NonnullOwnPtr<StructuredSerializeDataEncoder> encoder)
- : m_encoder(move(encoder))
-{
-}
-
-StructuredSerializeWriter::~StructuredSerializeWriter() = default;
-
-SerializationType StructuredSerializeWriter::type() const
-{
- return m_encoder->type();
-}
-
-template<typename T>
-static void encode_value(StructuredSerializeDataEncoder& encoder, T const& value)
-requires requires { encoder.encode(value); }
-{
- encoder.encode(value);
-}
-
-static void encode_value(StructuredSerializeDataEncoder& encoder, int value)
-{
- VERIFY(AK::is_within_range<i32>(value));
- encoder.encode(static_cast<i32>(value));
-}
-
-static void encode_value(StructuredSerializeDataEncoder& encoder, long value)
-{
- encoder.encode(static_cast<i64>(value));
-}
-
-static void encode_value(StructuredSerializeDataEncoder& encoder, long long value)
-{
- encoder.encode(static_cast<i64>(value));
-}
-
-static void encode_value(StructuredSerializeDataEncoder& encoder, unsigned long value)
-{
- encoder.encode(static_cast<u64>(value));
-}
-
-static void encode_value(StructuredSerializeDataEncoder& encoder, unsigned long long value)
-{
- encoder.encode(static_cast<u64>(value));
-}
-
-static void encode_value(StructuredSerializeDataEncoder& encoder, Bindings::InterfaceName value)
-{
- if (encoder.type() == SerializationType::IPC)
- encoder.encode(to_underlying(value));
- else
- encoder.encode(Utf16String::from_utf8(MUST(serializable_interface_name_to_storage_identifier(value))));
-}
-
-[[maybe_unused]] static void encode_value(StructuredSerializeDataEncoder& encoder, Bindings::KeyType value)
-{
- auto identifier = MUST(key_type_to_storage_identifier(value));
- if (encoder.type() == SerializationType::IPC)
- encoder.encode(to_underlying(value));
- else
- encoder.encode(Utf16String::from_utf8(identifier));
-}
-
-[[maybe_unused]] static void encode_value(StructuredSerializeDataEncoder& encoder, Bindings::KeyUsage value)
-{
- auto identifier = MUST(key_usage_to_storage_identifier(value));
- if (encoder.type() == SerializationType::IPC)
- encoder.encode(to_underlying(value));
- else
- encoder.encode(Utf16String::from_utf8(identifier));
-}
-
-static void encode_value(StructuredSerializeDataEncoder& encoder, Crypto::KeyType value)
-{
- encoder.encode(to_underlying(value));
-}
-
-[[maybe_unused]] static void encode_value(StructuredSerializeDataEncoder& encoder, Bindings::PredefinedColorSpace value)
-{
- auto identifier = MUST(color_space_to_storage_identifier(value));
- if (encoder.type() == SerializationType::IPC)
- encoder.encode(to_underlying(value));
- else
- encoder.encode(Utf16String::from_utf8(identifier));
-}
-
-[[maybe_unused]] static void encode_value(StructuredSerializeDataEncoder& encoder, Gfx::BitmapFormat value)
-{
- auto identifier = MUST(bitmap_format_to_storage_identifier(value));
- if (encoder.type() == SerializationType::IPC)
- encoder.encode(to_underlying(value));
- else
- encoder.encode(Utf16String::from_utf8(identifier));
-}
-
-[[maybe_unused]] static void encode_value(StructuredSerializeDataEncoder& encoder, Gfx::AlphaType value)
-{
- auto identifier = MUST(alpha_type_to_storage_identifier(value));
- if (encoder.type() == SerializationType::IPC)
- encoder.encode(to_underlying(value));
- else
- encoder.encode(Utf16String::from_utf8(identifier));
-}
-
-template<typename T, size_t inline_capacity>
-static void encode_value(StructuredSerializeDataEncoder& encoder, Vector<T, inline_capacity> const& value)
-{
- encoder.encode(static_cast<u64>(value.size()));
- for (auto const& element : value)
- encode_value(encoder, element);
-}
-
-template<typename T>
-static void encode_value(StructuredSerializeDataEncoder& encoder, Optional<T> const& value)
-{
- encoder.encode(value.has_value());
- if (value.has_value())
- encode_value(encoder, value.value());
-}
-
-template<typename T>
-void StructuredSerializeWriter::encode(T const& value)
-{
- encode_value(*m_encoder, value);
-}
-
// The same-process SharedArrayBuffer aliases of an IPCSerializationRecord. Only this file creates side tables, so the
// reader can rely on a record's side table being one of these.
class SharedArrayBufferSideTable final : public SameProcessSerializationSideTable {
@@ -770,34 +507,15 @@ private:
Vector<GC::Root<JS::ArrayBuffer>> m_array_buffers;
};
-void StructuredSerializeWriter::append(IPCSerializationRecord&& record)
+IPCSerializationRecord create_ipc_serialization_record(ReadonlyBytes data, Vector<GC::Root<JS::ArrayBuffer>> shared_array_buffers)
{
- // TransferDataEncoder only appends record.data. Silently accepting a side table here would
- // produce a record whose SharedArrayBuffer references cannot be decoded.
- VERIFY(!record.same_process_side_table);
- m_encoder->append(move(record));
-}
-
-u32 StructuredSerializeWriter::add_shared_array_buffer(JS::ArrayBuffer& array_buffer)
-{
- VERIFY(m_shared_array_buffers.size() < NumericLimits<u32>::max());
- m_shared_array_buffers.append(GC::make_root(array_buffer));
- return static_cast<u32>(m_shared_array_buffers.size() - 1);
-}
-
-IPCSerializationRecord StructuredSerializeWriter::take_ipc_record()
-{
- auto record = m_encoder->take_ipc_record();
- if (!m_shared_array_buffers.is_empty())
- record.same_process_side_table = adopt_ref(*new SharedArrayBufferSideTable(move(m_shared_array_buffers)));
+ IPCSerializationRecord record;
+ record.data.append(data.data(), data.size());
+ if (!shared_array_buffers.is_empty())
+ record.same_process_side_table = adopt_ref(*new SharedArrayBufferSideTable(move(shared_array_buffers)));
return record;
}
-StorageSerializationRecord StructuredSerializeWriter::take_storage_record()
-{
- return m_encoder->take_storage_record();
-}
-
ReadonlySpan<GC::Root<JS::ArrayBuffer>> same_process_shared_array_buffers(IPCSerializationRecord const& record)
{
if (!record.same_process_side_table)
@@ -1037,37 +755,9 @@ ErrorOr<T> StructuredSerializeReader::decode()
return value;
}
-// These templates are declared in the public header but their implementation
-// uses the private encode_value/decode_value overload set above. Explicitly
-// instantiate the concrete wire types used by LibWeb so users of the header do
-// not end up with unresolved template symbols at link time.
-template WEB_API void StructuredSerializeWriter::encode(ByteBuffer const&);
-template WEB_API void StructuredSerializeWriter::encode(Optional<::Crypto::ASN1::ObjectIdentifier> const&);
-template WEB_API void StructuredSerializeWriter::encode(Optional<double> const&);
-template WEB_API void StructuredSerializeWriter::encode(Span<u8 const> const&);
-template WEB_API void StructuredSerializeWriter::encode(Bindings::InterfaceName const&);
-template WEB_API void StructuredSerializeWriter::encode(Bindings::KeyType const&);
-template WEB_API void StructuredSerializeWriter::encode(Vector<Bindings::KeyUsage> const&);
-template WEB_API void StructuredSerializeWriter::encode(Bindings::KeyUsage const&);
-template WEB_API void StructuredSerializeWriter::encode(Gfx::AlphaType const&);
-template WEB_API void StructuredSerializeWriter::encode(Gfx::BitmapFormat const&);
-template WEB_API void StructuredSerializeWriter::encode(Bindings::PredefinedColorSpace const&);
-template WEB_API void StructuredSerializeWriter::encode(Crypto::KeyType const&);
-template WEB_API void StructuredSerializeWriter::encode(bool const&);
-template WEB_API void StructuredSerializeWriter::encode(double const&);
-template WEB_API void StructuredSerializeWriter::encode(int const&);
-template WEB_API void StructuredSerializeWriter::encode(Utf16String const&);
-template WEB_API void StructuredSerializeWriter::encode(Optional<Utf16String> const&);
-template WEB_API void StructuredSerializeWriter::encode(Optional<bool> const&);
-template WEB_API void StructuredSerializeWriter::encode(Optional<u64> const&);
-template WEB_API void StructuredSerializeWriter::encode(long const&);
-template WEB_API void StructuredSerializeWriter::encode(long long const&);
-template WEB_API void StructuredSerializeWriter::encode(unsigned long const&);
-template WEB_API void StructuredSerializeWriter::encode(unsigned long long const&);
-template WEB_API void StructuredSerializeWriter::encode(u8 const&);
-template WEB_API void StructuredSerializeWriter::encode(u32 const&);
-template WEB_API void StructuredSerializeWriter::encode(u16 const&);
-
+// This template is declared in the public header but its implementation uses the private decode_value overload set
+// above. Explicitly instantiate the concrete wire types used by LibWeb so users of the header do not end up with
+// unresolved template symbols at link time.
template WEB_API ErrorOr<ByteBuffer> StructuredSerializeReader::decode();
template WEB_API ErrorOr<int> StructuredSerializeReader::decode();
template WEB_API ErrorOr<Optional<::Crypto::ASN1::ObjectIdentifier>> StructuredSerializeReader::decode();
@@ -1102,7 +792,8 @@ WebIDL::Exception data_clone_error_from_serialization_error(JS::Realm& realm, AK
// The algorithms of structured serialization, which Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize runs.
extern "C" {
-JSCompletion web_rust_structured_serialize_internal(JSVM*, StructuredSerializeWriter*, JSValue, bool for_storage, SerializationMemory*, u8 allow_shared_array_buffers);
+JSCompletion web_rust_structured_serialize(JSVM*, JSValue, u8 allow_shared_array_buffers, Vector<Core::AnonymousBuffer>* shared_buffers, IPCSerializationRecord*);
+JSCompletion web_rust_structured_serialize_for_storage(JSVM*, JSValue, StorageSerializationRecord*);
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, 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);
@@ -1149,9 +840,9 @@ WebIDL::ExceptionOr<IPCSerializationRecord> structured_serialize(JS::VM& vm, JS:
WebIDL::ExceptionOr<IPCSerializationRecord> structured_serialize(JS::VM& vm, JS::Value value, AllowSharedArrayBuffers allow_shared_array_buffers)
{
// 1. Return ? StructuredSerializeInternal(value, false).
- auto serialized = StructuredSerializeWriter::create_ipc();
- TRY(structured_serialize_internal(vm, serialized, value, false, nullptr, allow_shared_array_buffers));
- return serialized.take_ipc_record();
+ IPCSerializationRecord serialized;
+ TRY(JS::HostABI::completion_from_abi<JS::Value>(web_rust_structured_serialize(JS::HostABI::vm_to_abi(vm), JS::HostABI::value_to_abi(value), to_underlying(allow_shared_array_buffers), nullptr, &serialized)));
+ return serialized;
}
// https://html.spec.whatwg.org/multipage/structured-data.html#structuredserialize
@@ -1161,20 +852,20 @@ WebIDL::ExceptionOr<IPCSerializationRecord> structured_serialize(JS::VM& vm, JS:
WebIDL::ExceptionOr<IPCSerializationRecord> structured_serialize(JS::VM& vm, JS::Value value, Vector<Core::AnonymousBuffer>& shared_buffers)
{
// 1. Return ? StructuredSerializeInternal(value, false).
- auto serialized = StructuredSerializeWriter::create_ipc();
- serialized.enable_shared_buffers();
- TRY(structured_serialize_internal(vm, serialized, value, false));
- shared_buffers = serialized.take_shared_buffers();
- return serialized.take_ipc_record();
+ IPCSerializationRecord serialized;
+ Vector<Core::AnonymousBuffer> serialized_shared_buffers;
+ TRY(JS::HostABI::completion_from_abi<JS::Value>(web_rust_structured_serialize(JS::HostABI::vm_to_abi(vm), JS::HostABI::value_to_abi(value), to_underlying(AllowSharedArrayBuffers::CrossOriginIsolatedOnly), &serialized_shared_buffers, &serialized)));
+ shared_buffers = move(serialized_shared_buffers);
+ return serialized;
}
// https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeforstorage
WebIDL::ExceptionOr<StorageSerializationRecord> structured_serialize_for_storage(JS::VM& vm, JS::Value value)
{
// 1. Return ? StructuredSerializeInternal(value, true).
- auto serialized = StructuredSerializeWriter::create_storage();
- TRY(structured_serialize_internal(vm, serialized, value, true));
- return serialized.take_storage_record();
+ StorageSerializationRecord serialized;
+ TRY(JS::HostABI::completion_from_abi<JS::Value>(web_rust_structured_serialize_for_storage(JS::HostABI::vm_to_abi(vm), JS::HostABI::value_to_abi(value), &serialized)));
+ return serialized;
}
// https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeforstorage
@@ -1185,13 +876,6 @@ StorageSerializationRecord structured_serialize_undefined_or_null_for_storage(JS
return value.is_undefined() ? storage_serialization_record_for_undefined() : storage_serialization_record_for_null();
}
-// https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal
-WebIDL::ExceptionOr<void> structured_serialize_internal(JS::VM& vm, StructuredSerializeWriter& serialized, JS::Value value, bool for_storage, SerializationMemory* memory, AllowSharedArrayBuffers allow_shared_array_buffers)
-{
- TRY(JS::HostABI::completion_from_abi<JS::Value>(web_rust_structured_serialize_internal(JS::HostABI::vm_to_abi(vm), &serialized, JS::HostABI::value_to_abi(value), for_storage, memory, to_underlying(allow_shared_array_buffers))));
- return {};
-}
-
// https://html.spec.whatwg.org/multipage/structured-data.html#structureddeserialize
WebIDL::ExceptionOr<JS::Value> structured_deserialize(JS::VM& vm, IPCSerializationRecord const& serialized, JS::Realm& target_realm, Vector<Core::AnonymousBuffer> const* shared_buffers)
{
@@ -1248,14 +932,6 @@ WebIDL::ExceptionOr<::Crypto::UnsignedBigInteger> TransferDataDecoder::decode_un
return ::Crypto::UnsignedBigInteger::import_data(buffer);
}
-void encode_signed_big_integer(StructuredSerializeWriter& writer, ::Crypto::SignedBigInteger const& value)
-{
- auto buffer = MUST(ByteBuffer::create_zeroed(value.byte_length()));
- auto written = value.export_data(buffer.bytes());
- VERIFY(written.size() == buffer.size());
- writer.encode(buffer);
-}
-
WebIDL::ExceptionOr<::Crypto::SignedBigInteger> decode_signed_big_integer(StructuredSerializeReader& reader, JS::Realm& realm)
{
auto buffer = TRY(decode_or_throw_data_clone_error<ByteBuffer>(realm, reader));
diff --git a/Libraries/LibWeb/HTML/StructuredSerialize.h b/Libraries/LibWeb/HTML/StructuredSerialize.h
index f31f3055993..d3e69267e1c 100644
--- a/Libraries/LibWeb/HTML/StructuredSerialize.h
+++ b/Libraries/LibWeb/HTML/StructuredSerialize.h
@@ -38,7 +38,6 @@ class HostObject;
namespace Web::HTML {
class StructuredSerializeDataDecoder;
-class StructuredSerializeDataEncoder;
class WEB_API TransferDataDecoder {
AK_ALLOC_WITH_KMALLOC;
@@ -71,40 +70,6 @@ private:
Vector<Core::AnonymousBuffer> const* m_shared_buffers { nullptr };
};
-class WEB_API StructuredSerializeWriter {
-public:
- static StructuredSerializeWriter create_ipc();
- static StructuredSerializeWriter create_storage();
- ~StructuredSerializeWriter();
-
- SerializationType type() const;
-
- template<typename T>
- void encode(T const&);
-
- void append(IPCSerializationRecord&&);
-
- u32 add_shared_array_buffer(JS::ArrayBuffer&);
-
- IPCSerializationRecord take_ipc_record();
- StorageSerializationRecord take_storage_record();
-
- // AD-HOC: On the messaging path, a side list carries each SharedArrayBuffer's cross-process shared memory by file
- // descriptor — so an agent in another process can share it. enable_shared_buffers() opts a writer in.
- void enable_shared_buffers() { m_supports_shared_buffers = true; }
- bool supports_shared_buffers() const { return m_supports_shared_buffers; }
- Vector<Core::AnonymousBuffer>& shared_buffers() { return m_shared_buffers; }
- Vector<Core::AnonymousBuffer> take_shared_buffers() { return move(m_shared_buffers); }
-
-private:
- explicit StructuredSerializeWriter(NonnullOwnPtr<StructuredSerializeDataEncoder>);
-
- NonnullOwnPtr<StructuredSerializeDataEncoder> m_encoder;
- Vector<GC::Root<JS::ArrayBuffer>> m_shared_array_buffers;
- Vector<Core::AnonymousBuffer> m_shared_buffers;
- bool m_supports_shared_buffers { false };
-};
-
class WEB_API StructuredSerializeReader {
public:
explicit StructuredSerializeReader(IPCSerializationRecord const&);
@@ -153,13 +118,13 @@ enum class AllowSharedArrayBuffers : u8 {
// The SharedArrayBuffers that a record produced in this process aliases instead of copying.
WEB_API ReadonlySpan<GC::Root<JS::ArrayBuffer>> same_process_shared_array_buffers(IPCSerializationRecord const&);
+IPCSerializationRecord create_ipc_serialization_record(ReadonlyBytes data, Vector<GC::Root<JS::ArrayBuffer>> shared_array_buffers);
WEB_API WebIDL::ExceptionOr<IPCSerializationRecord> structured_serialize(JS::VM&, JS::Value);
WEB_API WebIDL::ExceptionOr<IPCSerializationRecord> structured_serialize(JS::VM&, JS::Value, AllowSharedArrayBuffers);
WEB_API WebIDL::ExceptionOr<IPCSerializationRecord> structured_serialize(JS::VM&, JS::Value, Vector<Core::AnonymousBuffer>& shared_buffers);
WEB_API WebIDL::ExceptionOr<StorageSerializationRecord> structured_serialize_for_storage(JS::VM&, JS::Value);
WEB_API StorageSerializationRecord structured_serialize_undefined_or_null_for_storage(JS::Value);
-WEB_API WebIDL::ExceptionOr<void> structured_serialize_internal(JS::VM&, StructuredSerializeWriter&, JS::Value, bool for_storage, SerializationMemory* = nullptr, AllowSharedArrayBuffers = AllowSharedArrayBuffers::CrossOriginIsolatedOnly);
WEB_API WebIDL::ExceptionOr<JS::Value> structured_deserialize(JS::VM&, IPCSerializationRecord const&, JS::Realm&, Vector<Core::AnonymousBuffer> const* shared_buffers = nullptr);
WEB_API WebIDL::ExceptionOr<JS::Value> structured_deserialize(JS::VM&, StorageSerializationRecord const&, JS::Realm&);
@@ -167,7 +132,6 @@ WEB_API WebIDL::ExceptionOr<JS::Value> structured_deserialize_internal(JS::VM&,
WEB_API WebIDL::Exception data_clone_error_from_serialization_error(JS::Realm&, AK::Error const&);
-void encode_signed_big_integer(StructuredSerializeWriter&, ::Crypto::SignedBigInteger const&);
WebIDL::ExceptionOr<::Crypto::SignedBigInteger> decode_signed_big_integer(StructuredSerializeReader&, JS::Realm&);
template<typename T>
@@ -230,7 +194,8 @@ struct SerializablePlatformObject {
InterfaceName interface_name;
GC::Ptr<JS::Realm> realm;
- WebIDL::ExceptionOr<void> serialization_steps(HTML::StructuredSerializeWriter&, bool for_storage, HTML::SerializationMemory*) const;
+ // NB: The record that the steps write is the Rust SerializationWriter that the serialization passes on.
+ WebIDL::ExceptionOr<void> serialization_steps(void* serialized, bool for_storage) const;
};
// A platform object that is a transferable object, of an interface implemented in C++ or in Rust.
diff --git a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
index 90142ce4f40..d5a4899ac75 100644
--- a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
+++ b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
@@ -32,9 +32,8 @@
// What the Rust implementation of structured serialization asks of LibWeb's C++ code, declared on the Rust side in
// Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs. C++ keeps the records that the serializations
-// write and read, which the serialization steps of the interfaces implemented in C++ write and read as well, the
-// memories of the serializations, the platform objects, and the side tables that SharedArrayBuffers are shared
-// through.
+// hand their bytes over to, the records that the deserializations read, the platform objects, and the side tables that
+// SharedArrayBuffers are shared through.
using namespace Web;
using namespace Web::HTML;
@@ -49,25 +48,10 @@ enum class SerializableSteps : u8 {
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);
-void web_structured_serialize_writer_encode_i32(StructuredSerializeWriter*, i32);
-void web_structured_serialize_writer_encode_u16(StructuredSerializeWriter*, u16);
-void web_structured_serialize_writer_encode_u32(StructuredSerializeWriter*, u32);
-void web_structured_serialize_writer_encode_u64(StructuredSerializeWriter*, u64);
-void web_structured_serialize_writer_encode_f64(StructuredSerializeWriter*, double);
-void web_structured_serialize_writer_encode_utf16_string(StructuredSerializeWriter*, FlatPtr);
-void web_structured_serialize_writer_encode_optional_utf16_string(StructuredSerializeWriter*, bool has_value, FlatPtr);
-void web_structured_serialize_writer_encode_bytes(StructuredSerializeWriter*, ReadonlyBytes);
-void web_structured_serialize_writer_encode_interface_name(StructuredSerializeWriter*, u16);
-void web_structured_serialize_writer_encode_big_int(StructuredSerializeWriter*, JSValue);
-u32 web_structured_serialize_writer_add_shared_array_buffer(StructuredSerializeWriter*, JSObject* array_buffer);
-bool web_structured_serialize_writer_can_share_array_buffer_memory(StructuredSerializeWriter*, JSObject* array_buffer);
-u32 web_structured_serialize_writer_shared_buffer_count(StructuredSerializeWriter*);
-void web_structured_serialize_writer_append_shared_buffer(StructuredSerializeWriter*, JSObject* array_buffer);
+void web_structured_serialize_set_ipc_record(IPCSerializationRecord*, ReadonlyBytes data, JSObject* const* shared_array_buffers, size_t count);
+void web_structured_serialize_set_storage_record(StorageSerializationRecord*, ReadonlyBytes data);
+void web_structured_serialize_interface_storage_identifier(u16 interface_name, ReadonlyBytes* identifier);
+bool web_structured_serialize_shared_buffers_append_shared_memory(Vector<Core::AnonymousBuffer>*, JSObject* array_buffer, u32* index);
u8 web_structured_serialize_reader_type(StructuredSerializeReader*);
bool web_structured_serialize_reader_is_at_end(StructuredSerializeReader*);
@@ -100,7 +84,7 @@ bool web_structured_serialize_realm_agent_cluster(void* realm, u64* agent_cluste
bool web_structured_serialize_is_platform_object(JSObject*);
bool web_structured_serialize_serializable_interface_name(JSObject*, u16* interface_name);
-JSCompletion web_structured_serialize_serialization_steps(void* realm, JSObject*, StructuredSerializeWriter*, bool for_storage, SerializationMemory*);
+JSCompletion web_structured_serialize_serialization_steps(void* realm, JSObject*, void* serialized, bool for_storage);
bool web_structured_serialize_is_exposed(u16 interface_name, void* realm);
u8 web_structured_serialize_serializable_steps(u16 interface_name);
JSCompletion web_structured_serialize_deserialize_rust_platform_object(u16 interface_name, void* realm, StructuredSerializeReader*, DeserializationMemory*);
@@ -112,7 +96,7 @@ u8 web_structured_serialize_transferable_primary_interface(JSObject*);
JSCompletion web_structured_serialize_transfer_steps(void* realm, JSObject*, TransferDataEncoder*, ImageBitmapSharedPixels*);
bool web_structured_serialize_is_transferable_interface_exposed(u8 type, void* realm);
JSCompletion web_structured_serialize_create_transferred_platform_object(u8 type, void* realm, TransferDataDecoder*);
-ImageBitmapSharedPixels* web_structured_serialize_gather_image_bitmap_pixels(StructuredSerializeWriter*, JSObject* const* transfer_list, size_t count);
+ImageBitmapSharedPixels* web_structured_serialize_gather_image_bitmap_pixels(Vector<Core::AnonymousBuffer>*, JSObject* const* transfer_list, size_t count);
void web_structured_serialize_image_bitmap_pixels_destroy(ImageBitmapSharedPixels*);
TransferDataEncoder* web_structured_serialize_transfer_data_holder_create();
@@ -122,7 +106,8 @@ void web_structured_serialize_transfer_data_holder_encode_size(TransferDataEncod
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_set_serialized(SerializedTransferRecord*, ReadonlyBytes data, JSObject* const* shared_array_buffers, size_t count);
+Vector<Core::AnonymousBuffer>* web_structured_serialize_transfer_record_shared_buffers(SerializedTransferRecord*);
void web_structured_serialize_transfer_record_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);
@@ -172,103 +157,46 @@ 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()
+static Vector<GC::Root<JS::ArrayBuffer>> shared_array_buffers_from_abi(JSObject* const* shared_array_buffers, size_t count)
{
- auto* writer = new StructuredSerializeWriter(StructuredSerializeWriter::create_ipc());
- writer->enable_shared_buffers();
- return writer;
+ Vector<GC::Root<JS::ArrayBuffer>> roots;
+ roots.ensure_capacity(count);
+ for (size_t i = 0; i < count; ++i)
+ roots.unchecked_append(GC::make_root(array_buffer_from_abi(shared_array_buffers[i])));
+ return roots;
}
-void web_structured_serialize_writer_destroy(StructuredSerializeWriter* writer)
+void web_structured_serialize_set_ipc_record(IPCSerializationRecord* record, ReadonlyBytes data, JSObject* const* shared_array_buffers, size_t count)
{
- delete writer;
+ *record = create_ipc_serialization_record(data, shared_array_buffers_from_abi(shared_array_buffers, count));
}
-u8 web_structured_serialize_writer_type(StructuredSerializeWriter* writer)
+void web_structured_serialize_set_storage_record(StorageSerializationRecord* record, ReadonlyBytes data)
{
- return to_underlying(writer->type());
+ record->data = MUST(ByteBuffer::copy(data));
}
-void web_structured_serialize_writer_encode_u8(StructuredSerializeWriter* writer, u8 value)
+void web_structured_serialize_interface_storage_identifier(u16 interface_name, ReadonlyBytes* identifier)
{
- writer->encode(value);
-}
-
-void web_structured_serialize_writer_encode_bool(StructuredSerializeWriter* writer, bool value)
-{
- writer->encode(value);
-}
-
-void web_structured_serialize_writer_encode_i32(StructuredSerializeWriter* writer, i32 value)
-{
- writer->encode(static_cast<int>(value));
-}
-
-void web_structured_serialize_writer_encode_u16(StructuredSerializeWriter* writer, u16 value)
-{
- writer->encode(value);
-}
-
-void web_structured_serialize_writer_encode_u32(StructuredSerializeWriter* writer, u32 value)
-{
- writer->encode(value);
-}
-
-void web_structured_serialize_writer_encode_u64(StructuredSerializeWriter* writer, u64 value)
-{
- writer->encode(static_cast<unsigned long long>(value));
-}
-
-void web_structured_serialize_writer_encode_f64(StructuredSerializeWriter* writer, double value)
-{
- writer->encode(value);
-}
-
-void web_structured_serialize_writer_encode_utf16_string(StructuredSerializeWriter* writer, FlatPtr string)
-{
- writer->encode(Utf16String::from_raw(string));
-}
-
-void web_structured_serialize_writer_encode_optional_utf16_string(StructuredSerializeWriter* writer, bool has_value, FlatPtr string)
-{
- writer->encode(has_value ? Optional<Utf16String> { Utf16String::from_raw(string) } : Optional<Utf16String> {});
-}
-
-void web_structured_serialize_writer_encode_bytes(StructuredSerializeWriter* writer, ReadonlyBytes bytes)
-{
- writer->encode(bytes);
-}
-
-void web_structured_serialize_writer_encode_interface_name(StructuredSerializeWriter* writer, u16 interface_name)
-{
- writer->encode(static_cast<Bindings::InterfaceName>(interface_name));
-}
-
-void web_structured_serialize_writer_encode_big_int(StructuredSerializeWriter* writer, JSValue big_int)
-{
- encode_signed_big_integer(*writer, JS::HostABI::value_from_abi(big_int).as_bigint().big_integer());
-}
-
-u32 web_structured_serialize_writer_add_shared_array_buffer(StructuredSerializeWriter* writer, JSObject* array_buffer)
-{
- return writer->add_shared_array_buffer(array_buffer_from_abi(array_buffer));
-}
-
-bool web_structured_serialize_writer_can_share_array_buffer_memory(StructuredSerializeWriter* writer, JSObject* array_buffer)
-{
- return array_buffer_from_abi(array_buffer).shared_buffer().has_value() && writer->supports_shared_buffers();
-}
-
-u32 web_structured_serialize_writer_shared_buffer_count(StructuredSerializeWriter* writer)
-{
- return static_cast<u32>(writer->shared_buffers().size());
+ for (auto const& entry : serializable_storage_registry()) {
+ if (entry.interface_name == static_cast<Bindings::InterfaceName>(interface_name)) {
+ *identifier = entry.identifier.bytes();
+ return;
+ }
+ }
+ VERIFY_NOT_REACHED();
}
-void web_structured_serialize_writer_append_shared_buffer(StructuredSerializeWriter* writer, JSObject* array_buffer)
+// AD-HOC: A SharedArrayBuffer backed by cross-process shared memory shares it through the side list of a record on the
+// messaging path, which hands it over by file descriptor.
+bool web_structured_serialize_shared_buffers_append_shared_memory(Vector<Core::AnonymousBuffer>* shared_buffers, JSObject* array_buffer, u32* index)
{
- writer->shared_buffers().append(array_buffer_from_abi(array_buffer).shared_buffer().release_value());
+ auto shared_buffer = array_buffer_from_abi(array_buffer).shared_buffer();
+ if (!shared_buffer.has_value())
+ return false;
+ *index = static_cast<u32>(shared_buffers->size());
+ shared_buffers->append(shared_buffer.release_value());
+ return true;
}
u8 web_structured_serialize_reader_type(StructuredSerializeReader* reader)
@@ -499,11 +427,11 @@ bool web_structured_serialize_serializable_interface_name(JSObject* object, u16*
return true;
}
-JSCompletion web_structured_serialize_serialization_steps(void* realm, JSObject* object, StructuredSerializeWriter* writer, bool for_storage, SerializationMemory* memory)
+JSCompletion web_structured_serialize_serialization_steps(void* realm, JSObject* object, void* serialized, bool for_storage)
{
auto serializable = Bindings::serializable_from_object(*JS::HostABI::object_from_abi(object));
VERIFY(serializable.has_value());
- return void_completion_to_abi(realm_from_abi(realm), serializable->serialization_steps(*writer, for_storage, memory));
+ return void_completion_to_abi(realm_from_abi(realm), serializable->serialization_steps(serialized, for_storage));
}
bool web_structured_serialize_is_exposed(u16 interface_name, void* realm)
@@ -599,7 +527,7 @@ JSCompletion web_structured_serialize_create_transferred_platform_object(u8 type
// AD-HOC: Gather the pixels of the transferred ImageBitmaps in one buffer of shared memory. Without it, as when there
// is not enough memory for it, the pixels travel inline.
-ImageBitmapSharedPixels* web_structured_serialize_gather_image_bitmap_pixels(StructuredSerializeWriter* writer, JSObject* const* transfer_list, size_t count)
+ImageBitmapSharedPixels* web_structured_serialize_gather_image_bitmap_pixels(Vector<Core::AnonymousBuffer>* shared_buffers, JSObject* const* transfer_list, size_t count)
{
Checked<size_t> image_bitmap_pixels_size = 0;
for (size_t i = 0; i < count; ++i) {
@@ -611,8 +539,8 @@ ImageBitmapSharedPixels* web_structured_serialize_gather_image_bitmap_pixels(Str
auto buffer = Core::AnonymousBuffer::create_with_size(image_bitmap_pixels_size.value());
if (buffer.is_error())
return nullptr;
- auto* image_bitmap_pixels = new ImageBitmapSharedPixels { .buffer = buffer.release_value(), .buffer_index = static_cast<u32>(writer->shared_buffers().size()) };
- writer->shared_buffers().append(image_bitmap_pixels->buffer);
+ auto* image_bitmap_pixels = new ImageBitmapSharedPixels { .buffer = buffer.release_value(), .buffer_index = static_cast<u32>(shared_buffers->size()) };
+ shared_buffers->append(image_bitmap_pixels->buffer);
return image_bitmap_pixels;
}
@@ -656,11 +584,14 @@ void web_structured_serialize_transfer_record_destroy(SerializedTransferRecord*
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)
+void web_structured_serialize_transfer_record_set_serialized(SerializedTransferRecord* record, ReadonlyBytes data, JSObject* const* shared_array_buffers, size_t count)
+{
+ record->serialized = create_ipc_serialization_record(data, shared_array_buffers_from_abi(shared_array_buffers, count));
+}
+
+Vector<Core::AnonymousBuffer>* web_structured_serialize_transfer_record_shared_buffers(SerializedTransferRecord* record)
{
- record->serialized = writer->take_ipc_record();
- record->shared_buffers = writer->take_shared_buffers();
+ return &record->shared_buffers;
}
void web_structured_serialize_transfer_record_append_data_holder(SerializedTransferRecord* record, TransferDataEncoder* data_holder)
diff --git a/Libraries/LibWeb/HTML/StructuredSerializeTypes.h b/Libraries/LibWeb/HTML/StructuredSerializeTypes.h
index 8b213d7931f..7846a8fb5e6 100644
--- a/Libraries/LibWeb/HTML/StructuredSerializeTypes.h
+++ b/Libraries/LibWeb/HTML/StructuredSerializeTypes.h
@@ -16,9 +16,8 @@
namespace Web::HTML {
-// The memories of a structured serialization and deserialization, which the Rust implementation keeps, and which C++
-// only passes on to the serializations of the values that the serialization steps of a platform object hold.
-struct SerializationMemory;
+// The memory of a structured deserialization, which the Rust implementation keeps, and which C++ only passes on to the
+// deserializations of the values that the deserialization steps of a platform object hold.
struct DeserializationMemory;
enum class SerializationType : u8 {
diff --git a/Libraries/LibWebCommon/HTML/SerializationRecords.cpp b/Libraries/LibWebCommon/HTML/SerializationRecords.cpp
index dcfe558559b..e63febc7c0e 100644
--- a/Libraries/LibWebCommon/HTML/SerializationRecords.cpp
+++ b/Libraries/LibWebCommon/HTML/SerializationRecords.cpp
@@ -65,12 +65,6 @@ IPC::MessageBuffer TransferDataEncoder::take_buffer() const
return move(m_buffer);
}
-void TransferDataEncoder::append(IPCSerializationRecord&& record)
-{
- VERIFY(!m_buffer_has_been_taken);
- MUST(m_buffer.append_data(record.data.data(), record.data.size()));
-}
-
void TransferDataEncoder::encode_unsigned_big_integer(::Crypto::UnsignedBigInteger const& value)
{
auto buffer = MUST(ByteBuffer::create_zeroed(value.byte_length()));
diff --git a/Libraries/LibWebCommon/HTML/SerializationRecords.h b/Libraries/LibWebCommon/HTML/SerializationRecords.h
index 79dcce29949..df2eea48cae 100644
--- a/Libraries/LibWebCommon/HTML/SerializationRecords.h
+++ b/Libraries/LibWebCommon/HTML/SerializationRecords.h
@@ -135,7 +135,6 @@ public:
return m_encoder.encode_size(size);
}
- void append(IPCSerializationRecord&&);
void extend(Vector<TransferDataEncoder>);
void encode_unsigned_big_integer(::Crypto::UnsignedBigInteger const&);
diff --git a/Libraries/LibWebCommon/Rust/src/html/mod.rs b/Libraries/LibWebCommon/Rust/src/html/mod.rs
new file mode 100644
index 00000000000..6c160b8e0bb
--- /dev/null
+++ b/Libraries/LibWebCommon/Rust/src/html/mod.rs
@@ -0,0 +1,9 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The HTML Standard, https://html.spec.whatwg.org/
+
+pub mod serialization_records;
diff --git a/Libraries/LibWebCommon/Rust/src/html/serialization_records.rs b/Libraries/LibWebCommon/Rust/src/html/serialization_records.rs
new file mode 100644
index 00000000000..9a81b82c0a9
--- /dev/null
+++ b/Libraries/LibWebCommon/Rust/src/html/serialization_records.rs
@@ -0,0 +1,351 @@
+/*
+ * Copyright (c) 2022, Daniel Ehrenberg <[email protected]>
+ * Copyright (c) 2022, Andrew Kaster <[email protected]>
+ * Copyright (c) 2023-2024, Kenneth Myhra <[email protected]>
+ * Copyright (c) 2023, Idan Horowitz <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The formats of the records of structured serialization, https://html.spec.whatwg.org/multipage/structured-data.html
+//!
+//! A record, an HTML::IPCSerializationRecord or an HTML::StorageSerializationRecord of
+//! LibWebCommon/HTML/SerializationRecords.h, holds the values that a serialization writes in one of two formats. The
+//! IPC format is read only by the build that writes it, and holds integers at their full width in the byte order of
+//! the host. The storage format is stable on disk, for IndexedDB: a storage record starts with the prologue of the
+//! format, and holds integers as LEB128 varints and everything else in little-endian byte order.
+
+use ak::Utf16StringUnits;
+
+/// HTML::storage_format_magic, which every storage record starts with.
+const STORAGE_FORMAT_MAGIC: [u8; 4] = *b"LBSC";
+
+/// HTML::storage_format_version, the on-disk version of the storage format. Bumping it is a deliberate format change.
+const STORAGE_FORMAT_VERSION: u64 = 1;
+
+/// HTML::storage_format_flags, for optional features of the envelope. A change to the encoding of values bumps the
+/// version instead.
+const STORAGE_FORMAT_FLAGS: u64 = 0;
+
+/// HTML::SerializationType, the format of a record.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum SerializationType {
+ Ipc,
+ Storage,
+}
+
+fn append_unsigned_leb128(data: &mut Vec<u8>, mut value: u64) {
+ loop {
+ let byte = (value & 0x7f) as u8;
+ value >>= 7;
+ if value == 0 {
+ data.push(byte);
+ return;
+ }
+ data.push(byte | 0x80);
+ }
+}
+
+fn append_signed_leb128(data: &mut Vec<u8>, mut value: i64) {
+ loop {
+ let byte = (value & 0x7f) as u8;
+ // NB: An arithmetic shift, which keeps the sign.
+ value >>= 7;
+ let sign_bit_set = byte & 0x40 != 0;
+ if (value == 0 && !sign_bit_set) || (value == -1 && sign_bit_set) {
+ data.push(byte);
+ return;
+ }
+ data.push(byte | 0x80);
+ }
+}
+
+/// The bytes of a record, to which the encode functions append values in the format of the record.
+pub struct RecordEncoder {
+ serialization_type: SerializationType,
+ data: Vec<u8>,
+}
+
+impl RecordEncoder {
+ pub fn new(serialization_type: SerializationType) -> Self {
+ let mut data = Vec::new();
+ if serialization_type == SerializationType::Storage {
+ data.extend_from_slice(&STORAGE_FORMAT_MAGIC);
+ append_unsigned_leb128(&mut data, STORAGE_FORMAT_VERSION);
+ append_unsigned_leb128(&mut data, STORAGE_FORMAT_FLAGS);
+ }
+ Self {
+ serialization_type,
+ data,
+ }
+ }
+
+ pub fn serialization_type(&self) -> SerializationType {
+ self.serialization_type
+ }
+
+ pub fn bytes(&self) -> &[u8] {
+ &self.data
+ }
+
+ pub fn encode_u8(&mut self, value: u8) {
+ self.data.push(value);
+ }
+
+ pub fn encode_bool(&mut self, value: bool) {
+ self.encode_u8(u8::from(value));
+ }
+
+ pub fn encode_u16(&mut self, value: u16) {
+ match self.serialization_type {
+ SerializationType::Ipc => self.data.extend_from_slice(&value.to_ne_bytes()),
+ SerializationType::Storage => append_unsigned_leb128(&mut self.data, u64::from(value)),
+ }
+ }
+
+ pub fn encode_i32(&mut self, value: i32) {
+ match self.serialization_type {
+ SerializationType::Ipc => self.data.extend_from_slice(&value.to_ne_bytes()),
+ SerializationType::Storage => append_signed_leb128(&mut self.data, i64::from(value)),
+ }
+ }
+
+ pub fn encode_u32(&mut self, value: u32) {
+ match self.serialization_type {
+ SerializationType::Ipc => self.data.extend_from_slice(&value.to_ne_bytes()),
+ SerializationType::Storage => append_unsigned_leb128(&mut self.data, u64::from(value)),
+ }
+ }
+
+ pub fn encode_u64(&mut self, value: u64) {
+ match self.serialization_type {
+ SerializationType::Ipc => self.data.extend_from_slice(&value.to_ne_bytes()),
+ SerializationType::Storage => append_unsigned_leb128(&mut self.data, value),
+ }
+ }
+
+ pub fn encode_i64(&mut self, value: i64) {
+ match self.serialization_type {
+ SerializationType::Ipc => self.data.extend_from_slice(&value.to_ne_bytes()),
+ SerializationType::Storage => append_signed_leb128(&mut self.data, value),
+ }
+ }
+
+ pub fn encode_f64(&mut self, value: f64) {
+ match self.serialization_type {
+ SerializationType::Ipc => self.data.extend_from_slice(&value.to_bits().to_ne_bytes()),
+ SerializationType::Storage => self.data.extend_from_slice(&value.to_bits().to_le_bytes()),
+ }
+ }
+
+ /// The length of a string or of bytes in an IPC record, which LibIPC holds as a u32.
+ fn encode_ipc_size(&mut self, size: usize) {
+ let size = u32::try_from(size).expect("an IPC record holds fewer than 2^32 elements of a value");
+ self.data.extend_from_slice(&size.to_ne_bytes());
+ }
+
+ /// A string, whose ASCII storage the record keeps: an IPC record holds whether the string has it and the length of
+ /// the string, and a storage record holds both in one varint, the length shifted left by one.
+ pub fn encode_utf16_string(&mut self, string: Utf16StringUnits<'_>) {
+ let (has_ascii_storage, length) = match string {
+ Utf16StringUnits::Ascii(characters) => (true, characters.len()),
+ Utf16StringUnits::Utf16(code_units) => (false, code_units.len()),
+ };
+ match self.serialization_type {
+ SerializationType::Ipc => {
+ self.encode_bool(has_ascii_storage);
+ self.encode_ipc_size(length);
+ }
+ SerializationType::Storage => {
+ append_unsigned_leb128(&mut self.data, ((length as u64) << 1) | u64::from(has_ascii_storage));
+ }
+ }
+ match string {
+ Utf16StringUnits::Ascii(characters) => self.data.extend_from_slice(characters),
+ Utf16StringUnits::Utf16(code_units) => {
+ for &code_unit in code_units {
+ match self.serialization_type {
+ SerializationType::Ipc => self.data.extend_from_slice(&code_unit.to_ne_bytes()),
+ SerializationType::Storage => self.data.extend_from_slice(&code_unit.to_le_bytes()),
+ }
+ }
+ }
+ }
+ }
+
+ pub fn encode_bytes(&mut self, bytes: &[u8]) {
+ match self.serialization_type {
+ SerializationType::Ipc => self.encode_ipc_size(bytes.len()),
+ SerializationType::Storage => append_unsigned_leb128(&mut self.data, bytes.len() as u64),
+ }
+ self.data.extend_from_slice(bytes);
+ }
+
+ /// A BigInt, as the bytes that LibCrypto's SignedBigInteger::export_data() writes: 1 if the value is negative and 0
+ /// otherwise, then its magnitude, big-endian, without leading zeros, which is empty for zero.
+ pub fn encode_big_int(&mut self, is_negative: bool, magnitude: &[u8]) {
+ let mut bytes = Vec::with_capacity(1 + magnitude.len());
+ bytes.push(u8::from(is_negative));
+ bytes.extend_from_slice(magnitude);
+ self.encode_bytes(&bytes);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const PROLOGUE: [u8; 6] = [b'L', b'B', b'S', b'C', 0x01, 0x00];
+
+ fn storage(encode: impl FnOnce(&mut RecordEncoder)) -> Vec<u8> {
+ let mut encoder = RecordEncoder::new(SerializationType::Storage);
+ encode(&mut encoder);
+ assert_eq!(encoder.bytes()[..PROLOGUE.len()], PROLOGUE);
+ encoder.bytes()[PROLOGUE.len()..].to_vec()
+ }
+
+ fn ipc(encode: impl FnOnce(&mut RecordEncoder)) -> Vec<u8> {
+ let mut encoder = RecordEncoder::new(SerializationType::Ipc);
+ encode(&mut encoder);
+ encoder.bytes().to_vec()
+ }
+
+ #[test]
+ fn a_storage_record_starts_with_the_prologue() {
+ assert_eq!(RecordEncoder::new(SerializationType::Storage).bytes(), PROLOGUE);
+ assert!(RecordEncoder::new(SerializationType::Ipc).bytes().is_empty());
+ }
+
+ #[test]
+ fn a_storage_record_holds_integers_as_leb128_varints() {
+ assert_eq!(storage(|encoder| encoder.encode_bool(true)), [0x01]);
+ assert_eq!(storage(|encoder| encoder.encode_u8(0xff)), [0xff]);
+ assert_eq!(storage(|encoder| encoder.encode_u16(300)), [0xac, 0x02]);
+ assert_eq!(
+ storage(|encoder| encoder.encode_u32(0x0102_0304)),
+ [0x84, 0x86, 0x88, 0x08]
+ );
+ assert_eq!(storage(|encoder| encoder.encode_u64(0)), [0x00]);
+ assert_eq!(
+ storage(|encoder| encoder.encode_u64(u64::MAX)),
+ [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01]
+ );
+ assert_eq!(storage(|encoder| encoder.encode_i64(-2)), [0x7e]);
+ assert_eq!(storage(|encoder| encoder.encode_i64(63)), [0x3f]);
+ assert_eq!(storage(|encoder| encoder.encode_i64(64)), [0xc0, 0x00]);
+ assert_eq!(storage(|encoder| encoder.encode_i64(-65)), [0xbf, 0x7f]);
+ assert_eq!(
+ storage(|encoder| encoder.encode_i32(i32::MAX)),
+ [0xff, 0xff, 0xff, 0xff, 0x07]
+ );
+ assert_eq!(
+ storage(|encoder| encoder.encode_i32(i32::MIN)),
+ [0x80, 0x80, 0x80, 0x80, 0x78]
+ );
+ }
+
+ #[test]
+ fn a_storage_record_holds_a_double_as_its_little_endian_bits() {
+ assert_eq!(
+ storage(|encoder| encoder.encode_f64(1.0)),
+ [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3f]
+ );
+ assert_eq!(storage(|encoder| encoder.encode_f64(-0.0))[7], 0x80);
+ }
+
+ #[test]
+ fn an_ipc_record_holds_integers_at_their_full_width() {
+ assert_eq!(ipc(|encoder| encoder.encode_bool(false)), [0x00]);
+ assert_eq!(ipc(|encoder| encoder.encode_u16(0x0102)), 0x0102_u16.to_ne_bytes());
+ assert_eq!(ipc(|encoder| encoder.encode_i32(-2)), (-2_i32).to_ne_bytes());
+ assert_eq!(
+ ipc(|encoder| encoder.encode_u32(0x0102_0304)),
+ 0x0102_0304_u32.to_ne_bytes()
+ );
+ assert_eq!(ipc(|encoder| encoder.encode_u64(1)), 1_u64.to_ne_bytes());
+ assert_eq!(ipc(|encoder| encoder.encode_i64(-1)), (-1_i64).to_ne_bytes());
+ assert_eq!(
+ ipc(|encoder| encoder.encode_f64(13.5)),
+ 13.5_f64.to_bits().to_ne_bytes()
+ );
+ }
+
+ #[test]
+ fn a_storage_record_holds_an_ascii_string_as_one_byte_per_code_unit() {
+ assert_eq!(
+ storage(|encoder| encoder.encode_utf16_string(Utf16StringUnits::Ascii(b"AB"))),
+ [0x05, b'A', b'B']
+ );
+ assert_eq!(
+ storage(|encoder| encoder.encode_utf16_string(Utf16StringUnits::Ascii(b""))),
+ [0x01]
+ );
+ }
+
+ #[test]
+ fn a_storage_record_holds_a_utf16_string_as_little_endian_code_units() {
+ assert_eq!(
+ storage(|encoder| encoder.encode_utf16_string(Utf16StringUnits::Utf16(&[0x41, 0xd800, 0x42]))),
+ [0x06, 0x41, 0x00, 0x00, 0xd8, 0x42, 0x00]
+ );
+ }
+
+ #[test]
+ fn a_storage_record_holds_the_length_of_a_string_as_a_varint() {
+ let characters = [b'a'; 64];
+ assert_eq!(
+ storage(|encoder| encoder.encode_utf16_string(Utf16StringUnits::Ascii(&characters[..63])))[..1],
+ [0x7f]
+ );
+ assert_eq!(
+ storage(|encoder| encoder.encode_utf16_string(Utf16StringUnits::Ascii(&characters)))[..2],
+ [0x81, 0x01]
+ );
+ }
+
+ #[test]
+ fn an_ipc_record_holds_the_storage_and_the_length_of_a_string_before_it() {
+ let mut expected = vec![0x01];
+ expected.extend_from_slice(&2_u32.to_ne_bytes());
+ expected.extend_from_slice(b"AB");
+ assert_eq!(
+ ipc(|encoder| encoder.encode_utf16_string(Utf16StringUnits::Ascii(b"AB"))),
+ expected
+ );
+
+ let mut expected = vec![0x00];
+ expected.extend_from_slice(&1_u32.to_ne_bytes());
+ expected.extend_from_slice(&0xd800_u16.to_ne_bytes());
+ assert_eq!(
+ ipc(|encoder| encoder.encode_utf16_string(Utf16StringUnits::Utf16(&[0xd800]))),
+ expected
+ );
+ }
+
+ #[test]
+ fn a_record_holds_the_length_of_bytes_before_them() {
+ assert_eq!(
+ storage(|encoder| encoder.encode_bytes(&[0xde, 0xad])),
+ [0x02, 0xde, 0xad]
+ );
+ assert_eq!(storage(|encoder| encoder.encode_bytes(&[])), [0x00]);
+
+ let mut expected = 2_u32.to_ne_bytes().to_vec();
+ expected.extend_from_slice(&[0xde, 0xad]);
+ assert_eq!(ipc(|encoder| encoder.encode_bytes(&[0xde, 0xad])), expected);
+ }
+
+ #[test]
+ fn a_record_holds_a_big_int_as_its_sign_then_its_magnitude() {
+ assert_eq!(storage(|encoder| encoder.encode_big_int(false, &[])), [0x01, 0x00]);
+ assert_eq!(
+ storage(|encoder| encoder.encode_big_int(false, &[0x01, 0x00])),
+ [0x03, 0x00, 0x01, 0x00]
+ );
+ assert_eq!(
+ storage(|encoder| encoder.encode_big_int(true, &[0x05])),
+ [0x02, 0x01, 0x05]
+ );
+ }
+}
diff --git a/Libraries/LibWebCommon/Rust/src/lib.rs b/Libraries/LibWebCommon/Rust/src/lib.rs
index c45e00c7f77..c302808ff3c 100644
--- a/Libraries/LibWebCommon/Rust/src/lib.rs
+++ b/Libraries/LibWebCommon/Rust/src/lib.rs
@@ -14,4 +14,5 @@ mod rust_demangle;
mod rust_panic;
pub mod fetch;
+pub mod html;
pub mod mime_sniff;
diff --git a/Meta/Generators/libweb_bindings/structured_serialize.py b/Meta/Generators/libweb_bindings/structured_serialize.py
index 1f624d1276e..5243bb076c1 100644
--- a/Meta/Generators/libweb_bindings/structured_serialize.py
+++ b/Meta/Generators/libweb_bindings/structured_serialize.py
@@ -34,7 +34,7 @@ def write_rust_entry_point_declarations(
out.write(
f"""
// The serialization steps and the deserialization steps of {interface.name}.
-JSCompletion {rust_entry_point_name(interface, "serialization_steps")}(JSVM*, void* realm, void* cell, RustSerializationWriter*, bool for_storage);
+JSCompletion {rust_entry_point_name(interface, "serialization_steps")}(JSVM*, void* realm, void* cell, void* serialized, bool for_storage);
JSCompletion {rust_entry_point_name(interface, "deserialization_steps")}(JSVM*, void* realm, RustSerializationReader*);
"""
)
@@ -224,16 +224,15 @@ Optional<SerializablePlatformObject> serializable_from_object(JS::Object& object
}
}
-WebIDL::ExceptionOr<void> SerializablePlatformObject::serialization_steps(HTML::StructuredSerializeWriter& serialized, bool for_storage, HTML::SerializationMemory* memory) const
+WebIDL::ExceptionOr<void> SerializablePlatformObject::serialization_steps([[maybe_unused]] void* serialized, [[maybe_unused]] bool for_storage) const
{
- [[maybe_unused]] RustSerializationWriter writer { .realm = *realm, .serialized = serialized, .for_storage = for_storage, .memory = memory };
switch (interface_name) {
"""
)
for interface in rust_serializable:
out.write(
f""" case InterfaceName::{interface.name}:
- TRY(JS::HostABI::completion_from_abi<void>({rust_entry_point_name(interface, "serialization_steps")}(JS::HostABI::vm_to_abi(realm->vm()), realm.ptr(), rust_object.ptr(), &writer, for_storage)));
+ TRY(JS::HostABI::completion_from_abi<void>({rust_entry_point_name(interface, "serialization_steps")}(JS::HostABI::vm_to_abi(realm->vm()), realm.ptr(), rust_object.ptr(), serialized, for_storage)));
return {{}};
"""
)
diff --git a/Tests/LibWeb/StructuredSerializeTestHelpers.h b/Tests/LibWeb/StructuredSerializeTestHelpers.h
index b71b0f61b17..12f93b5b471 100644
--- a/Tests/LibWeb/StructuredSerializeTestHelpers.h
+++ b/Tests/LibWeb/StructuredSerializeTestHelpers.h
@@ -59,61 +59,6 @@ inline Record ipc_round_trip(Record const& record)
return MUST(decoder.decode<Record>());
}
-template<typename T>
-inline T structured_ipc_round_trip(T const& value)
-{
- auto writer = Web::HTML::StructuredSerializeWriter::create_ipc();
- writer.encode(value);
-
- auto record = writer.take_ipc_record();
- Web::HTML::StructuredSerializeReader reader { record };
- EXPECT_EQ(reader.type(), Web::HTML::SerializationType::IPC);
- return MUST(reader.decode<T>());
-}
-
-template<typename T>
-inline T structured_storage_round_trip(T const& value)
-{
- auto writer = Web::HTML::StructuredSerializeWriter::create_storage();
- writer.encode(value);
-
- auto record = writer.take_storage_record();
- Web::HTML::StructuredSerializeReader reader { record };
- EXPECT_EQ(reader.type(), Web::HTML::SerializationType::Storage);
- return MUST(reader.decode<T>());
-}
-
-template<typename T>
-inline void expect_structured_round_trip(T const& value)
-{
- EXPECT_EQ(structured_ipc_round_trip(value), value);
- EXPECT_EQ(structured_storage_round_trip(value), value);
-}
-
-template<typename T>
-inline ByteBuffer structured_ipc_buffer_round_trip(T const& value)
-{
- auto writer = Web::HTML::StructuredSerializeWriter::create_ipc();
- writer.encode(value);
-
- auto record = writer.take_ipc_record();
- Web::HTML::StructuredSerializeReader reader { record };
- EXPECT_EQ(reader.type(), Web::HTML::SerializationType::IPC);
- return MUST(reader.decode<ByteBuffer>());
-}
-
-template<typename T>
-inline ByteBuffer structured_storage_buffer_round_trip(T const& value)
-{
- auto writer = Web::HTML::StructuredSerializeWriter::create_storage();
- writer.encode(value);
-
- auto record = writer.take_storage_record();
- Web::HTML::StructuredSerializeReader reader { record };
- EXPECT_EQ(reader.type(), Web::HTML::SerializationType::Storage);
- return MUST(reader.decode<ByteBuffer>());
-}
-
inline void expect_utf16_equals(Utf16String const& actual, Utf16String const& expected)
{
EXPECT(actual.utf16_view() == expected.utf16_view());
@@ -162,28 +107,6 @@ inline void append_storage_ascii_utf16(Vector<u8>& bytes, StringView ascii)
bytes.append(ascii.bytes().data(), ascii.length());
}
-inline Vector<u8> expected_storage_identifier_record(StringView identifier)
-{
- Vector<u8> expected;
- append_storage_record_header(expected);
- append_storage_ascii_utf16(expected, identifier);
- return expected;
-}
-
-template<typename T>
-inline void expect_storage_identifier_encoding(T const& value, StringView identifier)
-{
- auto writer = Web::HTML::StructuredSerializeWriter::create_storage();
- writer.encode(value);
-
- auto record = writer.take_storage_record();
- auto expected = expected_storage_identifier_record(identifier);
- EXPECT_EQ(record.data.span(), expected.span());
-
- Web::HTML::StructuredSerializeReader reader { record };
- EXPECT_EQ(MUST(reader.decode<T>()), value);
-}
-
// CryptoKey needs the principal realm below because it is [SecureContext].
inline JS::Realm& test_realm()
{
diff --git a/Tests/LibWeb/TestStructuredSerializeFormat.cpp b/Tests/LibWeb/TestStructuredSerializeFormat.cpp
index fb5bd2c5cbf..4b3ef467185 100644
--- a/Tests/LibWeb/TestStructuredSerializeFormat.cpp
+++ b/Tests/LibWeb/TestStructuredSerializeFormat.cpp
@@ -67,58 +67,6 @@ static_assert(to_underlying(ValueTag::SerializableObject) == 24);
static_assert(to_underlying(ValueTag::Int32Primitive) == 25);
static_assert(to_underlying(ValueTag::EndObject) == 0xFF);
-template<typename Record>
-concept CanAppendToTransferDataEncoder = requires(Web::HTML::TransferDataEncoder encoder, Record record) {
- encoder.append(move(record));
-};
-
-static_assert(CanAppendToTransferDataEncoder<Web::HTML::IPCSerializationRecord>);
-static_assert(!CanAppendToTransferDataEncoder<Web::HTML::StorageSerializationRecord>);
-
-TEST_CASE(storage_writer_uses_stable_header_and_leb128_encoding)
-{
- auto writer = Web::HTML::StructuredSerializeWriter::create_storage();
- EXPECT_EQ(writer.type(), Web::HTML::SerializationType::Storage);
-
- writer.encode(true);
- writer.encode(static_cast<u32>(0x01020304));
- writer.encode(static_cast<i64>(-2));
- writer.encode(1.0);
-
- auto record = writer.take_storage_record();
-
- Array<u8, 20> expected {
- 'L',
- 'B',
- 'S',
- 'C',
- 0x01, // version (varint)
- 0x00, // flags (varint)
- 0x01, // true
- 0x84, // u32 0x01020304 as LEB128
- 0x86,
- 0x88,
- 0x08,
- 0x7e, // i64 -2 as signed LEB128
- 0x00, // double 1.0, fixed little-endian
- 0x00,
- 0x00,
- 0x00,
- 0x00,
- 0x00,
- 0xf0,
- 0x3f,
- };
- EXPECT_EQ(record.data.span(), expected);
-
- Web::HTML::StructuredSerializeReader reader { record };
- EXPECT_EQ(reader.type(), Web::HTML::SerializationType::Storage);
- EXPECT_EQ(MUST(reader.decode<bool>()), true);
- EXPECT_EQ(MUST(reader.decode<u32>()), 0x01020304u);
- EXPECT_EQ(MUST(reader.decode<i64>()), -2);
- EXPECT_EQ(MUST(reader.decode<double>()), 1.0);
-}
-
TEST_CASE(storage_writer_stores_int32_range_numbers_as_a_signed_varint_tag)
{
auto& vm = test_realm().vm();
@@ -175,94 +123,6 @@ TEST_CASE(storage_writer_encodes_enum_like_values_as_stable_identifiers)
}
}
-TEST_CASE(all_public_writer_reader_types_round_trip_through_ipc_and_storage)
-{
- expect_structured_round_trip(false);
- expect_structured_round_trip(true);
- expect_structured_round_trip(-12345);
- expect_structured_round_trip(static_cast<u32>(0xfedcba98));
- expect_structured_round_trip(static_cast<u64>(0x0102030405060708));
- expect_structured_round_trip(static_cast<i64>(-0x0102030405060708));
- expect_structured_round_trip(13.5);
-
- auto utf16 = Utf16String::from_utf8("stored UTF-16 string"sv);
- expect_utf16_equals(structured_ipc_round_trip(utf16), utf16);
- expect_utf16_equals(structured_storage_round_trip(utf16), utf16);
-
- // Non-ASCII forces 16-bit string storage rather than the ASCII fast path.
- auto non_ascii = Utf16String::from_utf8("héllo 🦬"sv);
- expect_utf16_equals(structured_ipc_round_trip(non_ascii), non_ascii);
- expect_utf16_equals(structured_storage_round_trip(non_ascii), non_ascii);
-
- expect_structured_round_trip(Web::Bindings::KeyType::Public);
- expect_structured_round_trip(Web::Bindings::KeyType::Private);
- expect_structured_round_trip(Web::Bindings::KeyType::Secret);
-
- expect_structured_round_trip(Web::Bindings::KeyUsage::Encrypt);
- expect_structured_round_trip(Web::Bindings::KeyUsage::Decrypt);
- expect_structured_round_trip(Web::Bindings::KeyUsage::Sign);
- expect_structured_round_trip(Web::Bindings::KeyUsage::Verify);
- expect_structured_round_trip(Web::Bindings::KeyUsage::DeriveKey);
- expect_structured_round_trip(Web::Bindings::KeyUsage::DeriveBits);
- expect_structured_round_trip(Web::Bindings::KeyUsage::WrapKey);
- expect_structured_round_trip(Web::Bindings::KeyUsage::UnwrapKey);
- expect_structured_round_trip(Web::Bindings::KeyUsage::EncapsulateKey);
- expect_structured_round_trip(Web::Bindings::KeyUsage::EncapsulateBits);
- expect_structured_round_trip(Web::Bindings::KeyUsage::DecapsulateKey);
- expect_structured_round_trip(Web::Bindings::KeyUsage::DecapsulateBits);
-
- expect_structured_round_trip(Web::Bindings::PredefinedColorSpace::Srgb);
- expect_structured_round_trip(Web::Bindings::PredefinedColorSpace::SrgbLinear);
- expect_structured_round_trip(Web::Bindings::PredefinedColorSpace::DisplayP3);
- expect_structured_round_trip(Web::Bindings::PredefinedColorSpace::DisplayP3Linear);
-
- expect_structured_round_trip(Gfx::BitmapFormat::BGRx8888);
- expect_structured_round_trip(Gfx::BitmapFormat::BGRA8888);
- expect_structured_round_trip(Gfx::BitmapFormat::RGBx8888);
- expect_structured_round_trip(Gfx::BitmapFormat::RGBA8888);
-
- expect_structured_round_trip(Gfx::AlphaType::Premultiplied);
- expect_structured_round_trip(Gfx::AlphaType::Unpremultiplied);
-
- Optional<double> no_double;
- expect_structured_round_trip(no_double);
- expect_structured_round_trip(Optional<double> { -0.25 });
-
- Optional<Utf16String> no_utf16;
- expect_optional_utf16_equals(structured_ipc_round_trip(no_utf16), no_utf16);
- expect_optional_utf16_equals(structured_storage_round_trip(no_utf16), no_utf16);
-
- auto optional_utf16 = Optional<Utf16String> { utf16 };
- expect_optional_utf16_equals(structured_ipc_round_trip(optional_utf16), optional_utf16);
- expect_optional_utf16_equals(structured_storage_round_trip(optional_utf16), optional_utf16);
-
- expect_structured_round_trip(Web::Bindings::InterfaceName::Blob);
- expect_structured_round_trip(Web::Bindings::InterfaceName::File);
- expect_structured_round_trip(Web::Bindings::InterfaceName::FileList);
- expect_structured_round_trip(Web::Bindings::InterfaceName::DOMException);
- expect_structured_round_trip(Web::Bindings::InterfaceName::DOMMatrixReadOnly);
- expect_structured_round_trip(Web::Bindings::InterfaceName::DOMMatrix);
- expect_structured_round_trip(Web::Bindings::InterfaceName::DOMPointReadOnly);
- expect_structured_round_trip(Web::Bindings::InterfaceName::DOMPoint);
- expect_structured_round_trip(Web::Bindings::InterfaceName::DOMRectReadOnly);
- expect_structured_round_trip(Web::Bindings::InterfaceName::DOMRect);
- expect_structured_round_trip(Web::Bindings::InterfaceName::CryptoKey);
- expect_structured_round_trip(Web::Bindings::InterfaceName::DOMQuad);
- expect_structured_round_trip(Web::Bindings::InterfaceName::ImageData);
- expect_structured_round_trip(Web::Bindings::InterfaceName::ImageBitmap);
- expect_structured_round_trip(Web::Bindings::InterfaceName::Module);
- expect_structured_round_trip(Web::Bindings::InterfaceName::QuotaExceededError);
-
- Array<u8, 4> raw_bytes { 0xde, 0xad, 0xbe, 0xef };
- ReadonlyBytes readonly_bytes { raw_bytes.data(), raw_bytes.size() };
- EXPECT_EQ(structured_ipc_buffer_round_trip(readonly_bytes).span(), raw_bytes);
- EXPECT_EQ(structured_storage_buffer_round_trip(readonly_bytes).span(), raw_bytes);
-
- auto byte_buffer = MUST(ByteBuffer::copy(raw_bytes.span()));
- EXPECT_EQ(structured_ipc_buffer_round_trip(byte_buffer).span(), raw_bytes);
- EXPECT_EQ(structured_storage_buffer_round_trip(byte_buffer).span(), raw_bytes);
-}
-
TEST_CASE(storage_writer_encodes_js_strings_as_utf16_code_units)
{
auto& vm = test_realm().vm();
diff --git a/Tests/LibWeb/TestStructuredSerializeSharedArrayBuffer.cpp b/Tests/LibWeb/TestStructuredSerializeSharedArrayBuffer.cpp
index 0b0fe313a49..c05f36a3d9d 100644
--- a/Tests/LibWeb/TestStructuredSerializeSharedArrayBuffer.cpp
+++ b/Tests/LibWeb/TestStructuredSerializeSharedArrayBuffer.cpp
@@ -237,23 +237,11 @@ TEST_CASE(cross_origin_isolation_gate_still_applies_by_default)
EXPECT(result.is_error());
}
-TEST_CASE(storage_serialization_rejects_shared_array_buffers_even_when_same_agent)
+TEST_CASE(storage_serialization_rejects_shared_array_buffers)
{
auto& vm = Web::Bindings::main_thread_vm();
auto source = make_shared_array_buffer(source_realm(), "not for storage"sv.bytes());
- auto writer = Web::HTML::StructuredSerializeWriter::create_storage();
- auto result = Web::HTML::structured_serialize_internal(vm, writer, JS::Value { source.ptr() }, true, nullptr, Web::HTML::AllowSharedArrayBuffers::SameAgentAlways);
+ auto result = Web::HTML::structured_serialize_for_storage(vm, JS::Value { source.ptr() });
EXPECT(result.is_error());
}
-
-TEST_CASE(appending_an_ipc_record_rejects_a_shared_array_buffer_side_table)
-{
- auto record = serialize_same_agent(JS::Value { make_shared_array_buffer(source_realm(), "side table"sv.bytes()).ptr() });
- EXPECT(!Web::HTML::same_process_shared_array_buffers(record).is_empty());
-
- auto writer = Web::HTML::StructuredSerializeWriter::create_ipc();
- EXPECT_DEATH("Appending an IPC record with a SharedArrayBuffer side table", [&] {
- writer.append(move(record));
- }());
-}