Skip to content

Truly independent web browser

LibJS+LibWeb: Read structured serialization records in Rust

Shannon Boothbc1ec97f7387
diff --git a/Libraries/LibJS/Rust/src/runtime/big_int.rs b/Libraries/LibJS/Rust/src/runtime/big_int.rs
index 35a58b792b8..099b0d99953 100644
--- a/Libraries/LibJS/Rust/src/runtime/big_int.rs
+++ b/Libraries/LibJS/Rust/src/runtime/big_int.rs
@@ -49,6 +49,12 @@ impl BigInt {
Self::create(vm, SignedBigInteger::from(value))
}
+ /// The BigInt with the sign and the magnitude, big-endian, which can have leading zeros.
+ pub fn create_from_magnitude_bytes_be(vm: &Vm, is_negative: bool, magnitude: &[u8]) -> Gc<BigInt> {
+ let sign = if is_negative { Sign::Minus } else { Sign::Plus };
+ Self::create(vm, SignedBigInteger::from_bytes_be(sign, magnitude))
+ }
+
pub fn big_integer(&self) -> &SignedBigInteger {
&self.big_integer
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs
index 060e341a21b..8512c4e88ea 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs
@@ -10,11 +10,11 @@
//!
//! 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.
+//! The serialization and deserialization steps write and read the record of the algorithm, which it passes through C++
+//! to them. The transfer steps and the transfer-receiving 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.
use core::cell::Cell;
use core::ffi::c_void;
@@ -23,45 +23,22 @@ use core::ptr::NonNull;
use ak::Utf16String;
use libjs_rust::api::{RawNativeFunctionResult, ThrowCompletionOr, Value};
+use libwebcommon_rust::html::serialization_records::SerializationType;
use crate::bindings::interface::{ConstructedObject, Interface, Ref, cell_from_abi, realm_arguments, wrap};
use crate::bindings::transport::TransportHandle;
use crate::bindings::{CallContext, WebIdlResult};
-use crate::html::structured_serialize::cpp::{OwnedSerializedTransferRecord, TransferDataDecoder};
+use crate::html::structured_serialize::cpp::{
+ OwnedSerializedTransferRecord, TransferDataDecoder, data_clone_error_from_serialization_error,
+};
+use crate::html::structured_serialize::reader::StructuredSerializeReader;
use crate::html::structured_serialize::writer::StructuredSerializeWriter;
use crate::html::structured_serialize::{
- Serializer, encode_serializable_object_header, structured_deserialize_with_transfer_internal,
- structured_serialize_with_transfer,
+ Deserializer, Serializer, decode_serializable_object_header, encode_serializable_object_header,
+ structured_deserialize_with_transfer_internal, structured_serialize_with_transfer,
};
unsafe extern "C" {
- 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;
- fn web_bindings_deserialize_i32(serialized: *mut c_void, out_value: &mut i32) -> RawNativeFunctionResult;
- fn web_bindings_deserialize_u32(serialized: *mut c_void, out_value: &mut u32) -> RawNativeFunctionResult;
- fn web_bindings_deserialize_u64(serialized: *mut c_void, out_value: &mut u64) -> RawNativeFunctionResult;
- fn web_bindings_deserialize_f64(serialized: *mut c_void, out_value: &mut f64) -> RawNativeFunctionResult;
- fn web_bindings_deserialize_bool(serialized: *mut c_void, out_value: &mut bool) -> RawNativeFunctionResult;
- fn web_bindings_deserialize_i64(serialized: *mut c_void, out_value: &mut i64) -> RawNativeFunctionResult;
- fn web_bindings_deserialize_optional_u64(
- serialized: *mut c_void,
- out_has_value: &mut bool,
- out_value: &mut u64,
- ) -> RawNativeFunctionResult;
- fn web_bindings_deserialize_bytes(
- serialized: *mut c_void,
- bytes: *mut c_void,
- append: unsafe extern "C" fn(*mut c_void, *const u8, usize),
- ) -> RawNativeFunctionResult;
- fn web_bindings_deserialize_utf16_string(
- serialized: *mut c_void,
- out_string: &mut usize,
- ) -> RawNativeFunctionResult;
- fn web_bindings_deserialize_inline_object_header(
- serialized: *mut c_void,
- interface_name: u16,
- ) -> RawNativeFunctionResult;
fn web_bindings_transfer_data_encode_bool(data_holder: *mut c_void, value: bool) -> RawNativeFunctionResult;
fn web_bindings_transfer_data_encode_records(
data_holder: *mut c_void,
@@ -164,118 +141,93 @@ impl<'a, 'memory> SerializationWriter<'a, 'memory> {
}
}
-/// The record of a structured deserialization, which the deserialization steps of an object read from: a
-/// Web::Bindings::RustSerializationReader that C++ lends for the steps. What it reads that the record does not hold
+/// The record of a structured deserialization, which the deserialization steps of an object read from, and the
+/// deserialization that the sub-deserializations of the steps run in. What it reads that the record does not hold
/// throws a "DataCloneError" DOMException.
-pub(crate) struct SerializationReader<'a> {
- raw: NonNull<c_void>,
- _lent: PhantomData<&'a mut c_void>,
+pub(crate) struct SerializationReader<'a, 'memory> {
+ deserializer: &'a Deserializer<'a, 'a, 'memory>,
}
-impl SerializationReader<'_> {
- /// The reader as the C ABI of an interface's C++ class takes it, for what only C++ decodes.
- pub(crate) fn as_raw(&mut self) -> *mut c_void {
- self.raw.as_ptr()
+impl<'a, 'memory> SerializationReader<'a, 'memory> {
+ pub(crate) fn new(deserializer: &'a Deserializer<'a, 'a, 'memory>) -> Self {
+ Self { deserializer }
+ }
+
+ fn serialized(&self) -> &'a StructuredSerializeReader<'a> {
+ self.deserializer.serialized()
}
/// The value of a field of the serialized form, which is a sub-serialization,
/// https://html.spec.whatwg.org/multipage/structured-data.html#sub-deserialization
pub(crate) fn read_value(&mut self) -> WebIdlResult<Value> {
- // SAFETY: The reader is lent for the steps.
- Ok(unsafe { web_bindings_deserialize_value(self.raw.as_ptr()) }.into_completion()?)
+ self.deserializer.deserialize()
}
/// Whether the record is one for storage, rather than for IPC.
pub(crate) fn is_for_storage(&mut self) -> bool {
- // SAFETY: The reader is lent for the steps.
- unsafe { web_bindings_deserialize_is_for_storage(self.raw.as_ptr()) }
+ self.serialized().serialization_type() == SerializationType::Storage
}
pub(crate) fn read_u8(&mut self) -> WebIdlResult<u8> {
- let mut value = 0;
- // SAFETY: The reader is lent for the steps.
- unsafe { web_bindings_deserialize_u8(self.raw.as_ptr(), &mut value) }.into_completion()?;
- Ok(value)
+ self.serialized().decode_u8()
}
pub(crate) fn read_i32(&mut self) -> WebIdlResult<i32> {
- let mut value = 0;
- // SAFETY: The reader is lent for the steps.
- unsafe { web_bindings_deserialize_i32(self.raw.as_ptr(), &mut value) }.into_completion()?;
- Ok(value)
+ self.serialized().decode_i32()
}
pub(crate) fn read_u32(&mut self) -> WebIdlResult<u32> {
- let mut value = 0;
- // SAFETY: The reader is lent for the steps.
- unsafe { web_bindings_deserialize_u32(self.raw.as_ptr(), &mut value) }.into_completion()?;
- Ok(value)
+ self.serialized().decode_u32()
}
pub(crate) fn read_u64(&mut self) -> WebIdlResult<u64> {
- let mut value = 0;
- // SAFETY: The reader is lent for the steps.
- unsafe { web_bindings_deserialize_u64(self.raw.as_ptr(), &mut value) }.into_completion()?;
- Ok(value)
+ self.serialized().decode_u64()
}
pub(crate) fn read_f64(&mut self) -> WebIdlResult<f64> {
- let mut value = 0.0;
- // SAFETY: The reader is lent for the steps.
- unsafe { web_bindings_deserialize_f64(self.raw.as_ptr(), &mut value) }.into_completion()?;
- Ok(value)
+ self.serialized().decode_f64()
}
/// Reads what SerializationWriter::write_object_in_place() writes, and returns the new object.
pub(crate) fn read_object_in_place<T: Serializable>(&mut self, cx: &mut CallContext) -> WebIdlResult<Ref<T>> {
- // SAFETY: The reader is lent for the steps.
- unsafe { web_bindings_deserialize_inline_object_header(self.raw.as_ptr(), T::INTERFACE_NAME) }
- .into_completion()?;
+ decode_serializable_object_header(self.serialized(), T::INTERFACE_NAME)?;
let object = T::deserialization_steps(cx, self)?;
Ok(object.into_object(cx.vm()))
}
pub(crate) fn read_bool(&mut self) -> WebIdlResult<bool> {
- let mut value = false;
- // SAFETY: The reader is lent for the steps.
- unsafe { web_bindings_deserialize_bool(self.raw.as_ptr(), &mut value) }.into_completion()?;
- Ok(value)
+ self.serialized().decode_bool()
}
pub(crate) fn read_i64(&mut self) -> WebIdlResult<i64> {
- let mut value = 0;
- // SAFETY: The reader is lent for the steps.
- unsafe { web_bindings_deserialize_i64(self.raw.as_ptr(), &mut value) }.into_completion()?;
- Ok(value)
+ self.serialized().decode_i64()
}
pub(crate) fn read_optional_u64(&mut self) -> WebIdlResult<Option<u64>> {
- let mut has_value = false;
- let mut value = 0;
- // SAFETY: The reader is lent for the steps.
- unsafe { web_bindings_deserialize_optional_u64(self.raw.as_ptr(), &mut has_value, &mut value) }
- .into_completion()?;
- Ok(has_value.then_some(value))
+ self.serialized().decode_optional_u64()
}
+ /// Bytes that the record holds, which it lends for as long as the deserialization runs.
+ pub(crate) fn read_borrowed_bytes(&mut self) -> WebIdlResult<&'a [u8]> {
+ self.serialized().decode_bytes()
+ }
+
+ /// A copy of bytes that the record holds. If the copy cannot be allocated, a "DataCloneError" DOMException.
pub(crate) fn read_bytes(&mut self) -> WebIdlResult<Vec<u8>> {
- unsafe extern "C" fn append(bytes: *mut c_void, data: *const u8, length: usize) {
- // SAFETY: The bytes are the Vec that read_bytes() lends, and LibWeb passes that many bytes.
- unsafe { (*bytes.cast::<Vec<u8>>()).extend_from_slice(ak::slice_from_raw_parts(data, length)) };
- }
- let mut bytes = Vec::new();
- // SAFETY: The reader and the bytes are lent for the steps.
- unsafe { web_bindings_deserialize_bytes(self.raw.as_ptr(), (&raw mut bytes).cast(), append) }
- .into_completion()?;
- Ok(bytes)
+ let bytes = self.read_borrowed_bytes()?;
+ let mut copy = Vec::new();
+ copy.try_reserve_exact(bytes.len()).map_err(|_| {
+ data_clone_error_from_serialization_error(
+ self.serialized().realm(),
+ "Unable to allocate a copy of the bytes",
+ )
+ })?;
+ copy.extend_from_slice(bytes);
+ Ok(copy)
}
pub(crate) fn read_utf16_string(&mut self) -> WebIdlResult<Utf16String> {
- let mut string = 0;
- // SAFETY: The reader is lent for the steps.
- unsafe { web_bindings_deserialize_utf16_string(self.raw.as_ptr(), &mut string) }.into_completion()?;
- // SAFETY: LibWeb hands over the string it read.
- Ok(unsafe { Utf16String::from_raw_owned(string) })
+ self.serialized().decode_utf16_string()
}
}
@@ -448,7 +400,8 @@ pub(crate) unsafe fn serialization_steps<T: Serializable>(
///
/// # Safety
///
-/// The pointers must be the VM, a live realm, and a reader that C++ lends.
+/// The pointers must be the VM, a live realm, and the SerializationReader that crate::html::structured_serialize
+/// lends through C++.
pub(crate) unsafe fn deserialization_steps<T: Serializable>(
vm: *mut c_void,
realm: *mut c_void,
@@ -457,11 +410,9 @@ pub(crate) unsafe fn deserialization_steps<T: Serializable>(
// SAFETY: The caller passes the VM and a live realm.
let (vm, realm) = unsafe { realm_arguments(vm, realm) };
let mut cx = CallContext::new(vm, realm);
- let mut serialized = SerializationReader {
- raw: NonNull::new(serialized).expect("C++ lends a reader"),
- _lent: PhantomData,
- };
- let result = T::deserialization_steps(&mut cx, &mut serialized);
+ // SAFETY: The caller passes the reader that the deserialization lends for the steps.
+ let serialized = unsafe { &mut *serialized.cast::<SerializationReader<'_, '_>>() };
+ let result = T::deserialization_steps(&mut cx, serialized);
completion(&cx, result.map(|implementation| wrap_new_object(&cx, implementation)))
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs
index 78171feb17a..1bacf7d1b40 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs
@@ -17,7 +17,7 @@ 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, StructuredSerializeReader};
+use crate::html::structured_serialize::reader::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
@@ -104,7 +104,7 @@ fn encode_identifier(serialized: &StructuredSerializeWriter, identifier: &[u8])
/// The index of the identifier that a storage record holds.
fn decode_identifier(
- serialized: StructuredSerializeReader,
+ serialized: &StructuredSerializeReader,
identifiers: &[&[u8]],
unknown_message: &[u8],
) -> WebIdlResult<u8> {
@@ -215,7 +215,7 @@ fn write_fields(serialized: &StructuredSerializeWriter, value: &RawFields<'_>) {
/// Runs the deserialization steps of CryptoKey, which create the key in the realm from what they read.
pub(crate) fn deserialization_steps(
realm: Gc<Realm>,
- serialized: StructuredSerializeReader,
+ serialized: &StructuredSerializeReader,
) -> WebIdlResult<Gc<Object>> {
let for_storage = serialized.serialization_type() == SerializationType::Storage;
@@ -243,7 +243,7 @@ pub(crate) fn deserialization_steps(
match algorithm_type {
ALGORITHM_RSA | ALGORITHM_RSA_HASHED => {
modulus_length = serialized.decode_u32()?;
- public_exponent = Some(serialized.decode_byte_buffer()?);
+ public_exponent = Some(serialized.decode_bytes()?);
if algorithm_type == ALGORITHM_RSA_HASHED {
hash = serialized.decode_utf16_string()?;
}
@@ -278,10 +278,10 @@ pub(crate) fn deserialization_steps(
let Some(&buffer_count) = HANDLE_BUFFER_COUNTS.get(usize::from(handle_tag)) else {
return Err(data_clone_error(b"Invalid CryptoKey handle tag"));
};
- let mut buffers: Vec<DecodedBytes> = Vec::new();
+ let mut buffers: Vec<&[u8]> = Vec::new();
let (mut has_ec_parameters, mut ec_parameters, mut has_ec_public_key) = (false, Vec::new(), false);
if handle_tag == HANDLE_EC_PRIVATE_KEY {
- buffers.push(serialized.decode_byte_buffer()?);
+ buffers.push(serialized.decode_bytes()?);
has_ec_parameters = serialized.decode_bool()?;
if has_ec_parameters {
let parameter_count = serialized.decode_u64()?;
@@ -291,18 +291,18 @@ pub(crate) fn deserialization_steps(
}
has_ec_public_key = serialized.decode_bool()?;
if has_ec_public_key {
- buffers.push(serialized.decode_byte_buffer()?);
- buffers.push(serialized.decode_byte_buffer()?);
+ buffers.push(serialized.decode_bytes()?);
+ buffers.push(serialized.decode_bytes()?);
}
} else {
for _ in 0..buffer_count {
- buffers.push(serialized.decode_byte_buffer()?);
+ buffers.push(serialized.decode_bytes()?);
}
}
let mut handle_buffers = [ak::Span::default(); MAX_HANDLE_BUFFERS];
for (span, buffer) in handle_buffers.iter_mut().zip(&buffers) {
- *span = ak::Span::new(buffer.bytes());
+ *span = ak::Span::new(buffer);
}
let fields = RawFields {
r#type,
@@ -312,7 +312,7 @@ pub(crate) fn deserialization_steps(
modulus_length,
public_exponent: public_exponent
.as_ref()
- .map_or_else(ak::Span::default, |bytes| ak::Span::new(bytes.bytes())),
+ .map_or_else(ak::Span::default, |bytes| ak::Span::new(bytes)),
hash: hash.raw_identity(),
named_curve: named_curve.raw_identity(),
length,
diff --git a/Libraries/LibWeb/Bindings/Rust/src/file_api/blob.rs b/Libraries/LibWeb/Bindings/Rust/src/file_api/blob.rs
index 6be78083e67..70e1dcad864 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/file_api/blob.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/file_api/blob.rs
@@ -12,7 +12,7 @@ use core::ops::Deref;
use core::ptr::NonNull;
use ak::{Utf16String, Utf16StringUnits};
-use libjs_rust::api::{MarkedVec, RawNativeFunctionResult, Trace};
+use libjs_rust::api::{MarkedVec, Trace};
use super::file::File;
use crate::bindings::conversions::{BufferSource, UsvString};
@@ -29,10 +29,6 @@ unsafe extern "C" {
fn web_blob_text(realm: *mut c_void, bytes: ak::Span<'_, u8>) -> *mut c_void;
fn web_blob_array_buffer(realm: *mut c_void, bytes: ak::Span<'_, u8>) -> *mut c_void;
fn web_blob_bytes(realm: *mut c_void, bytes: ak::Span<'_, u8>) -> *mut c_void;
- fn web_blob_deserialize_byte_sequence(
- serialized: *mut c_void,
- out_bytes: &mut ForeignBytesAbi,
- ) -> RawNativeFunctionResult;
}
/// The enumeration EndingType of FileAPI/Blob.idl.
@@ -547,16 +543,7 @@ impl Blob {
let r#type = serialized.read_utf16_string()?;
// 2. Set value’s underlying byte sequence to serialized.[[ByteSequence]].
- let mut bytes = ForeignBytesAbi {
- owner: core::ptr::null_mut(),
- data: core::ptr::null(),
- length: 0,
- };
- // SAFETY: The reader is lent for the steps.
- unsafe { web_blob_deserialize_byte_sequence(serialized.as_raw(), &mut bytes) }.into_completion()?;
-
- // SAFETY: C++ hands over the bytes it decoded.
- Ok(unsafe { Self::with_foreign_bytes(bytes, r#type) })
+ Ok(Self::new(serialized.read_bytes()?, r#type))
}
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/image_bitmap.rs b/Libraries/LibWeb/Bindings/Rust/src/html/image_bitmap.rs
index c44e8b1e19b..a08c7dd0aed 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/image_bitmap.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/image_bitmap.rs
@@ -207,10 +207,10 @@ fn deserialize_bitmap_data(cx: &CallContext, serialized: &mut SerializationReade
b"Invalid structured serialize alpha type",
b"Unknown structured serialize alpha type",
)?;
- let data = serialized.read_bytes()?;
+ let data = serialized.read_borrowed_bytes()?;
let (mut color_space_kind, mut color_primaries, mut transfer_characteristics) = (COLOR_SPACE_KIND_SRGB, 0, 0);
- let mut icc_profile = Vec::new();
+ let mut icc_profile: &[u8] = &[];
if kind == BITMAP_KIND_WITH_COLOR_SPACE {
color_space_kind = serialized.read_u8()?;
match color_space_kind {
@@ -219,7 +219,7 @@ fn deserialize_bitmap_data(cx: &CallContext, serialized: &mut SerializationReade
color_primaries = serialized.read_u8()?;
transfer_characteristics = serialized.read_u8()?;
}
- COLOR_SPACE_KIND_ICC_PROFILE => icc_profile = serialized.read_bytes()?,
+ COLOR_SPACE_KIND_ICC_PROFILE => icc_profile = serialized.read_borrowed_bytes()?,
_ => return Err(data_clone_error(b"Invalid ImageBitmap color space")),
}
}
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 d7b28498bf3..291683afbab 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs
@@ -6,20 +6,18 @@
//! What structured serialization asks of LibWeb's C++ code, which implements it in
//! 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.
+//! bytes over to and the deserializations read the bytes of, the registry of serializable interfaces, the platform
+//! objects, and the side tables that SharedArrayBuffers are shared through.
use core::ffi::c_void;
+use core::marker::PhantomData;
use core::mem::ManuallyDrop;
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::structured_data::{SerializationReader, SerializationWriter};
use crate::bindings::{CallContext, Exception, WebIdlResult};
-use crate::html::structured_serialize::memory::DeserializationMemory;
unsafe extern "C" {
fn web_structured_serialize_set_ipc_record(
@@ -32,72 +30,31 @@ unsafe extern "C" {
fn web_structured_serialize_interface_storage_identifier(
interface_name: u16,
identifier: &mut ak::Span<'static, u8>,
- );
+ ) -> bool;
+ fn web_structured_serialize_interface_name_from_storage_identifier(
+ identifier: ak::Span<'_, u8>,
+ interface_name: &mut u16,
+ ) -> bool;
fn web_structured_serialize_shared_buffers_append_shared_memory(
shared_buffers: *mut c_void,
array_buffer: *mut c_void,
index: &mut u32,
) -> bool;
- fn web_structured_serialize_reader_type(reader: *mut c_void) -> u8;
- fn web_structured_serialize_reader_is_at_end(reader: *mut c_void) -> bool;
- fn web_structured_serialize_reader_decode_u8(
- reader: *mut c_void,
- realm: *mut c_void,
- value: &mut u8,
- ) -> RawNativeFunctionResult;
- fn web_structured_serialize_reader_decode_bool(
- reader: *mut c_void,
+ fn web_structured_serialize_ipc_record_data(record: *const c_void, data: &mut ak::Span<'static, u8>);
+ fn web_structured_serialize_ipc_record_shared_array_buffer(
+ record: *const c_void,
realm: *mut c_void,
- value: &mut bool,
- ) -> RawNativeFunctionResult;
- fn web_structured_serialize_reader_decode_i32(
- reader: *mut c_void,
- realm: *mut c_void,
- value: &mut i32,
- ) -> RawNativeFunctionResult;
- fn web_structured_serialize_reader_decode_u16(
- reader: *mut c_void,
- realm: *mut c_void,
- value: &mut u16,
- ) -> RawNativeFunctionResult;
- fn web_structured_serialize_reader_decode_u32(
- reader: *mut c_void,
- realm: *mut c_void,
- value: &mut u32,
- ) -> RawNativeFunctionResult;
- fn web_structured_serialize_reader_decode_u64(
- reader: *mut c_void,
- realm: *mut c_void,
- value: &mut u64,
- ) -> RawNativeFunctionResult;
- fn web_structured_serialize_reader_decode_size(
- reader: *mut c_void,
- realm: *mut c_void,
- value: &mut usize,
- ) -> RawNativeFunctionResult;
- fn web_structured_serialize_reader_decode_f64(
- reader: *mut c_void,
- realm: *mut c_void,
- value: &mut f64,
- ) -> RawNativeFunctionResult;
- fn web_structured_serialize_reader_decode_utf16_string(
- reader: *mut c_void,
- realm: *mut c_void,
- string: &mut usize,
- ) -> RawNativeFunctionResult;
- fn web_structured_serialize_reader_decode_optional_utf16_string(
- reader: *mut c_void,
- realm: *mut c_void,
- has_value: &mut bool,
- string: &mut usize,
- ) -> RawNativeFunctionResult;
- fn web_structured_serialize_reader_decode_byte_buffer(
- reader: *mut c_void,
+ side_table_index: u32,
+ byte_length: usize,
+ preserve_growability: bool,
+ ) -> *mut c_void;
+ fn web_structured_serialize_shared_buffers_shared_array_buffer(
+ shared_buffers: *mut c_void,
realm: *mut c_void,
- buffer: &mut *mut c_void,
+ index: u32,
+ shared_object_id: u64,
) -> RawNativeFunctionResult;
- fn web_structured_serialize_byte_buffer_data(buffer: *mut c_void) -> *const u8;
fn web_structured_serialize_byte_buffer_size(buffer: *mut c_void) -> usize;
fn web_structured_serialize_array_buffer_from_byte_buffer(
realm: *mut c_void,
@@ -105,28 +62,6 @@ unsafe extern "C" {
shared: bool,
) -> *mut c_void;
fn web_structured_serialize_byte_buffer_destroy(buffer: *mut c_void);
- fn web_structured_serialize_reader_decode_interface_name(
- reader: *mut c_void,
- realm: *mut c_void,
- interface_name: &mut u16,
- ) -> RawNativeFunctionResult;
- fn web_structured_serialize_reader_decode_big_int(
- reader: *mut c_void,
- realm: *mut c_void,
- ) -> RawNativeFunctionResult;
- fn web_structured_serialize_reader_array_buffer_from_shared_memory(
- reader: *mut c_void,
- realm: *mut c_void,
- index: u32,
- shared_object_id: u64,
- ) -> RawNativeFunctionResult;
- fn web_structured_serialize_reader_array_buffer_sharing_side_table_entry(
- reader: *mut c_void,
- realm: *mut c_void,
- side_table_index: u32,
- byte_length: usize,
- preserve_growability: bool,
- ) -> *mut c_void;
fn web_structured_serialize_data_clone_error_from_serialization_error(
realm: *mut c_void,
message: ak::Span<'_, u8>,
@@ -151,8 +86,7 @@ unsafe extern "C" {
fn web_structured_serialize_deserialize_rust_platform_object(
interface_name: u16,
realm: *mut c_void,
- reader: *mut c_void,
- memory: *mut c_void,
+ serialized: *mut c_void,
) -> RawNativeFunctionResult;
fn web_structured_serialize_is_transferable(object: *mut c_void) -> bool;
@@ -195,11 +129,7 @@ unsafe extern "C" {
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;
- fn web_structured_serialize_transfer_record_deserialize(
- record: *mut c_void,
- realm: *mut c_void,
- memory: *mut c_void,
- ) -> RawNativeFunctionResult;
+ fn web_structured_serialize_transfer_record_serialized(record: *mut c_void) -> *const c_void;
fn web_structured_serialize_transfer_record_clear_shared_buffers(record: *mut c_void);
fn web_structured_serialize_transferred_values_append(transferred_values: *mut c_void, value: *mut c_void);
fn web_structured_serialize_transfer_data_decoder_decode_u8(
@@ -220,14 +150,6 @@ unsafe extern "C" {
fn web_structured_serialize_transfer_data_decoder_destroy(decoder: *mut c_void);
}
-fn serialization_type_from_abi(value: u8) -> SerializationType {
- match value {
- 0 => SerializationType::Ipc,
- 1 => SerializationType::Storage,
- _ => unreachable!("LibWeb has no other serialization type"),
- }
-}
-
fn object_into_abi<T>(object: Gc<T>) -> *mut c_void {
object.as_ptr().cast()
}
@@ -244,7 +166,7 @@ fn completion(result: RawNativeFunctionResult) -> WebIdlResult<Value> {
Ok(result.into_completion()?)
}
-/// The bytes of a record, which C++ decoded into a buffer that this owns until an ArrayBuffer takes it over.
+/// The bytes of a data holder, which C++ decoded into a buffer that this owns until an ArrayBuffer takes it over.
pub(crate) struct DecodedBytes(NonNull<c_void>);
impl DecodedBytes {
@@ -253,11 +175,6 @@ impl DecodedBytes {
unsafe { web_structured_serialize_byte_buffer_size(self.0.as_ptr()) }
}
- pub(crate) fn bytes(&self) -> &[u8] {
- // SAFETY: This owns the buffer, whose bytes live as long as it does.
- unsafe { ak::slice_from_raw_parts(web_structured_serialize_byte_buffer_data(self.0.as_ptr()), self.len()) }
- }
-
/// A new ArrayBuffer in the realm, which takes over the bytes.
pub(crate) fn into_array_buffer(self, realm: Gc<Realm>, is_shared: ArrayBufferShared) -> Gc<ArrayBuffer> {
let buffer = ManuallyDrop::new(self);
@@ -332,12 +249,70 @@ impl StorageSerializationRecord {
}
}
-/// 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] {
+/// The identifier of the serializable interface that a storage record holds, from LibWeb's registry of them, if the
+/// Bindings::InterfaceName names one.
+pub(crate) fn serializable_interface_storage_identifier(interface_name: u16) -> Option<&'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()
+ unsafe { web_structured_serialize_interface_storage_identifier(interface_name, &mut identifier) }
+ .then(|| identifier.as_slice())
+}
+
+/// The Bindings::InterfaceName of the serializable interface with the identifier, if LibWeb's registry has one.
+pub(crate) fn serializable_interface_name_from_storage_identifier(identifier: &[u8]) -> Option<u16> {
+ let mut interface_name = 0;
+ // SAFETY: The call borrows the identifier, and writes to the local.
+ unsafe {
+ web_structured_serialize_interface_name_from_storage_identifier(ak::Span::new(identifier), &mut interface_name)
+ }
+ .then_some(interface_name)
+}
+
+/// An HTML::IPCSerializationRecord that C++ lends for a deserialization to read.
+#[derive(Clone, Copy)]
+pub(crate) struct ReceivedIPCSerializationRecord<'a> {
+ raw: NonNull<c_void>,
+ _lent: PhantomData<&'a c_void>,
+}
+
+impl<'a> ReceivedIPCSerializationRecord<'a> {
+ /// # Safety
+ ///
+ /// `record` must be a record that C++ lends for `'a`.
+ pub(crate) unsafe fn from_raw(record: *const c_void) -> Self {
+ Self {
+ raw: NonNull::new(record.cast_mut()).expect("C++ lends a record"),
+ _lent: PhantomData,
+ }
+ }
+
+ pub(crate) fn data(self) -> &'a [u8] {
+ let mut data = ak::Span::default();
+ // SAFETY: The record is lent for 'a, and its bytes with it.
+ unsafe { web_structured_serialize_ipc_record_data(self.raw.as_ptr(), &mut data) };
+ data.as_slice()
+ }
+
+ /// A new SharedArrayBuffer in the realm that shares the storage of the buffer at the index of the record's
+ /// same-process side table, if there is such a buffer, and its storage can be shared.
+ pub(crate) fn shared_array_buffer(
+ self,
+ realm: Gc<Realm>,
+ side_table_index: u32,
+ byte_length: usize,
+ preserve_growability: bool,
+ ) -> Option<Gc<Object>> {
+ // SAFETY: The record is lent, and the realm is live. LibWeb returns a live object or null.
+ unsafe {
+ object_from_abi(web_structured_serialize_ipc_record_shared_array_buffer(
+ self.raw.as_ptr(),
+ realm.as_ptr().cast(),
+ side_table_index,
+ byte_length,
+ preserve_growability,
+ ))
+ }
+ }
}
/// The side list of the cross-process shared memory that a record on the messaging path shares its SharedArrayBuffers
@@ -368,6 +343,24 @@ impl SharedBuffers {
.then_some(index)
}
+ /// A new SharedArrayBuffer in the realm over the cross-process shared memory at the index of the list.
+ pub(crate) fn shared_array_buffer(
+ self,
+ realm: Gc<Realm>,
+ index: u32,
+ shared_object_id: u64,
+ ) -> WebIdlResult<Value> {
+ // SAFETY: The list is lent, and the realm is live.
+ completion(unsafe {
+ web_structured_serialize_shared_buffers_shared_array_buffer(
+ self.0.as_ptr(),
+ realm.as_ptr().cast(),
+ index,
+ shared_object_id,
+ )
+ })
+ }
+
/// Gathers the pixels of the ImageBitmaps of the transfer list in one buffer of shared memory, which the list
/// holds.
pub(crate) fn gather_image_bitmap_pixels(self, transfer_list: &[Gc<Object>]) -> ImageBitmapSharedPixels {
@@ -383,203 +376,6 @@ impl SharedBuffers {
}
}
-/// 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)]
-pub(crate) struct StructuredSerializeReader {
- raw: NonNull<c_void>,
- realm: Gc<Realm>,
-}
-
-impl StructuredSerializeReader {
- /// # Safety
- ///
- /// `reader` must be a reader that C++ lends while this is used.
- pub(crate) unsafe fn from_raw(reader: *mut c_void, realm: Gc<Realm>) -> Self {
- Self {
- raw: NonNull::new(reader).expect("C++ lends a reader"),
- realm,
- }
- }
-
- pub(crate) fn as_raw(self) -> *mut c_void {
- self.raw.as_ptr()
- }
-
- fn realm_raw(self) -> *mut c_void {
- self.realm.as_ptr().cast()
- }
-
- pub(crate) fn serialization_type(self) -> SerializationType {
- // SAFETY: The reader is lent.
- serialization_type_from_abi(unsafe { web_structured_serialize_reader_type(self.as_raw()) })
- }
-
- pub(crate) fn is_at_end(self) -> bool {
- // SAFETY: The reader is lent.
- unsafe { web_structured_serialize_reader_is_at_end(self.as_raw()) }
- }
-
- pub(crate) fn decode_u8(self) -> WebIdlResult<u8> {
- let mut value = 0;
- // SAFETY: The reader is lent, and the realm is live.
- completion(unsafe { web_structured_serialize_reader_decode_u8(self.as_raw(), self.realm_raw(), &mut value) })?;
- Ok(value)
- }
-
- pub(crate) fn decode_bool(self) -> WebIdlResult<bool> {
- let mut value = false;
- // SAFETY: The reader is lent, and the realm is live.
- completion(unsafe {
- web_structured_serialize_reader_decode_bool(self.as_raw(), self.realm_raw(), &mut value)
- })?;
- Ok(value)
- }
-
- pub(crate) fn decode_i32(self) -> WebIdlResult<i32> {
- let mut value = 0;
- // SAFETY: The reader is lent, and the realm is live.
- completion(unsafe { web_structured_serialize_reader_decode_i32(self.as_raw(), self.realm_raw(), &mut value) })?;
- Ok(value)
- }
-
- pub(crate) fn decode_u16(self) -> WebIdlResult<u16> {
- let mut value = 0;
- // SAFETY: The reader is lent, and the realm is live.
- completion(unsafe { web_structured_serialize_reader_decode_u16(self.as_raw(), self.realm_raw(), &mut value) })?;
- Ok(value)
- }
-
- pub(crate) fn decode_u32(self) -> WebIdlResult<u32> {
- let mut value = 0;
- // SAFETY: The reader is lent, and the realm is live.
- completion(unsafe { web_structured_serialize_reader_decode_u32(self.as_raw(), self.realm_raw(), &mut value) })?;
- Ok(value)
- }
-
- pub(crate) fn decode_u64(self) -> WebIdlResult<u64> {
- let mut value = 0;
- // SAFETY: The reader is lent, and the realm is live.
- completion(unsafe { web_structured_serialize_reader_decode_u64(self.as_raw(), self.realm_raw(), &mut value) })?;
- Ok(value)
- }
-
- pub(crate) fn decode_size(self) -> WebIdlResult<usize> {
- let mut value = 0;
- // SAFETY: The reader is lent, and the realm is live.
- completion(unsafe {
- web_structured_serialize_reader_decode_size(self.as_raw(), self.realm_raw(), &mut value)
- })?;
- Ok(value)
- }
-
- pub(crate) fn decode_f64(self) -> WebIdlResult<f64> {
- let mut value = 0.0;
- // SAFETY: The reader is lent, and the realm is live.
- completion(unsafe { web_structured_serialize_reader_decode_f64(self.as_raw(), self.realm_raw(), &mut value) })?;
- Ok(value)
- }
-
- pub(crate) fn decode_optional_f64(self) -> WebIdlResult<Option<f64>> {
- if !self.decode_bool()? {
- return Ok(None);
- }
- Ok(Some(self.decode_f64()?))
- }
-
- pub(crate) fn decode_utf16_string(self) -> WebIdlResult<Utf16String> {
- let mut string = 0;
- // SAFETY: The reader is lent, and the realm is live.
- let result = unsafe {
- web_structured_serialize_reader_decode_utf16_string(self.as_raw(), self.realm_raw(), &mut string)
- };
- // SAFETY: LibWeb hands over the string it read, which is empty if it read none.
- let string = unsafe { Utf16String::from_raw_owned(string) };
- completion(result)?;
- Ok(string)
- }
-
- pub(crate) fn decode_optional_utf16_string(self) -> WebIdlResult<Option<Utf16String>> {
- let mut has_value = false;
- let mut string = 0;
- // SAFETY: The reader is lent, and the realm is live.
- let result = unsafe {
- web_structured_serialize_reader_decode_optional_utf16_string(
- self.as_raw(),
- self.realm_raw(),
- &mut has_value,
- &mut string,
- )
- };
- // SAFETY: LibWeb hands over the string it read, if it read one.
- let string = has_value.then(|| unsafe { Utf16String::from_raw_owned(string) });
- completion(result)?;
- Ok(string)
- }
-
- pub(crate) fn decode_byte_buffer(self) -> WebIdlResult<DecodedBytes> {
- let mut buffer = core::ptr::null_mut();
- // SAFETY: The reader is lent, the realm is live, and the buffer outlives the call.
- completion(unsafe {
- web_structured_serialize_reader_decode_byte_buffer(self.as_raw(), self.realm_raw(), &mut buffer)
- })?;
- Ok(DecodedBytes(NonNull::new(buffer).expect("LibWeb decodes a buffer")))
- }
-
- pub(crate) fn decode_interface_name(self) -> WebIdlResult<u16> {
- let mut interface_name = 0;
- // SAFETY: The reader is lent, and the realm is live.
- completion(unsafe {
- web_structured_serialize_reader_decode_interface_name(self.as_raw(), self.realm_raw(), &mut interface_name)
- })?;
- Ok(interface_name)
- }
-
- /// A new BigInt with the value that decode_signed_big_integer() reads.
- pub(crate) fn decode_big_int(self) -> WebIdlResult<Value> {
- // SAFETY: The reader is lent, and the realm is live.
- completion(unsafe { web_structured_serialize_reader_decode_big_int(self.as_raw(), self.realm_raw()) })
- }
-
- /// A new SharedArrayBuffer over the cross-process shared memory at the index of the reader's side list.
- pub(crate) fn array_buffer_from_shared_memory(self, index: u32, shared_object_id: u64) -> WebIdlResult<Value> {
- // SAFETY: The reader is lent, and the realm is live.
- completion(unsafe {
- web_structured_serialize_reader_array_buffer_from_shared_memory(
- self.as_raw(),
- self.realm_raw(),
- index,
- shared_object_id,
- )
- })
- }
-
- /// A new SharedArrayBuffer that shares the storage of the buffer at the index of the record's same-process side
- /// table, if there is such a buffer, and its storage can be shared.
- pub(crate) fn array_buffer_sharing_side_table_entry(
- self,
- side_table_index: u32,
- byte_length: usize,
- preserve_growability: bool,
- ) -> Option<Gc<Object>> {
- // SAFETY: The reader is lent, and the realm is live. LibWeb returns a live object or null.
- unsafe {
- object_from_abi(web_structured_serialize_reader_array_buffer_sharing_side_table_entry(
- self.as_raw(),
- self.realm_raw(),
- side_table_index,
- byte_length,
- preserve_growability,
- ))
- }
- }
-
- /// The realm that the deserialization creates its values in.
- pub(crate) fn realm(self) -> Gc<Realm> {
- self.realm
- }
-}
-
/// data_clone_error_from_serialization_error(): the "DataCloneError" DOMException in the realm for a record that does
/// not hold what deserializing it reads.
pub(crate) fn data_clone_error_from_serialization_error(realm: Gc<Realm>, message: &str) -> Exception {
@@ -690,19 +486,19 @@ pub(crate) fn serializable_steps(interface_name: u16) -> SerializableSteps {
}
}
-/// The deserialization steps of an interface implemented in Rust, which create the new instance from what they read.
+/// The deserialization steps of an interface implemented in Rust, which create the new instance in the realm from what
+/// they read, and which C++ runs through the bindings of the interface, given the reader, which it passes on.
pub(crate) fn deserialize_rust_platform_object(
interface_name: u16,
- serialized: StructuredSerializeReader,
- memory: &DeserializationMemory,
+ realm: Gc<Realm>,
+ serialized: &mut SerializationReader,
) -> WebIdlResult<Value> {
- // SAFETY: The realm is live, and the reader and the memory are lent.
+ // SAFETY: The realm is live, and the reader is lent for the call.
completion(unsafe {
web_structured_serialize_deserialize_rust_platform_object(
interface_name,
- serialized.realm_raw(),
- serialized.as_raw(),
- memory.as_abi(),
+ realm.as_ptr().cast(),
+ core::ptr::from_mut(serialized).cast(),
)
})
}
@@ -875,16 +671,18 @@ impl SerializedTransferRecord {
.map(|decoder| OwnedTransferDataDecoder(TransferDataDecoder(decoder)))
}
- /// StructuredDeserialize of the record's [[Serialized]], with its shared memory.
- pub(crate) fn deserialize(self, realm: Gc<Realm>, memory: &DeserializationMemory) -> WebIdlResult<Value> {
- // SAFETY: The record and the memory are lent, and the realm is live.
- completion(unsafe {
- web_structured_serialize_transfer_record_deserialize(
+ /// The record's [[Serialized]], which it lends for as long as it is lent.
+ ///
+ /// # Safety
+ ///
+ /// The record must be lent for `'a`.
+ pub(crate) unsafe fn serialized<'a>(self) -> ReceivedIPCSerializationRecord<'a> {
+ // SAFETY: The caller lends the record for 'a, and so its [[Serialized]].
+ unsafe {
+ ReceivedIPCSerializationRecord::from_raw(web_structured_serialize_transfer_record_serialized(
self.0.as_ptr(),
- realm.as_ptr().cast(),
- memory.as_abi(),
- )
- })
+ ))
+ }
}
pub(crate) fn clear_shared_buffers(self) {
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 eab7f8aad0d..1f6875a0026 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/exports.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/exports.rs
@@ -16,10 +16,11 @@ use libwebcommon_rust::html::serialization_records::SerializationType;
use crate::bindings::interface::realm_arguments;
use crate::bindings::{CallContext, WebIdlResult};
use crate::html::structured_serialize::cpp::{
- IPCSerializationRecord, SerializedTransferRecord, SharedBuffers, StorageSerializationRecord,
- StructuredSerializeReader, TransferDataDecoder, TransferredValues,
+ IPCSerializationRecord, ReceivedIPCSerializationRecord, SerializedTransferRecord, SharedBuffers,
+ StorageSerializationRecord, TransferDataDecoder, TransferredValues,
};
use crate::html::structured_serialize::memory::{DeserializationMemory, SerializationMemory};
+use crate::html::structured_serialize::reader::StructuredSerializeReader;
use crate::html::structured_serialize::writer::StructuredSerializeWriter;
use crate::html::structured_serialize::{
AllowSharedArrayBuffers, structured_deserialize_internal, structured_deserialize_with_transfer,
@@ -127,35 +128,53 @@ pub unsafe extern "C" fn web_rust_structured_serialize_for_storage(
RawNativeFunctionResult::from_completion(Ok(Value::UNDEFINED))
}
-/// StructuredDeserialize in the realm, which throws a "DataCloneError" DOMException for a storage record with bytes
-/// after its value if `check_fully_consumed` is true.
+/// StructuredDeserialize of the IPC record in the realm. 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 live realm, a reader that C++ lends, and the memory of the deserialization that a
-/// deserialization step deserializes a value of, or null for a new one.
+/// The pointers must be the VM, a live realm, a record that C++ lends, and a list that C++ lends or null.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_rust_structured_deserialize_internal(
+pub unsafe extern "C" fn web_rust_structured_deserialize(
vm: *mut c_void,
target_realm: *mut c_void,
- serialized: *mut c_void,
- memory: *mut c_void,
- check_fully_consumed: bool,
+ record: *const c_void,
+ shared_buffers: *mut c_void,
) -> RawNativeFunctionResult {
// SAFETY: The caller passes the VM and a live realm.
let (vm, target_realm) = unsafe { realm_arguments(vm, target_realm) };
let cx = CallContext::new(vm, target_realm);
- // SAFETY: The caller lends the reader.
- let serialized = unsafe { StructuredSerializeReader::from_raw(serialized, target_realm) };
- let new_memory;
- let memory = if memory.is_null() {
- new_memory = DeserializationMemory::new(vm);
- &new_memory
- } else {
- // SAFETY: The caller passes the memory of the deserialization that it runs in.
- unsafe { DeserializationMemory::from_abi(memory) }
+ // SAFETY: The caller lends the record, and the list if there is one.
+ let (record, shared_buffers) = unsafe {
+ (
+ ReceivedIPCSerializationRecord::from_raw(record),
+ (!shared_buffers.is_null()).then(|| SharedBuffers::from_raw(shared_buffers)),
+ )
};
- let result = structured_deserialize_internal(&cx, serialized, memory, check_fully_consumed);
+ let serialized = StructuredSerializeReader::new_ipc(target_realm, record, shared_buffers);
+ let memory = DeserializationMemory::new(vm);
+ completion(&cx, structured_deserialize_internal(&cx, &serialized, &memory, false))
+}
+
+/// StructuredDeserialize of the bytes of the storage record in the realm, which throws a "DataCloneError" DOMException
+/// for bytes after its value.
+///
+/// # Safety
+///
+/// The pointers must be the VM and a live realm.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_structured_deserialize_for_storage(
+ vm: *mut c_void,
+ target_realm: *mut c_void,
+ data: ak::Span<'_, u8>,
+) -> RawNativeFunctionResult {
+ // SAFETY: The caller passes the VM and a live realm.
+ let (vm, target_realm) = unsafe { realm_arguments(vm, target_realm) };
+ let cx = CallContext::new(vm, target_realm);
+ let result = StructuredSerializeReader::new_storage(target_realm, data.as_slice()).and_then(|serialized| {
+ let memory = DeserializationMemory::new(vm);
+ structured_deserialize_internal(&cx, &serialized, &memory, true)
+ });
completion(&cx, result)
}
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 552e6c5c4aa..a997aa00ffd 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/memory.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/memory.rs
@@ -4,12 +4,9 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! 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.
+//! The memories of structured serializations and deserializations.
use core::cell::RefCell;
-use core::ffi::c_void;
use std::collections::HashMap;
use libjs_rust::api::{MarkedVec, Value, Vm};
@@ -57,20 +54,6 @@ impl<'vm> DeserializationMemory<'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 size(&self) -> usize {
self.values.len()
}
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 98cb7d28589..e7b87b2ec3e 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs
@@ -10,12 +10,12 @@
//! Safe passing of structured data, https://html.spec.whatwg.org/multipage/structured-data.html
//!
-//! The algorithms run here, and write their records through writer.rs. The records that they read stay LibWeb's C++
-//! HTML::StructuredSerializeReader (cpp.rs).
+//! The algorithms run here, and write and read their records through writer.rs and reader.rs.
pub(crate) mod cpp;
pub(crate) mod exports;
pub(crate) mod memory;
+pub(crate) mod reader;
pub(crate) mod writer;
use ak::Utf16String;
@@ -29,12 +29,13 @@ use libjs_rust::api::{
};
use libwebcommon_rust::html::serialization_records::SerializationType;
-use crate::bindings::structured_data::SerializationWriter;
+use crate::bindings::interface::with_temporary_execution_context;
+use crate::bindings::structured_data::{SerializationReader, SerializationWriter};
use crate::bindings::{CallContext, Exception, WebIdlResult};
use crate::crypto::crypto_key;
use crate::html::structured_serialize::cpp::{
- OwnedSerializedTransferRecord, SerializableSteps, SerializedTransferRecord, StructuredSerializeReader,
- TransferDataDecoder, TransferDataHolder, create_transferred_platform_object, current_settings_object_agent_cluster,
+ OwnedSerializedTransferRecord, SerializableSteps, SerializedTransferRecord, 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,
@@ -42,6 +43,7 @@ use crate::html::structured_serialize::cpp::{
transferable_set_detached,
};
use crate::html::structured_serialize::memory::{DeserializationMemory, SerializationMemory};
+use crate::html::structured_serialize::reader::StructuredSerializeReader;
use crate::html::structured_serialize::writer::StructuredSerializeWriter;
use crate::webidl::dom_exception::{self, DOMExceptionFields};
use crate::webidl::quota_exceeded_error::{self, QuotaExceededErrorFields};
@@ -198,7 +200,7 @@ fn encode_error_type(serialized: &StructuredSerializeWriter, error_type: ErrorTy
}
}
-fn decode_error_type(serialized: StructuredSerializeReader) -> WebIdlResult<ErrorType> {
+fn decode_error_type(serialized: &StructuredSerializeReader) -> WebIdlResult<ErrorType> {
if serialized.serialization_type() == SerializationType::Ipc {
let decoded = serialized.decode_u8()?;
return match error_type_from_ipc(decoded) {
@@ -921,15 +923,56 @@ pub(crate) fn encode_serializable_object_header(serialized: &StructuredSerialize
}
}
-struct Deserializer<'a, 'vm, 'memory> {
+pub(crate) fn decode_serializable_object_header(
+ serialized: &StructuredSerializeReader,
+ interface_name: u16,
+) -> WebIdlResult<()> {
+ let tag = serialized.decode_u8()?;
+ let name = serialized.decode_interface_name()?;
+ if tag != ValueTag::SerializableObject as u8 || name != interface_name {
+ return Err(data_clone_error("Unexpected serializable object"));
+ }
+ if serialized.serialization_type() == SerializationType::Storage
+ && serialized.decode_u64()? != serializable_payload_version()
+ {
+ return Err(data_clone_error("Unsupported serializable payload version"));
+ }
+ Ok(())
+}
+
+/// A new ArrayBuffer in the realm with a copy of the bytes. If this throws an exception, catch it, and then throw a
+/// "DataCloneError" DOMException.
+fn array_buffer_from_bytes(
+ vm: &Vm,
+ realm: Gc<Realm>,
+ bytes: &[u8],
+ is_shared: ArrayBufferShared,
+) -> WebIdlResult<Gc<ArrayBuffer>> {
+ ArrayBuffer::try_create_written_by(vm, realm, bytes.len(), is_shared, |data| {
+ for (byte, &value) in data.iter_mut().zip(bytes) {
+ byte.write(value);
+ }
+ bytes.len()
+ })
+ .map_err(|_| data_clone_error_from_serialization_error(realm, "Unable to allocate an ArrayBuffer"))
+}
+
+pub(crate) struct Deserializer<'a, 'vm, 'memory> {
cx: &'a CallContext<'vm>,
- serialized: StructuredSerializeReader,
+ serialized: &'a StructuredSerializeReader<'a>,
memory: &'a DeserializationMemory<'memory>,
}
+impl<'a> Deserializer<'a, '_, '_> {
+ /// The record that the deserialization reads.
+ pub(crate) fn serialized(&self) -> &'a StructuredSerializeReader<'a> {
+ self.serialized
+ }
+}
+
impl Deserializer<'_, '_, '_> {
// https://html.spec.whatwg.org/multipage/structured-data.html#structureddeserialize
- fn deserialize(&self) -> WebIdlResult<Value> {
+ pub(crate) fn deserialize(&self) -> WebIdlResult<Value> {
self.deserialize_value(self.serialized.decode_u8()?)
}
@@ -1030,7 +1073,7 @@ impl Deserializer<'_, '_, '_> {
is_primitive = true;
}
ValueTag::BigIntPrimitive => {
- value = self.serialized.decode_big_int()?;
+ value = self.serialized.decode_big_int(vm)?;
is_primitive = true;
}
ValueTag::StringPrimitive => {
@@ -1050,7 +1093,7 @@ impl Deserializer<'_, '_, '_> {
// 9. Otherwise, if serialized.[[Type]] is "BigInt", then set value to a new BigInt object in targetRealm whose [[BigIntData]] internal slot value is serialized.[[BigIntData]].
ValueTag::BigIntObject => {
- let big_int = self.serialized.decode_big_int()?.as_bigint();
+ let big_int = self.serialized.decode_big_int(vm)?.as_bigint();
value = Value::from_object(BigIntObject::create(vm, realm, big_int));
}
@@ -1100,11 +1143,11 @@ impl Deserializer<'_, '_, '_> {
break 'shared_array_buffer;
}
- let buffer = self.serialized.decode_byte_buffer()?;
+ let bytes = self.serialized.decode_bytes()?;
if let Some(array_buffer) =
self.serialized
- .array_buffer_sharing_side_table_entry(side_table_index, buffer.len(), false)
+ .array_buffer_sharing_side_table_entry(side_table_index, bytes.len(), false)
{
value = Value::from_object(array_buffer);
break 'shared_array_buffer;
@@ -1112,7 +1155,7 @@ impl Deserializer<'_, '_, '_> {
// A buffer with no cross-process shared memory to share (a zero-length one, e.g.) whose record crossed a
// process boundary arrives with an empty side table — so it's reconstructed from the byte copy.
- value = Value::from_object(buffer.into_array_buffer(realm, ArrayBufferShared::Yes));
+ value = Value::from_object(array_buffer_from_bytes(vm, realm, bytes, ArrayBufferShared::Yes)?);
}
// 14. Otherwise, if serialized.[[Type]] is "GrowableSharedArrayBuffer", then set value to a new SharedArrayBuffer object in targetRealm whose [[ArrayBufferData]] internal slot value is serialized.[[ArrayBufferData]], whose [[ArrayBufferByteLengthData]] internal slot value is serialized.[[ArrayBufferByteLengthData]], and whose [[ArrayBufferMaxByteLength]] internal slot value is serialized.[[ArrayBufferMaxByteLength]].
@@ -1122,11 +1165,11 @@ impl Deserializer<'_, '_, '_> {
self.deserialize_agent_cluster()?;
let side_table_index = self.serialized.decode_u32()?;
- let buffer = self.serialized.decode_byte_buffer()?;
+ let bytes = self.serialized.decode_bytes()?;
let max_byte_length = self.serialized.decode_size()?;
// NB: Creating a resizable buffer throws a RangeError if its byte length is greater than its max byte length.
- if max_byte_length < buffer.len() {
+ if max_byte_length < bytes.len() {
return Err(data_clone_error_from_serialization_error(
realm,
"ArrayBuffer byte length exceeds its max byte length",
@@ -1135,7 +1178,7 @@ impl Deserializer<'_, '_, '_> {
if let Some(array_buffer) =
self.serialized
- .array_buffer_sharing_side_table_entry(side_table_index, buffer.len(), true)
+ .array_buffer_sharing_side_table_entry(side_table_index, bytes.len(), true)
{
let data = array_buffer
.downcast::<ArrayBuffer>()
@@ -1145,7 +1188,7 @@ impl Deserializer<'_, '_, '_> {
break 'growable_shared_array_buffer;
}
- let data = buffer.into_array_buffer(realm, ArrayBufferShared::Yes);
+ let data = array_buffer_from_bytes(vm, realm, bytes, ArrayBufferShared::Yes)?;
data.set_max_byte_length(max_byte_length);
value = Value::from_object(data);
@@ -1153,28 +1196,26 @@ impl Deserializer<'_, '_, '_> {
// 15. Otherwise, if serialized.[[Type]] is "ArrayBuffer", then set value to a new ArrayBuffer object in targetRealm whose [[ArrayBufferData]] internal slot value is serialized.[[ArrayBufferData]], and whose [[ArrayBufferByteLength]] internal slot value is serialized.[[ArrayBufferByteLength]].
// If this throws an exception, catch it, and then throw a "DataCloneError" DOMException.
- // NB: The bytes were allocated when they were decoded, which throws a "DataCloneError" DOMException if it fails.
ValueTag::ArrayBuffer => {
- let buffer = self.serialized.decode_byte_buffer()?;
- value = Value::from_object(buffer.into_array_buffer(realm, ArrayBufferShared::No));
+ let bytes = self.serialized.decode_bytes()?;
+ value = Value::from_object(array_buffer_from_bytes(vm, realm, bytes, ArrayBufferShared::No)?);
}
// 16. Otherwise, if serialized.[[Type]] is "ResizableArrayBuffer", then set value to a new ArrayBuffer object in targetRealm whose [[ArrayBufferData]] internal slot value is serialized.[[ArrayBufferData]], whose [[ArrayBufferByteLength]] internal slot value is serialized.[[ArrayBufferByteLength]], and whose [[ArrayBufferMaxByteLength]] internal slot value is serialized.[[ArrayBufferMaxByteLength]].
// If this throws an exception, catch it, and then throw a "DataCloneError" DOMException.
- // NB: The bytes were allocated when they were decoded, which throws a "DataCloneError" DOMException if it fails.
ValueTag::ResizeableArrayBuffer => {
- let buffer = self.serialized.decode_byte_buffer()?;
+ let bytes = self.serialized.decode_bytes()?;
let max_byte_length = self.serialized.decode_size()?;
// NB: Creating a resizable buffer throws a RangeError if its byte length is greater than its max byte length.
- if max_byte_length < buffer.len() {
+ if max_byte_length < bytes.len() {
return Err(data_clone_error_from_serialization_error(
realm,
"ArrayBuffer byte length exceeds its max byte length",
));
}
- let data = buffer.into_array_buffer(realm, ArrayBufferShared::No);
+ let data = array_buffer_from_bytes(vm, realm, bytes, ArrayBufferShared::No)?;
data.set_max_byte_length(max_byte_length);
value = Value::from_object(data);
@@ -1409,7 +1450,7 @@ impl Deserializer<'_, '_, '_> {
Value::from_object(crypto_key::deserialization_steps(realm, self.serialized)?)
}
SerializableSteps::Rust => {
- deserialize_rust_platform_object(interface_name, self.serialized, self.memory)?
+ deserialize_rust_platform_object(interface_name, realm, &mut SerializationReader::new(self))?
}
};
self.memory.set(memory_index, value);
@@ -1690,7 +1731,15 @@ pub(crate) fn structured_deserialize_with_transfer<'vm>(
}
// 6. Let deserialized be ? StructuredDeserialize(serializeWithTransferResult.[[Serialized]], targetRealm, memory).
- let deserialized = serialize_with_transfer_result.deserialize(target_realm, &memory)?;
+ let serialized = StructuredSerializeReader::new_ipc(
+ target_realm,
+ // SAFETY: The caller lends the record for the deserialization.
+ unsafe { serialize_with_transfer_result.serialized() },
+ Some(serialize_with_transfer_result.shared_buffers()),
+ );
+ let deserialized = with_temporary_execution_context(target_realm, || {
+ structured_deserialize_internal(cx, &serialized, &memory, false)
+ })?;
// NB: The deserialized values hold their own references to the shared memory they use. The record can outlive its
// delivery, as in a task that awaits garbage collection, so it must not keep that memory alive.
@@ -1787,7 +1836,7 @@ pub(crate) fn structured_serialize_internal<'memory>(
pub(crate) fn structured_deserialize_internal(
cx: &CallContext,
- serialized: StructuredSerializeReader,
+ serialized: &StructuredSerializeReader,
memory: &DeserializationMemory,
check_fully_consumed: bool,
) -> WebIdlResult<Value> {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs
new file mode 100644
index 00000000000..711db6ed1d4
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs
@@ -0,0 +1,196 @@
+/*
+ * 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 deserialization reads: the bytes of the values in the format of the record
+//! (libwebcommon_rust::html::serialization_records), which C++ lends, and the SharedArrayBuffers that the record shares
+//! beside them. What the deserialization reads that the record does not hold throws a "DataCloneError" DOMException in
+//! the realm that it creates its values in.
+
+use ak::Utf16String;
+use libjs_rust::api::{BigInt, Gc, Object, Realm, Value, Vm};
+use libwebcommon_rust::html::serialization_records::{DecodeError, DecodedString, RecordDecoder, SerializationType};
+
+use crate::bindings::WebIdlResult;
+use crate::html::structured_serialize::cpp::{
+ ReceivedIPCSerializationRecord, SharedBuffers, data_clone_error_from_serialization_error,
+ serializable_interface_name_from_storage_identifier, serializable_interface_storage_identifier,
+};
+
+pub(crate) struct StructuredSerializeReader<'a> {
+ decoder: RecordDecoder<'a>,
+ realm: Gc<Realm>,
+ ipc_record: Option<ReceivedIPCSerializationRecord<'a>>,
+ shared_buffers: Option<SharedBuffers>,
+}
+
+impl<'a> StructuredSerializeReader<'a> {
+ pub(crate) fn new_ipc(
+ realm: Gc<Realm>,
+ record: ReceivedIPCSerializationRecord<'a>,
+ shared_buffers: Option<SharedBuffers>,
+ ) -> Self {
+ Self {
+ decoder: RecordDecoder::new(SerializationType::Ipc, record.data()).expect("an IPC record has no prologue"),
+ realm,
+ ipc_record: Some(record),
+ shared_buffers,
+ }
+ }
+
+ /// The reader of the bytes of a storage record, which throws if they do not start with the prologue of the format.
+ pub(crate) fn new_storage(realm: Gc<Realm>, data: &'a [u8]) -> WebIdlResult<Self> {
+ let decoder = RecordDecoder::new(SerializationType::Storage, data)
+ .map_err(|error| data_clone_error_from_serialization_error(realm, error.0))?;
+ Ok(Self {
+ decoder,
+ realm,
+ ipc_record: None,
+ shared_buffers: None,
+ })
+ }
+
+ /// The realm that the deserialization creates its values in.
+ pub(crate) fn realm(&self) -> Gc<Realm> {
+ self.realm
+ }
+
+ pub(crate) fn serialization_type(&self) -> SerializationType {
+ self.decoder.serialization_type()
+ }
+
+ pub(crate) fn is_at_end(&self) -> bool {
+ self.decoder.is_at_end()
+ }
+
+ fn decoded<T>(&self, result: Result<T, DecodeError>) -> WebIdlResult<T> {
+ result.map_err(|error| data_clone_error_from_serialization_error(self.realm, error.0))
+ }
+
+ pub(crate) fn decode_u8(&self) -> WebIdlResult<u8> {
+ self.decoded(self.decoder.decode_u8())
+ }
+
+ pub(crate) fn decode_bool(&self) -> WebIdlResult<bool> {
+ self.decoded(self.decoder.decode_bool())
+ }
+
+ pub(crate) fn decode_i32(&self) -> WebIdlResult<i32> {
+ self.decoded(self.decoder.decode_i32())
+ }
+
+ pub(crate) fn decode_u16(&self) -> WebIdlResult<u16> {
+ self.decoded(self.decoder.decode_u16())
+ }
+
+ pub(crate) fn decode_u32(&self) -> WebIdlResult<u32> {
+ self.decoded(self.decoder.decode_u32())
+ }
+
+ pub(crate) fn decode_u64(&self) -> WebIdlResult<u64> {
+ self.decoded(self.decoder.decode_u64())
+ }
+
+ /// A u64 that is the size of something in memory.
+ pub(crate) fn decode_size(&self) -> WebIdlResult<usize> {
+ let size = self.decode_u64()?;
+ self.decoded(
+ usize::try_from(size)
+ .map_err(|_| DecodeError("Structured serialize integer does not fit in native integer type")),
+ )
+ }
+
+ pub(crate) fn decode_i64(&self) -> WebIdlResult<i64> {
+ self.decoded(self.decoder.decode_i64())
+ }
+
+ pub(crate) fn decode_f64(&self) -> WebIdlResult<f64> {
+ self.decoded(self.decoder.decode_f64())
+ }
+
+ pub(crate) fn decode_optional_f64(&self) -> WebIdlResult<Option<f64>> {
+ if !self.decode_bool()? {
+ return Ok(None);
+ }
+ Ok(Some(self.decode_f64()?))
+ }
+
+ pub(crate) fn decode_optional_u64(&self) -> WebIdlResult<Option<u64>> {
+ if !self.decode_bool()? {
+ return Ok(None);
+ }
+ Ok(Some(self.decode_u64()?))
+ }
+
+ pub(crate) fn decode_utf16_string(&self) -> WebIdlResult<Utf16String> {
+ Ok(match self.decoded(self.decoder.decode_utf16_string())? {
+ DecodedString::Ascii(characters) => Utf16String::from_ascii(characters),
+ DecodedString::Utf16(code_units) => Utf16String::from_utf16(&code_units),
+ })
+ }
+
+ pub(crate) fn decode_optional_utf16_string(&self) -> WebIdlResult<Option<Utf16String>> {
+ if !self.decode_bool()? {
+ return Ok(None);
+ }
+ Ok(Some(self.decode_utf16_string()?))
+ }
+
+ pub(crate) fn decode_bytes(&self) -> WebIdlResult<&'a [u8]> {
+ self.decoded(self.decoder.decode_bytes())
+ }
+
+ /// Bindings::InterfaceName, which a storage record holds as the identifier of the interface. It is the name of a
+ /// serializable interface.
+ pub(crate) fn decode_interface_name(&self) -> WebIdlResult<u16> {
+ let interface_name = match self.serialization_type() {
+ SerializationType::Ipc => {
+ let interface_name = self.decode_u16()?;
+ serializable_interface_storage_identifier(interface_name).map(|_| interface_name)
+ }
+ SerializationType::Storage => match self.decode_utf16_string()?.as_units() {
+ ak::Utf16StringUnits::Ascii(identifier) => {
+ serializable_interface_name_from_storage_identifier(identifier)
+ }
+ ak::Utf16StringUnits::Utf16(_) => None,
+ },
+ };
+ self.decoded(interface_name.ok_or(DecodeError("Unknown structured serialize interface name")))
+ }
+
+ /// A new BigInt with the value that StructuredSerializeWriter::encode_big_int() wrote.
+ pub(crate) fn decode_big_int(&self, vm: &Vm) -> WebIdlResult<Value> {
+ let (is_negative, magnitude) = self.decoded(self.decoder.decode_big_int())?;
+ Ok(Value::from_bigint(BigInt::create_from_magnitude_bytes_be(
+ vm,
+ is_negative,
+ magnitude,
+ )))
+ }
+
+ pub(crate) fn array_buffer_from_shared_memory(&self, index: u32, shared_object_id: u64) -> WebIdlResult<Value> {
+ let Some(shared_buffers) = self.shared_buffers else {
+ return Err(data_clone_error_from_serialization_error(
+ self.realm,
+ "SharedArrayBuffer side-list index out of range",
+ ));
+ };
+ shared_buffers.shared_array_buffer(self.realm, index, shared_object_id)
+ }
+
+ pub(crate) fn array_buffer_sharing_side_table_entry(
+ &self,
+ side_table_index: u32,
+ byte_length: usize,
+ preserve_growability: bool,
+ ) -> Option<Gc<Object>> {
+ self.ipc_record?
+ .shared_array_buffer(self.realm, side_table_index, byte_length, preserve_growability)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rs
index 30b5bc3a996..9cc9bc6fcfa 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rs
@@ -120,7 +120,8 @@ impl<'vm> StructuredSerializeWriter<'vm> {
match self.serialization_type() {
SerializationType::Ipc => self.encode_u16(interface_name),
SerializationType::Storage => {
- let identifier = serializable_interface_storage_identifier(interface_name);
+ let identifier =
+ serializable_interface_storage_identifier(interface_name).expect("the interface is serializable");
self.encoder
.borrow_mut()
.encode_utf16_string(Utf16StringUnits::Ascii(identifier));
diff --git a/Libraries/LibWeb/Bindings/Rust/src/webidl/dom_exception.rs b/Libraries/LibWeb/Bindings/Rust/src/webidl/dom_exception.rs
index d36aeaf7670..eb462ee6957 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/webidl/dom_exception.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/webidl/dom_exception.rs
@@ -15,7 +15,7 @@ use ak::Utf16String;
use libjs_rust::api::{Gc, Object, Realm};
use crate::bindings::WebIdlResult;
-use crate::html::structured_serialize::cpp::StructuredSerializeReader;
+use crate::html::structured_serialize::reader::StructuredSerializeReader;
use crate::html::structured_serialize::writer::StructuredSerializeWriter;
unsafe extern "C" {
@@ -71,7 +71,7 @@ pub(crate) fn serialization_steps(value: &DOMExceptionFields, serialized: &Struc
}
// https://webidl.spec.whatwg.org/#idl-DOMException
-pub(crate) fn deserialization_steps(serialized: StructuredSerializeReader) -> WebIdlResult<DOMExceptionFields> {
+pub(crate) fn deserialization_steps(serialized: &StructuredSerializeReader) -> WebIdlResult<DOMExceptionFields> {
// 1. Set value’s name to serialized.[[Name]].
let name = serialized.decode_utf16_string()?;
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 a1dc29c42d4..e975359265f 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,7 @@ use libjs_rust::api::{Gc, Object, Realm};
use super::dom_exception::{self, DOMExceptionFields};
use crate::bindings::WebIdlResult;
-use crate::html::structured_serialize::cpp::StructuredSerializeReader;
+use crate::html::structured_serialize::reader::StructuredSerializeReader;
use crate::html::structured_serialize::writer::StructuredSerializeWriter;
unsafe extern "C" {
@@ -98,7 +98,7 @@ pub(crate) fn serialization_steps(value: &QuotaExceededErrorFields, serialized:
}
// https://webidl.spec.whatwg.org/#ref-for-quotaexceedederror⑦
-pub(crate) fn deserialization_steps(serialized: StructuredSerializeReader) -> WebIdlResult<QuotaExceededErrorFields> {
+pub(crate) fn deserialization_steps(serialized: &StructuredSerializeReader) -> WebIdlResult<QuotaExceededErrorFields> {
// 1. Run the DOMException deserialization steps given serialized and value.
let dom_exception = dom_exception::deserialization_steps(serialized)?;
diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
index fa1bf31bc2a..eed519f7b85 100644
--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
@@ -78,17 +78,6 @@ JSCompletion completion_to_abi(JS::Realm& realm, WebIDL::ExceptionOr<JS::Value>
return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<JS::Value> { result.release_value() });
}
-// A value of the type that the record of a structured deserialization holds next.
-template<typename T>
-static JSCompletion deserialize_plain_value(RustSerializationReader* reader, T* out_value)
-{
- auto value = HTML::decode_or_throw_data_clone_error<T>(reader->realm, reader->serialized);
- if (value.is_exception())
- return completion_to_abi(reader->realm, value.exception());
- *out_value = value.release_value();
- return completion_to_abi(reader->realm, JS::js_undefined());
-}
-
// A value that the data holder of a transferred object holds, which its transfer steps write.
template<typename T>
static JSCompletion encode_transfer_data(RustTransferDataWriter* writer, T const& value)
@@ -130,19 +119,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_deserialize_value(RustSerializationReader*);
-bool web_bindings_deserialize_is_for_storage(RustSerializationReader*);
-JSCompletion web_bindings_deserialize_u8(RustSerializationReader*, u8* out_value);
-JSCompletion web_bindings_deserialize_i32(RustSerializationReader*, i32* out_value);
-JSCompletion web_bindings_deserialize_u32(RustSerializationReader*, u32* out_value);
-JSCompletion web_bindings_deserialize_u64(RustSerializationReader*, u64* out_value);
-JSCompletion web_bindings_deserialize_f64(RustSerializationReader*, double* out_value);
-JSCompletion web_bindings_deserialize_bool(RustSerializationReader*, bool* out_value);
-JSCompletion web_bindings_deserialize_i64(RustSerializationReader*, i64* out_value);
-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);
-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);
JSCompletion web_bindings_transfer_data_encode_transport_handle(RustTransferDataWriter*, IPC::TransportHandle const*);
@@ -229,97 +205,6 @@ bool web_bindings_extract_an_origin(JSObject* object, void* ctx, void (*on_origi
return true;
}
-// 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)
-{
- return completion_to_abi(reader->realm, HTML::structured_deserialize_internal(reader->realm->vm(), reader->serialized, reader->realm, reader->memory));
-}
-
-bool web_bindings_deserialize_is_for_storage(RustSerializationReader* reader)
-{
- return reader->serialized.type() == HTML::SerializationType::Storage;
-}
-
-JSCompletion web_bindings_deserialize_u8(RustSerializationReader* reader, u8* out_value)
-{
- return deserialize_plain_value(reader, out_value);
-}
-
-JSCompletion web_bindings_deserialize_i32(RustSerializationReader* reader, i32* out_value)
-{
- return deserialize_plain_value(reader, out_value);
-}
-
-JSCompletion web_bindings_deserialize_u32(RustSerializationReader* reader, u32* out_value)
-{
- return deserialize_plain_value(reader, out_value);
-}
-
-JSCompletion web_bindings_deserialize_u64(RustSerializationReader* reader, u64* out_value)
-{
- return deserialize_plain_value(reader, out_value);
-}
-
-JSCompletion web_bindings_deserialize_f64(RustSerializationReader* reader, double* out_value)
-{
- return deserialize_plain_value(reader, out_value);
-}
-
-JSCompletion web_bindings_deserialize_bool(RustSerializationReader* reader, bool* out_value)
-{
- return deserialize_plain_value(reader, out_value);
-}
-
-JSCompletion web_bindings_deserialize_i64(RustSerializationReader* reader, i64* out_value)
-{
- return deserialize_plain_value(reader, out_value);
-}
-
-JSCompletion web_bindings_deserialize_optional_u64(RustSerializationReader* reader, bool* out_has_value, u64* out_value)
-{
- Optional<u64> value;
- auto result = deserialize_plain_value(reader, &value);
- *out_has_value = value.has_value();
- *out_value = value.value_or(0);
- return result;
-}
-
-JSCompletion web_bindings_deserialize_bytes(RustSerializationReader* reader, void* bytes, void (*append)(void*, u8 const*, size_t))
-{
- ByteBuffer buffer;
- auto result = deserialize_plain_value(reader, &buffer);
- if (!buffer.is_empty())
- append(bytes, buffer.data(), buffer.size());
- return result;
-}
-
-JSCompletion web_bindings_deserialize_utf16_string(RustSerializationReader* reader, FlatPtr* out_string)
-{
- Utf16String string;
- auto result = deserialize_plain_value(reader, &string);
- *out_string = move(string).into_raw();
- return result;
-}
-
-// 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> {
- auto tag = TRY(HTML::decode_or_throw_data_clone_error<u8>(reader->realm, reader->serialized));
- auto name = TRY(HTML::decode_or_throw_data_clone_error<InterfaceName>(reader->realm, reader->serialized));
- if (tag != to_underlying(HTML::ValueTag::SerializableObject) || name != static_cast<InterfaceName>(interface_name))
- return WebIDL::DataCloneError::create(reader->realm, "Unexpected serializable object"_utf16);
- if (reader->serialized.type() == HTML::SerializationType::Storage) {
- auto version = TRY(HTML::decode_or_throw_data_clone_error<u64>(reader->realm, reader->serialized));
- if (version != HTML::serializable_payload_version)
- return WebIDL::DataCloneError::create(reader->realm, "Unsupported serializable payload version"_utf16);
- }
- return JS::js_undefined();
- }();
- return completion_to_abi(reader->realm, move(result));
-}
-
JSCompletion web_bindings_transfer_data_encode_bool(RustTransferDataWriter* writer, bool value)
{
return encode_transfer_data(writer, value);
diff --git a/Libraries/LibWeb/Bindings/RustSerialization.h b/Libraries/LibWeb/Bindings/RustSerialization.h
index ae789c94db9..96a9c66daf3 100644
--- a/Libraries/LibWeb/Bindings/RustSerialization.h
+++ b/Libraries/LibWeb/Bindings/RustSerialization.h
@@ -21,19 +21,6 @@ struct ImageBitmapSharedPixels;
namespace Web::Bindings {
-// 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.
-struct RustSerializationReader {
- GC::Ref<JS::Realm> realm;
- HTML::StructuredSerializeReader& serialized;
- HTML::DeserializationMemory* memory { nullptr };
-};
-
// The data holder of a transferred object. What the steps throw is created in the realm of the transfer.
struct RustTransferDataWriter {
GC::Ref<JS::Realm> realm;
diff --git a/Libraries/LibWeb/FileAPI/Blob.cpp b/Libraries/LibWeb/FileAPI/Blob.cpp
index 06184b4b4a9..8734eddb13b 100644
--- a/Libraries/LibWeb/FileAPI/Blob.cpp
+++ b/Libraries/LibWeb/FileAPI/Blob.cpp
@@ -65,7 +65,6 @@ void* web_blob_get_stream(void* realm, ReadonlyBytes);
WebIDL::Promise* web_blob_text(void* realm, ReadonlyBytes);
WebIDL::Promise* web_blob_array_buffer(void* realm, ReadonlyBytes);
WebIDL::Promise* web_blob_bytes(void* realm, ReadonlyBytes);
-JSCompletion web_blob_deserialize_byte_sequence(Bindings::RustSerializationReader*, BlobBytesABI* out_bytes);
}
GC::Ref<Blob> Blob::create(ByteBuffer bytes, Utf16String type)
@@ -255,13 +254,4 @@ void web_blob_bytes_destroy(BlobBytes* bytes)
delete bytes;
}
-JSCompletion web_blob_deserialize_byte_sequence(Bindings::RustSerializationReader* reader, BlobBytesABI* out_bytes)
-{
- auto bytes = HTML::decode_or_throw_data_clone_error<ByteBuffer>(reader->realm, reader->serialized);
- if (bytes.is_exception())
- return Bindings::completion_to_abi(reader->realm, bytes.exception());
- *out_bytes = hand_over(bytes.release_value());
- return Bindings::completion_to_abi(reader->realm, JS::js_undefined());
-}
-
}
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index c489eb1d6bb..b3bf33e0f48 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -800,7 +800,6 @@ class SharedResourceRequest;
class SharedWorker;
class SharedWorkerGlobalScope;
class Storage;
-class StructuredSerializeReader;
class SubmitEvent;
class TextTrack;
class TextTrackCue;
diff --git a/Libraries/LibWeb/HTML/StructuredSerialize.cpp b/Libraries/LibWeb/HTML/StructuredSerialize.cpp
index 34492845491..e9ff1ff54ed 100644
--- a/Libraries/LibWeb/HTML/StructuredSerialize.cpp
+++ b/Libraries/LibWeb/HTML/StructuredSerialize.cpp
@@ -8,59 +8,18 @@
*/
#include <AK/Array.h>
-#include <AK/BitCast.h>
-#include <AK/Checked.h>
#include <AK/Debug.h>
-#include <AK/Endian.h>
-#include <AK/LEB128.h>
-#include <AK/StdLibExtras.h>
-#include <AK/String.h>
-#include <AK/UnicodeUtils.h>
-#include <LibCrypto/ASN1/DER.h>
-#include <LibCrypto/BigInt/SignedBigInteger.h>
#include <LibCrypto/BigInt/UnsignedBigInteger.h>
-#include <LibGC/RootVector.h>
-#include <LibGfx/Bitmap.h>
-#include <LibGfx/Color.h>
-#include <LibIPC/File.h>
#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/ArrayBuffer.h>
-#include <LibJS/Runtime/BigInt.h>
#include <LibJS/Runtime/VM.h>
-#include <LibWeb/Bindings/CryptoKey.h>
-#include <LibWeb/Bindings/DOMException.h>
-#include <LibWeb/Bindings/DOMMatrix.h>
-#include <LibWeb/Bindings/DOMMatrixReadOnly.h>
-#include <LibWeb/Bindings/DOMPoint.h>
-#include <LibWeb/Bindings/DOMPointReadOnly.h>
-#include <LibWeb/Bindings/DOMQuad.h>
-#include <LibWeb/Bindings/DOMRect.h>
-#include <LibWeb/Bindings/DOMRectReadOnly.h>
-#include <LibWeb/Bindings/File.h>
-#include <LibWeb/Bindings/FileList.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/PredefinedColorSpace.h>
-#include <LibWeb/Bindings/QuotaExceededError.h>
-#include <LibWeb/Bindings/Transferable.h>
-#include <LibWeb/Crypto/CryptoKey.h>
-#include <LibWeb/FileAPI/Blob.h>
-#include <LibWeb/FileAPI/File.h>
-#include <LibWeb/FileAPI/FileList.h>
-#include <LibWeb/HTML/ImageData.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/StructuredSerialize.h>
#include <LibWeb/WebIDL/DOMException.h>
-#include <LibWeb/WebIDL/QuotaExceededError.h>
namespace Web::HTML {
-// Text storage uses Utf16String; converting back enforces String's strict-UTF-8 invariant.
-static ErrorOr<String> utf16_to_utf8_text(Utf16String const& text)
-{
- return text.utf16_view().to_utf8(AK::UnicodeUtils::AllowLonelySurrogates::No);
-}
-
-// Explicit return types keep these non-capturing lambdas function-pointer compatible.
+// The identifier that a storage record holds for the primary interface of each serializable object.
static constexpr auto s_serializable_storage_registry = to_array<SerializableRegistryEntry>({
{ Bindings::InterfaceName::Blob, "Blob"sv },
{ Bindings::InterfaceName::CryptoKey, "CryptoKey"sv },
@@ -85,415 +44,8 @@ ReadonlySpan<SerializableRegistryEntry> serializable_storage_registry()
return s_serializable_storage_registry.span();
}
-static ErrorOr<StringView> serializable_interface_name_to_storage_identifier(Bindings::InterfaceName interface_name)
-{
- for (auto const& entry : s_serializable_storage_registry) {
- if (entry.interface_name == interface_name)
- return entry.identifier;
- }
- return Error::from_string_literal("Invalid structured serialize interface name");
-}
-
-static ErrorOr<Bindings::InterfaceName> storage_identifier_to_serializable_interface_name(StringView identifier)
-{
- for (auto const& entry : s_serializable_storage_registry) {
- if (entry.identifier == identifier)
- return entry.interface_name;
- }
- return Error::from_string_literal("Unknown structured serialize interface name");
-}
-
-static ErrorOr<StringView> key_type_to_storage_identifier(Bindings::KeyType key_type)
-{
- switch (key_type) {
- case Bindings::KeyType::Public:
- return "public"sv;
- case Bindings::KeyType::Private:
- return "private"sv;
- case Bindings::KeyType::Secret:
- return "secret"sv;
- }
- return Error::from_string_literal("Invalid structured serialize key type");
-}
-
-static ErrorOr<Bindings::KeyType> storage_identifier_to_key_type(StringView identifier)
-{
- if (identifier == "public"sv)
- return Bindings::KeyType::Public;
- if (identifier == "private"sv)
- return Bindings::KeyType::Private;
- if (identifier == "secret"sv)
- return Bindings::KeyType::Secret;
- return Error::from_string_literal("Unknown structured serialize key type");
-}
-
-static ErrorOr<StringView> key_usage_to_storage_identifier(Bindings::KeyUsage key_usage)
-{
- switch (key_usage) {
- case Bindings::KeyUsage::Encrypt:
- return "encrypt"sv;
- case Bindings::KeyUsage::Decrypt:
- return "decrypt"sv;
- case Bindings::KeyUsage::Sign:
- return "sign"sv;
- case Bindings::KeyUsage::Verify:
- return "verify"sv;
- case Bindings::KeyUsage::DeriveKey:
- return "deriveKey"sv;
- case Bindings::KeyUsage::DeriveBits:
- return "deriveBits"sv;
- case Bindings::KeyUsage::WrapKey:
- return "wrapKey"sv;
- case Bindings::KeyUsage::UnwrapKey:
- return "unwrapKey"sv;
- case Bindings::KeyUsage::EncapsulateKey:
- return "encapsulateKey"sv;
- case Bindings::KeyUsage::EncapsulateBits:
- return "encapsulateBits"sv;
- case Bindings::KeyUsage::DecapsulateKey:
- return "decapsulateKey"sv;
- case Bindings::KeyUsage::DecapsulateBits:
- return "decapsulateBits"sv;
- }
- return Error::from_string_literal("Invalid structured serialize key usage");
-}
-
-static ErrorOr<Bindings::KeyUsage> storage_identifier_to_key_usage(StringView identifier)
-{
- if (identifier == "encrypt"sv)
- return Bindings::KeyUsage::Encrypt;
- if (identifier == "decrypt"sv)
- return Bindings::KeyUsage::Decrypt;
- if (identifier == "sign"sv)
- return Bindings::KeyUsage::Sign;
- if (identifier == "verify"sv)
- return Bindings::KeyUsage::Verify;
- if (identifier == "deriveKey"sv)
- return Bindings::KeyUsage::DeriveKey;
- if (identifier == "deriveBits"sv)
- return Bindings::KeyUsage::DeriveBits;
- if (identifier == "wrapKey"sv)
- return Bindings::KeyUsage::WrapKey;
- if (identifier == "unwrapKey"sv)
- return Bindings::KeyUsage::UnwrapKey;
- if (identifier == "encapsulateKey"sv)
- return Bindings::KeyUsage::EncapsulateKey;
- if (identifier == "encapsulateBits"sv)
- return Bindings::KeyUsage::EncapsulateBits;
- if (identifier == "decapsulateKey"sv)
- return Bindings::KeyUsage::DecapsulateKey;
- if (identifier == "decapsulateBits"sv)
- return Bindings::KeyUsage::DecapsulateBits;
- return Error::from_string_literal("Unknown structured serialize key usage");
-}
-
-static ErrorOr<StringView> color_space_to_storage_identifier(Bindings::PredefinedColorSpace color_space)
-{
- switch (color_space) {
- case Bindings::PredefinedColorSpace::Srgb:
- return "srgb"sv;
- case Bindings::PredefinedColorSpace::SrgbLinear:
- return "srgb-linear"sv;
- case Bindings::PredefinedColorSpace::DisplayP3:
- return "display-p3"sv;
- case Bindings::PredefinedColorSpace::DisplayP3Linear:
- return "display-p3-linear"sv;
- }
- return Error::from_string_literal("Invalid structured serialize color space");
-}
-
-static ErrorOr<Bindings::PredefinedColorSpace> storage_identifier_to_color_space(StringView identifier)
-{
- if (identifier == "srgb"sv)
- return Bindings::PredefinedColorSpace::Srgb;
- if (identifier == "srgb-linear"sv)
- return Bindings::PredefinedColorSpace::SrgbLinear;
- if (identifier == "display-p3"sv)
- return Bindings::PredefinedColorSpace::DisplayP3;
- if (identifier == "display-p3-linear"sv)
- return Bindings::PredefinedColorSpace::DisplayP3Linear;
- return Error::from_string_literal("Unknown structured serialize color space");
-}
-
-static ErrorOr<StringView> bitmap_format_to_storage_identifier(Gfx::BitmapFormat format)
-{
- switch (format) {
- case Gfx::BitmapFormat::Invalid:
- break;
- case Gfx::BitmapFormat::BGRx8888:
- return "BGRx8888"sv;
- case Gfx::BitmapFormat::BGRA8888:
- return "BGRA8888"sv;
- case Gfx::BitmapFormat::RGBx8888:
- return "RGBx8888"sv;
- case Gfx::BitmapFormat::RGBA8888:
- return "RGBA8888"sv;
- }
- return Error::from_string_literal("Invalid structured serialize bitmap format");
-}
-
-static ErrorOr<Gfx::BitmapFormat> storage_identifier_to_bitmap_format(StringView identifier)
-{
- if (identifier == "BGRx8888"sv)
- return Gfx::BitmapFormat::BGRx8888;
- if (identifier == "BGRA8888"sv)
- return Gfx::BitmapFormat::BGRA8888;
- if (identifier == "RGBx8888"sv)
- return Gfx::BitmapFormat::RGBx8888;
- if (identifier == "RGBA8888"sv)
- return Gfx::BitmapFormat::RGBA8888;
- return Error::from_string_literal("Unknown structured serialize bitmap format");
-}
-
-static ErrorOr<StringView> alpha_type_to_storage_identifier(Gfx::AlphaType alpha_type)
-{
- switch (alpha_type) {
- case Gfx::AlphaType::Premultiplied:
- return "premultiplied"sv;
- case Gfx::AlphaType::Unpremultiplied:
- return "unpremultiplied"sv;
- }
- return Error::from_string_literal("Invalid structured serialize alpha type");
-}
-
-static ErrorOr<Gfx::AlphaType> storage_identifier_to_alpha_type(StringView identifier)
-{
- if (identifier == "premultiplied"sv)
- return Gfx::AlphaType::Premultiplied;
- if (identifier == "unpremultiplied"sv)
- return Gfx::AlphaType::Unpremultiplied;
- return Error::from_string_literal("Unknown structured serialize alpha type");
-}
-
-class StructuredSerializeDataDecoder {
-public:
- AK_ALLOC_WITH_KMALLOC;
-
- virtual ~StructuredSerializeDataDecoder() = default;
-
- virtual SerializationType type() const = 0;
-
- // True once all input has been consumed. Only the storage path checks this (to reject trailing bytes).
- virtual bool is_at_end() const { return true; }
-
- virtual ErrorOr<void> decode(bool&) = 0;
- virtual ErrorOr<void> decode(u8&) = 0;
- virtual ErrorOr<void> decode(u16&) = 0;
- virtual ErrorOr<void> decode(i32&) = 0;
- virtual ErrorOr<void> decode(u32&) = 0;
- virtual ErrorOr<void> decode(i64&) = 0;
- virtual ErrorOr<void> decode(u64&) = 0;
- virtual ErrorOr<void> decode(double&) = 0;
- virtual ErrorOr<void> decode(Utf16String&) = 0;
- virtual ErrorOr<void> decode(ByteBuffer&) = 0;
-};
-
-class IPCStructuredSerializeDataDecoder final : public StructuredSerializeDataDecoder {
-public:
- explicit IPCStructuredSerializeDataDecoder(IPCSerializationRecord const& record)
- : m_decoder(record)
- {
- }
-
- explicit IPCStructuredSerializeDataDecoder(TransferDataEncoder&& data_holder)
- : m_decoder(move(data_holder))
- {
- }
-
- virtual SerializationType type() const override { return SerializationType::IPC; }
-
- virtual ErrorOr<void> decode(bool& value) override { return decode_from_ipc(value); }
- virtual ErrorOr<void> decode(u8& value) override { return decode_from_ipc(value); }
- virtual ErrorOr<void> decode(u16& value) override { return decode_from_ipc(value); }
- virtual ErrorOr<void> decode(i32& value) override { return decode_from_ipc(value); }
- virtual ErrorOr<void> decode(u32& value) override { return decode_from_ipc(value); }
- virtual ErrorOr<void> decode(i64& value) override { return decode_from_ipc(value); }
- virtual ErrorOr<void> decode(u64& value) override { return decode_from_ipc(value); }
- virtual ErrorOr<void> decode(double& value) override { return decode_from_ipc(value); }
- virtual ErrorOr<void> decode(Utf16String& value) override { return decode_from_ipc(value); }
- virtual ErrorOr<void> decode(ByteBuffer& value) override
- {
- value = TRY(m_decoder.decode<ByteBuffer>());
- return {};
- }
-
-private:
- template<typename T>
- ErrorOr<void> decode_from_ipc(T& value)
- {
- value = TRY(m_decoder.decode<T>());
- return {};
- }
-
- TransferDataDecoder m_decoder;
-};
-
-class StorageStructuredSerializeDataDecoder final : public StructuredSerializeDataDecoder {
-public:
- explicit StorageStructuredSerializeDataDecoder(StorageSerializationRecord const& record)
- : m_stream(record.data.span())
- {
- auto magic = read_bytes(sizeof(storage_format_magic));
- if (magic.is_error()) {
- m_error = magic.release_error();
- return;
- }
- if (magic.value() != storage_format_magic) {
- m_error = Error::from_string_literal("Invalid structured serialize storage magic");
- return;
- }
-
- u64 version = 0;
- if (auto result = decode(version); result.is_error()) {
- m_error = result.release_error();
- return;
- }
- if (version != storage_format_version) {
- m_error = Error::from_string_literal("Unsupported structured serialize storage version");
- return;
- }
-
- u64 flags = 0;
- if (auto result = decode(flags); result.is_error()) {
- m_error = result.release_error();
- return;
- }
- if (flags != storage_format_flags)
- m_error = Error::from_string_literal("Unsupported structured serialize storage flags");
- }
-
- virtual SerializationType type() const override { return SerializationType::Storage; }
- virtual bool is_at_end() const override { return m_stream.is_eof(); }
-
- virtual ErrorOr<void> decode(bool& result) override
- {
- u8 value = 0;
- TRY(decode(value));
- if (value > 1)
- return Error::from_string_literal("Invalid structured serialize bool");
- result = value != 0;
- return {};
- }
-
- virtual ErrorOr<void> decode(u8& value) override
- {
- auto bytes = TRY(read_bytes(sizeof(u8)));
- value = bytes[0];
- return {};
- }
-
- virtual ErrorOr<void> decode(u16& value) override { return read_leb128(value); }
-
- virtual ErrorOr<void> decode(u32& value) override { return read_leb128(value); }
-
- virtual ErrorOr<void> decode(i32& value) override { return read_leb128(value); }
-
- virtual ErrorOr<void> decode(u64& value) override { return read_leb128(value); }
-
- virtual ErrorOr<void> decode(i64& value) override { return read_leb128(value); }
-
- virtual ErrorOr<void> decode(double& value) override
- {
- u64 raw_value = 0;
- TRY(read_little_endian(raw_value));
- value = bit_cast<double>(raw_value);
- return {};
- }
-
- virtual ErrorOr<void> decode(Utf16String& string) override
- {
- u64 header = 0;
- TRY(decode(header));
- bool is_ascii = (header & 1) != 0;
- size_t length = TRY(host_size_from_stable_size(header >> 1));
- if (length == 0) {
- string = {};
- return {};
- }
- // Validate the byte count before try_resize(), which multiplies length without an overflow check.
- Checked<size_t> byte_count = length;
- if (!is_ascii)
- byte_count *= sizeof(u16);
- if (byte_count.has_overflow() || byte_count.value() > m_stream.remaining())
- return Error::from_string_literal("Truncated structured serialize storage record");
- auto bytes = TRY(read_bytes(byte_count.value()));
- if (is_ascii) {
- if (!StringView { bytes }.is_ascii())
- return Error::from_string_literal("Invalid ASCII in structured serialize storage record");
- string = Utf16String::from_ascii_without_validation(bytes);
- return {};
- }
- // The stream offset can be odd, so the bytes cannot be viewed as char16_t in place.
- Vector<char16_t> code_units;
- TRY(code_units.try_resize(length));
- if constexpr (AK::HostIsLittleEndian) {
- memcpy(code_units.data(), bytes.data(), byte_count.value());
- } else {
- for (size_t i = 0; i < length; ++i)
- code_units[i] = static_cast<char16_t>(bytes[2 * i] | (bytes[2 * i + 1] << 8));
- }
- string = Utf16String::from_utf16({ code_units.data(), code_units.size() });
- return {};
- }
-
- virtual ErrorOr<void> decode(ByteBuffer& buffer) override
- {
- auto length = TRY(decode_size());
- auto bytes = TRY(read_bytes(length));
- buffer = TRY(ByteBuffer::copy(bytes));
- return {};
- }
-
-private:
- ErrorOr<void> fail_if_error() const
- {
- if (m_error.has_value())
- return Error::copy(m_error.value());
- return {};
- }
-
- static ErrorOr<size_t> host_size_from_stable_size(u64 size)
- {
- if (!AK::is_within_range<size_t>(size))
- return Error::from_string_literal("Structured serialize storage size does not fit on this platform");
- return static_cast<size_t>(size);
- }
-
- ErrorOr<size_t> decode_size()
- {
- u64 size = 0;
- TRY(decode(size));
- return host_size_from_stable_size(size);
- }
-
- ErrorOr<ReadonlyBytes> read_bytes(size_t size)
- {
- TRY(fail_if_error());
- return m_stream.read_in_place<u8 const>(size);
- }
-
- template<typename T>
- ErrorOr<void> read_leb128(T& value)
- {
- TRY(fail_if_error());
- value = TRY(m_stream.read_value<LEB128<T>>());
- return {};
- }
-
- template<typename T>
- ErrorOr<void> read_little_endian(T& value)
- {
- TRY(fail_if_error());
- value = TRY(m_stream.read_value<AK::LittleEndian<T>>());
- return {};
- }
-
- FixedMemoryStream m_stream;
- Optional<AK::Error> m_error;
-};
-
-// 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.
+// The same-process SharedArrayBuffer aliases of an IPCSerializationRecord. Only this file creates side tables, so a
+// record's side table is one of these.
class SharedArrayBufferSideTable final : public SameProcessSerializationSideTable {
public:
explicit SharedArrayBufferSideTable(Vector<GC::Root<JS::ArrayBuffer>> array_buffers)
@@ -523,267 +75,6 @@ ReadonlySpan<GC::Root<JS::ArrayBuffer>> same_process_shared_array_buffers(IPCSer
return static_cast<SharedArrayBufferSideTable const&>(*record.same_process_side_table).array_buffers();
}
-StructuredSerializeReader::StructuredSerializeReader(IPCSerializationRecord const& record)
- : m_decoder(make<IPCStructuredSerializeDataDecoder>(record))
- , m_shared_array_buffers(same_process_shared_array_buffers(record))
-{
-}
-
-StructuredSerializeReader::StructuredSerializeReader(StorageSerializationRecord const& record)
- : m_decoder(make<StorageStructuredSerializeDataDecoder>(record))
-{
-}
-
-StructuredSerializeReader::StructuredSerializeReader(TransferDataEncoder&& data_holder)
- : m_decoder(make<IPCStructuredSerializeDataDecoder>(move(data_holder)))
-{
-}
-
-StructuredSerializeReader::~StructuredSerializeReader() = default;
-
-SerializationType StructuredSerializeReader::type() const
-{
- return m_decoder->type();
-}
-
-bool StructuredSerializeReader::is_at_end() const
-{
- return m_decoder->is_at_end();
-}
-
-template<typename T>
-static ErrorOr<void> decode_value(StructuredSerializeDataDecoder& decoder, T& value)
-requires requires { decoder.decode(value); }
-{
- return decoder.decode(value);
-}
-
-static ErrorOr<void> decode_value(StructuredSerializeDataDecoder& decoder, int& value)
-{
- i32 decoded = 0;
- TRY(decoder.decode(decoded));
- if (!AK::is_within_range<int>(decoded))
- return Error::from_string_literal("Structured serialize i32 does not fit in int");
- value = static_cast<int>(decoded);
- return {};
-}
-
-template<typename NativeType, typename WireType>
-static ErrorOr<void> decode_native_integer(StructuredSerializeDataDecoder& decoder, NativeType& value)
-{
- WireType decoded = 0;
- TRY(decoder.decode(decoded));
- if (!AK::is_within_range<NativeType>(decoded))
- return Error::from_string_literal("Structured serialize integer does not fit in native integer type");
- value = static_cast<NativeType>(decoded);
- return {};
-}
-
-static ErrorOr<void> decode_value(StructuredSerializeDataDecoder& decoder, long& value)
-{
- return decode_native_integer<long, i64>(decoder, value);
-}
-
-static ErrorOr<void> decode_value(StructuredSerializeDataDecoder& decoder, long long& value)
-{
- return decode_native_integer<long long, i64>(decoder, value);
-}
-
-static ErrorOr<void> decode_value(StructuredSerializeDataDecoder& decoder, unsigned long& value)
-{
- return decode_native_integer<unsigned long, u64>(decoder, value);
-}
-
-static ErrorOr<void> decode_value(StructuredSerializeDataDecoder& decoder, unsigned long long& value)
-{
- return decode_native_integer<unsigned long long, u64>(decoder, value);
-}
-
-static ErrorOr<String> decode_utf8_text(StructuredSerializeDataDecoder& decoder)
-{
- Utf16String text;
- TRY(decoder.decode(text));
- return utf16_to_utf8_text(text);
-}
-
-static ErrorOr<void> decode_value(StructuredSerializeDataDecoder& decoder, Bindings::InterfaceName& value)
-{
- if (decoder.type() == SerializationType::IPC) {
- u16 decoded = 0;
- TRY(decoder.decode(decoded));
- auto interface_name = static_cast<Bindings::InterfaceName>(decoded);
- TRY(serializable_interface_name_to_storage_identifier(interface_name));
- value = interface_name;
- return {};
- }
-
- auto identifier = TRY(decode_utf8_text(decoder));
- value = TRY(storage_identifier_to_serializable_interface_name(identifier.bytes_as_string_view()));
- return {};
-}
-
-[[maybe_unused]] static ErrorOr<void> decode_value(StructuredSerializeDataDecoder& decoder, Bindings::KeyType& value)
-{
- if (decoder.type() == SerializationType::IPC) {
- u8 decoded = 0;
- TRY(decoder.decode(decoded));
- auto key_type = static_cast<Bindings::KeyType>(decoded);
- TRY(key_type_to_storage_identifier(key_type));
- value = key_type;
- return {};
- }
-
- auto identifier = TRY(decode_utf8_text(decoder));
- value = TRY(storage_identifier_to_key_type(identifier.bytes_as_string_view()));
- return {};
-}
-
-[[maybe_unused]] static ErrorOr<void> decode_value(StructuredSerializeDataDecoder& decoder, Bindings::KeyUsage& value)
-{
- if (decoder.type() == SerializationType::IPC) {
- u8 decoded = 0;
- TRY(decoder.decode(decoded));
- auto key_usage = static_cast<Bindings::KeyUsage>(decoded);
- TRY(key_usage_to_storage_identifier(key_usage));
- value = key_usage;
- return {};
- }
-
- auto identifier = TRY(decode_utf8_text(decoder));
- value = TRY(storage_identifier_to_key_usage(identifier.bytes_as_string_view()));
- return {};
-}
-
-static ErrorOr<void> decode_value(StructuredSerializeDataDecoder& decoder, Crypto::KeyType& value)
-{
- int decoded = 0;
- TRY(decoder.decode(decoded));
- auto key_type = static_cast<Crypto::KeyType>(decoded);
- switch (key_type) {
- case Crypto::KeyType::Public:
- case Crypto::KeyType::Private:
- case Crypto::KeyType::Secret:
- value = key_type;
- return {};
- }
- return Error::from_string_literal("Unknown structured serialize key type");
-}
-
-[[maybe_unused]] static ErrorOr<void> decode_value(StructuredSerializeDataDecoder& decoder, Bindings::PredefinedColorSpace& value)
-{
- if (decoder.type() == SerializationType::IPC) {
- u8 decoded = 0;
- TRY(decoder.decode(decoded));
- auto color_space = static_cast<Bindings::PredefinedColorSpace>(decoded);
- TRY(color_space_to_storage_identifier(color_space));
- value = color_space;
- return {};
- }
-
- auto identifier = TRY(decode_utf8_text(decoder));
- value = TRY(storage_identifier_to_color_space(identifier.bytes_as_string_view()));
- return {};
-}
-
-[[maybe_unused]] static ErrorOr<void> decode_value(StructuredSerializeDataDecoder& decoder, Gfx::BitmapFormat& value)
-{
- if (decoder.type() == SerializationType::IPC) {
- u32 decoded = 0;
- TRY(decoder.decode(decoded));
- auto format = static_cast<Gfx::BitmapFormat>(decoded);
- TRY(bitmap_format_to_storage_identifier(format));
- value = format;
- return {};
- }
-
- auto identifier = TRY(decode_utf8_text(decoder));
- value = TRY(storage_identifier_to_bitmap_format(identifier.bytes_as_string_view()));
- return {};
-}
-
-[[maybe_unused]] static ErrorOr<void> decode_value(StructuredSerializeDataDecoder& decoder, Gfx::AlphaType& value)
-{
- if (decoder.type() == SerializationType::IPC) {
- u32 decoded = 0;
- TRY(decoder.decode(decoded));
- auto alpha_type = static_cast<Gfx::AlphaType>(decoded);
- TRY(alpha_type_to_storage_identifier(alpha_type));
- value = alpha_type;
- return {};
- }
-
- auto identifier = TRY(decode_utf8_text(decoder));
- value = TRY(storage_identifier_to_alpha_type(identifier.bytes_as_string_view()));
- return {};
-}
-
-template<typename T, size_t inline_capacity>
-static ErrorOr<void> decode_value(StructuredSerializeDataDecoder& decoder, Vector<T, inline_capacity>& value)
-{
- u64 size = 0;
- TRY(decoder.decode(size));
- value.clear_with_capacity();
- for (u64 i = 0; i < size; ++i) {
- T element {};
- TRY(decode_value(decoder, element));
- TRY(value.try_append(move(element)));
- }
- return {};
-}
-
-template<typename T>
-static ErrorOr<void> decode_value(StructuredSerializeDataDecoder& decoder, Optional<T>& value)
-{
- bool has_value = false;
- TRY(decoder.decode(has_value));
- if (!has_value) {
- value = OptionalNone {};
- return {};
- }
-
- T decoded {};
- TRY(decode_value(decoder, decoded));
- value = move(decoded);
- return {};
-}
-
-template<typename T>
-ErrorOr<T> StructuredSerializeReader::decode()
-{
- T value {};
- TRY(decode_value(*m_decoder, value));
- return value;
-}
-
-// 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();
-template WEB_API ErrorOr<Optional<double>> StructuredSerializeReader::decode();
-template WEB_API ErrorOr<Bindings::InterfaceName> StructuredSerializeReader::decode();
-template WEB_API ErrorOr<Bindings::KeyType> StructuredSerializeReader::decode();
-template WEB_API ErrorOr<Vector<Bindings::KeyUsage>> StructuredSerializeReader::decode();
-template WEB_API ErrorOr<Bindings::KeyUsage> StructuredSerializeReader::decode();
-template WEB_API ErrorOr<Gfx::AlphaType> StructuredSerializeReader::decode();
-template WEB_API ErrorOr<Gfx::BitmapFormat> StructuredSerializeReader::decode();
-template WEB_API ErrorOr<Bindings::PredefinedColorSpace> StructuredSerializeReader::decode();
-template WEB_API ErrorOr<Crypto::KeyType> StructuredSerializeReader::decode();
-template WEB_API ErrorOr<bool> StructuredSerializeReader::decode();
-template WEB_API ErrorOr<double> StructuredSerializeReader::decode();
-template WEB_API ErrorOr<Utf16String> StructuredSerializeReader::decode();
-template WEB_API ErrorOr<Optional<Utf16String>> StructuredSerializeReader::decode();
-template WEB_API ErrorOr<Optional<bool>> StructuredSerializeReader::decode();
-template WEB_API ErrorOr<Optional<u64>> StructuredSerializeReader::decode();
-template WEB_API ErrorOr<long> StructuredSerializeReader::decode();
-template WEB_API ErrorOr<long long> StructuredSerializeReader::decode();
-template WEB_API ErrorOr<unsigned long> StructuredSerializeReader::decode();
-template WEB_API ErrorOr<unsigned long long> StructuredSerializeReader::decode();
-template WEB_API ErrorOr<u8> StructuredSerializeReader::decode();
-template WEB_API ErrorOr<u32> StructuredSerializeReader::decode();
-template WEB_API ErrorOr<u16> StructuredSerializeReader::decode();
-
WebIDL::Exception data_clone_error_from_serialization_error(JS::Realm& realm, AK::Error const& error)
{
dbgln_if(STRUCTURED_SERIALIZE_DEBUG, "Rejecting structured serialized data: {}", error);
@@ -794,7 +85,8 @@ WebIDL::Exception data_clone_error_from_serialization_error(JS::Realm& realm, AK
extern "C" {
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_deserialize(JSVM*, void* target_realm, IPCSerializationRecord const*, Vector<Core::AnonymousBuffer> const* shared_buffers);
+JSCompletion web_rust_structured_deserialize_for_storage(JSVM*, void* target_realm, ReadonlyBytes);
JSCompletion web_rust_structured_serialize_with_transfer(JSVM*, void* realm, JSValue, JSObject* const* transfer_list, size_t count, SerializedTransferRecord** out_record);
JSCompletion web_rust_structured_deserialize_with_transfer(JSVM*, void* target_realm, SerializedTransferRecord*, Vector<GC::Root<JS::Object>>* transferred_values);
JSCompletion web_rust_structured_deserialize_with_transfer_internal(JSVM*, void* target_realm, TransferDataDecoder*);
@@ -880,30 +172,13 @@ StorageSerializationRecord structured_serialize_undefined_or_null_for_storage(JS
WebIDL::ExceptionOr<JS::Value> structured_deserialize(JS::VM& vm, IPCSerializationRecord const& serialized, JS::Realm& target_realm, Vector<Core::AnonymousBuffer> const* shared_buffers)
{
TemporaryExecutionContext execution_context { target_realm };
-
- StructuredSerializeReader decoder { serialized };
- if (shared_buffers)
- decoder.set_shared_buffers(*shared_buffers);
- return structured_deserialize_internal(vm, decoder, target_realm);
+ return TRY(JS::HostABI::completion_from_abi<JS::Value>(web_rust_structured_deserialize(JS::HostABI::vm_to_abi(vm), &target_realm, &serialized, shared_buffers)));
}
WebIDL::ExceptionOr<JS::Value> structured_deserialize(JS::VM& vm, StorageSerializationRecord const& serialized, JS::Realm& target_realm)
{
TemporaryExecutionContext execution_context { target_realm };
-
- StructuredSerializeReader decoder { serialized };
- return structured_deserialize_internal(vm, decoder, target_realm, nullptr, CheckFullyConsumed::Yes);
-}
-
-WebIDL::ExceptionOr<JS::Value> structured_deserialize_internal(JS::VM& vm, StructuredSerializeReader& serialized, JS::Realm& target_realm, DeserializationMemory* memory, CheckFullyConsumed check_fully_consumed)
-{
- return TRY(JS::HostABI::completion_from_abi<JS::Value>(web_rust_structured_deserialize_internal(JS::HostABI::vm_to_abi(vm), &target_realm, &serialized, memory, check_fully_consumed == CheckFullyConsumed::Yes)));
-}
-
-TransferDataDecoder::TransferDataDecoder(IPCSerializationRecord const& record)
- : m_stream(record.data.span())
- , m_decoder(m_stream, m_attachments)
-{
+ return TRY(JS::HostABI::completion_from_abi<JS::Value>(web_rust_structured_deserialize_for_storage(JS::HostABI::vm_to_abi(vm), &target_realm, serialized.data.bytes())));
}
TransferDataDecoder::TransferDataDecoder(TransferDataEncoder&& data_holder)
@@ -932,12 +207,4 @@ WebIDL::ExceptionOr<::Crypto::UnsignedBigInteger> TransferDataDecoder::decode_un
return ::Crypto::UnsignedBigInteger::import_data(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));
- if (buffer.is_empty())
- return data_clone_error_from_serialization_error(realm, AK::Error::from_string_literal("Invalid BigInt"));
- return ::Crypto::SignedBigInteger::import_data(buffer);
-}
-
}
diff --git a/Libraries/LibWeb/HTML/StructuredSerialize.h b/Libraries/LibWeb/HTML/StructuredSerialize.h
index d3e69267e1c..676d0fea0b4 100644
--- a/Libraries/LibWeb/HTML/StructuredSerialize.h
+++ b/Libraries/LibWeb/HTML/StructuredSerialize.h
@@ -11,7 +11,6 @@
#include <AK/Assertions.h>
#include <AK/Error.h>
#include <AK/MemoryStream.h>
-#include <AK/NonnullOwnPtr.h>
#include <AK/Span.h>
#include <AK/StringView.h>
#include <AK/Vector.h>
@@ -37,13 +36,10 @@ class HostObject;
namespace Web::HTML {
-class StructuredSerializeDataDecoder;
-
class WEB_API TransferDataDecoder {
AK_ALLOC_WITH_KMALLOC;
public:
- explicit TransferDataDecoder(IPCSerializationRecord const&);
explicit TransferDataDecoder(TransferDataEncoder&&);
template<typename T>
@@ -70,33 +66,6 @@ private:
Vector<Core::AnonymousBuffer> const* m_shared_buffers { nullptr };
};
-class WEB_API StructuredSerializeReader {
-public:
- explicit StructuredSerializeReader(IPCSerializationRecord const&);
- explicit StructuredSerializeReader(StorageSerializationRecord const&);
- explicit StructuredSerializeReader(TransferDataEncoder&&);
- ~StructuredSerializeReader();
-
- SerializationType type() const;
- bool is_at_end() const;
-
- template<typename T>
- ErrorOr<T> decode();
-
- // The record's SharedArrayBuffer side table; empty for records that crossed a process boundary
- // and for the storage and transfer-data paths.
- ReadonlySpan<GC::Root<JS::ArrayBuffer>> shared_array_buffers() const { return m_shared_array_buffers; }
-
- // Set on the messaging path so the deserializer can map SharedArrayBuffers back to their cross-process shared memory.
- void set_shared_buffers(Vector<Core::AnonymousBuffer> const& shared_buffers) { m_shared_buffers = &shared_buffers; }
- Vector<Core::AnonymousBuffer> const* shared_buffers() const { return m_shared_buffers; }
-
-private:
- NonnullOwnPtr<StructuredSerializeDataDecoder> m_decoder;
- Vector<GC::Root<JS::ArrayBuffer>> m_shared_array_buffers;
- Vector<Core::AnonymousBuffer> const* m_shared_buffers { nullptr };
-};
-
struct StructuredSerializeOptions {
GC::RootVector<GC::Ref<JS::Object>> transfer;
};
@@ -128,21 +97,9 @@ WEB_API StorageSerializationRecord structured_serialize_undefined_or_null_for_st
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&);
-WEB_API WebIDL::ExceptionOr<JS::Value> structured_deserialize_internal(JS::VM&, StructuredSerializeReader&, JS::Realm&, DeserializationMemory* = nullptr, CheckFullyConsumed = CheckFullyConsumed::No);
WEB_API WebIDL::Exception data_clone_error_from_serialization_error(JS::Realm&, AK::Error const&);
-WebIDL::ExceptionOr<::Crypto::SignedBigInteger> decode_signed_big_integer(StructuredSerializeReader&, JS::Realm&);
-
-template<typename T>
-WebIDL::ExceptionOr<T> decode_or_throw_data_clone_error(JS::Realm& realm, StructuredSerializeReader& reader)
-{
- auto result = reader.decode<T>();
- if (result.is_error())
- return data_clone_error_from_serialization_error(realm, result.release_error());
- return result.release_value();
-}
-
// Pairs each serializable interface with its storage identifier.
struct SerializableRegistryEntry {
Bindings::InterfaceName interface_name;
@@ -218,8 +175,9 @@ WEB_API bool is_platform_object(JS::Object const&);
WEB_API WebIDL::ExceptionOr<GC::Ref<JS::HostObject>> create_transferred_platform_object(HTML::TransferType, JS::Realm&, HTML::TransferDataDecoder&);
// The deserialization steps of an interface implemented in Rust create its object from what they read, rather than
-// fill in an object that was created before them.
+// fill in an object that was created before them. The record that they read is the Rust SerializationReader that the
+// deserialization passes on.
WEB_API bool serializable_interface_is_implemented_in_rust(InterfaceName);
-WEB_API WebIDL::ExceptionOr<GC::Ref<JS::HostObject>> deserialize_rust_platform_object(InterfaceName, JS::Realm&, HTML::StructuredSerializeReader&, HTML::DeserializationMemory*);
+WEB_API WebIDL::ExceptionOr<GC::Ref<JS::HostObject>> deserialize_rust_platform_object(InterfaceName, JS::Realm&, void* serialized);
}
diff --git a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
index d5a4899ac75..4b268bbf540 100644
--- a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
+++ b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
@@ -10,11 +10,9 @@
#include <AK/Checked.h>
#include <LibCore/AnonymousBuffer.h>
-#include <LibCrypto/BigInt/SignedBigInteger.h>
#include <LibGC/RootVector.h>
#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/ArrayBuffer.h>
-#include <LibJS/Runtime/BigInt.h>
#include <LibJS/Runtime/Realm.h>
#include <LibWeb/Bindings/ImageBitmap.h>
#include <LibWeb/Bindings/Intrinsics.h>
@@ -26,14 +24,13 @@
#include <LibWeb/Bindings/WritableStream.h>
#include <LibWeb/HTML/ImageBitmap.h>
#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/StructuredSerialize.h>
#include <LibWeb/WebIDL/DOMException.h>
// 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
-// hand their bytes over to, the records that the deserializations read, the platform objects, and the side tables that
-// SharedArrayBuffers are shared through.
+// hand their bytes over to and the deserializations read the bytes of, the registry of serializable interfaces, the
+// platform objects, and the side tables that SharedArrayBuffers are shared through.
using namespace Web;
using namespace Web::HTML;
@@ -50,30 +47,16 @@ extern "C" {
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_interface_storage_identifier(u16 interface_name, ReadonlyBytes* identifier);
+bool web_structured_serialize_interface_name_from_storage_identifier(ReadonlyBytes identifier, u16* interface_name);
bool web_structured_serialize_shared_buffers_append_shared_memory(Vector<Core::AnonymousBuffer>*, JSObject* array_buffer, u32* index);
-u8 web_structured_serialize_reader_type(StructuredSerializeReader*);
-bool web_structured_serialize_reader_is_at_end(StructuredSerializeReader*);
-JSCompletion web_structured_serialize_reader_decode_u8(StructuredSerializeReader*, void* realm, u8*);
-JSCompletion web_structured_serialize_reader_decode_bool(StructuredSerializeReader*, void* realm, bool*);
-JSCompletion web_structured_serialize_reader_decode_i32(StructuredSerializeReader*, void* realm, i32*);
-JSCompletion web_structured_serialize_reader_decode_u16(StructuredSerializeReader*, void* realm, u16*);
-JSCompletion web_structured_serialize_reader_decode_u32(StructuredSerializeReader*, void* realm, u32*);
-JSCompletion web_structured_serialize_reader_decode_u64(StructuredSerializeReader*, void* realm, u64*);
-JSCompletion web_structured_serialize_reader_decode_size(StructuredSerializeReader*, void* realm, size_t*);
-JSCompletion web_structured_serialize_reader_decode_f64(StructuredSerializeReader*, void* realm, double*);
-JSCompletion web_structured_serialize_reader_decode_utf16_string(StructuredSerializeReader*, void* realm, FlatPtr*);
-JSCompletion web_structured_serialize_reader_decode_optional_utf16_string(StructuredSerializeReader*, void* realm, bool* has_value, FlatPtr*);
-JSCompletion web_structured_serialize_reader_decode_byte_buffer(StructuredSerializeReader*, void* realm, ByteBuffer** buffer);
-u8 const* web_structured_serialize_byte_buffer_data(ByteBuffer*);
+void web_structured_serialize_ipc_record_data(IPCSerializationRecord const*, ReadonlyBytes* data);
+JSObject* web_structured_serialize_ipc_record_shared_array_buffer(IPCSerializationRecord const*, void* realm, u32 side_table_index, size_t byte_length, bool preserve_growability);
+JSCompletion web_structured_serialize_shared_buffers_shared_array_buffer(Vector<Core::AnonymousBuffer> const*, void* realm, u32 index, u64 shared_object_id);
size_t web_structured_serialize_byte_buffer_size(ByteBuffer*);
JSObject* web_structured_serialize_array_buffer_from_byte_buffer(void* realm, ByteBuffer*, bool shared);
void web_structured_serialize_byte_buffer_destroy(ByteBuffer*);
-JSCompletion web_structured_serialize_reader_decode_interface_name(StructuredSerializeReader*, void* realm, u16*);
-JSCompletion web_structured_serialize_reader_decode_big_int(StructuredSerializeReader*, void* realm);
-JSCompletion web_structured_serialize_reader_array_buffer_from_shared_memory(StructuredSerializeReader*, void* realm, u32 index, u64 shared_object_id);
-JSObject* web_structured_serialize_reader_array_buffer_sharing_side_table_entry(StructuredSerializeReader*, void* realm, u32 side_table_index, size_t byte_length, bool preserve_growability);
JSCompletion web_structured_serialize_data_clone_error_from_serialization_error(void* realm, ReadonlyBytes message);
u64 web_structured_serialize_serializable_payload_version();
@@ -87,7 +70,7 @@ bool web_structured_serialize_serializable_interface_name(JSObject*, u16* interf
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*);
+JSCompletion web_structured_serialize_deserialize_rust_platform_object(u16 interface_name, void* realm, void* serialized);
bool web_structured_serialize_is_transferable(JSObject*);
bool web_structured_serialize_transferable_is_detached(JSObject*);
@@ -111,7 +94,7 @@ Vector<Core::AnonymousBuffer>* web_structured_serialize_transfer_record_shared_b
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);
-JSCompletion web_structured_serialize_transfer_record_deserialize(SerializedTransferRecord*, void* realm, DeserializationMemory*);
+IPCSerializationRecord const* web_structured_serialize_transfer_record_serialized(SerializedTransferRecord*);
void web_structured_serialize_transfer_record_clear_shared_buffers(SerializedTransferRecord*);
void web_structured_serialize_transferred_values_append(Vector<GC::Root<JS::Object>>*, JSObject*);
JSCompletion web_structured_serialize_transfer_data_decoder_decode_u8(TransferDataDecoder*, void* realm, u8*);
@@ -132,16 +115,6 @@ static JSCompletion void_completion_to_abi(JS::Realm& realm, WebIDL::ExceptionOr
return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<JS::Value> { JS::js_undefined() });
}
-template<typename T>
-static JSCompletion decode_into(JS::Realm& realm, StructuredSerializeReader& reader, T& out_value)
-{
- auto value = decode_or_throw_data_clone_error<T>(realm, reader);
- if (value.is_exception())
- return Bindings::completion_to_abi(realm, WebIDL::ExceptionOr<JS::Value> { value.release_error() });
- out_value = value.release_value();
- return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<JS::Value> { JS::js_undefined() });
-}
-
template<typename T>
static JSCompletion decode_into(JS::Realm& realm, TransferDataDecoder& decoder, T& out_value)
{
@@ -176,15 +149,26 @@ void web_structured_serialize_set_storage_record(StorageSerializationRecord* rec
record->data = MUST(ByteBuffer::copy(data));
}
-void web_structured_serialize_interface_storage_identifier(u16 interface_name, ReadonlyBytes* identifier)
+bool web_structured_serialize_interface_storage_identifier(u16 interface_name, ReadonlyBytes* identifier)
{
for (auto const& entry : serializable_storage_registry()) {
if (entry.interface_name == static_cast<Bindings::InterfaceName>(interface_name)) {
*identifier = entry.identifier.bytes();
- return;
+ return true;
}
}
- VERIFY_NOT_REACHED();
+ return false;
+}
+
+bool web_structured_serialize_interface_name_from_storage_identifier(ReadonlyBytes identifier, u16* interface_name)
+{
+ for (auto const& entry : serializable_storage_registry()) {
+ if (entry.identifier.bytes() == identifier) {
+ *interface_name = to_underlying(entry.interface_name);
+ return true;
+ }
+ }
+ return false;
}
// AD-HOC: A SharedArrayBuffer backed by cross-process shared memory shares it through the side list of a record on the
@@ -199,93 +183,9 @@ bool web_structured_serialize_shared_buffers_append_shared_memory(Vector<Core::A
return true;
}
-u8 web_structured_serialize_reader_type(StructuredSerializeReader* reader)
-{
- return to_underlying(reader->type());
-}
-
-bool web_structured_serialize_reader_is_at_end(StructuredSerializeReader* reader)
-{
- return reader->is_at_end();
-}
-
-JSCompletion web_structured_serialize_reader_decode_u8(StructuredSerializeReader* reader, void* realm, u8* value)
-{
- return decode_into(realm_from_abi(realm), *reader, *value);
-}
-
-JSCompletion web_structured_serialize_reader_decode_bool(StructuredSerializeReader* reader, void* realm, bool* value)
-{
- return decode_into(realm_from_abi(realm), *reader, *value);
-}
-
-JSCompletion web_structured_serialize_reader_decode_i32(StructuredSerializeReader* reader, void* realm, i32* value)
-{
- int decoded = 0;
- auto completion = decode_into(realm_from_abi(realm), *reader, decoded);
- *value = decoded;
- return completion;
-}
-
-JSCompletion web_structured_serialize_reader_decode_u16(StructuredSerializeReader* reader, void* realm, u16* value)
-{
- return decode_into(realm_from_abi(realm), *reader, *value);
-}
-
-JSCompletion web_structured_serialize_reader_decode_u32(StructuredSerializeReader* reader, void* realm, u32* value)
+void web_structured_serialize_ipc_record_data(IPCSerializationRecord const* record, ReadonlyBytes* data)
{
- return decode_into(realm_from_abi(realm), *reader, *value);
-}
-
-JSCompletion web_structured_serialize_reader_decode_u64(StructuredSerializeReader* reader, void* realm, u64* value)
-{
- unsigned long long decoded = 0;
- auto completion = decode_into(realm_from_abi(realm), *reader, decoded);
- *value = decoded;
- return completion;
-}
-
-JSCompletion web_structured_serialize_reader_decode_size(StructuredSerializeReader* reader, void* realm, size_t* value)
-{
- return decode_into(realm_from_abi(realm), *reader, *value);
-}
-
-JSCompletion web_structured_serialize_reader_decode_f64(StructuredSerializeReader* reader, void* realm, double* value)
-{
- return decode_into(realm_from_abi(realm), *reader, *value);
-}
-
-JSCompletion web_structured_serialize_reader_decode_utf16_string(StructuredSerializeReader* reader, void* realm, FlatPtr* string)
-{
- Utf16String decoded;
- auto completion = decode_into(realm_from_abi(realm), *reader, decoded);
- *string = move(decoded).into_raw();
- return completion;
-}
-
-JSCompletion web_structured_serialize_reader_decode_optional_utf16_string(StructuredSerializeReader* reader, void* realm, bool* has_value, FlatPtr* string)
-{
- Optional<Utf16String> decoded;
- auto completion = decode_into(realm_from_abi(realm), *reader, decoded);
- *has_value = decoded.has_value();
- *string = decoded.has_value() ? decoded.release_value().into_raw() : 0;
- return completion;
-}
-
-// The bytes of a record, decoded into a buffer of their own, which the ArrayBuffer made from them takes over.
-JSCompletion web_structured_serialize_reader_decode_byte_buffer(StructuredSerializeReader* reader, void* realm, ByteBuffer** buffer)
-{
- auto& js_realm = realm_from_abi(realm);
- auto decoded = decode_or_throw_data_clone_error<ByteBuffer>(js_realm, *reader);
- if (decoded.is_exception())
- return Bindings::completion_to_abi(js_realm, WebIDL::ExceptionOr<JS::Value> { decoded.release_error() });
- *buffer = new ByteBuffer(decoded.release_value());
- return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<JS::Value> { JS::js_undefined() });
-}
-
-u8 const* web_structured_serialize_byte_buffer_data(ByteBuffer* buffer)
-{
- return buffer->data();
+ *data = record->data.span();
}
size_t web_structured_serialize_byte_buffer_size(ByteBuffer* buffer)
@@ -305,30 +205,12 @@ void web_structured_serialize_byte_buffer_destroy(ByteBuffer* buffer)
delete buffer;
}
-JSCompletion web_structured_serialize_reader_decode_interface_name(StructuredSerializeReader* reader, void* realm, u16* interface_name)
-{
- Bindings::InterfaceName decoded {};
- auto completion = decode_into(realm_from_abi(realm), *reader, decoded);
- *interface_name = to_underlying(decoded);
- return completion;
-}
-
-JSCompletion web_structured_serialize_reader_decode_big_int(StructuredSerializeReader* reader, void* realm)
-{
- auto& js_realm = realm_from_abi(realm);
- auto big_integer = decode_signed_big_integer(*reader, js_realm);
- if (big_integer.is_exception())
- return Bindings::completion_to_abi(js_realm, WebIDL::ExceptionOr<JS::Value> { big_integer.release_error() });
- return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<JS::Value> { JS::BigInt::create(js_realm.vm(), big_integer.release_value()) });
-}
-
// AD-HOC: When the backing was transferred as cross-process shared memory, map it from the side list by index — so
// both agents reference the same bytes.
-JSCompletion web_structured_serialize_reader_array_buffer_from_shared_memory(StructuredSerializeReader* reader, void* realm, u32 index, u64 shared_object_id)
+JSCompletion web_structured_serialize_shared_buffers_shared_array_buffer(Vector<Core::AnonymousBuffer> const* shared_buffers, void* realm, u32 index, u64 shared_object_id)
{
auto& js_realm = realm_from_abi(realm);
- auto const* shared_buffers = reader->shared_buffers();
- if (!shared_buffers || index >= shared_buffers->size())
+ if (index >= shared_buffers->size())
return Bindings::completion_to_abi(js_realm, WebIDL::ExceptionOr<JS::Value> { data_clone_error_from_serialization_error(js_realm, AK::Error::from_string_literal("SharedArrayBuffer side-list index out of range")) });
return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<JS::Value> { JS::ArrayBuffer::create(js_realm, shared_buffers->at(index), shared_object_id) });
}
@@ -367,9 +249,9 @@ static Optional<JS::DataBlock> data_block_sharing_storage_with(JS::ArrayBuffer&
// A new SharedArrayBuffer that shares the storage of the buffer at the index of the record's same-process side table,
// or null if there is no such buffer, or its storage cannot be shared.
-JSObject* web_structured_serialize_reader_array_buffer_sharing_side_table_entry(StructuredSerializeReader* reader, void* realm, u32 side_table_index, size_t byte_length, bool preserve_growability)
+JSObject* web_structured_serialize_ipc_record_shared_array_buffer(IPCSerializationRecord const* record, void* realm, u32 side_table_index, size_t byte_length, bool preserve_growability)
{
- auto shared_array_buffers = reader->shared_array_buffers();
+ auto shared_array_buffers = same_process_shared_array_buffers(*record);
if (side_table_index >= shared_array_buffers.size())
return nullptr;
auto data_block = data_block_sharing_storage_with(*shared_array_buffers[side_table_index], byte_length, preserve_growability);
@@ -454,10 +336,10 @@ u8 web_structured_serialize_serializable_steps(u16 interface_name)
}
}
-JSCompletion web_structured_serialize_deserialize_rust_platform_object(u16 interface_name, void* realm, StructuredSerializeReader* reader, DeserializationMemory* memory)
+JSCompletion web_structured_serialize_deserialize_rust_platform_object(u16 interface_name, void* realm, void* serialized)
{
auto& js_realm = realm_from_abi(realm);
- auto object = Bindings::deserialize_rust_platform_object(static_cast<Bindings::InterfaceName>(interface_name), js_realm, *reader, memory);
+ auto object = Bindings::deserialize_rust_platform_object(static_cast<Bindings::InterfaceName>(interface_name), js_realm, serialized);
if (object.is_exception())
return Bindings::completion_to_abi(js_realm, WebIDL::ExceptionOr<JS::Value> { object.release_error() });
return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<JS::Value> { object.release_value() });
@@ -616,16 +498,9 @@ TransferDataDecoder* web_structured_serialize_transfer_record_take_data_holder(S
return decoder;
}
-JSCompletion web_structured_serialize_transfer_record_deserialize(SerializedTransferRecord* record, void* realm, DeserializationMemory* memory)
+IPCSerializationRecord const* web_structured_serialize_transfer_record_serialized(SerializedTransferRecord* record)
{
- auto& js_realm = realm_from_abi(realm);
- TemporaryExecutionContext execution_context { js_realm };
- StructuredSerializeReader reader { record->serialized };
- reader.set_shared_buffers(record->shared_buffers);
- auto deserialized = structured_deserialize_internal(js_realm.vm(), reader, js_realm, memory);
- if (deserialized.is_exception())
- return Bindings::completion_to_abi(js_realm, WebIDL::ExceptionOr<JS::Value> { deserialized.release_error() });
- return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<JS::Value> { deserialized.release_value() });
+ return &record->serialized;
}
void web_structured_serialize_transfer_record_clear_shared_buffers(SerializedTransferRecord* record)
diff --git a/Libraries/LibWeb/HTML/StructuredSerializeTypes.h b/Libraries/LibWeb/HTML/StructuredSerializeTypes.h
index 7846a8fb5e6..e7e67afd792 100644
--- a/Libraries/LibWeb/HTML/StructuredSerializeTypes.h
+++ b/Libraries/LibWeb/HTML/StructuredSerializeTypes.h
@@ -16,20 +16,6 @@
namespace Web::HTML {
-// 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 {
- IPC,
- Storage,
-};
-
-enum class CheckFullyConsumed : u8 {
- No,
- Yes,
-};
-
enum class TransferType : u8 {
Unknown = 0,
MessagePort = 1,
diff --git a/Libraries/LibWebCommon/Rust/src/html/serialization_records.rs b/Libraries/LibWebCommon/Rust/src/html/serialization_records.rs
index 9a81b82c0a9..4a4728115fc 100644
--- a/Libraries/LibWebCommon/Rust/src/html/serialization_records.rs
+++ b/Libraries/LibWebCommon/Rust/src/html/serialization_records.rs
@@ -16,6 +16,8 @@
//! 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 core::cell::Cell;
+
use ak::Utf16StringUnits;
/// HTML::storage_format_magic, which every storage record starts with.
@@ -192,6 +194,242 @@ impl RecordEncoder {
}
}
+fn storage_size(size: u64) -> Result<usize, DecodeError> {
+ usize::try_from(size).map_err(|_| DecodeError("Structured serialize storage size does not fit on this platform"))
+}
+
+/// Why a record cannot be read: it does not hold what reading it expects.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct DecodeError(pub &'static str);
+
+/// A string that a record holds: the characters of a string with ASCII storage, or the code units of any other.
+#[derive(Debug, PartialEq, Eq)]
+pub enum DecodedString<'a> {
+ Ascii(&'a [u8]),
+ Utf16(Vec<u16>),
+}
+
+/// The bytes of a record, from which the decode functions read what the encode functions of RecordEncoder wrote. They
+/// reject what AK's decoding of the formats rejected, as a truncated record or a varint too long for its type, and
+/// accept the varints it accepted, as one with redundant bytes.
+pub struct RecordDecoder<'a> {
+ serialization_type: SerializationType,
+ data: &'a [u8],
+ position: Cell<usize>,
+}
+
+impl<'a> RecordDecoder<'a> {
+ /// A decoder of the bytes of a record, which reads the prologue of a storage record.
+ pub fn new(serialization_type: SerializationType, data: &'a [u8]) -> Result<Self, DecodeError> {
+ let decoder = Self {
+ serialization_type,
+ data,
+ position: Cell::new(0),
+ };
+ if serialization_type == SerializationType::Storage {
+ if decoder.read_bytes(STORAGE_FORMAT_MAGIC.len())? != STORAGE_FORMAT_MAGIC {
+ return Err(DecodeError("Invalid structured serialize storage magic"));
+ }
+ if decoder.decode_u64()? != STORAGE_FORMAT_VERSION {
+ return Err(DecodeError("Unsupported structured serialize storage version"));
+ }
+ if decoder.decode_u64()? != STORAGE_FORMAT_FLAGS {
+ return Err(DecodeError("Unsupported structured serialize storage flags"));
+ }
+ }
+ Ok(decoder)
+ }
+
+ pub fn serialization_type(&self) -> SerializationType {
+ self.serialization_type
+ }
+
+ /// Whether the decoder has read every byte of the record.
+ pub fn is_at_end(&self) -> bool {
+ self.position.get() == self.data.len()
+ }
+
+ fn remaining(&self) -> usize {
+ self.data.len() - self.position.get()
+ }
+
+ fn read_bytes(&self, count: usize) -> Result<&'a [u8], DecodeError> {
+ if count > self.remaining() {
+ return Err(DecodeError("Truncated structured serialization record"));
+ }
+ let start = self.position.get();
+ self.position.set(start + count);
+ Ok(&self.data[start..start + count])
+ }
+
+ fn read_array<const N: usize>(&self) -> Result<[u8; N], DecodeError> {
+ Ok(self.read_bytes(N)?.try_into().expect("read_bytes() reads N bytes"))
+ }
+
+ /// An unsigned LEB128 varint of a value of `bits` bits, as AK::LEB128 reads one: the last byte that can hold bits
+ /// of the value ends the varint, and holds no bits that the value does not have.
+ fn read_unsigned_leb128(&self, bits: u32) -> Result<u64, DecodeError> {
+ let mut value = 0;
+ let mut shift = 0;
+ loop {
+ let byte = self.decode_u8()?;
+ value |= u64::from(byte & 0x7f) << shift;
+ if shift + 7 >= bits {
+ if u32::from(byte) >> (bits - shift) != 0 {
+ return Err(DecodeError("LEB128 varint does not fit its type"));
+ }
+ return Ok(value);
+ }
+ if byte & 0x80 == 0 {
+ return Ok(value);
+ }
+ shift += 7;
+ }
+ }
+
+ /// A signed LEB128 varint of a value of `bits` bits, as AK::LEB128 reads one: the last byte that can hold bits of
+ /// the value ends the varint, and its bits that the value does not have are copies of the sign bit.
+ fn read_signed_leb128(&self, bits: u32) -> Result<i64, DecodeError> {
+ let mut value: u64 = 0;
+ let mut shift = 0;
+ loop {
+ let byte = self.decode_u8()?;
+ value |= u64::from(byte & 0x7f) << shift;
+ if shift + 7 >= bits {
+ let sign_and_unused = ((byte << 1) as i8) >> (bits - shift);
+ if byte & 0x80 != 0 || (sign_and_unused != 0 && sign_and_unused != -1) {
+ return Err(DecodeError("LEB128 varint does not fit its type"));
+ }
+ let unused = 64 - bits;
+ return Ok(((value << unused) as i64) >> unused);
+ }
+ shift += 7;
+ if byte & 0x80 == 0 {
+ let mut value = value as i64;
+ if byte & 0x40 != 0 {
+ value |= -1 << shift;
+ }
+ return Ok(value);
+ }
+ }
+ }
+
+ /// The length of a string or of bytes: in an IPC record a u32, which is no more than the bytes of the record that
+ /// follow it, as LibIPC reads one, and in a storage record a varint.
+ fn decode_size(&self) -> Result<usize, DecodeError> {
+ match self.serialization_type {
+ SerializationType::Ipc => {
+ let size = u32::from_ne_bytes(self.read_array()?) as usize;
+ if size > self.remaining() {
+ return Err(DecodeError("IPC decode: Size exceeds the rest of the message"));
+ }
+ Ok(size)
+ }
+ SerializationType::Storage => storage_size(self.decode_u64()?),
+ }
+ }
+
+ pub fn decode_u8(&self) -> Result<u8, DecodeError> {
+ Ok(self.read_array::<1>()?[0])
+ }
+
+ pub fn decode_bool(&self) -> Result<bool, DecodeError> {
+ match self.decode_u8()? {
+ 0 => Ok(false),
+ 1 => Ok(true),
+ _ => Err(DecodeError("Invalid structured serialization bool")),
+ }
+ }
+
+ pub fn decode_u16(&self) -> Result<u16, DecodeError> {
+ match self.serialization_type {
+ SerializationType::Ipc => Ok(u16::from_ne_bytes(self.read_array()?)),
+ SerializationType::Storage => Ok(self.read_unsigned_leb128(16)? as u16),
+ }
+ }
+
+ pub fn decode_i32(&self) -> Result<i32, DecodeError> {
+ match self.serialization_type {
+ SerializationType::Ipc => Ok(i32::from_ne_bytes(self.read_array()?)),
+ SerializationType::Storage => Ok(self.read_signed_leb128(32)? as i32),
+ }
+ }
+
+ pub fn decode_u32(&self) -> Result<u32, DecodeError> {
+ match self.serialization_type {
+ SerializationType::Ipc => Ok(u32::from_ne_bytes(self.read_array()?)),
+ SerializationType::Storage => Ok(self.read_unsigned_leb128(32)? as u32),
+ }
+ }
+
+ pub fn decode_u64(&self) -> Result<u64, DecodeError> {
+ match self.serialization_type {
+ SerializationType::Ipc => Ok(u64::from_ne_bytes(self.read_array()?)),
+ SerializationType::Storage => self.read_unsigned_leb128(64),
+ }
+ }
+
+ pub fn decode_i64(&self) -> Result<i64, DecodeError> {
+ match self.serialization_type {
+ SerializationType::Ipc => Ok(i64::from_ne_bytes(self.read_array()?)),
+ SerializationType::Storage => self.read_signed_leb128(64),
+ }
+ }
+
+ pub fn decode_f64(&self) -> Result<f64, DecodeError> {
+ match self.serialization_type {
+ SerializationType::Ipc => Ok(f64::from_bits(u64::from_ne_bytes(self.read_array()?))),
+ SerializationType::Storage => Ok(f64::from_bits(u64::from_le_bytes(self.read_array()?))),
+ }
+ }
+
+ pub fn decode_utf16_string(&self) -> Result<DecodedString<'a>, DecodeError> {
+ let (has_ascii_storage, length) = match self.serialization_type {
+ SerializationType::Ipc => (self.decode_bool()?, self.decode_size()?),
+ SerializationType::Storage => {
+ let header = self.decode_u64()?;
+ (header & 1 != 0, storage_size(header >> 1)?)
+ }
+ };
+ if has_ascii_storage {
+ let characters = self.read_bytes(length)?;
+ if !characters.is_ascii() {
+ return Err(DecodeError("Invalid ASCII in structured serialization record"));
+ }
+ return Ok(DecodedString::Ascii(characters));
+ }
+ let byte_count = length
+ .checked_mul(2)
+ .ok_or(DecodeError("Truncated structured serialization record"))?;
+ let bytes = self.read_bytes(byte_count)?;
+ let code_unit_from_bytes = match self.serialization_type {
+ SerializationType::Ipc => u16::from_ne_bytes,
+ SerializationType::Storage => u16::from_le_bytes,
+ };
+ Ok(DecodedString::Utf16(
+ bytes
+ .as_chunks::<2>()
+ .0
+ .iter()
+ .map(|&bytes| code_unit_from_bytes(bytes))
+ .collect(),
+ ))
+ }
+
+ pub fn decode_bytes(&self) -> Result<&'a [u8], DecodeError> {
+ let length = self.decode_size()?;
+ self.read_bytes(length)
+ }
+
+ /// What encode_big_int() writes: whether the value is negative, which any sign but 0 says, and its magnitude.
+ pub fn decode_big_int(&self) -> Result<(bool, &'a [u8]), DecodeError> {
+ let Some((&sign, magnitude)) = self.decode_bytes()?.split_first() else {
+ return Err(DecodeError("Invalid BigInt"));
+ };
+ Ok((sign != 0, magnitude))
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -348,4 +586,197 @@ mod tests {
[0x02, 0x01, 0x05]
);
}
+
+ fn storage_record(value: &[u8]) -> Vec<u8> {
+ let mut bytes = PROLOGUE.to_vec();
+ bytes.extend_from_slice(value);
+ bytes
+ }
+
+ fn storage_decoder(bytes: &[u8]) -> RecordDecoder<'_> {
+ RecordDecoder::new(SerializationType::Storage, bytes).expect("the record has a prologue")
+ }
+
+ fn round_trip(
+ serialization_type: SerializationType,
+ encode: impl FnOnce(&mut RecordEncoder),
+ decode: impl FnOnce(&RecordDecoder),
+ ) {
+ let mut encoder = RecordEncoder::new(serialization_type);
+ encode(&mut encoder);
+ let decoder = RecordDecoder::new(serialization_type, encoder.bytes()).expect("the record has a prologue");
+ decode(&decoder);
+ assert!(decoder.is_at_end());
+ }
+
+ #[test]
+ fn every_value_round_trips_through_both_formats() {
+ for serialization_type in [SerializationType::Ipc, SerializationType::Storage] {
+ round_trip(
+ serialization_type,
+ |encoder| {
+ encoder.encode_bool(false);
+ encoder.encode_bool(true);
+ encoder.encode_u8(0xab);
+ encoder.encode_u16(0xfedc);
+ encoder.encode_i32(-12345);
+ encoder.encode_i32(i32::MIN);
+ encoder.encode_u32(0xfedc_ba98);
+ encoder.encode_u64(0x0102_0304_0506_0708);
+ encoder.encode_u64(u64::MAX);
+ encoder.encode_i64(-0x0102_0304_0506_0708);
+ encoder.encode_i64(i64::MIN);
+ encoder.encode_f64(13.5);
+ encoder.encode_f64(-0.0);
+ encoder.encode_utf16_string(Utf16StringUnits::Ascii(b"stored string"));
+ encoder.encode_utf16_string(Utf16StringUnits::Utf16(&[0x68, 0xe9, 0xd83e, 0xdeac]));
+ encoder.encode_utf16_string(Utf16StringUnits::Ascii(b""));
+ encoder.encode_bytes(&[0xde, 0xad, 0xbe, 0xef]);
+ encoder.encode_big_int(true, &[0x01, 0x00]);
+ },
+ |decoder| {
+ assert_eq!(decoder.decode_bool(), Ok(false));
+ assert_eq!(decoder.decode_bool(), Ok(true));
+ assert_eq!(decoder.decode_u8(), Ok(0xab));
+ assert_eq!(decoder.decode_u16(), Ok(0xfedc));
+ assert_eq!(decoder.decode_i32(), Ok(-12345));
+ assert_eq!(decoder.decode_i32(), Ok(i32::MIN));
+ assert_eq!(decoder.decode_u32(), Ok(0xfedc_ba98));
+ assert_eq!(decoder.decode_u64(), Ok(0x0102_0304_0506_0708));
+ assert_eq!(decoder.decode_u64(), Ok(u64::MAX));
+ assert_eq!(decoder.decode_i64(), Ok(-0x0102_0304_0506_0708));
+ assert_eq!(decoder.decode_i64(), Ok(i64::MIN));
+ assert_eq!(decoder.decode_f64(), Ok(13.5));
+ assert!(
+ decoder
+ .decode_f64()
+ .is_ok_and(|value| value == 0.0 && value.is_sign_negative())
+ );
+ assert_eq!(
+ decoder.decode_utf16_string(),
+ Ok(DecodedString::Ascii(b"stored string"))
+ );
+ assert_eq!(
+ decoder.decode_utf16_string(),
+ Ok(DecodedString::Utf16(vec![0x68, 0xe9, 0xd83e, 0xdeac]))
+ );
+ assert_eq!(decoder.decode_utf16_string(), Ok(DecodedString::Ascii(b"")));
+ assert_eq!(decoder.decode_bytes(), Ok(&[0xde, 0xad, 0xbe, 0xef][..]));
+ assert_eq!(decoder.decode_big_int(), Ok((true, &[0x01, 0x00][..])));
+ },
+ );
+ }
+ }
+
+ #[test]
+ fn a_storage_record_needs_the_prologue() {
+ assert!(RecordDecoder::new(SerializationType::Storage, &PROLOGUE).is_ok());
+ assert!(RecordDecoder::new(SerializationType::Storage, b"LBS").is_err());
+ assert!(RecordDecoder::new(SerializationType::Storage, &[b'L', b'B', b'S', b'D', 0x01, 0x00]).is_err());
+ assert!(RecordDecoder::new(SerializationType::Storage, &[b'L', b'B', b'S', b'C', 0x02, 0x00]).is_err());
+ assert!(RecordDecoder::new(SerializationType::Storage, &[b'L', b'B', b'S', b'C', 0x01, 0x01]).is_err());
+ assert!(RecordDecoder::new(SerializationType::Ipc, &[]).is_ok());
+ }
+
+ #[test]
+ fn a_record_holds_a_bool_as_0_or_1() {
+ let record = storage_record(&[0x02]);
+ assert!(storage_decoder(&record).decode_bool().is_err());
+ assert!(
+ RecordDecoder::new(SerializationType::Ipc, &[0x02]).is_ok_and(|decoder| decoder.decode_bool().is_err())
+ );
+ }
+
+ #[test]
+ fn a_varint_ends_at_the_last_byte_its_type_can_hold() {
+ // A non-canonical varint that its type can hold reads as its value.
+ let record = storage_record(&[0x81, 0x80, 0x80, 0x80, 0x00]);
+ assert_eq!(storage_decoder(&record).decode_u32(), Ok(1));
+
+ let record = storage_record(&[0xff, 0xff, 0xff, 0xff, 0x0f]);
+ assert_eq!(storage_decoder(&record).decode_u32(), Ok(u32::MAX));
+ let record = storage_record(&[0xff, 0xff, 0xff, 0xff, 0x1f]);
+ assert!(storage_decoder(&record).decode_u32().is_err());
+ let record = storage_record(&[0x80, 0x80, 0x80, 0x80, 0x80, 0x00]);
+ assert!(storage_decoder(&record).decode_u32().is_err());
+
+ let record = storage_record(&[0xff, 0xff, 0x03]);
+ assert_eq!(storage_decoder(&record).decode_u16(), Ok(u16::MAX));
+ let record = storage_record(&[0xff, 0xff, 0x07]);
+ assert!(storage_decoder(&record).decode_u16().is_err());
+
+ let record = storage_record(&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02]);
+ assert!(storage_decoder(&record).decode_u64().is_err());
+
+ let record = storage_record(&[0x80]);
+ assert!(storage_decoder(&record).decode_u64().is_err());
+ }
+
+ #[test]
+ fn a_signed_varint_sign_extends_its_last_byte() {
+ let record = storage_record(&[0xff, 0xff, 0xff, 0xff, 0x07]);
+ assert_eq!(storage_decoder(&record).decode_i32(), Ok(i32::MAX));
+ let record = storage_record(&[0x80, 0x80, 0x80, 0x80, 0x78]);
+ assert_eq!(storage_decoder(&record).decode_i32(), Ok(i32::MIN));
+ // The unused bits of the last byte differ from the sign bit.
+ let record = storage_record(&[0xff, 0xff, 0xff, 0xff, 0x0f]);
+ assert!(storage_decoder(&record).decode_i32().is_err());
+ let record = storage_record(&[0x80, 0x80, 0x80, 0x80, 0x80, 0x00]);
+ assert!(storage_decoder(&record).decode_i32().is_err());
+ let record = storage_record(&[0xff]);
+ assert!(storage_decoder(&record).decode_i32().is_err());
+
+ let record = storage_record(&[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x7f]);
+ assert_eq!(storage_decoder(&record).decode_i64(), Ok(i64::MIN));
+ let record = storage_record(&[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01]);
+ assert!(storage_decoder(&record).decode_i64().is_err());
+ }
+
+ #[test]
+ fn a_string_holds_the_characters_its_header_claims() {
+ // ASCII storage that holds a byte that is not ASCII.
+ let record = storage_record(&[0x03, 0xe9]);
+ assert!(storage_decoder(&record).decode_utf16_string().is_err());
+
+ // Fewer bytes than the length claims.
+ let record = storage_record(&[0x07, b'a', b'b']);
+ assert!(storage_decoder(&record).decode_utf16_string().is_err());
+ let record = storage_record(&[0x04, 0x41, 0x00, 0x42]);
+ assert!(storage_decoder(&record).decode_utf16_string().is_err());
+ let record = storage_record(&[0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01]);
+ assert!(storage_decoder(&record).decode_utf16_string().is_err());
+
+ // A non-canonical length.
+ let record = storage_record(&[0x85, 0x00, b'a', b'b']);
+ assert_eq!(
+ storage_decoder(&record).decode_utf16_string(),
+ Ok(DecodedString::Ascii(b"ab"))
+ );
+
+ // A string ends at its length, not at the end of the record.
+ let record = storage_record(&[0x03, b'a', b'b']);
+ let decoder = storage_decoder(&record);
+ assert_eq!(decoder.decode_utf16_string(), Ok(DecodedString::Ascii(b"a")));
+ assert!(!decoder.is_at_end());
+ }
+
+ #[test]
+ fn bytes_need_their_whole_length() {
+ let record = storage_record(&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01]);
+ assert!(storage_decoder(&record).decode_bytes().is_err());
+
+ let mut record = 3_u32.to_ne_bytes().to_vec();
+ record.extend_from_slice(&[0x01, 0x02]);
+ assert!(
+ RecordDecoder::new(SerializationType::Ipc, &record).is_ok_and(|decoder| decoder.decode_bytes().is_err())
+ );
+ }
+
+ #[test]
+ fn a_big_int_has_a_sign() {
+ let record = storage_record(&[0x00]);
+ assert!(storage_decoder(&record).decode_big_int().is_err());
+ let record = storage_record(&[0x01, 0x00]);
+ assert_eq!(storage_decoder(&record).decode_big_int(), Ok((false, &[][..])));
+ }
}
diff --git a/Meta/Generators/libweb_bindings/structured_serialize.py b/Meta/Generators/libweb_bindings/structured_serialize.py
index 5243bb076c1..3eb6229ce62 100644
--- a/Meta/Generators/libweb_bindings/structured_serialize.py
+++ b/Meta/Generators/libweb_bindings/structured_serialize.py
@@ -35,7 +35,7 @@ def write_rust_entry_point_declarations(
f"""
// The serialization steps and the deserialization steps of {interface.name}.
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*);
+JSCompletion {rust_entry_point_name(interface, "deserialization_steps")}(JSVM*, void* realm, void* serialized);
"""
)
for interface in transferable:
@@ -257,16 +257,15 @@ bool serializable_interface_is_implemented_in_rust(InterfaceName interface_name)
}
}
-WebIDL::ExceptionOr<GC::Ref<JS::HostObject>> deserialize_rust_platform_object(InterfaceName interface_name, JS::Realm& realm, HTML::StructuredSerializeReader& serialized, HTML::DeserializationMemory* memory)
+WebIDL::ExceptionOr<GC::Ref<JS::HostObject>> deserialize_rust_platform_object(InterfaceName interface_name, JS::Realm& realm, [[maybe_unused]] void* serialized)
{
- [[maybe_unused]] RustSerializationReader reader { .realm = realm, .serialized = serialized, .memory = memory };
switch (interface_name) {
"""
)
for interface in rust_serializable:
out.write(
f""" case InterfaceName::{interface.name}: {{
- auto wrapper = TRY(JS::HostABI::completion_from_abi<JS::Value>({rust_entry_point_name(interface, "deserialization_steps")}(JS::HostABI::vm_to_abi(realm.vm()), &realm, &reader)));
+ auto wrapper = TRY(JS::HostABI::completion_from_abi<JS::Value>({rust_entry_point_name(interface, "deserialization_steps")}(JS::HostABI::vm_to_abi(realm.vm()), &realm, serialized)));
return GC::Ref {{ as<JS::HostObject>(wrapper.as_object()) }};
}}
"""
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index 039f3a331e3..ab2c9c8258f 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -52,9 +52,9 @@ ALLOWED_REALM_MENTIONS = {
"FileAPI": (2, 9, "Blob glue still creates streams and buffers in selected realms"),
"HTML": (
65,
- 193,
+ 187,
"HTML algorithms still contain structured serialization, including posted-message preparation, canvas, navigation transfer/reconstruction, worker/worklet, and event realm use, and cross-origin Window/Location property functions are created in the current realm; RemoteWindow mirrors Window's postMessage; "
- "the C++ glue of the Rust structured serialization reads records and creates platform objects in a given realm",
+ "the C++ glue of the Rust structured serialization creates platform objects and SharedArrayBuffers in a given realm",
),
"IndexedDB": (
4,