Skip to content

Truly independent web browser

LibWeb: Pass custom property stores as Arcs inside the style engine

Andreas Klingd6e336bae1c2
diff --git a/Libraries/LibWeb/Rust/src/css/cascaded_properties.rs b/Libraries/LibWeb/Rust/src/css/cascaded_properties.rs
index 82c9467de67..bf43739aea4 100644
--- a/Libraries/LibWeb/Rust/src/css/cascaded_properties.rs
+++ b/Libraries/LibWeb/Rust/src/css/cascaded_properties.rs
@@ -15,9 +15,9 @@
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
-use std::ffi::c_void;
use std::hash::BuildHasherDefault;
use std::hash::Hasher;
+use std::sync::Arc;
use crate::css::custom_properties::{CustomPropertyStore, finalize_element_custom_property};
use crate::css::parser::value_parser::{
@@ -434,19 +434,19 @@ fn custom_property_needs_resolution(value: &StyleValueData) -> bool {
}
/// Resolves the custom properties `store` declares, finalizing each registered value against
-/// `finalization`. Answers the store holding them over the parent's, which transfers one strong
-/// reference to the caller, or null where the element declares nothing that differs from the
-/// parent and may reuse its store; and what the registered values read as they computed.
-///
-/// # Safety
-/// `resolved_parent_store` must be null or a live raw `Arc` pointer to a `CustomPropertyStore`.
-pub(crate) unsafe fn resolve_declared_custom_properties(
+/// `finalization`. Answers the store holding them over the parent's, or none where the element
+/// declares nothing that differs from the parent and may reuse its store; and what the registered
+/// values read as they computed.
+pub(crate) fn resolve_declared_custom_properties(
store: &CustomPropertyStore,
- resolved_parent_store: *const c_void,
+ resolved_parent_store: Option<&Arc<CustomPropertyStore>>,
reuse_resolved_parent_if_empty: bool,
resolution_context: &mut CascadeResolutionContext,
finalization: crate::css::custom_properties::CustomPropertyFinalization<'_>,
-) -> (*const c_void, crate::css::custom_properties::RegisteredValueReads) {
+) -> (
+ Option<Arc<CustomPropertyStore>>,
+ crate::css::custom_properties::RegisteredValueReads,
+) {
let names = &store.declared_names;
let own_entry = |name_raw: &usize| {
store
@@ -468,8 +468,7 @@ pub(crate) unsafe fn resolve_declared_custom_properties(
.collect();
let mut reads = crate::css::custom_properties::RegisteredValueReads::default();
let outputs = resolve_unresolved_style_values(resolution_context, &inputs, &finalization, &mut reads);
- // SAFETY: Guaranteed by the caller.
- let resolved_parent = unsafe { resolved_parent_store.cast::<CustomPropertyStore>().as_ref() };
+ let resolved_parent = resolved_parent_store;
let resolved_values: Vec<_> = names
.iter()
.zip(outputs)
@@ -479,10 +478,9 @@ pub(crate) unsafe fn resolve_declared_custom_properties(
.map(|(name_raw, value)| (*name_raw, value))
.collect();
let rust_store = if resolved_values.is_empty() && reuse_resolved_parent_if_empty {
- std::ptr::null()
+ None
} else {
- // SAFETY: Guaranteed by the caller.
- unsafe { store.resolved_child(resolved_parent_store, resolved_values) }
+ Some(store.resolved_child(resolved_parent_store.cloned(), resolved_values))
};
(rust_store, reads)
}
diff --git a/Libraries/LibWeb/Rust/src/css/custom_properties.rs b/Libraries/LibWeb/Rust/src/css/custom_properties.rs
index b540ccce101..dc874fa5f99 100644
--- a/Libraries/LibWeb/Rust/src/css/custom_properties.rs
+++ b/Libraries/LibWeb/Rust/src/css/custom_properties.rs
@@ -723,19 +723,10 @@ impl CustomPropertyStore {
.is_some_and(|entry| entry.value.pointer().cast() == value)
}
- unsafe fn retained_parent(parent: *const c_void) -> Option<Arc<CustomPropertyStore>> {
- if parent.is_null() {
- return None;
- }
- let parent = parent.cast::<CustomPropertyStore>();
- unsafe { Arc::increment_strong_count(parent) };
- Some(unsafe { Arc::from_raw(parent) })
- }
-
fn child(
mut parent: Option<Arc<CustomPropertyStore>>,
entries: Vec<(usize, CustomPropertyEntry)>,
- ) -> *const c_void {
+ ) -> Arc<CustomPropertyStore> {
let mut own_names = HashMap::with_capacity(entries.len());
let mut own_values = HashMap::with_capacity(entries.len());
let mut declared_names = Vec::with_capacity(entries.len());
@@ -776,24 +767,21 @@ impl CustomPropertyStore {
0
};
- Arc::into_raw(Arc::new(CustomPropertyStore {
+ Arc::new(CustomPropertyStore {
own_values,
declared_names,
own_names,
inheritance_parent,
parent,
ancestor_count,
- }))
- .cast()
+ })
}
- /// # Safety
- /// `parent` must be null or a live raw `Arc` pointer to a `CustomPropertyStore`.
- pub(crate) unsafe fn resolved_child(
+ pub(crate) fn resolved_child(
&self,
- parent: *const c_void,
+ parent: Option<Arc<CustomPropertyStore>>,
values: Vec<(usize, RetainedStyleValueData)>,
- ) -> *const c_void {
+ ) -> Arc<CustomPropertyStore> {
let entries = values
.into_iter()
.map(|(name_raw, value)| {
@@ -812,16 +800,15 @@ impl CustomPropertyStore {
)
})
.collect();
- Self::child(unsafe { Self::retained_parent(parent) }, entries)
+ Self::child(parent, entries)
}
/// # Safety
- /// `parent` must be null or a live raw `Arc` pointer, and every value pointer must remain live
- /// for this call.
+ /// Every name and value pointer must remain live for this call.
pub(crate) unsafe fn cascaded_child(
- parent: *const c_void,
+ parent: Option<Arc<CustomPropertyStore>>,
values: Vec<(usize, Arc<[u16]>, bool, *const c_void)>,
- ) -> *const c_void {
+ ) -> Arc<CustomPropertyStore> {
let entries = values
.into_iter()
.map(|(name_raw, name, important, value)| {
@@ -840,7 +827,7 @@ impl CustomPropertyStore {
)
})
.collect();
- Self::child(unsafe { Self::retained_parent(parent) }, entries)
+ Self::child(parent, entries)
}
}
@@ -3511,8 +3498,6 @@ mod tests {
},
)],
);
- // SAFETY: child returns one owned Arc reference.
- let store = unsafe { Arc::from_raw(store.cast::<CustomPropertyStore>()) };
let value = store.get(0).unwrap().value.clone();
drop(store);
assert!(matches!(value.data(), StyleValueData::Number { value } if *value == 1.0));
diff --git a/Libraries/LibWeb/Rust/src/css/style/bridge.rs b/Libraries/LibWeb/Rust/src/css/style/bridge.rs
index e855f2fb6fa..b67ffd83c1d 100644
--- a/Libraries/LibWeb/Rust/src/css/style/bridge.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/bridge.rs
@@ -1269,22 +1269,17 @@ pub unsafe extern "C" fn style_engine_note_custom_property_environment(
}
/// [`style_engine_note_custom_property_environment`] on `engine`.
-///
-/// # Safety
-/// As for [`style_engine_note_custom_property_environment`], for the arguments after `engine`.
-pub unsafe fn note_custom_property_environment(
+pub fn note_custom_property_environment(
engine: &mut StyleEngine,
identity: u64,
- store: *const c_void,
+ store: Option<&std::sync::Arc<crate::css::custom_properties::CustomPropertyStore>>,
inheritable: u64,
- inheritable_store: *const c_void,
+ inheritable_store: Option<&std::sync::Arc<crate::css::custom_properties::CustomPropertyStore>>,
) {
- unsafe {
- engine.custom_property_environments.retain(identity, store);
- engine
- .custom_property_environments
- .note_inheritable(identity, inheritable, inheritable_store);
- }
+ engine.custom_property_environments.retain(identity, store);
+ engine
+ .custom_property_environments
+ .note_inheritable(identity, inheritable, inheritable_store);
}
/// The environment a child inherits from one the engine resolved: itself, unless a registration
@@ -2014,7 +2009,7 @@ pub(crate) fn publish_computed_groups_from_inputs(
unsafe {
engine
.custom_property_environments
- .retain(custom_property_environment, custom_property_store);
+ .retain_raw(custom_property_environment, custom_property_store);
}
if pseudo_kind == u8::MAX
&& let Some(node) = StyleNodeID::from_raw(node)
@@ -2475,7 +2470,7 @@ pub unsafe extern "C" fn style_engine_republish_record_environment(
let Some(node) = StyleNodeID::from_raw(node) else {
return (0, None);
};
- unsafe { engine.custom_property_environments.retain(environment, store) };
+ unsafe { engine.custom_property_environments.retain_raw(environment, store) };
let Some(style_record) = engine.republish_record_environment(node, environment) else {
return (0, None);
};
@@ -2748,11 +2743,8 @@ pub unsafe extern "C" fn style_engine_borrow_engine_custom_property_environment(
let Some((store, parent_identity)) = engine.custom_property_environments.engine_environment(identity) else {
return std::ptr::null();
};
- unsafe {
- std::sync::Arc::increment_strong_count(store.cast::<crate::css::custom_properties::CustomPropertyStore>());
- *parent = parent_identity;
- }
- store
+ unsafe { *parent = parent_identity };
+ std::sync::Arc::into_raw(std::sync::Arc::clone(store)).cast()
})
}
diff --git a/Libraries/LibWeb/Rust/src/css/style/container_queries.rs b/Libraries/LibWeb/Rust/src/css/style/container_queries.rs
index d857796e557..d0fe20091e4 100644
--- a/Libraries/LibWeb/Rust/src/css/style/container_queries.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/container_queries.rs
@@ -507,8 +507,7 @@ impl RetainedState {
.unwrap_or_default()
{
0 => None,
- // SAFETY: The store is live while the container's record names its environment.
- identity => Some(unsafe { &*self.custom_property_environments.store(identity)?.cast() }),
+ identity => Some(&**self.custom_property_environments.store(identity)?),
};
let values = crate::css::computed_value_views::ComputedValuesView::new(
crate::css::host_shared::SharedPayload::as_pointer_slice(view.payloads),
diff --git a/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs b/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs
index a48ae29f35e..9a54cf5aef6 100644
--- a/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs
@@ -1470,13 +1470,13 @@ impl RetainedState {
/// names an environment keeps its store alive, and C++ makes a store for every environment,
/// so a parent's is always held. `None` if it is not anyway: an environment built over no
/// store would drop every custom property the node inherits.
- fn inherited_environment_store(&self, environment: u64) -> Option<*const c_void> {
+ fn inherited_environment_store(&self, environment: u64) -> Option<Option<Arc<CustomPropertyStore>>> {
if environment == 0 {
- return Some(std::ptr::null());
+ return Some(None);
}
let store = self.custom_property_environments.store(environment);
debug_assert!(store.is_some(), "an inherited environment keeps its store");
- store
+ store.cloned().map(Some)
}
/// The environment of a node the engine computes a record for: the one it inherits of its
@@ -1739,7 +1739,7 @@ impl RetainedState {
self.counters.bump(Counter::EngineCustomPropertyEnvironmentBails);
return Err(Unanswered::Refused);
};
- let parent = unsafe { parent_store.cast::<CustomPropertyStore>().as_ref() };
+ let parent = parent_store.as_deref();
let mut values = Vec::with_capacity(cascaded.len());
for (declared, value) in &cascaded {
let Some(name) = self.declared_custom_property_name(declared.name) else {
@@ -1770,9 +1770,8 @@ impl RetainedState {
// The attributes an `attr()` among the declarations reads.
let attributes =
reads_attributes.then(|| SubstitutionAttributes::of(&self.facts, node, self.html_element_namespace));
- // SAFETY: The parent store is live for as long as a record names its environment, and the
- // values are the program's interned values, live for the call.
- let cascaded_store = unsafe { Arc::from_raw(CustomPropertyStore::cascaded_child(parent_store, values).cast()) };
+ // SAFETY: The values are the program's interned values, live for the call.
+ let cascaded_store = unsafe { CustomPropertyStore::cascaded_child(parent_store.clone(), values) };
let mut random_function_index = 0_usize;
let mut parse_context = registry_ref.parse_context(&mut random_function_index);
parse_context.in_quirks_mode = inputs.in_quirks_mode;
@@ -1783,12 +1782,10 @@ impl RetainedState {
// The custom properties a `style()` query reads are the element's style query references,
// which the host records with its record.
let mut style_query_references = None;
- // SAFETY: The store is live for as long as a record names its environment.
- let inheritance_store = unsafe { inheritance_store.cast::<CustomPropertyStore>().as_ref() };
let mut resolution_context = engine_resolution_context(
&parse_context,
Some(&cascaded_store),
- inheritance_store,
+ inheritance_store.as_deref(),
registry_ref,
attributes.as_ref(),
&media_environment,
@@ -1820,16 +1817,13 @@ impl RetainedState {
color_scheme: registered.as_ref().map_or(0, |registered| registered.color_scheme),
draw_random_base_value: Some(&draw_random_base_value),
};
- // SAFETY: The parent store is live for as long as a record names its environment.
- let (rust_store, reads) = unsafe {
- resolve_declared_custom_properties(
- &cascaded_store,
- parent_store,
- !parent_store.is_null(),
- &mut resolution_context,
- finalization,
- )
- };
+ let (rust_store, reads) = resolve_declared_custom_properties(
+ &cascaded_store,
+ parent_store.as_ref(),
+ parent_store.is_some(),
+ &mut resolution_context,
+ finalization,
+ );
drop(cascaded_store);
self.counters.bump(Counter::EngineCustomPropertyEnvironmentsResolved);
// What the registered values and style queries read beyond the element's fonts reaches
@@ -1863,22 +1857,21 @@ impl RetainedState {
},
);
}
- let identity = if rust_store.is_null() {
- inherited_environment
- } else if let Some(previous) =
- self.environment_resolving_to_the_same_values(node, pseudo, rust_store, registry_ref)
- {
- // SAFETY: The resolution handed over one strong reference to the store, which nothing else holds.
- drop(unsafe { Arc::from_raw(rust_store.cast::<CustomPropertyStore>()) });
- previous
- } else {
- unsafe {
- self.custom_property_environments.adopt_engine_environment(
- rust_store,
- inherited_environment,
- parent_store,
- registry_ref,
- )
+ let identity = match rust_store {
+ None => inherited_environment,
+ Some(rust_store) => {
+ if let Some(previous) =
+ self.environment_resolving_to_the_same_values(node, pseudo, &rust_store, registry_ref)
+ {
+ previous
+ } else {
+ self.custom_property_environments.adopt_engine_environment(
+ rust_store,
+ inherited_environment,
+ parent_store.as_deref(),
+ registry_ref,
+ )
+ }
}
};
// A viewport change reaches the records under the environment. One the element shares with
@@ -1903,7 +1896,7 @@ impl RetainedState {
&self,
node: StyleNodeID,
pseudo: Option<u8>,
- resolved: *const c_void,
+ resolved: &CustomPropertyStore,
registry: &crate::css::custom_properties::CustomPropertyRegistry,
) -> Option<u64> {
if pseudo.is_some() {
@@ -1917,14 +1910,6 @@ impl RetainedState {
return None;
}
let previous_store = self.custom_property_environments.store(previous)?;
- // SAFETY: Both stores are live: the previous one while the environment naming it is, the resolved one for
- // the call.
- let (previous_store, resolved) = unsafe {
- (
- &*previous_store.cast::<CustomPropertyStore>(),
- &*resolved.cast::<CustomPropertyStore>(),
- )
- };
(resolved.hands_down_every_value(registry) && resolved.holds_same_values_as(previous_store)).then_some(previous)
}
@@ -2070,7 +2055,9 @@ impl RetainedState {
}))
.collect();
// SAFETY: The base store is live for the sample, and the values are live for the call.
- let cascaded_store = unsafe { Arc::from_raw(CustomPropertyStore::cascaded_child(base, values).cast()) };
+ let base = unsafe { super::environment_move::retained_store(base) };
+ // SAFETY: The values are live for the call.
+ let cascaded_store = unsafe { CustomPropertyStore::cascaded_child(base.clone(), values) };
let registry = self.document_style_computation_inputs.custom_property_registry();
let mut random_function_index = 0_usize;
let mut parse_context = registry.parse_context(&mut random_function_index);
@@ -2102,15 +2089,16 @@ impl RetainedState {
draw_random_base_value: Some(&draw_random_base_value),
..finalization
};
- // SAFETY: As above.
- let (resolved, _) = unsafe {
- resolve_declared_custom_properties(&cascaded_store, base, true, &mut resolution_context, finalization)
- };
- if resolved.is_null() {
+ let (resolved, _) = resolve_declared_custom_properties(
+ &cascaded_store,
+ base.as_ref(),
+ true,
+ &mut resolution_context,
+ finalization,
+ );
+ let Some(resolved) = resolved else {
return Vec::new();
- }
- // SAFETY: The resolution hands over one strong reference to the store.
- let resolved = unsafe { Arc::from_raw(resolved.cast::<CustomPropertyStore>()) };
+ };
readers
.iter()
.filter_map(|(name, _, _)| {
@@ -2173,6 +2161,13 @@ impl RetainedState {
style_query_references: Some(style_query_references),
functions: functions.as_ref(),
};
+ // SAFETY: The stores are null or live for the sample.
+ let (store, inheritance_store) = unsafe {
+ (
+ store.cast::<CustomPropertyStore>().as_ref(),
+ inheritance_store.cast::<CustomPropertyStore>().as_ref(),
+ )
+ };
substitute_against_stores(
store,
inheritance_store,
@@ -2219,8 +2214,8 @@ impl RetainedState {
return Ok(value);
}
let store_of = |identity| match identity {
- 0 => Some(std::ptr::null()),
- identity => environments.store(identity),
+ 0 => Some(None),
+ identity => environments.store(identity).map(|store| Some(&**store)),
};
let Some(store) = store_of(environment.own) else {
counters.bump(Counter::EngineComputedRecordBailSubstitution);
@@ -2233,7 +2228,7 @@ impl RetainedState {
};
store
} else {
- std::ptr::null()
+ None
};
// The resolution reads the attributes and the custom functions only where the value does.
let inputs = SubstitutionInputs {
@@ -2257,8 +2252,8 @@ impl RetainedState {
/// source no grammar accepts, is the guaranteed-invalid value: the declaration is invalid at
/// computed-value time.
fn substitute_against_stores(
- store: *const c_void,
- inheritance_store: *const c_void,
+ store: Option<&CustomPropertyStore>,
+ inheritance_store: Option<&CustomPropertyStore>,
inputs: &SubstitutionInputs<'_>,
property: u16,
root_custom_property_name: &[u16],
@@ -2278,13 +2273,6 @@ fn substitute_against_stores(
functions.map_or(&[][..], |functions| functions.visibilities.as_slice()),
);
let mut style_query_references = inputs.style_query_references.map(std::cell::RefCell::borrow_mut);
- // SAFETY: The stores are null or live while a record names their environments.
- let (store, inheritance_store) = unsafe {
- (
- store.cast::<CustomPropertyStore>().as_ref(),
- inheritance_store.cast::<CustomPropertyStore>().as_ref(),
- )
- };
let resolution_inputs = VarResolutionInputs {
store,
inheritance_store,
diff --git a/Libraries/LibWeb/Rust/src/css/style/custom_property_environments.rs b/Libraries/LibWeb/Rust/src/css/style/custom_property_environments.rs
index c6d2db9a645..6c78275abcd 100644
--- a/Libraries/LibWeb/Rust/src/css/style/custom_property_environments.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/custom_property_environments.rs
@@ -74,49 +74,23 @@ struct MemoizedSubstitution {
}
/// One strong reference to a custom-property store, released with the handle.
-pub(crate) struct RetainedCustomPropertyStore(*const c_void);
-
-// SAFETY: The pointer is a raw `Arc<CustomPropertyStore>`, so the reference count this handle
-// owns is atomic, and `CustomPropertyStore` is itself `Send + Sync` (see the safety note on its
-// definition: store nodes are immutable after construction and only borrowed while a step
-// resolves substitution text). The handle exposes nothing but `pointer()`; it is cloned nowhere
-// and dropped only by the retained catalog and the walk's pending table, both of which are
-// settled by the serial installer.
-unsafe impl Send for RetainedCustomPropertyStore where CustomPropertyStore: Send + Sync {}
-unsafe impl Sync for RetainedCustomPropertyStore where CustomPropertyStore: Send + Sync {}
+#[derive(Clone)]
+pub(crate) struct RetainedCustomPropertyStore(Arc<CustomPropertyStore>);
impl RetainedCustomPropertyStore {
/// # Safety
/// `store` must be a live raw `Arc` pointer to a `CustomPropertyStore`.
pub(super) unsafe fn from_borrowed(store: *const c_void) -> Self {
- unsafe { Arc::increment_strong_count(store.cast::<CustomPropertyStore>()) };
- Self(store)
- }
-
- /// # Safety
- /// `store` must be a live raw `Arc` pointer whose one strong reference this handle takes over.
- unsafe fn from_transferred(store: *const c_void) -> Self {
- Self(store)
- }
-
- pub(super) fn pointer(&self) -> *const c_void {
- self.0
- }
-}
-
-/// A fork's handle holds its own strong reference.
-impl Clone for RetainedCustomPropertyStore {
- fn clone(&self) -> Self {
- // SAFETY: The handle owns a strong reference, so the store is live.
- unsafe { Arc::increment_strong_count(self.0.cast::<CustomPropertyStore>()) };
- Self(self.0)
+ let store = store.cast::<CustomPropertyStore>();
+ // SAFETY: Guaranteed by the caller.
+ unsafe {
+ Arc::increment_strong_count(store);
+ Self(Arc::from_raw(store))
+ }
}
-}
-impl Drop for RetainedCustomPropertyStore {
- fn drop(&mut self) {
- // SAFETY: The handle owns exactly one strong reference taken at construction.
- unsafe { Arc::decrement_strong_count(self.0.cast::<CustomPropertyStore>()) };
+ pub(super) fn store(&self) -> &Arc<CustomPropertyStore> {
+ &self.0
}
}
@@ -215,10 +189,20 @@ impl CustomPropertyEnvironments {
/// Keep the store behind an environment while a record names it. The first publication of an
/// identity decides its store; an identity never changes what it resolves to.
+ pub(super) fn retain(&mut self, identity: u64, store: Option<&Arc<CustomPropertyStore>>) {
+ let Some(store) = store.filter(|_| identity != 0) else {
+ return;
+ };
+ self.stores
+ .entry(identity)
+ .or_insert_with(|| RetainedCustomPropertyStore(Arc::clone(store)));
+ }
+
+ /// [`Self::retain`], for a store C++ names by its raw `Arc` pointer.
///
/// # Safety
/// `store` must be null or a live raw `Arc` pointer to a `CustomPropertyStore`.
- pub(super) unsafe fn retain(&mut self, identity: u64, store: *const c_void) {
+ pub(super) unsafe fn retain_raw(&mut self, identity: u64, store: *const c_void) {
if identity == 0 || store.is_null() {
return;
}
@@ -228,26 +212,24 @@ impl CustomPropertyEnvironments {
}
/// The store behind an environment, whether C++ published it or the engine resolved it.
- pub(super) fn store(&self, identity: u64) -> Option<*const c_void> {
+ pub(super) fn store(&self, identity: u64) -> Option<&Arc<CustomPropertyStore>> {
if identity == 0 {
return None;
}
self.stores
.get(&identity)
- .map(RetainedCustomPropertyStore::pointer)
- .or_else(|| {
- self.engine
- .get(&identity)
- .map(|environment| environment.store.pointer())
- })
+ .map(RetainedCustomPropertyStore::store)
+ .or_else(|| self.engine.get(&identity).map(|environment| environment.store.store()))
}
/// Keep the environment a child inherits from `identity`, which C++ made without the custom
/// properties a registration keeps from inheriting.
- ///
- /// # Safety
- /// `store` must be null or a live raw `Arc` pointer to a `CustomPropertyStore`.
- pub(super) unsafe fn note_inheritable(&mut self, identity: u64, inheritable: u64, store: *const c_void) {
+ pub(super) fn note_inheritable(
+ &mut self,
+ identity: u64,
+ inheritable: u64,
+ store: Option<&Arc<CustomPropertyStore>>,
+ ) {
if identity == 0 {
return;
}
@@ -256,7 +238,7 @@ impl CustomPropertyEnvironments {
self.inheritable.remove(&identity);
return;
}
- unsafe { self.retain(inheritable, store) };
+ self.retain(inheritable, store);
self.inheritable.insert(identity, inheritable);
}
@@ -271,14 +253,8 @@ impl CustomPropertyEnvironments {
let Some(overlay_store) = overlay_store else {
return base;
};
- // SAFETY: The stores are live while the identities naming them are.
- let store = unsafe {
- CustomPropertyStore::animated_values_over(
- &*overlay_store.cast::<CustomPropertyStore>(),
- self.store(base).map(|store| &*store.cast::<CustomPropertyStore>()),
- )
- };
- let identity = self.mint(Arc::into_raw(Arc::new(store)).cast(), base);
+ let store = CustomPropertyStore::animated_values_over(overlay_store, self.store(base).map(Arc::as_ref));
+ let identity = self.mint(Arc::new(store), base);
self.overlays_moved.insert((overlay, base), identity);
identity
}
@@ -301,10 +277,10 @@ impl CustomPropertyEnvironments {
}
/// An engine-resolved environment's store and the environment it was resolved over.
- pub(super) fn engine_environment(&self, identity: u64) -> Option<(*const c_void, u64)> {
+ pub(super) fn engine_environment(&self, identity: u64) -> Option<(&Arc<CustomPropertyStore>, u64)> {
self.engine
.get(&identity)
- .map(|environment| (environment.store.pointer(), environment.parent))
+ .map(|environment| (environment.store.store(), environment.parent))
}
pub(super) fn memoized(&self, inputs: &EnvironmentInputs) -> Option<u64> {
@@ -339,42 +315,36 @@ impl CustomPropertyEnvironments {
/// give it an identity of the engine's own. What its children inherit is the store without
/// the custom properties `registry` keeps from inheriting: `parent` again when nothing else
/// is left that `parent` does not hold.
- ///
- /// # Safety
- /// `store` must be a live raw `Arc` pointer whose one strong reference is transferred here,
- /// and `parent_store` null or a live one.
- pub(super) unsafe fn adopt_engine_environment(
+ pub(super) fn adopt_engine_environment(
&mut self,
- store: *const c_void,
+ store: Arc<CustomPropertyStore>,
parent: u64,
- parent_store: *const c_void,
+ parent_store: Option<&CustomPropertyStore>,
registry: &CustomPropertyRegistry,
) -> u64 {
+ let inheritable = store.inheritable(registry);
let identity = self.mint(store, parent);
- let resolved = unsafe { &*store.cast::<CustomPropertyStore>() };
- if let Some(inheritable) = resolved.inheritable(registry) {
+ if let Some(inheritable) = inheritable {
let parent_holds_every_value = inheritable.own_values.iter().all(|(&name, entry)| {
- unsafe { parent_store.cast::<CustomPropertyStore>().as_ref() }
- .is_some_and(|parent| parent.value_is_identical(name, entry.value.pointer().cast()))
+ parent_store.is_some_and(|parent| parent.value_is_identical(name, entry.value.pointer().cast()))
});
let inheritable = if parent_holds_every_value {
parent
} else {
- self.mint(Arc::into_raw(inheritable).cast(), parent)
+ self.mint(inheritable, parent)
};
self.inheritable.insert(identity, inheritable);
}
identity
}
- fn mint(&mut self, store: *const c_void, parent: u64) -> u64 {
+ fn mint(&mut self, store: Arc<CustomPropertyStore>, parent: u64) -> u64 {
self.minted += 1;
let identity = ENGINE_ENVIRONMENT_IDENTITY_BIT | self.minted;
self.engine.insert(
identity,
EngineEnvironment {
- // SAFETY: The caller transfers the store's one strong reference.
- store: unsafe { RetainedCustomPropertyStore::from_transferred(store) },
+ store: RetainedCustomPropertyStore(store),
parent,
},
);
diff --git a/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs b/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs
index e36b7d78009..9b09e4cb28f 100644
--- a/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs
@@ -302,19 +302,17 @@ impl EngineWrite {
inheritable,
inheritable_store,
} => {
- let pointer = |store: &Option<super::custom_property_environments::RetainedCustomPropertyStore>| {
- store.as_ref().map_or(std::ptr::null(), |store| store.pointer())
- };
- // SAFETY: The write retains both stores.
- unsafe {
- super::bridge::note_custom_property_environment(
- engine,
- identity,
- pointer(&store),
- inheritable,
- pointer(&inheritable_store),
- );
- }
+ super::bridge::note_custom_property_environment(
+ engine,
+ identity,
+ store
+ .as_ref()
+ .map(super::custom_property_environments::RetainedCustomPropertyStore::store),
+ inheritable,
+ inheritable_store
+ .as_ref()
+ .map(super::custom_property_environments::RetainedCustomPropertyStore::store),
+ );
}
Self::AbsorbElementStyleInput {
node,
diff --git a/Libraries/LibWeb/Rust/src/css/style/engine_sample.rs b/Libraries/LibWeb/Rust/src/css/style/engine_sample.rs
index 86d760c86d7..0b856d8b66d 100644
--- a/Libraries/LibWeb/Rust/src/css/style/engine_sample.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/engine_sample.rs
@@ -624,7 +624,7 @@ impl super::StyleEngine {
let [store, inheritance_store] = custom_property_environments.map(|identity| {
self.custom_property_environments
.store(identity)
- .unwrap_or(std::ptr::null())
+ .map_or(std::ptr::null(), |store| std::sync::Arc::as_ptr(store).cast())
});
let inheritance_parent_style_record = inheritance_parent
.and_then(|parent| self.held_style_records.get(&parent).copied())
diff --git a/Libraries/LibWeb/Rust/src/css/style/environment_move.rs b/Libraries/LibWeb/Rust/src/css/style/environment_move.rs
index 66c947c99aa..6ee00f14e05 100644
--- a/Libraries/LibWeb/Rust/src/css/style/environment_move.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/environment_move.rs
@@ -128,7 +128,7 @@ fn custom_property_value_moved(
/// # Safety
/// `store` must be null or a live raw `Arc` pointer to a `CustomPropertyStore`.
-unsafe fn retained_store(store: *const c_void) -> Option<Arc<CustomPropertyStore>> {
+pub(super) unsafe fn retained_store(store: *const c_void) -> Option<Arc<CustomPropertyStore>> {
if store.is_null() {
return None;
}
@@ -160,7 +160,7 @@ impl StyleEngine {
unsafe {
self.retained
.custom_property_environments
- .retain(moved.new_inheritable.identity, moved.new_inheritable.store);
+ .retain_raw(moved.new_inheritable.identity, moved.new_inheritable.store);
}
let mut changed_names = None;
let mut pending = Vec::new();
@@ -330,11 +330,8 @@ impl StyleEngine {
let Some(store) = environments.store(identity) else {
return false;
};
- // SAFETY: The store is live while the identity naming it is.
- let built_over = unsafe { &*store.cast::<CustomPropertyStore>() }
- .inheritance_parent()
- .map_or(std::ptr::null(), |parent| Arc::as_ptr(parent).cast());
- built_over == environments.store(parent).unwrap_or(std::ptr::null())
+ let built_over = store.inheritance_parent().map_or(std::ptr::null(), Arc::as_ptr);
+ built_over == environments.store(parent).map_or(std::ptr::null(), Arc::as_ptr)
}
/// Whether a moved environment computes the element again rather than handing it the moved
@@ -503,13 +500,10 @@ mod tests {
/// Give `identity` a store of no values built over the one `parent` names, or over none.
fn note_store_built_over(engine: &mut StyleEngine, identity: u64, parent: u64) {
let environments = &mut engine.retained.custom_property_environments;
- let parent = environments.store(parent).unwrap_or(std::ptr::null());
- // SAFETY: The parent is null or a live store, and the environments retain the new one.
- unsafe {
- let store = CustomPropertyStore::cascaded_child(parent, Vec::new());
- environments.retain(identity, store);
- drop(Arc::from_raw(store.cast::<CustomPropertyStore>()));
- }
+ let parent = environments.store(parent).cloned();
+ // SAFETY: The store holds no values.
+ let store = unsafe { CustomPropertyStore::cascaded_child(parent, Vec::new()) };
+ environments.retain(identity, Some(&store));
}
#[test]
diff --git a/Libraries/LibWeb/Rust/src/css/style/publication.rs b/Libraries/LibWeb/Rust/src/css/style/publication.rs
index 6bc433e14f1..21de4930845 100644
--- a/Libraries/LibWeb/Rust/src/css/style/publication.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/publication.rs
@@ -218,27 +218,19 @@ impl RetainedState {
inherited
} else {
let store = self.custom_property_environments.store(held)?;
- let parent_store = self
- .custom_property_environments
- .store(inherited)
- .unwrap_or(std::ptr::null());
- // SAFETY: The catalog keeps both stores alive. The rebuilt store transfers its
- // one Arc reference to the engine environment.
- unsafe {
- let store = &*store.cast::<crate::css::custom_properties::CustomPropertyStore>();
- let values = store
- .declared_names
- .iter()
- .map(|&name| (name, store.own_values[&name].value.clone_retained()))
- .collect();
- let rebuilt = store.resolved_child(parent_store, values);
- self.custom_property_environments.adopt_engine_environment(
- rebuilt,
- inherited,
- parent_store,
- inputs.custom_property_registry(),
- )
- }
+ let parent_store = self.custom_property_environments.store(inherited).cloned();
+ let values = store
+ .declared_names
+ .iter()
+ .map(|&name| (name, store.own_values[&name].value.clone_retained()))
+ .collect();
+ let rebuilt = store.resolved_child(parent_store.clone(), values);
+ self.custom_property_environments.adopt_engine_environment(
+ rebuilt,
+ inherited,
+ parent_store.as_deref(),
+ inputs.custom_property_registry(),
+ )
}
}
// A node declaring none inherits its parent's environment as it is now.
@@ -5296,11 +5288,11 @@ mod tests {
let inherited_name = ak::Utf16FlyString::from_utf16(&"--inherited".encode_utf16().collect::<Vec<_>>());
let own_name = ak::Utf16FlyString::from_utf16(&"--own".encode_utf16().collect::<Vec<_>>());
- let make_store = |parent, name: &ak::Utf16FlyString, text: &str, value| {
+ let make_store = |parent: Option<Arc<CustomPropertyStore>>, name: &ak::Utf16FlyString, text: &str, value| {
let value = RetainedStyleValueData::from_owned(StyleValueData::Number { value });
// SAFETY: The parent is null or retained by this test, and both the name and value
// remain live while cascaded_child retains them.
- let raw = unsafe {
+ unsafe {
CustomPropertyStore::cascaded_child(
parent,
vec![(
@@ -5310,13 +5302,11 @@ mod tests {
value.pointer().cast(),
)],
)
- };
- // SAFETY: cascaded_child transfers one Arc reference to its caller.
- unsafe { Arc::from_raw(raw.cast::<CustomPropertyStore>()) }
+ }
};
- let old_parent = make_store(std::ptr::null(), &inherited_name, "--inherited", 1.0);
- let new_parent = make_store(std::ptr::null(), &inherited_name, "--inherited", 2.0);
- let own = make_store(Arc::as_ptr(&old_parent).cast(), &own_name, "--own", 42.0);
+ let old_parent = make_store(None, &inherited_name, "--inherited", 1.0);
+ let new_parent = make_store(None, &inherited_name, "--inherited", 2.0);
+ let own = make_store(Some(old_parent.clone()), &own_name, "--own", 42.0);
let mut engine = StyleEngine::new();
let mut raw_nodes = [0; 3];
engine.allocate_style_nodes(&mut raw_nodes);
@@ -5324,13 +5314,10 @@ mod tests {
engine.tree.set_parent(ancestor, Some(root));
engine.tree.set_parent(inheritor, Some(root));
for (identity, store) in [(1, &old_parent), (2, &new_parent), (3, &own)] {
- // SAFETY: The test keeps these stores alive while the catalog retains them.
- unsafe {
- engine
- .retained
- .custom_property_environments
- .retain(identity, Arc::as_ptr(store).cast())
- };
+ engine
+ .retained
+ .custom_property_environments
+ .retain(identity, Some(store));
}
for (node, environment) in [(root, 1), (ancestor, 3), (inheritor, 1)] {
engine.publish_computed_groups(
@@ -5356,8 +5343,6 @@ mod tests {
.current_custom_property_environment(ancestor, &Default::default(), &mut scratch)
.unwrap();
let store = retained.custom_property_environments.store(current).unwrap();
- // SAFETY: The catalog retains the refreshed environment.
- let store = unsafe { &*store.cast::<CustomPropertyStore>() };
assert!(matches!(
store.get(inherited_name.raw_identity()).unwrap().value.data(),
StyleValueData::Number { value: 2.0 }