Skip to content

Truly independent web browser

LibWeb: Serialize IndexedDB values with the Rust serializer

Shannon Booth437f8ce66eb2
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 e7b87b2ec3e..ef133a49f29 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs
@@ -1813,6 +1813,37 @@ pub(crate) fn structured_deserialize_with_transfer_internal(
Ok(value)
}
+// https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeforstorage
+pub(crate) fn structured_serialize_for_storage(cx: &CallContext, value: Value) -> WebIdlResult<Vec<u8>> {
+ let vm = cx.vm();
+ let memory = SerializationMemory::new(vm);
+ let serialized = StructuredSerializeWriter::new(vm, SerializationType::Storage);
+
+ // 1. Return ? StructuredSerializeInternal(value, true).
+ structured_serialize_internal(
+ vm,
+ Some(cx.realm()),
+ &serialized,
+ value,
+ true,
+ &memory,
+ AllowSharedArrayBuffers::CrossOriginIsolatedOnly,
+ )?;
+ Ok(serialized.into_storage_bytes())
+}
+
+// https://html.spec.whatwg.org/multipage/structured-data.html#structureddeserialize
+// NB: The bytes of a storage record, which throws a "DataCloneError" DOMException for bytes after its value, in the realm
+// of the call.
+pub(crate) fn structured_deserialize_for_storage(cx: &CallContext, serialized: &[u8]) -> WebIdlResult<Value> {
+ let target_realm = cx.realm();
+ let serialized = StructuredSerializeReader::new_storage(target_realm, serialized)?;
+ let memory = DeserializationMemory::new(cx.vm());
+ with_temporary_execution_context(target_realm, || {
+ structured_deserialize_internal(cx, &serialized, &memory, true)
+ })
+}
+
// https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal
pub(crate) fn structured_serialize_internal<'memory>(
vm: &Vm,
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 9cc9bc6fcfa..59eb4e92792 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/writer.rs
@@ -154,6 +154,16 @@ impl<'vm> StructuredSerializeWriter<'vm> {
record.set(self.encoder.borrow().bytes(), &self.shared_array_buffers.values());
}
+ /// The bytes of the storage record that the writer wrote, for Rust code that keeps them, as IndexedDB does.
+ pub(crate) fn into_storage_bytes(self) -> Vec<u8> {
+ assert_eq!(self.serialization_type(), SerializationType::Storage);
+ assert!(
+ self.shared_array_buffers.is_empty(),
+ "a storage record shares no SharedArrayBuffer"
+ );
+ self.encoder.into_inner().into_bytes()
+ }
+
/// Sets the storage record that C++ lends to what the writer wrote.
pub(crate) fn finish_storage_record(self, record: StorageSerializationRecord) {
assert_eq!(self.serialization_type(), SerializationType::Storage);
diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/cpp.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/cpp.rs
index 8615f31e740..8f5b87f5687 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/cpp.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/cpp.rs
@@ -6,20 +6,17 @@
//! What IndexedDB asks of LibWeb's C++ code, defined in Libraries/LibWeb/IndexedDB/RustIntegration.cpp.
-use std::rc::Rc;
-
use core::ffi::c_void;
use core::ptr::NonNull;
use ak::Utf16String;
-use libjs_rust::api::{EmbedderCell, Gc, Object, RawNativeFunctionResult, Realm, Trace, Value, Vm};
+use libjs_rust::api::{EmbedderCell, Gc, Object, Realm, Trace, Vm};
use liburl_rust::FfiOrigin;
use liburl_rust::origin::Origin;
use crate::bindings::conversions::CppInterface;
use crate::bindings::cpp_cell::CppCell;
-use crate::bindings::{CallContext, Exception, WebIdlResult};
-use crate::indexed_db::idb_record::StorageSerializationRecord;
+use crate::bindings::{CallContext, Exception};
use crate::indexed_db::internal::database::Database;
use crate::indexed_db::internal::function::{Function, FunctionCell, call_function};
use crate::indexed_db::internal::key::{Key, KeyValue};
@@ -36,13 +33,6 @@ unsafe extern "C" {
on_origin: unsafe extern "C" fn(*mut c_void, *const FfiOrigin),
) -> bool;
fn web_indexed_db_create_dom_string_list(realm: *mut c_void, strings: *const usize, count: usize) -> *mut c_void;
- fn web_indexed_db_structured_serialize_for_storage(
- realm: *mut c_void,
- value: u64,
- bytes: *mut c_void,
- append: unsafe extern "C" fn(*mut c_void, *const u8, usize),
- ) -> RawNativeFunctionResult;
- fn web_indexed_db_structured_deserialize(realm: *mut c_void, bytes: ak::Span<'_, u8>) -> RawNativeFunctionResult;
fn web_indexed_db_queue_a_database_task(cell: *mut c_void, steps: unsafe extern "C" fn(*mut c_void, *mut c_void));
fn web_indexed_db_run_in_parallel(cell: *mut c_void, steps: unsafe extern "C" fn(*mut c_void, *mut c_void));
fn web_indexed_db_main_thread_event_loop() -> *mut c_void;
@@ -136,39 +126,6 @@ pub(crate) fn create_dom_string_list(cx: &CallContext, strings: &[Utf16String])
unsafe { CppInterface::from_wrapper(Gc::from_non_null(wrapper)) }
}
-// https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeforstorage
-pub(crate) fn structured_serialize_for_storage(
- cx: &CallContext,
- value: Value,
-) -> WebIdlResult<StorageSerializationRecord> {
- unsafe extern "C" fn append(bytes: *mut c_void, data: *const u8, length: usize) {
- // SAFETY: The bytes are the Vec below, 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<u8> = Vec::new();
- // SAFETY: The realm and the value are live, and the bytes outlive the call.
- unsafe {
- web_indexed_db_structured_serialize_for_storage(
- cx.realm().as_ptr().cast(),
- value.to_raw(),
- (&raw mut bytes).cast(),
- append,
- )
- }
- .into_completion()?;
- Ok(Rc::from(bytes))
-}
-
-// https://html.spec.whatwg.org/multipage/structured-data.html#structureddeserialize
-pub(crate) fn structured_deserialize(cx: &CallContext, serialized: &StorageSerializationRecord) -> WebIdlResult<Value> {
- // SAFETY: The realm is live, and the bytes are lent for the call.
- Ok(
- unsafe { web_indexed_db_structured_deserialize(cx.realm().as_ptr().cast(), ak::Span::new(serialized)) }
- .into_completion()?,
- )
-}
-
unsafe extern "C" fn run_function(vm: *mut c_void, cell: *mut c_void) {
// SAFETY: LibWeb passes the VM and the cell of the function, which it kept alive.
let (vm, function) = unsafe {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/algorithms.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/algorithms.rs
index 218594ecaca..281829249c8 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/algorithms.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/algorithms.rs
@@ -30,9 +30,8 @@ use crate::bindings::{CallContext, Exception, MustNotThrow, WebIdlResult};
use crate::dom::event::EventInit;
use crate::file_api::blob::{AnyBlob, Blob};
use crate::file_api::file::File;
-use crate::indexed_db::cpp::{
- DomException, create_dom_string_list, structured_deserialize, structured_serialize_for_storage,
-};
+use crate::html::structured_serialize::{structured_deserialize_for_storage, structured_serialize_for_storage};
+use crate::indexed_db::cpp::{DomException, create_dom_string_list};
use crate::indexed_db::idb_cursor::{AnyIDBCursor, IDBCursorDirection};
use crate::indexed_db::idb_database::{ConnectionState, IDBDatabase, IDBTransactionDurability};
use crate::indexed_db::idb_key_range::{IDBKeyRange, key_range_from_value};
@@ -1220,7 +1219,7 @@ pub(crate) fn clone_in_realm(cx: &CallContext, value: Value, transaction: Ref<ID
let serialized = structured_serialize_for_storage(cx, value)?;
// 4. Let clone be ? StructuredDeserialize(serialized, targetRealm).
- let clone = structured_deserialize(cx, &serialized)?;
+ let clone = structured_deserialize_for_storage(cx, &serialized)?;
// 5. Set transaction’s state to active.
// NB: This is handled by the scope guard after step 2.
@@ -1956,7 +1955,7 @@ pub(crate) fn store_a_record_into_an_object_store(
// The record is stored in the object store’s list of records such that the list is sorted according to the key of the records in ascending order.
let record = ObjectStoreRecord {
key: key.clone(),
- value: structured_serialize_for_storage(cx, value).must(),
+ value: Rc::from(structured_serialize_for_storage(cx, value).must()),
};
store.store_a_record(vm, record);
@@ -1978,7 +1977,7 @@ pub(crate) fn store_a_record_into_an_object_store(
// corrupt or written by a newer format version, so treat failure as the "error occurs while
// reading the value from the underlying storage" case: a "NotReadableError" DOMException.
fn deserialize_a_stored_record(cx: &CallContext, serialized: &StorageSerializationRecord) -> WebIdlResult<Value> {
- structured_deserialize(cx, serialized).map_err(|_| {
+ structured_deserialize_for_storage(cx, serialized).map_err(|_| {
Exception::Dom(
"NotReadableError",
Utf16String::from_utf8("Stored value could not be read"),
diff --git a/Libraries/LibWeb/IndexedDB/RustIntegration.cpp b/Libraries/LibWeb/IndexedDB/RustIntegration.cpp
index 71e42d82e4b..0987c731f8f 100644
--- a/Libraries/LibWeb/IndexedDB/RustIntegration.cpp
+++ b/Libraries/LibWeb/IndexedDB/RustIntegration.cpp
@@ -20,12 +20,10 @@
#include <LibWeb/HTML/DOMStringList.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HTML/StructuredSerialize.h>
#include <LibWeb/Page/Page.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/StorageAPI/StorageKey.h>
#include <LibWeb/WebIDL/DOMException.h>
-#include <LibWeb/WebIDL/ExceptionOrUtils.h>
#include <LibWebCommon/IndexedDB/TransactionChanges.h>
// What the Rust implementation of IndexedDB asks of LibWeb's C++ code, declared on the Rust side in
@@ -42,8 +40,6 @@ void* web_indexed_db_dom_exception_from_value(JSValue);
JSObject* web_indexed_db_wrap_dom_exception(void* realm, void* exception);
bool web_indexed_db_obtain_a_storage_key(void* realm, void* ctx, void (*on_origin)(void*, URL::FFI::FfiOrigin const*));
JSObject* web_indexed_db_create_dom_string_list(void* realm, FlatPtr const* strings, size_t count);
-JSCompletion web_indexed_db_structured_serialize_for_storage(void* realm, JSValue, void* bytes, void (*append)(void*, u8 const*, size_t));
-JSCompletion web_indexed_db_structured_deserialize(void* realm, ReadonlyBytes);
void web_indexed_db_queue_a_database_task(void* cell, void (*steps)(JSVM*, void*));
void web_indexed_db_run_in_parallel(void* cell, void (*steps)(JSVM*, void*));
void* web_indexed_db_main_thread_event_loop();
@@ -103,29 +99,6 @@ JSObject* web_indexed_db_create_dom_string_list(void* realm, FlatPtr const* stri
return JS::HostABI::object_to_abi(Bindings::wrap(Bindings::host_defined_wrapper_world(js_realm), js_realm, list).ptr());
}
-// https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeforstorage
-JSCompletion web_indexed_db_structured_serialize_for_storage(void* realm, JSValue raw_value, void* bytes, void (*append)(void*, u8 const*, size_t))
-{
- auto& js_realm = *static_cast<JS::Realm*>(realm);
- auto serialized = HTML::structured_serialize_for_storage(js_realm.vm(), JS::HostABI::value_from_abi(raw_value));
- if (serialized.is_exception())
- return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<JS::Value> { WebIDL::exception_to_throw_completion(js_realm.vm(), js_realm, serialized.release_error()) });
- auto record = serialized.release_value();
- append(bytes, record.data.data(), record.data.size());
- return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<JS::Value> { JS::js_undefined() });
-}
-
-// https://html.spec.whatwg.org/multipage/structured-data.html#structureddeserialize
-JSCompletion web_indexed_db_structured_deserialize(void* realm, ReadonlyBytes bytes)
-{
- auto& js_realm = *static_cast<JS::Realm*>(realm);
- HTML::StorageSerializationRecord record { MUST(ByteBuffer::copy(bytes)) };
- auto value = HTML::structured_deserialize(js_realm.vm(), record, js_realm);
- if (value.is_exception())
- return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<JS::Value> { WebIDL::exception_to_throw_completion(js_realm.vm(), js_realm, value.release_error()) });
- return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<JS::Value> { value.release_value() });
-}
-
// https://w3c.github.io/IndexedDB/#queue-a-database-task
void web_indexed_db_queue_a_database_task(void* cell, void (*steps)(JSVM*, void*))
{
diff --git a/Libraries/LibWebCommon/Rust/src/html/serialization_records.rs b/Libraries/LibWebCommon/Rust/src/html/serialization_records.rs
index 4a4728115fc..a3612df13d7 100644
--- a/Libraries/LibWebCommon/Rust/src/html/serialization_records.rs
+++ b/Libraries/LibWebCommon/Rust/src/html/serialization_records.rs
@@ -91,6 +91,10 @@ impl RecordEncoder {
&self.data
}
+ pub fn into_bytes(self) -> Vec<u8> {
+ self.data
+ }
+
pub fn encode_u8(&mut self, value: u8) {
self.data.push(value);
}
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index ab2c9c8258f..1c65847b236 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -58,9 +58,8 @@ ALLOWED_REALM_MENTIONS = {
),
"IndexedDB": (
4,
- 14,
- "the C++ glue of the Rust IndexedDB creates the factory in a global's realm and serializes, deserializes, "
- "and wraps values in a given realm",
+ 12,
+ "the C++ glue of the Rust IndexedDB creates the factory in a global's realm and wraps values in a given realm",
),
"Infra": (2, 13, "JSON parse/serialization helpers still expose JS values in selected realms"),
"Internals": (3, 3, "test-only internals still expose JS-facing helper objects and promises"),