Skip to content

Truly independent web browser

LibWeb: Take objects C++ holds strongly as RcRef and ArcRef

Andreas Klinga5e44ad7d92b
diff --git a/Libraries/LibWeb/Rust/src/css/counter_representation.rs b/Libraries/LibWeb/Rust/src/css/counter_representation.rs
index 583eee5cb69..1fbfcb9f089 100644
--- a/Libraries/LibWeb/Rust/src/css/counter_representation.rs
+++ b/Libraries/LibWeb/Rust/src/css/counter_representation.rs
@@ -971,17 +971,11 @@ pub(crate) fn generate_a_counter_representation<'a>(
// them to the layout node arena, and ask what a list marker shows.
/// Takes another reference to a scope's registered counter styles.
-///
-/// # Safety
-///
-/// `styles` must be a live reference from `rust_counter_styles_resolve`.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_counter_styles_retain(
- styles: *const RegisteredCounterStyles,
+pub extern "C" fn rust_counter_styles_retain(
+ styles: crate::css::ffi_support::ArcRef<'_, RegisteredCounterStyles>,
) -> *const RegisteredCounterStyles {
- // SAFETY: The caller holds a reference, so the allocation is live.
- unsafe { Arc::increment_strong_count(styles) };
- styles
+ Arc::into_raw(styles.to_arc())
}
/// # Safety
@@ -1053,7 +1047,10 @@ pub unsafe extern "C" fn render_state_publish_counter_styles(
styles: if styles.is_null() {
Arc::default()
} else {
- unsafe { Arc::from_raw(rust_counter_styles_retain(styles)) }
+ unsafe {
+ Arc::increment_strong_count(styles);
+ Arc::from_raw(styles)
+ }
},
};
host.queue_change(crate::render_state::ArenaChange::Layout(
diff --git a/Libraries/LibWeb/Rust/src/css/counter_style.rs b/Libraries/LibWeb/Rust/src/css/counter_style.rs
index 8f77c4b42a2..5e52b5ecd44 100644
--- a/Libraries/LibWeb/Rust/src/css/counter_style.rs
+++ b/Libraries/LibWeb/Rust/src/css/counter_style.rs
@@ -531,7 +531,9 @@ pub unsafe extern "C" fn rust_counter_styles_resolve(
let registered = RegisteredCounterStyles(registered);
// SAFETY: Guaranteed by the caller.
if unsafe { previous.as_ref() }.is_some_and(|previous| *previous == registered) {
- return unsafe { crate::css::counter_representation::rust_counter_styles_retain(previous) };
+ // SAFETY: The caller holds a reference to the previous styles.
+ unsafe { Arc::increment_strong_count(previous) };
+ return previous;
}
Arc::into_raw(Arc::new(registered))
}
diff --git a/Libraries/LibWeb/Rust/src/css/declaration_block.rs b/Libraries/LibWeb/Rust/src/css/declaration_block.rs
index 2a6c8890c0a..87a0dd411c9 100644
--- a/Libraries/LibWeb/Rust/src/css/declaration_block.rs
+++ b/Libraries/LibWeb/Rust/src/css/declaration_block.rs
@@ -497,17 +497,11 @@ pub extern "C" fn rust_declaration_block_snapshot(block: &DeclarationBlock) -> *
}
/// Retain an immutable declaration snapshot without creating a live declaration owner.
-///
-/// # Safety
-/// `data` must be a live, Arc-owned declaration snapshot.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_declaration_data_retain(
- data: *const DeclarationBlockData,
+pub extern "C" fn rust_declaration_data_retain(
+ data: crate::css::ffi_support::ArcRef<'_, DeclarationBlockData>,
) -> *const DeclarationBlockData {
- unsafe {
- Arc::increment_strong_count(data);
- }
- data
+ Arc::into_raw(data.to_arc())
}
/// Release an immutable declaration snapshot returned by the style engine or retained from a view.
diff --git a/Libraries/LibWeb/Rust/src/css/ffi_support.rs b/Libraries/LibWeb/Rust/src/css/ffi_support.rs
index 61e1d3f6ce3..89fcca2d360 100644
--- a/Libraries/LibWeb/Rust/src/css/ffi_support.rs
+++ b/Libraries/LibWeb/Rust/src/css/ffi_support.rs
@@ -25,6 +25,56 @@ pub struct FfiStringView {
pub length: usize,
}
+/// An object C++ holds a strong reference to, through a pointer `Rc::into_raw()` gave it, lent for `'a`.
+///
+/// Only C++ makes one, and a test from a borrowed `Rc`, so it is never null.
+#[repr(transparent)]
+pub struct RcRef<'a, T> {
+ pointer: *const T,
+ lent: PhantomData<&'a std::rc::Rc<T>>,
+}
+
+#[cfg(test)]
+impl<'a, T> RcRef<'a, T> {
+ pub(crate) fn new(rc: &'a std::rc::Rc<T>) -> Self {
+ Self {
+ pointer: std::rc::Rc::as_ptr(rc),
+ lent: PhantomData,
+ }
+ }
+}
+
+impl<T> RcRef<'_, T> {
+ /// A strong reference of Rust's own to the object.
+ pub(crate) fn to_rc(&self) -> std::rc::Rc<T> {
+ assert!(!self.pointer.is_null(), "C++ lends a live object");
+ // SAFETY: The pointer comes from `Rc::into_raw()`, and the object is live for 'a.
+ unsafe {
+ std::rc::Rc::increment_strong_count(self.pointer);
+ std::rc::Rc::from_raw(self.pointer)
+ }
+ }
+}
+
+/// [`RcRef`] for an object C++ holds through a pointer `Arc::into_raw()` gave it, which only C++ makes.
+#[repr(transparent)]
+pub struct ArcRef<'a, T> {
+ pointer: *const T,
+ lent: PhantomData<&'a std::sync::Arc<T>>,
+}
+
+impl<T> ArcRef<'_, T> {
+ /// A strong reference of Rust's own to the object.
+ pub(crate) fn to_arc(&self) -> std::sync::Arc<T> {
+ assert!(!self.pointer.is_null(), "C++ lends a live object");
+ // SAFETY: The pointer comes from `Arc::into_raw()`, and the object is live while it is lent.
+ unsafe {
+ std::sync::Arc::increment_strong_count(self.pointer);
+ std::sync::Arc::from_raw(self.pointer)
+ }
+ }
+}
+
/// 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-empty
diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax.rs
index c0cedd3251e..3ec477f2c5a 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/syntax.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax.rs
@@ -441,12 +441,9 @@ pub extern "C" fn rust_parse_syntax(source: FfiUtf16View, limit_ident_to_custom_
Arc::into_raw(Arc::new(syntax)).cast()
}
-/// # Safety
-/// `syntax` must be a live parsed-syntax handle.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_syntax_retain(syntax: *const c_void) -> *const c_void {
- unsafe { Arc::increment_strong_count(syntax.cast::<SyntaxNode>()) };
- syntax
+pub extern "C" fn rust_syntax_retain(syntax: crate::css::ffi_support::ArcRef<'_, SyntaxNode>) -> *const SyntaxNode {
+ Arc::into_raw(syntax.to_arc())
}
/// # Safety
diff --git a/Libraries/LibWeb/Rust/src/css/rule.rs b/Libraries/LibWeb/Rust/src/css/rule.rs
index 82b55e645cc..b0bdb0ce204 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::FfiUtf16View;
+use crate::css::ffi_support::{ArcRef, FfiUtf16View, RcRef};
use crate::css::font_feature_values::FontFeatureValuesRule;
use crate::css::function_signature::FunctionSignature;
use crate::css::import_rule::ImportRuleData;
@@ -776,14 +776,6 @@ fn reserve_rule_identities(count: u64) -> u64 {
.expect("rule identity overflow")
}
-unsafe fn retain_arc<T>(data: *const T) -> Arc<T> {
- assert!(!data.is_null());
- unsafe {
- Arc::increment_strong_count(data);
- Arc::from_raw(data)
- }
-}
-
#[unsafe(no_mangle)]
pub extern "C" fn rust_nested_declarations_create(declarations: &DeclarationBlock) -> *const NativeRule {
Rc::into_raw(NativeRule::new(
@@ -795,9 +787,8 @@ pub extern "C" fn rust_nested_declarations_create(declarations: &DeclarationBloc
}
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_rule_retain(rule: *const NativeRule) -> *const NativeRule {
- unsafe { Rc::increment_strong_count(rule) };
- rule
+pub extern "C" fn rust_rule_retain(rule: RcRef<'_, NativeRule>) -> *const NativeRule {
+ Rc::into_raw(rule.to_rc())
}
#[unsafe(no_mangle)]
@@ -1034,11 +1025,11 @@ pub unsafe extern "C" fn rust_rule_payload(rule: &NativeRule) -> FfiRulePayload<
}
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_rule_set_page_selectors(rule: &NativeRule, selectors: *const PageSelectorList) {
+pub extern "C" fn rust_rule_set_page_selectors(rule: &NativeRule, selectors: ArcRef<'_, PageSelectorList>) {
let RulePayload::Page { selectors: current, .. } = &rule.payload else {
unreachable!()
};
- *current.borrow_mut() = unsafe { retain_arc(selectors) };
+ *current.borrow_mut() = selectors.to_arc();
}
#[unsafe(no_mangle)]
@@ -1062,9 +1053,8 @@ pub extern "C" fn rust_rule_list_remove_imports(list: &NativeRuleList) {
}
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_rule_list_retain(list: *const NativeRuleList) -> *const NativeRuleList {
- unsafe { Rc::increment_strong_count(list) };
- list
+pub extern "C" fn rust_rule_list_retain(list: RcRef<'_, NativeRuleList>) -> *const NativeRuleList {
+ Rc::into_raw(list.to_rc())
}
#[unsafe(no_mangle)]
@@ -1136,9 +1126,8 @@ pub extern "C" fn rust_rule_list_identity_at(list: &NativeRuleList, index: usize
}
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_rule_list_insert(list: &NativeRuleList, index: usize, rule: *const NativeRule) {
- unsafe { Rc::increment_strong_count(rule) };
- list.insert(index, unsafe { Rc::from_raw(rule) });
+pub extern "C" fn rust_rule_list_insert(list: &NativeRuleList, index: usize, rule: RcRef<'_, NativeRule>) {
+ list.insert(index, rule.to_rc());
}
#[repr(u8)]
@@ -1151,18 +1140,14 @@ pub enum RuleInsertionResult {
}
/// https://drafts.csswg.org/cssom/#insert-a-css-rule
-///
-/// # Safety
-/// Rule must be a live Rc-owned native rule. Call on the document thread.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_rule_list_insert_css_rule(
+pub extern "C" fn rust_rule_list_insert_css_rule(
list: &NativeRuleList,
index: usize,
- rule: *const NativeRule,
+ rule: RcRef<'_, NativeRule>,
nested: bool,
) -> RuleInsertionResult {
- unsafe { Rc::increment_strong_count(rule) };
- list.insert_css_rule(index, unsafe { Rc::from_raw(rule) }, nested)
+ list.insert_css_rule(index, rule.to_rc(), nested)
}
#[unsafe(no_mangle)]
diff --git a/Libraries/LibWeb/Rust/src/css/rule/compilation.rs b/Libraries/LibWeb/Rust/src/css/rule/compilation.rs
index ebddc868bb1..453d282c43b 100644
--- a/Libraries/LibWeb/Rust/src/css/rule/compilation.rs
+++ b/Libraries/LibWeb/Rust/src/css/rule/compilation.rs
@@ -1251,7 +1251,7 @@ mod tests {
};
let child = unsafe {
Rc::from_raw(rust_style_sheet_create(
- std::ptr::from_ref(parsed_child.rules()),
+ crate::css::ffi_support::RcRef::new(parsed_child.shared_rules()),
&media,
))
};
@@ -1589,8 +1589,8 @@ mod tests {
let import = &rules[0];
let namespace = &rules[1];
let style = &rules[2];
- let insert = |rule: &Rc<NativeRule>, index, nested| unsafe {
- rust_rule_list_insert_css_rule(target.rules(), index, Rc::as_ptr(rule), nested)
+ let insert = |rule: &Rc<NativeRule>, index, nested| {
+ rust_rule_list_insert_css_rule(target.rules(), index, crate::css::ffi_support::RcRef::new(rule), nested)
};
assert_eq!(insert(style, 2, false), RuleInsertionResult::IndexSizeError);
assert_eq!(insert(style, 0, false), RuleInsertionResult::HierarchyRequestError);
diff --git a/Libraries/LibWeb/Rust/src/css/rule/function.rs b/Libraries/LibWeb/Rust/src/css/rule/function.rs
index f7c6721a939..0d495560b54 100644
--- a/Libraries/LibWeb/Rust/src/css/rule/function.rs
+++ b/Libraries/LibWeb/Rust/src/css/rule/function.rs
@@ -112,14 +112,11 @@ pub unsafe extern "C" fn rust_compiled_function_release(function: *const Compile
}
}
-/// # Safety
-/// The function must be live and Arc-owned.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_compiled_function_retain(function: *const CompiledFunction) -> *const CompiledFunction {
- unsafe {
- Arc::increment_strong_count(function);
- }
- function
+pub extern "C" fn rust_compiled_function_retain(
+ function: crate::css::ffi_support::ArcRef<'_, CompiledFunction>,
+) -> *const CompiledFunction {
+ Arc::into_raw(function.to_arc())
}
/// The functions a style sheet's top-level `@function` rules compile to, in order, with no rule
diff --git a/Libraries/LibWeb/Rust/src/css/rule/read.rs b/Libraries/LibWeb/Rust/src/css/rule/read.rs
index 0941f1b15d3..69b73582f71 100644
--- a/Libraries/LibWeb/Rust/src/css/rule/read.rs
+++ b/Libraries/LibWeb/Rust/src/css/rule/read.rs
@@ -167,17 +167,14 @@ pub extern "C" fn rust_rule_view_import_media(view: &NativeRuleView<'_>) -> *mut
/// Materialize a facade's import rule, including one first exposed after detachment.
///
/// # Safety
-/// Identity must identify this import. Data must be Arc-owned; media must be its loading state.
+/// Identity must identify this import, and media must be its loading state.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_rule_materialize_import(
identity: u64,
- data: *const ImportRuleData,
+ data: crate::css::ffi_support::ArcRef<'_, ImportRuleData>,
media: &MediaList,
) -> *const NativeRule {
- unsafe {
- Arc::increment_strong_count(data);
- }
- let data = unsafe { Arc::from_raw(data) };
+ let data = data.to_arc();
let scope = data.scope.clone();
std::rc::Rc::into_raw(NativeRule::with_identity(
identity,
diff --git a/Libraries/LibWeb/Rust/src/css/scope_selectors.rs b/Libraries/LibWeb/Rust/src/css/scope_selectors.rs
index fc8bb7cd0fe..f84cb5f11dd 100644
--- a/Libraries/LibWeb/Rust/src/css/scope_selectors.rs
+++ b/Libraries/LibWeb/Rust/src/css/scope_selectors.rs
@@ -19,10 +19,10 @@ const _: () = {
};
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_scope_selectors_retain(selectors: *const ScopeSelectors) -> *const ScopeSelectors {
- assert!(!selectors.is_null());
- unsafe { Arc::increment_strong_count(selectors) };
- selectors
+pub extern "C" fn rust_scope_selectors_retain(
+ selectors: crate::css::ffi_support::ArcRef<'_, ScopeSelectors>,
+) -> *const ScopeSelectors {
+ Arc::into_raw(selectors.to_arc())
}
#[unsafe(no_mangle)]
diff --git a/Libraries/LibWeb/Rust/src/css/style_sheet.rs b/Libraries/LibWeb/Rust/src/css/style_sheet.rs
index a70f79e76bf..f8034e9ee19 100644
--- a/Libraries/LibWeb/Rust/src/css/style_sheet.rs
+++ b/Libraries/LibWeb/Rust/src/css/style_sheet.rs
@@ -100,6 +100,11 @@ impl NativeStyleSheet {
&self.rules
}
+ #[cfg(test)]
+ pub(crate) fn shared_rules(&self) -> &Rc<NativeRuleList> {
+ &self.rules
+ }
+
pub(super) fn imported_sheet(&self, identity: u64) -> Option<Rc<Self>> {
self.imports.borrow().get(&identity).cloned()
}
@@ -453,12 +458,11 @@ impl Drop for NativeStyleSheet {
}
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_style_sheet_create(
- rules: *const NativeRuleList,
+pub extern "C" fn rust_style_sheet_create(
+ rules: crate::css::ffi_support::RcRef<'_, NativeRuleList>,
media: &MediaList,
) -> *const NativeStyleSheet {
- unsafe { Rc::increment_strong_count(rules) };
- Rc::into_raw(NativeStyleSheet::new(unsafe { Rc::from_raw(rules) }, media.clone()))
+ Rc::into_raw(NativeStyleSheet::new(rules.to_rc(), media.clone()))
}
#[unsafe(no_mangle)]