Truly independent web browser
LibWeb: Take objects C++ hands back as OwnedRc, OwnedArc and OwnedBox
Andreas Klinga6b6565ac607
diff --git a/Libraries/LibWeb/Rust/build.rs b/Libraries/LibWeb/Rust/build.rsindex def6cbce09b..c5edf6ed49c 100644--- a/Libraries/LibWeb/Rust/build.rs+++ b/Libraries/LibWeb/Rust/build.rs@@ -2480,6 +2480,15 @@ fn main() -> Result<(), Box<dyn Error>> {.map(String::from).to_vec();expose_compositing_types_as_cpp_types(&mut style_value_config);+ // A calculation's Typed OM reification is opaque to C++, which holds it by pointer.+ style_value_config+ .export+ .rename+ .insert("CalcReificationStorage".to_string(), "void".to_string());+ style_value_config+ .export+ .exclude+ .push("CalcReificationStorage".to_string());// A compositor keyframe value is substituted by the document's style engine, which the document host reaches.declare_document_host_of_layout_header(&mut style_value_config);@@ -2740,6 +2749,20 @@ fn main() -> Result<(), Box<dyn Error>> {.rename.insert("OptionalF64".to_string(), "Optional<double>".to_string());computed_values_config.includes.push("AK/Optional.h".to_string());+ // The custom property registry and stores, a sample's animated custom properties and a shorthand expansion are+ // opaque to C++, which holds each by pointer.+ for name in [+ "CustomPropertyRegistry",+ "CustomPropertyStore",+ "AnimatedCustomPropertyResults",+ "ShorthandExpansion",+ ] {+ computed_values_config+ .export+ .rename+ .insert(name.to_string(), "void".to_string());+ computed_values_config.export.exclude.push(name.to_string());+ }computed_values_config.export.rename.insert("DeclarationBlockData".to_string(),"Web::CSS::Parser::ValueParserFFI::DeclarationBlockData".to_string(),@@ -2812,6 +2835,9 @@ fn main() -> Result<(), Box<dyn Error>> {"FfiReplacedContentFacts".to_string(),"FfiStylePayloads".to_string(),"FfiUtf16View".to_string(),+ // Handed back through the layout header, which builds on this one.+ "OwnedArc".to_string(),+ "OwnedBox".to_string(),"NodeFlag".to_string(),"NodeKind".to_string(),];diff --git a/Libraries/LibWeb/Rust/src/css/animated_overlay.rs b/Libraries/LibWeb/Rust/src/css/animated_overlay.rsindex 903ec875d5b..df7e3073191 100644--- a/Libraries/LibWeb/Rust/src/css/animated_overlay.rs+++ b/Libraries/LibWeb/Rust/src/css/animated_overlay.rs@@ -16,6 +16,7 @@//! effective-value queries on both the overlay itself and the computed//! longhand table.+use crate::css::ffi_support::OwnedBox;use std::ffi::c_void;use std::sync::Arc;@@ -217,11 +218,9 @@ pub extern "C" fn rust_animated_overlay_contains(overlay: &AnimatedOverlay, propoverlay.get(property).is_some()}-/// # Safety-/// `overlay` must be a valid overlay that is not used after this call.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_animated_overlay_free(overlay: *mut AnimatedOverlay) {- drop(unsafe { Box::from_raw(overlay) });+pub extern "C" fn rust_animated_overlay_free(overlay: OwnedBox<AnimatedOverlay>) {+ drop(overlay);}/// Stores or replaces the overlay entry for a longhand, retaining `value`.diff --git a/Libraries/LibWeb/Rust/src/css/calc.rs b/Libraries/LibWeb/Rust/src/css/calc.rsindex b6ce9c69238..89aead3c267 100644--- a/Libraries/LibWeb/Rust/src/css/calc.rs+++ b/Libraries/LibWeb/Rust/src/css/calc.rs@@ -13,6 +13,7 @@//! Nothing constructs these yet; the FFI construction surface follows with//! the C++ staging.+use crate::css::ffi_support::{OwnedArc, OwnedBox};use std::sync::Arc;use crate::css::style_value::{RetainedStyleValueData, StyleValueData};@@ -1246,12 +1247,9 @@ pub unsafe extern "C" fn rust_calc_node_create_variadic(}/// Creates a single-child node: kind selects negate (0) or invert (1).-///-/// # Safety-/// `child` must be a valid transferred handle.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_calc_node_create_unary(kind: u8, child: *const CalcNode) -> *const CalcNode {- let child = unsafe { Arc::from_raw(child) };+pub extern "C" fn rust_calc_node_create_unary(kind: u8, child: OwnedArc<CalcNode>) -> *const CalcNode {+ let child = child.into_arc();let node = match kind {0 => CalcNode::Negate(child),1 => CalcNode::Invert(child),@@ -1260,26 +1258,22 @@ pub unsafe extern "C" fn rust_calc_node_create_unary(kind: u8, child: *const Calhandle(node)}-/// # Safety-/// All three children must be valid transferred handles.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_calc_node_create_clamp(- min: *const CalcNode,- center: *const CalcNode,- max: *const CalcNode,+pub extern "C" fn rust_calc_node_create_clamp(+ min: OwnedArc<CalcNode>,+ center: OwnedArc<CalcNode>,+ max: OwnedArc<CalcNode>,) -> *const CalcNode {handle(CalcNode::Clamp {- min: unsafe { Arc::from_raw(min) },- center: unsafe { Arc::from_raw(center) },- max: unsafe { Arc::from_raw(max) },+ min: min.into_arc(),+ center: center.into_arc(),+ max: max.into_arc(),})}-/// # Safety-/// `node` must be a valid transferred handle; this releases it.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_calc_node_release(node: *const CalcNode) {- drop(unsafe { Arc::from_raw(node) });+pub extern "C" fn rust_calc_node_release(node: OwnedArc<CalcNode>) {+ drop(node);}/// https://drafts.csswg.org/css-values-4/#determine-the-type-of-a-calculation@@ -4925,7 +4919,7 @@ pub struct FfiCalcReification {pub storage: *mut std::ffi::c_void,}-struct CalcReificationStorage {+pub struct CalcReificationStorage {nodes: Box<[FfiCalcReificationNode]>,children: Box<[usize]>,}@@ -5040,12 +5034,7 @@ pub extern "C" fn rust_calc_describe_for_typed_om(}}-/// # Safety-/// `storage` must be null or a value returned by `rust_calc_describe_for_typed_om` that has not-/// already been released.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_calc_reification_release(storage: *mut std::ffi::c_void) {- if !storage.is_null() {- drop(unsafe { Box::from_raw(storage.cast::<CalcReificationStorage>()) });- }+pub extern "C" fn rust_calc_reification_release(storage: OwnedBox<CalcReificationStorage>) {+ drop(storage);}diff --git a/Libraries/LibWeb/Rust/src/css/container_conditions.rs b/Libraries/LibWeb/Rust/src/css/container_conditions.rsindex 2d0b52d28ff..ec7f476a7cb 100644--- a/Libraries/LibWeb/Rust/src/css/container_conditions.rs+++ b/Libraries/LibWeb/Rust/src/css/container_conditions.rs@@ -5,7 +5,7 @@*/use crate::css::css_string::CssString;-use crate::css::ffi_support::FfiUtf16View;+use crate::css::ffi_support::{FfiUtf16View, OwnedArc};use crate::css::parser::query_parser::{CONTAINER_QUERY_REQUIRES_BLOCK_SIZE, CONTAINER_QUERY_REQUIRES_HEIGHT, CONTAINER_QUERY_REQUIRES_INLINE_SIZE,CONTAINER_QUERY_REQUIRES_SCROLL_STATE, CONTAINER_QUERY_REQUIRES_WIDTH, FfiQueryHandle,@@ -63,10 +63,8 @@ pub unsafe extern "C" fn rust_container_conditions_retain(}#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_container_conditions_release(conditions: *const ContainerConditionsData) {- if !conditions.is_null() {- unsafe { Arc::decrement_strong_count(conditions) };- }+pub extern "C" fn rust_container_conditions_release(conditions: OwnedArc<ContainerConditionsData>) {+ drop(conditions);}#[unsafe(no_mangle)]diff --git a/Libraries/LibWeb/Rust/src/css/counter_representation.rs b/Libraries/LibWeb/Rust/src/css/counter_representation.rsindex 1fbfcb9f089..ff6e7b6aeb7 100644--- a/Libraries/LibWeb/Rust/src/css/counter_representation.rs+++ b/Libraries/LibWeb/Rust/src/css/counter_representation.rs@@ -13,6 +13,7 @@use crate::css::css_enums::symbols_type;use crate::css::css_string::CssString;+use crate::css::ffi_support::OwnedArc;use crate::css::style_value::StyleValueData;use std::collections::HashMap;use std::ffi::c_void;@@ -978,16 +979,9 @@ pub extern "C" fn rust_counter_styles_retain(Arc::into_raw(styles.to_arc())}-/// # Safety-///-/// `styles` must be null or a reference from `rust_counter_styles_resolve` or-/// `rust_counter_styles_retain` that has not been released.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_counter_styles_release(styles: *const RegisteredCounterStyles) {- if !styles.is_null() {- // SAFETY: The caller gives up the reference it holds.- drop(unsafe { Arc::from_raw(styles) });- }+pub extern "C" fn rust_counter_styles_release(styles: OwnedArc<RegisteredCounterStyles>) {+ drop(styles);}/// Whether the marker text of a list item whose `list-style-type` is `list_style_type` depends ondiff --git a/Libraries/LibWeb/Rust/src/css/custom_properties.rs b/Libraries/LibWeb/Rust/src/css/custom_properties.rsindex a7ae1ae4e66..ca0dde33fcc 100644--- a/Libraries/LibWeb/Rust/src/css/custom_properties.rs+++ b/Libraries/LibWeb/Rust/src/css/custom_properties.rs@@ -19,7 +19,7 @@ use ak::ScopeGuard;use crate::css::calc::CanonicalNumericType;use crate::css::css_tokenizer::{CssNumberType, ParserTokenKind, TokenizerInput, tokenize_for_parser};-use crate::css::ffi_support::FfiUtf16View;+use crate::css::ffi_support::{FfiUtf16View, OwnedArc};use crate::css::function_signature::FunctionSignature;use crate::css::parser::arbitrary_substitution::{arbitrary_substitution_function, arguments_are_valid, collect_arbitrary_substitution_function_presence,@@ -3959,12 +3959,9 @@ pub unsafe extern "C" fn rust_custom_property_registry_update(}/// Gives up the document's reference to its registry.-///-/// # Safety-/// `registry` must be the document's live registry, which it gives up once.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_custom_property_registry_destroy(registry: *const c_void) {- drop(unsafe { Arc::from_raw(registry.cast::<CustomPropertyRegistry>()) });+pub extern "C" fn rust_custom_property_registry_destroy(registry: OwnedArc<CustomPropertyRegistry>) {+ drop(registry);}/// Takes a reference of its own to the document registry `registry`, for a style transaction that@@ -4082,13 +4079,9 @@ pub unsafe extern "C" fn rust_custom_property_store_create_animation_overlay(}/// Releases one store reference returned by `rust_custom_property_store_create`.-///-/// # Safety-/// `store` must be a non-null pointer returned by `rust_custom_property_store_create` that has-/// not already been released.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_custom_property_store_destroy(store: *const c_void) {- drop(unsafe { Arc::from_raw(store.cast::<CustomPropertyStore>()) });+pub extern "C" fn rust_custom_property_store_destroy(store: OwnedArc<CustomPropertyStore>) {+ drop(store);}/// Hands every custom property a store declares itself to `callback`, in declaration order, withdiff --git a/Libraries/LibWeb/Rust/src/css/declaration_block.rs b/Libraries/LibWeb/Rust/src/css/declaration_block.rsindex 09f133aa399..1287a6b1c38 100644--- a/Libraries/LibWeb/Rust/src/css/declaration_block.rs+++ b/Libraries/LibWeb/Rust/src/css/declaration_block.rs@@ -5,7 +5,7 @@*/use crate::css::css_string::CssString;-use crate::css::ffi_support::FfiUtf16View;+use crate::css::ffi_support::{FfiUtf16View, OwnedArc, OwnedBox};use crate::css::property_metadata::{property_is_logical_alias_including_shorthands, property_logical_group};use crate::css::style_compute::expand_shorthands_with;use crate::css::style_value::StyleValueData;@@ -505,14 +505,9 @@ pub extern "C" fn rust_declaration_data_retain(}/// Release an immutable declaration snapshot returned by the style engine or retained from a view.-///-/// # Safety-/// `data` must be null or own an Arc reference to declaration data.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_declaration_data_release(data: *const DeclarationBlockData) {- if !data.is_null() {- drop(unsafe { Arc::from_raw(data) });- }+pub extern "C" fn rust_declaration_data_release(data: OwnedArc<DeclarationBlockData>) {+ drop(data);}#[unsafe(no_mangle)]@@ -549,10 +544,8 @@ pub extern "C" fn rust_declaration_data_visit(}#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_declaration_block_destroy(block: *mut DeclarationBlock) {- if !block.is_null() {- drop(unsafe { Box::from_raw(block) });- }+pub extern "C" fn rust_declaration_block_destroy(block: OwnedBox<DeclarationBlock>) {+ drop(block);}#[unsafe(no_mangle)]diff --git a/Libraries/LibWeb/Rust/src/css/descriptor_block.rs b/Libraries/LibWeb/Rust/src/css/descriptor_block.rsindex bed5f5f71d5..ea0f21f09ca 100644--- a/Libraries/LibWeb/Rust/src/css/descriptor_block.rs+++ b/Libraries/LibWeb/Rust/src/css/descriptor_block.rs@@ -6,7 +6,7 @@use crate::css::css_string::CssString;use crate::css::descriptor_metadata::CUSTOM_DESCRIPTOR_ID;-use crate::css::ffi_support::FfiUtf16View;+use crate::css::ffi_support::{FfiUtf16View, OwnedBox};use crate::css::serialize::{SerializationMode, StringUnits, TextSink, serialize_an_identifier, serialize_style_value, sink_into_raw,};@@ -152,10 +152,8 @@ pub extern "C" fn rust_descriptor_block_replace(block: &mut FfiDescriptorBlock,}#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_descriptor_block_destroy(block: *mut FfiDescriptorBlock) {- if !block.is_null() {- drop(unsafe { Box::from_raw(block) });- }+pub extern "C" fn rust_descriptor_block_destroy(block: OwnedBox<FfiDescriptorBlock>) {+ drop(block);}#[unsafe(no_mangle)]diff --git a/Libraries/LibWeb/Rust/src/css/dom_selector_matching.rs b/Libraries/LibWeb/Rust/src/css/dom_selector_matching.rsindex 67e148d2728..f75e2ef532b 100644--- a/Libraries/LibWeb/Rust/src/css/dom_selector_matching.rs+++ b/Libraries/LibWeb/Rust/src/css/dom_selector_matching.rs@@ -12,6 +12,7 @@//! it and the style engine is not consulted. Every fact a selector tests is asked of the DOM through the callbacks the//! host passes in.+use crate::css::ffi_support::OwnedBox;use std::convert::Infallible;use std::ffi::c_void;use std::mem::MaybeUninit;@@ -318,13 +319,9 @@ pub unsafe extern "C" fn rust_dom_selector_program_create(}))}-/// # Safety-/// `program` must be null or a program `rust_dom_selector_program_create` returned, which is not used again.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_dom_selector_program_destroy(program: *mut DomSelectorProgram) {- if !program.is_null() {- drop(unsafe { Box::from_raw(program) });- }+pub extern "C" fn rust_dom_selector_program_destroy(program: OwnedBox<DomSelectorProgram>) {+ drop(program);}/// The DOM, as the callbacks show it.diff --git a/Libraries/LibWeb/Rust/src/css/ffi_support.rs b/Libraries/LibWeb/Rust/src/css/ffi_support.rsindex 89fcca2d360..790c577cfb4 100644--- a/Libraries/LibWeb/Rust/src/css/ffi_support.rs+++ b/Libraries/LibWeb/Rust/src/css/ffi_support.rs@@ -56,13 +56,23 @@ impl<T> RcRef<'_, T> {}}-/// [`RcRef`] for an object C++ holds through a pointer `Arc::into_raw()` gave it, which only C++ makes.+/// [`RcRef`] for an object C++ holds through a pointer `Arc::into_raw()` gave it.#[repr(transparent)]pub struct ArcRef<'a, T> {pointer: *const T,lent: PhantomData<&'a std::sync::Arc<T>>,}+#[cfg(test)]+impl<'a, T> ArcRef<'a, T> {+ pub(crate) fn new(arc: &'a std::sync::Arc<T>) -> Self {+ Self {+ pointer: std::sync::Arc::as_ptr(arc),+ lent: PhantomData,+ }+ }+}+impl<T> ArcRef<'_, T> {/// A strong reference of Rust's own to the object.pub(crate) fn to_arc(&self) -> std::sync::Arc<T> {@@ -75,6 +85,78 @@ impl<T> ArcRef<'_, T> {}}+/// A strong reference C++ hands back, through a pointer `Rc::into_raw()` gave it, or null for none.+///+/// Only C++ makes one, so the reference is Rust's own once it is handed over, and dropping one releases it.+#[repr(transparent)]+pub struct OwnedRc<T> {+ pointer: *const T,+ owned: PhantomData<std::rc::Rc<T>>,+}++impl<T> OwnedRc<T> {+ fn take(&mut self) -> Option<std::rc::Rc<T>> {+ let pointer = std::mem::replace(&mut self.pointer, std::ptr::null());+ // SAFETY: A non-null pointer comes from `Rc::into_raw()`, and its reference is this handle's own.+ (!pointer.is_null()).then(|| unsafe { std::rc::Rc::from_raw(pointer) })+ }+}++impl<T> Drop for OwnedRc<T> {+ fn drop(&mut self) {+ drop(self.take());+ }+}++/// [`OwnedRc`] for a reference C++ hands back through a pointer `Arc::into_raw()` gave it.+#[repr(transparent)]+pub struct OwnedArc<T> {+ pointer: *const T,+ owned: PhantomData<std::sync::Arc<T>>,+}++impl<T> OwnedArc<T> {+ fn take(&mut self) -> Option<std::sync::Arc<T>> {+ let pointer = std::mem::replace(&mut self.pointer, std::ptr::null());+ // SAFETY: A non-null pointer comes from `Arc::into_raw()`, and its reference is this handle's own.+ (!pointer.is_null()).then(|| unsafe { std::sync::Arc::from_raw(pointer) })+ }++ /// The reference, which must not be null.+ pub(crate) fn into_arc(mut self) -> std::sync::Arc<T> {+ self.take().expect("C++ hands over a live object")+ }+}++impl<T> Drop for OwnedArc<T> {+ fn drop(&mut self) {+ drop(self.take());+ }+}++/// An object C++ hands back, through a pointer `Box::into_raw()` gave it, or null for none.+///+/// Only C++ makes one, so the object is Rust's own once it is handed over, and dropping one drops it.+#[repr(transparent)]+pub struct OwnedBox<T> {+ pointer: *mut T,+ owned: PhantomData<Box<T>>,+}++impl<T> OwnedBox<T> {+ fn take(&mut self) -> Option<Box<T>> {+ let pointer = std::mem::replace(&mut self.pointer, std::ptr::null_mut());+ // SAFETY: A non-null pointer comes from `Box::into_raw()`, and its object is this handle's own.+ (!pointer.is_null()).then(|| unsafe { Box::from_raw(pointer) })+ }+}++impl<T> Drop for OwnedBox<T> {+ fn drop(&mut self) {+ drop(self.take());+ }+}+/// Text borrowed for `'a`, as ASCII bytes or UTF-16 code units.////// Rust builds a view only from a borrowed slice, and C++ hands one over under the same contract: exactly one non-emptydiff --git a/Libraries/LibWeb/Rust/src/css/font_feature_values.rs b/Libraries/LibWeb/Rust/src/css/font_feature_values.rsindex 3306a6907ee..acb453363bc 100644--- a/Libraries/LibWeb/Rust/src/css/font_feature_values.rs+++ b/Libraries/LibWeb/Rust/src/css/font_feature_values.rs@@ -5,7 +5,7 @@*/use crate::css::css_string::CssString;-use crate::css::ffi_support::FfiUtf16View;+use crate::css::ffi_support::{FfiUtf16View, OwnedArc};use crate::css::parser::value_parser::equals_ascii_case_insensitive;use crate::css::style_value::StyleValueData;use std::cell::RefCell;@@ -78,13 +78,9 @@ impl FontFeatureValuesRule {}}-/// # Safety-/// Data must be null or own an Arc reference returned by a rule view.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_font_feature_values_data_release(data: *const FontFeatureValuesData) {- if !data.is_null() {- drop(unsafe { Arc::from_raw(data) });- }+pub extern "C" fn rust_font_feature_values_data_release(data: OwnedArc<FontFeatureValuesData>) {+ drop(data);}#[unsafe(no_mangle)]diff --git a/Libraries/LibWeb/Rust/src/css/import_rule.rs b/Libraries/LibWeb/Rust/src/css/import_rule.rsindex 30076b286e3..1f34a3b631e 100644--- a/Libraries/LibWeb/Rust/src/css/import_rule.rs+++ b/Libraries/LibWeb/Rust/src/css/import_rule.rs@@ -5,7 +5,7 @@*/use crate::css::css_string::CssString;-use crate::css::ffi_support::FfiUtf16View;+use crate::css::ffi_support::{FfiUtf16View, OwnedArc};use crate::css::parser::query_parser::FfiQueryHandle;use crate::css::scope_selectors::ScopeSelectors;use crate::css::style_value::StyleValueData;@@ -41,10 +41,8 @@ pub unsafe extern "C" fn rust_import_rule_retain(rule: *const ImportRuleData) ->}#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_import_rule_release(rule: *const ImportRuleData) {- if !rule.is_null() {- unsafe { Arc::decrement_strong_count(rule) };- }+pub extern "C" fn rust_import_rule_release(rule: OwnedArc<ImportRuleData>) {+ drop(rule);}#[unsafe(no_mangle)]diff --git a/Libraries/LibWeb/Rust/src/css/media_list.rs b/Libraries/LibWeb/Rust/src/css/media_list.rsindex 5c2be623e24..2620c11bcf6 100644--- a/Libraries/LibWeb/Rust/src/css/media_list.rs+++ b/Libraries/LibWeb/Rust/src/css/media_list.rs@@ -5,7 +5,7 @@*/use crate::css::css_tokenizer::TokenizerInput;-use crate::css::ffi_support::FfiUtf16View;+use crate::css::ffi_support::{FfiUtf16View, OwnedBox};use crate::css::parser::query_parser::{FfiMediaEnvironment, FfiQueryHandle, MediaEnvironment, VisitQuerySerialization, invalid_media_query,media_query_handle, parse_media_query_list, resolve_query_feature,@@ -114,10 +114,8 @@ pub extern "C" fn rust_media_list_share(list: &MediaList) -> *mut MediaList {}#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_media_list_free(list: *mut MediaList) {- if !list.is_null() {- drop(unsafe { Box::from_raw(list) });- }+pub extern "C" fn rust_media_list_free(list: OwnedBox<MediaList>) {+ drop(list);}#[unsafe(no_mangle)]diff --git a/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/query_parser.rsindex 33c56717c48..92bb6a74ad4 100644--- a/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs@@ -8,7 +8,7 @@ use crate::css::css_enums::keyword_from_ascii_case_insensitive;use crate::css::css_pixels::CssPixels;use crate::css::css_tokenizer::{ParserString, ParserTokenKind, TextDetacher, TokenizerInput, tokenize_for_parser};use crate::css::custom_properties::environment_variable_is_known;-use crate::css::ffi_support::FfiUtf16View;+use crate::css::ffi_support::{FfiUtf16View, OwnedArc};use crate::css::parser::component_value::{ComponentKind, ComponentValue, consume_a_list_of_component_values, trim_whitespace,};@@ -2988,14 +2988,9 @@ pub unsafe extern "C" fn css_query_ref(handle: *const FfiQueryHandle) -> *const}/// Releases one strong reference to a query handle.-///-/// # Safety-/// `handle` must be null or own one strong reference to a live query handle.#[unsafe(no_mangle)]-pub unsafe extern "C" fn css_query_unref(handle: *const FfiQueryHandle) {- if !handle.is_null() {- unsafe { Arc::decrement_strong_count(handle) };- }+pub extern "C" fn css_query_unref(handle: OwnedArc<FfiQueryHandle>) {+ drop(handle);}/// Evaluates a retained supports condition whose feature results were captured while parsing.diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax.rsindex f216996141d..6189965ee65 100644--- a/Libraries/LibWeb/Rust/src/css/parser/syntax.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax.rs@@ -6,7 +6,7 @@use crate::css::css_enums::keyword_from_ascii_case_insensitive;use crate::css::css_tokenizer::tokenize_for_parser;-use crate::css::ffi_support::FfiUtf16View;+use crate::css::ffi_support::{FfiUtf16View, OwnedArc};use crate::css::parser::arbitrary_substitution::{SubstitutionFunctionsPresence, collect_arbitrary_substitution_function_presence, declaration_value_is_valid,};@@ -437,11 +437,9 @@ pub extern "C" fn rust_syntax_retain(syntax: crate::css::ffi_support::ArcRef<'_,Arc::into_raw(syntax.to_arc())}-/// # Safety-/// `syntax` must be a live parsed-syntax handle whose strong count is released exactly once.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_syntax_release(syntax: *const c_void) {- unsafe { Arc::decrement_strong_count(syntax.cast::<SyntaxNode>()) };+pub extern "C" fn rust_syntax_release(syntax: OwnedArc<SyntaxNode>) {+ drop(syntax);}/// # Safetydiff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rsindex fcf62f8672c..237ce935725 100644--- a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs@@ -15,7 +15,7 @@ use crate::css::css_tokenizer::{use crate::css::declaration_block::{DeclarationBlock, DeclarationBlockData, DeclaredProperty};use crate::css::descriptor_block::{DescriptorBlockData, DescriptorData, FfiDescriptorBlock};use crate::css::descriptor_metadata::{CUSTOM_DESCRIPTOR_ID, descriptor_longhands};-use crate::css::ffi_support::FfiUtf16View;+use crate::css::ffi_support::{ArcRef, FfiUtf16View, OwnedArc};pub use crate::css::font_feature_values::FontFeatureValuesRuleKind;use crate::css::font_feature_values::{FontFeatureValuesData, FontFeatureValuesRule};use crate::css::function_signature::{FunctionParameterData, FunctionSignature};@@ -2430,11 +2430,8 @@ impl ParsedStyleSheet {}#[unsafe(no_mangle)]-/// # Safety-/// `parse` must point to a live stylesheet owned by an `Arc`.-pub unsafe extern "C" fn rust_css_syntax_native_rules(parse: *const ParsedStyleSheet) -> *const NativeRuleList {- unsafe { Arc::increment_strong_count(parse) };- Rc::into_raw(NativeRuleList::from_parsed(unsafe { Arc::from_raw(parse) }))+pub extern "C" fn rust_css_syntax_native_rules(parse: ArcRef<'_, ParsedStyleSheet>) -> *const NativeRuleList {+ Rc::into_raw(NativeRuleList::from_parsed(parse.to_arc()))}#[unsafe(no_mangle)]@@ -3921,13 +3918,9 @@ pub unsafe extern "C" fn rust_page_selector_list_retain(list: *const PageSelectolist}-/// # Safety-/// `list` must be null or own a reference to a live page-selector list.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_page_selector_list_release(list: *const PageSelectorList) {- if !list.is_null() {- unsafe { Arc::decrement_strong_count(list) };- }+pub extern "C" fn rust_page_selector_list_release(list: OwnedArc<PageSelectorList>) {+ drop(list);}#[unsafe(no_mangle)]@@ -4044,14 +4037,9 @@ pub(crate) fn parse_shared_block(Arc::new(parse.finish())}-/// # Safety-/// `parse` must be null or an owned syntax parse handle on the current thread.-/// Each owned reference must only be freed once.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_css_syntax_parse_free(parse: *const ParsedStyleSheet) {- if !parse.is_null() {- drop(unsafe { Arc::from_raw(parse) });- }+pub extern "C" fn rust_css_syntax_parse_free(parse: OwnedArc<ParsedStyleSheet>) {+ drop(parse);}#[cfg(test)]@@ -4190,7 +4178,11 @@ mod tests {assert_eq!(super::rust_css_syntax_root_count(&parse), 2);super::rust_css_syntax_visit_diagnostics(&parse, diagnostic);super::rust_css_syntax_visit_declaration_errors(&parse, declaration);- let rules = unsafe { std::rc::Rc::from_raw(super::rust_css_syntax_native_rules(&*parse)) };+ let rules = unsafe {+ std::rc::Rc::from_raw(super::rust_css_syntax_native_rules(+ crate::css::ffi_support::ArcRef::new(&parse),+ ))+ };assert_eq!(crate::css::rule::rust_rule_list_count(&rules), 1);}diff --git a/Libraries/LibWeb/Rust/src/css/rule.rs b/Libraries/LibWeb/Rust/src/css/rule.rsindex ff6af6d054d..e67c4a40f44 100644--- a/Libraries/LibWeb/Rust/src/css/rule.rs+++ b/Libraries/LibWeb/Rust/src/css/rule.rs@@ -10,7 +10,7 @@ use crate::css::css_string::CssString;use crate::css::css_tokenizer::TokenizerInput;use crate::css::declaration_block::{DeclarationBlock, visit_declaration_images};use crate::css::descriptor_block::FfiDescriptorBlock;-use crate::css::ffi_support::{ArcRef, FfiUtf16View, RcRef};+use crate::css::ffi_support::{ArcRef, FfiUtf16View, OwnedArc, OwnedRc, RcRef};use crate::css::font_feature_values::FontFeatureValuesRule;use crate::css::function_signature::FunctionSignature;use crate::css::import_rule::ImportRuleData;@@ -728,13 +728,9 @@ pub unsafe extern "C" fn rust_namespace_context_retain(context}-/// # Safety-/// Context must be null or an owned reference returned by this module.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_namespace_context_release(context: *const NativeNamespaceContext) {- if !context.is_null() {- drop(unsafe { Arc::from_raw(context) });- }+pub extern "C" fn rust_namespace_context_release(context: OwnedArc<NativeNamespaceContext>) {+ drop(context);}#[unsafe(no_mangle)]@@ -799,10 +795,8 @@ pub extern "C" fn rust_rule_retain(rule: RcRef<'_, NativeRule>) -> *const Native}#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_rule_release(rule: *const NativeRule) {- if !rule.is_null() {- drop(unsafe { Rc::from_raw(rule) });- }+pub extern "C" fn rust_rule_release(rule: OwnedRc<NativeRule>) {+ drop(rule);}#[unsafe(no_mangle)]@@ -1067,10 +1061,8 @@ pub extern "C" fn rust_rule_list_retain(list: RcRef<'_, NativeRuleList>) -> *con}#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_rule_list_release(list: *const NativeRuleList) {- if !list.is_null() {- drop(unsafe { Rc::from_raw(list) });- }+pub extern "C" fn rust_rule_list_release(list: OwnedRc<NativeRuleList>) {+ drop(list);}#[unsafe(no_mangle)]diff --git a/Libraries/LibWeb/Rust/src/css/rule/function.rs b/Libraries/LibWeb/Rust/src/css/rule/function.rsindex e9a7fbc4f02..21fcf7c1d26 100644--- a/Libraries/LibWeb/Rust/src/css/rule/function.rs+++ b/Libraries/LibWeb/Rust/src/css/rule/function.rs@@ -10,6 +10,7 @@ use crate::css::container_conditions::ContainerConditionsData;use crate::css::custom_properties::{SubstitutionFunctionDeclaration, prepare_function_declarations, prepare_function_parameter_defaults,};+use crate::css::ffi_support::OwnedArc;use crate::css::function_signature::FunctionSignature;use crate::css::media_list::MediaListData;use crate::css::parser::component_value::ComponentValueList;@@ -116,13 +117,9 @@ pub extern "C" fn rust_rule_view_compile_function(view: &NativeRuleView<'_>) ->Arc::into_raw(Arc::new(CompiledFunction::compile(view)))}-/// # Safety-/// The function must be an owned reference returned by compilation or retention.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_compiled_function_release(function: *const CompiledFunction) {- if !function.is_null() {- drop(unsafe { Arc::from_raw(function) });- }+pub extern "C" fn rust_compiled_function_release(function: OwnedArc<CompiledFunction>) {+ drop(function);}#[unsafe(no_mangle)]diff --git a/Libraries/LibWeb/Rust/src/css/scope_selectors.rs b/Libraries/LibWeb/Rust/src/css/scope_selectors.rsindex f84cb5f11dd..18d7961bb09 100644--- a/Libraries/LibWeb/Rust/src/css/scope_selectors.rs+++ b/Libraries/LibWeb/Rust/src/css/scope_selectors.rs@@ -4,6 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+use crate::css::ffi_support::OwnedArc;use crate::css::selector_parser::RustParsedSelectorList;use std::ffi::c_void;use std::sync::Arc;@@ -26,10 +27,8 @@ pub extern "C" fn rust_scope_selectors_retain(}#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_scope_selectors_release(selectors: *const ScopeSelectors) {- if !selectors.is_null() {- drop(unsafe { Arc::from_raw(selectors) });- }+pub extern "C" fn rust_scope_selectors_release(selectors: OwnedArc<ScopeSelectors>) {+ drop(selectors);}#[unsafe(no_mangle)]diff --git a/Libraries/LibWeb/Rust/src/css/selector.rs b/Libraries/LibWeb/Rust/src/css/selector.rsindex 806976108f8..f15d5db1223 100644--- a/Libraries/LibWeb/Rust/src/css/selector.rs+++ b/Libraries/LibWeb/Rust/src/css/selector.rs@@ -7,7 +7,7 @@use std::sync::Arc;pub use crate::css::ffi_support::FfiStringView;-use crate::css::ffi_support::ascii_lowercase;+use crate::css::ffi_support::{OwnedBox, ascii_lowercase};use crate::css::retained_fly_string::RetainedUtf16FlyString;pub type SelectorString = crate::css::css_string::CssString;@@ -643,15 +643,9 @@ pub fn is_ascii_case_insensitive_html_attribute(name: &RetainedUtf16FlyString) -})}-/// # Safety-/// `selector` must be an owned selector handle that has not already been destroyed.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_selector_destroy(selector: *mut RustSelector) {- if !selector.is_null() {- // SAFETY: The caller guarantees that this is an owned handle returned by- // a selector-producing FFI function and that it has not already been destroyed.- drop(unsafe { Box::from_raw(selector) });- }+pub extern "C" fn rust_selector_destroy(selector: OwnedBox<RustSelector>) {+ drop(selector);}/// Returns the selector's specificity in the packed representation used by the DevTools protocol.diff --git a/Libraries/LibWeb/Rust/src/css/selector_parser.rs b/Libraries/LibWeb/Rust/src/css/selector_parser.rsindex dce111bf522..fa37f2b863a 100644--- a/Libraries/LibWeb/Rust/src/css/selector_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/selector_parser.rs@@ -6,6 +6,7 @@//! CSS selector parsing.+use crate::css::ffi_support::OwnedBox;use std::sync::Arc;use super::css_tokenizer::{CssNumberType, ParserTokenKind, TokenizerInput, tokenize_for_parser};@@ -1416,15 +1417,9 @@ pub extern "C" fn rust_selector_parse_pseudo_element(input: FfiUtf16View) -> Ffi}}-/// # Safety-/// `list` must be null or an owned selector list that has not been destroyed.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_parsed_selector_list_destroy(list: *mut RustParsedSelectorList) {- unsafe {- if !list.is_null() {- drop(Box::from_raw(list));- }- }+pub extern "C" fn rust_parsed_selector_list_destroy(list: OwnedBox<RustParsedSelectorList>) {+ drop(list);}#[unsafe(no_mangle)]diff --git a/Libraries/LibWeb/Rust/src/css/style/identities.rs b/Libraries/LibWeb/Rust/src/css/style/identities.rsindex ba31af36c73..cae853c7d93 100644--- a/Libraries/LibWeb/Rust/src/css/style/identities.rs+++ b/Libraries/LibWeb/Rust/src/css/style/identities.rs@@ -13,6 +13,7 @@//! reused in is the one the engine kept when it owned the space.use super::tree::StyleNodeID;+use crate::css::ffi_support::OwnedBox;/// The identities of one document's style nodes, in two spaces: elements (with shadow roots and the document), and/// text nodes.@@ -84,12 +85,9 @@ pub extern "C" fn style_node_id_allocator_create() -> *mut StyleNodeIdAllocatorBox::into_raw(Box::default())}-/// # Safety-/// `allocator` must come from [`style_node_id_allocator_create`] and be destroyed once.#[unsafe(no_mangle)]-pub unsafe extern "C" fn style_node_id_allocator_destroy(allocator: *mut StyleNodeIdAllocator) {- // SAFETY: Guaranteed by the caller.- drop(unsafe { Box::from_raw(allocator) });+pub extern "C" fn style_node_id_allocator_destroy(allocator: OwnedBox<StyleNodeIdAllocator>) {+ drop(allocator);}/// Mints `count` identities into `out`: text identities where `text`, otherwise element ones.diff --git a/Libraries/LibWeb/Rust/src/css/style_compute.rs b/Libraries/LibWeb/Rust/src/css/style_compute.rsindex 70abdc62ba7..ea9518fa609 100644--- a/Libraries/LibWeb/Rust/src/css/style_compute.rs+++ b/Libraries/LibWeb/Rust/src/css/style_compute.rs@@ -15,6 +15,7 @@//! Element-bound inputs, such as container sizes and tree positions, are//! snapshotted by C++ before entering the Rust computation drive.+use crate::css::ffi_support::OwnedBox;use std::borrow::Cow;use std::ffi::c_void;use std::sync::{Arc, OnceLock};@@ -6122,20 +6123,15 @@ impl FfiHostAnimationSampleResult {}/// The custom properties a sample composed, with the names and values the rows point into.-struct AnimatedCustomPropertyResults {+pub struct AnimatedCustomPropertyResults {rows: Vec<FfiAnimatedCustomPropertyResult>,_retained: Vec<(RetainedUtf16FlyString, RetainedStyleValueData)>,}/// Release what `rust_sample_animation_effects` handed back for the animated custom properties.-///-/// # Safety-/// `storage` must be null or a sample result's `animated_custom_properties_storage`, released once.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_release_animated_custom_property_results(storage: *mut c_void) {- if !storage.is_null() {- drop(unsafe { Box::from_raw(storage.cast::<AnimatedCustomPropertyResults>()) });- }+pub extern "C" fn rust_release_animated_custom_property_results(storage: OwnedBox<AnimatedCustomPropertyResults>) {+ drop(storage);}pub(crate) fn animation_length_resolution_context(@@ -7094,7 +7090,7 @@ pub(crate) fn expand_shorthands_with<Sink>(sink(property_id, data, has_style_sheet_context);}-struct ShorthandExpansion {+pub struct ShorthandExpansion {properties: Vec<FfiExpandedProperty>,_values: Vec<RetainedStyleValueData>,}@@ -7140,11 +7136,9 @@ pub unsafe extern "C" fn rust_expand_property_shorthands(}}-/// # Safety-/// `storage` must be a live pointer returned by `rust_expand_property_shorthands`.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_shorthand_expansion_destroy(storage: *mut c_void) {- drop(unsafe { Box::from_raw(storage.cast::<ShorthandExpansion>()) });+pub extern "C" fn rust_shorthand_expansion_destroy(storage: OwnedBox<ShorthandExpansion>) {+ drop(storage);}pub(crate) fn display_is_none(raw: u32) -> bool {diff --git a/Libraries/LibWeb/Rust/src/css/style_sheet.rs b/Libraries/LibWeb/Rust/src/css/style_sheet.rsindex 3653107fb04..6b6ac872231 100644--- a/Libraries/LibWeb/Rust/src/css/style_sheet.rs+++ b/Libraries/LibWeb/Rust/src/css/style_sheet.rs@@ -5,7 +5,7 @@*/use crate::css::container_conditions::ContainerConditionsData;-use crate::css::ffi_support::FfiUtf16View;+use crate::css::ffi_support::{FfiUtf16View, OwnedBox, OwnedRc};use crate::css::media_list::MediaList;use crate::css::parser::query_parser::{FfiMediaEnvironment, MediaEnvironment};use crate::css::rule::read::{NativeRuleView, RuleRef};@@ -60,11 +60,9 @@ pub extern "C" fn rust_media_evaluation_state_create() -> *mut NativeMediaEvaluaBox::into_raw(Box::default())}-/// # Safety-/// The state must be an owned pointer returned by rust_media_evaluation_state_create.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_media_evaluation_state_free(state: *mut NativeMediaEvaluationState) {- drop(unsafe { Box::from_raw(state) });+pub extern "C" fn rust_media_evaluation_state_free(state: OwnedBox<NativeMediaEvaluationState>) {+ drop(state);}// Document-local state. The rule and media owners retain their immutable parsed data separately,@@ -466,10 +464,8 @@ pub extern "C" fn rust_style_sheet_create(}#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_style_sheet_release(sheet: *const NativeStyleSheet) {- if !sheet.is_null() {- drop(unsafe { Rc::from_raw(sheet) });- }+pub extern "C" fn rust_style_sheet_release(sheet: OwnedRc<NativeStyleSheet>) {+ drop(sheet);}#[unsafe(no_mangle)]diff --git a/Libraries/LibWeb/Rust/src/painting/ffi.rs b/Libraries/LibWeb/Rust/src/painting/ffi.rsindex 7069e950f31..5c721351ee1 100644--- a/Libraries/LibWeb/Rust/src/painting/ffi.rs+++ b/Libraries/LibWeb/Rust/src/painting/ffi.rs@@ -5,7 +5,7 @@*/use crate::css::css_pixels::{CssPixelRect, CssPixels};-use crate::css::ffi_support::FfiUtf16View;+use crate::css::ffi_support::{FfiUtf16View, OwnedBox};use crate::layout::LayoutNodeArena;use crate::layout::node_data::NodeSlotId;use crate::layout::svg_formatting_context;@@ -1256,16 +1256,9 @@ pub extern "C" fn compositor_animation_effect_state_create() -> *mut CompositorABox::into_raw(Box::new(CompositorAnimationEffectState::default()))}-/// # Safety-///-/// `state` must be a handle from `compositor_animation_effect_state_create` that is given up here.#[unsafe(no_mangle)]-pub unsafe extern "C" fn compositor_animation_effect_state_destroy(state: *mut CompositorAnimationEffectState) {- if state.is_null() {- return;- }- // SAFETY: The caller gives up the handle it created.- drop(unsafe { Box::from_raw(state) });+pub extern "C" fn compositor_animation_effect_state_destroy(state: OwnedBox<CompositorAnimationEffectState>) {+ drop(state);}/// Builds the animation of the request's target kind for the effect and keeps it pending with thediff --git a/Libraries/LibWeb/Rust/src/render_state/clock.rs b/Libraries/LibWeb/Rust/src/render_state/clock.rsindex 0bebde5fcb0..6222cc1a91b 100644--- a/Libraries/LibWeb/Rust/src/render_state/clock.rs+++ b/Libraries/LibWeb/Rust/src/render_state/clock.rs@@ -29,6 +29,7 @@use super::owner::DocumentId;use super::{DocumentHost, RenderState};use crate::css::css_pixels::CssPixelRect;+use crate::css::ffi_support::OwnedArc;use crate::css::style::animations::{AnimationTimelineSamples, ScrollProgress};use crate::css::style::engine_sample::{DependentRestyle, NeedsHost, TickShownRecords};use crate::css::style::tree::StyleNodeID;@@ -1596,14 +1597,9 @@ pub unsafe extern "C" fn clock_ticks_tick(}/// Gives up the reference `ticks` holds.-///-/// # Safety-///-/// `ticks` must come from `document_host_clock_ticks`, and be released once.#[unsafe(no_mangle)]-pub unsafe extern "C" fn clock_ticks_release(ticks: *const ClockTicks) {- // SAFETY: Guaranteed by the caller.- drop(unsafe { Arc::from_raw(ticks) });+pub extern "C" fn clock_ticks_release(ticks: OwnedArc<ClockTicks>) {+ drop(ticks);}/// A reference to the ticks the render clock hands the lanes of `host`'s document, which the caller releases withdiff --git a/Libraries/LibWeb/Rust/src/svg/path_parser.rs b/Libraries/LibWeb/Rust/src/svg/path_parser.rsindex 9560d8cc472..210d6673011 100644--- a/Libraries/LibWeb/Rust/src/svg/path_parser.rs+++ b/Libraries/LibWeb/Rust/src/svg/path_parser.rs@@ -6,7 +6,7 @@use super::parser::{Input, Parser as Lexer};use crate::css::css_tokenizer::TokenizerInput;-use crate::css::ffi_support::FfiUtf16View;+use crate::css::ffi_support::{FfiUtf16View, OwnedBox};use libgfx_rust::path::Path;use libgfx_rust::{FloatPoint, FloatSize};use std::ffi::c_void;@@ -1349,11 +1349,9 @@ pub extern "C" fn rust_svg_path_clone(path: &ParsedPath) -> *mut ParsedPath {Box::into_raw(Box::new(path.clone()))}-/// # Safety-/// `path` must be a `ParsedPath` allocation returned by this module that has not yet been destroyed.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_svg_path_destroy(path: *mut ParsedPath) {- drop(unsafe { Box::from_raw(path) });+pub extern "C" fn rust_svg_path_destroy(path: OwnedBox<ParsedPath>) {+ drop(path);}#[unsafe(no_mangle)]