Skip to content

Truly independent web browser

LibWeb: Make FfiMediaEnvironment a borrowed view that reads safely

Andreas Kling6c56b8e771c0
diff --git a/Libraries/LibWeb/Rust/src/css/custom_properties.rs b/Libraries/LibWeb/Rust/src/css/custom_properties.rs
index f7e9b1e7217..b540ccce101 100644
--- a/Libraries/LibWeb/Rust/src/css/custom_properties.rs
+++ b/Libraries/LibWeb/Rust/src/css/custom_properties.rs
@@ -942,7 +942,7 @@ struct ASFResolutionContext<'a> {
uses_attr_tainted_url: bool,
custom_functions: Option<&'a CustomFunctionRegistry>,
parse_context: Option<&'a ParseContext>,
- media_environment: Option<&'a FfiMediaEnvironment>,
+ media_environment: Option<&'a FfiMediaEnvironment<'a>>,
/// What lengths in a style query resolve against: the element's last computed style.
style_query_length_resolution_context: Option<&'a crate::css::style_compute::FfiLengthResolutionContext>,
/// What colors in a style query resolve against, where the queried element's are known.
@@ -2516,7 +2516,7 @@ fn evaluate_if_condition(
return ConditionEvaluation::NotHandled;
};
let source = serialize_tokens(&test[1..close]);
- return match unsafe { parse_and_evaluate_media_if_condition(&source, environment) } {
+ return match parse_and_evaluate_media_if_condition(&source, environment) {
Some(MatchResult::True) => ConditionEvaluation::Match(true),
Some(MatchResult::False | MatchResult::Unknown) => ConditionEvaluation::Match(false),
None => ConditionEvaluation::Invalid,
@@ -3369,7 +3369,7 @@ pub(crate) struct VarResolutionInputs<'a> {
pub(crate) inheritance_store: Option<&'a CustomPropertyStore>,
pub(crate) registry: Option<&'a CustomPropertyRegistry>,
pub(crate) parse_context: Option<&'a ParseContext>,
- pub(crate) media_environment: Option<&'a FfiMediaEnvironment>,
+ pub(crate) media_environment: Option<&'a FfiMediaEnvironment<'a>>,
pub(crate) attribute_names_are_ascii_case_insensitive: bool,
pub(crate) style_query_inputs: Option<&'a crate::css::cascaded_properties::FfiStyleQueryInputs>,
}
diff --git a/Libraries/LibWeb/Rust/src/css/media_list.rs b/Libraries/LibWeb/Rust/src/css/media_list.rs
index ce3b3d9d674..5c2be623e24 100644
--- a/Libraries/LibWeb/Rust/src/css/media_list.rs
+++ b/Libraries/LibWeb/Rust/src/css/media_list.rs
@@ -228,6 +228,6 @@ pub extern "C" fn rust_media_list_item_matches(list: &MediaList, index: usize) -
}
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_media_list_evaluate(list: &MediaList, environment: FfiMediaEnvironment) -> bool {
- list.evaluate(unsafe { environment.borrow() })
+pub extern "C" fn rust_media_list_evaluate(list: &MediaList, environment: FfiMediaEnvironment<'_>) -> bool {
+ list.evaluate(environment.borrow())
}
diff --git a/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs
index 344c92aa58a..9d665e0d53f 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs
@@ -27,6 +27,7 @@ use crate::css::serialize::{StringUnits, TextSink, serialize_an_identifier, seri
use crate::css::style_compute::{FfiLengthResolutionContext, LENGTH_UNIT_NAMES, px_length_unit};
use crate::css::style_value::StyleValueData;
use std::ffi::c_void;
+use std::marker::PhantomData;
use std::sync::Arc;
include!(concat!(env!("OUT_DIR"), "/media_features_generated.rs"));
@@ -185,12 +186,17 @@ pub struct FfiMediaFeatureValue {
pub second_value: f64,
}
+/// The media feature values and length resolution context media queries evaluate against, borrowed for `'a`.
+///
+/// Rust builds one only from borrowed values, and C++ hands one over under the same contract: `values` identifies
+/// `value_count` values, and a non-null `length_resolution_context` a context, which stay readable for `'a`.
#[derive(Clone, Copy)]
#[repr(C)]
-pub struct FfiMediaEnvironment {
- pub values: *const FfiMediaFeatureValue,
- pub value_count: usize,
- pub length_resolution_context: *const c_void,
+pub struct FfiMediaEnvironment<'a> {
+ values: *const FfiMediaFeatureValue,
+ value_count: usize,
+ length_resolution_context: *const c_void,
+ lent: PhantomData<(&'a [FfiMediaFeatureValue], Option<&'a FfiLengthResolutionContext>)>,
}
#[derive(Clone, Copy)]
@@ -199,16 +205,39 @@ pub(crate) struct MediaEnvironment<'a> {
length_context: Option<&'a FfiLengthResolutionContext>,
}
-impl FfiMediaEnvironment {
- /// # Safety
- /// The feature values and optional length context must remain readable while borrowed.
- pub(crate) unsafe fn borrow(&self) -> MediaEnvironment<'_> {
- let data = unsafe { ffi_media_environment(self) };
+impl<'a> FfiMediaEnvironment<'a> {
+ pub(crate) fn new(values: &'a [FfiMediaFeatureValue], length: Option<&'a FfiLengthResolutionContext>) -> Self {
+ Self {
+ values: values.as_ptr(),
+ value_count: values.len(),
+ length_resolution_context: length.map_or(std::ptr::null(), |length| std::ptr::from_ref(length).cast()),
+ lent: PhantomData,
+ }
+ }
+
+ pub(crate) fn borrow(&self) -> MediaEnvironment<'a> {
+ let data = self.parts();
MediaEnvironment {
values: data.map(|(values, _)| values),
length_context: data.and_then(|(_, context)| context),
}
}
+
+ /// The feature values and the length context, or none for an environment that names values it has no storage for.
+ fn parts(&self) -> Option<(&'a [FfiMediaFeatureValue], Option<&'a FfiLengthResolutionContext>)> {
+ if self.value_count != 0 && self.values.is_null() {
+ return None;
+ }
+ // SAFETY: The environment is readable for 'a, as the type says.
+ unsafe {
+ Some((
+ ak::slice_from_raw_parts(self.values, self.value_count),
+ self.length_resolution_context
+ .cast::<FfiLengthResolutionContext>()
+ .as_ref(),
+ ))
+ }
+ }
}
#[derive(Clone, Copy)]
@@ -2414,29 +2443,9 @@ fn evaluate_supports_expression(expression: &Expression) -> MatchResult {
}
}
-unsafe fn ffi_media_environment(
- environment: &FfiMediaEnvironment,
-) -> Option<(&[FfiMediaFeatureValue], Option<&FfiLengthResolutionContext>)> {
- let values = if environment.value_count == 0 {
- &[]
- } else {
- if environment.values.is_null() {
- return None;
- }
- unsafe { ak::slice_from_raw_parts(environment.values, environment.value_count) }
- };
- let length_context = unsafe {
- environment
- .length_resolution_context
- .cast::<FfiLengthResolutionContext>()
- .as_ref()
- };
- Some((values, length_context))
-}
-
-pub(crate) unsafe fn parse_and_evaluate_media_if_condition(
+pub(crate) fn parse_and_evaluate_media_if_condition(
source: &[u16],
- environment: &FfiMediaEnvironment,
+ environment: &FfiMediaEnvironment<'_>,
) -> Option<MatchResult> {
// NB: Mirrors the media arm of evaluate_condition_for_substitution, which this series removed
// from Libraries/LibWeb/CSS/StyleComputer.cpp. Try a standalone media feature first, then
@@ -2445,7 +2454,7 @@ pub(crate) unsafe fn parse_and_evaluate_media_if_condition(
let values = components_from_source(source)?;
parse_media_condition(&values, &resolve_query_feature)
})?;
- let (values, length_context) = unsafe { ffi_media_environment(environment) }?;
+ let (values, length_context) = environment.parts()?;
Some(evaluate_media_expression(&expression, values, length_context))
}
@@ -2912,7 +2921,7 @@ fn parse_sizes_attribute(
pub unsafe extern "C" fn rust_parse_sizes_attribute(
source: FfiUtf16View,
context: Option<&ParseContext>,
- media_environment: Option<&FfiMediaEnvironment>,
+ media_environment: Option<&FfiMediaEnvironment<'_>>,
img_auto_width: Option<&f64>,
) -> *const c_void {
crate::css::ffi_stats::bump(crate::css::ffi_stats::FfiOp::SizesAttributeParseEntry);
@@ -2922,7 +2931,7 @@ pub unsafe extern "C" fn rust_parse_sizes_attribute(
let Some(context) = context else {
return std::ptr::null();
};
- let media_environment = media_environment.and_then(|environment| unsafe { ffi_media_environment(environment) });
+ let media_environment = media_environment.and_then(FfiMediaEnvironment::parts);
let img_auto_width = img_auto_width.copied();
Arc::into_raw(Arc::new(parse_sizes_attribute(
context,
diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rs
index ff64e16b6cd..08eb0d47f38 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rs
@@ -1120,7 +1120,10 @@ fn media_mutation_preserves_live_owners_and_shared_snapshots() {
let retained = media.clone();
unsafe {
let shared = Box::from_raw(rust_media_list_share(&media));
- assert!(rust_media_list_evaluate(&media, std::mem::zeroed()));
+ assert!(rust_media_list_evaluate(
+ &media,
+ crate::css::parser::query_parser::FfiMediaEnvironment::new(&[], None)
+ ));
assert!(rust_media_list_matches(&retained));
assert!(!rust_media_list_matches(&shared));
assert!(matches!(
diff --git a/Libraries/LibWeb/Rust/src/css/rule/compilation.rs b/Libraries/LibWeb/Rust/src/css/rule/compilation.rs
index ee9605860d5..ebddc868bb1 100644
--- a/Libraries/LibWeb/Rust/src/css/rule/compilation.rs
+++ b/Libraries/LibWeb/Rust/src/css/rule/compilation.rs
@@ -312,13 +312,13 @@ pub(crate) unsafe fn style_sheet_visit_compilation(
rule_identity: u64,
purpose: NativeCompilationPurpose,
source: *const c_void,
- environment: FfiMediaEnvironment,
+ environment: FfiMediaEnvironment<'_>,
callbacks: &NativeCompilationCallbacks,
) {
// SAFETY: Guaranteed by the caller.
let (host, source) = unsafe { CompilationHost::new(callbacks, source) };
// SAFETY: Guaranteed by the caller.
- let environment = unsafe { environment.borrow() };
+ let environment = environment.borrow();
visit_compilation(sheet, rule_identity, purpose, source, environment, host, None);
}
@@ -334,7 +334,7 @@ pub unsafe extern "C" fn rust_style_sheet_compile(
sheet: &NativeStyleSheet,
rule_identity: u64,
source: *const c_void,
- environment: FfiMediaEnvironment,
+ environment: FfiMediaEnvironment<'_>,
callbacks: &NativeCompilationCallbacks,
publication: &NativeStylePublication,
) {
@@ -343,7 +343,7 @@ pub unsafe extern "C" fn rust_style_sheet_compile(
// SAFETY: Guaranteed by the caller.
let (host, source) = unsafe { CompilationHost::new(callbacks, source) };
// SAFETY: Guaranteed by the caller.
- let environment = unsafe { environment.borrow() };
+ let environment = environment.borrow();
visit_compilation(
sheet,
rule_identity,
@@ -365,11 +365,11 @@ pub unsafe extern "C" fn rust_style_sheet_replace_selectors(
sheet: &NativeStyleSheet,
rule_identity: u64,
source: *const c_void,
- environment: FfiMediaEnvironment,
+ environment: FfiMediaEnvironment<'_>,
callbacks: &NativeCompilationCallbacks,
publication: &NativeStylePublication,
) {
- let environment = unsafe { environment.borrow() };
+ let environment = environment.borrow();
// SAFETY: Guaranteed by the caller.
let publisher = unsafe { Publisher::new(publication) };
// SAFETY: Guaranteed by the caller.
@@ -623,12 +623,8 @@ mod tests {
];
values[id].kind = FfiMediaFeatureValueKind::Length;
values[id].value = width;
- let environment = FfiMediaEnvironment {
- values: values.as_ptr(),
- value_count: values.len(),
- length_resolution_context: std::ptr::null(),
- };
- visit(unsafe { environment.borrow() })
+ let environment = FfiMediaEnvironment::new(&values, None);
+ visit(environment.borrow())
}
fn media_at(sheet: &NativeStyleSheet, path: &[usize]) -> MediaList {
@@ -1149,15 +1145,11 @@ mod tests {
let mut images = 0_usize;
unsafe { rust_rule_list_visit_images(rules, (&raw mut images).cast(), image) };
assert_eq!(images, 1);
- let environment = FfiMediaEnvironment {
- values: std::ptr::null(),
- value_count: 0,
- length_resolution_context: std::ptr::null(),
- };
+ let environment = FfiMediaEnvironment::new(&[], None);
let mut media_state = crate::css::style_sheet::NativeMediaEvaluationState::default();
assert!(
!source
- .evaluate_media_queries(unsafe { environment.borrow() }, &mut media_state, &mut |_, _| {})
+ .evaluate_media_queries(environment.borrow(), &mut media_state, &mut |_, _| {})
.any_changed
);
assert!(rules.rules.borrow().is_none());
@@ -1181,7 +1173,7 @@ mod tests {
});
assert!(
!source
- .evaluate_media_queries(unsafe { environment.borrow() }, &mut media_state, &mut |_, _| {})
+ .evaluate_media_queries(environment.borrow(), &mut media_state, &mut |_, _| {})
.any_changed
);
}
@@ -1290,12 +1282,8 @@ mod tests {
sheet: compiled_sheet,
before: 0,
};
- let environment = FfiMediaEnvironment {
- values: std::ptr::null(),
- value_count: 0,
- length_resolution_context: std::ptr::null(),
- };
- let borrowed_environment = unsafe { environment.borrow() };
+ let environment = FfiMediaEnvironment::new(&[], None);
+ let borrowed_environment = environment.borrow();
let mut media_state = crate::css::style_sheet::NativeMediaEvaluationState::default();
assert!(
!source
@@ -1333,7 +1321,7 @@ mod tests {
);
}
assert_eq!(compiled.get(), 9);
- unsafe { crate::css::style_sheet::rust_style_sheet_publish_conditions(&source, host.host(), environment) };
+ crate::css::style_sheet::rust_style_sheet_publish_conditions(&source, host.host(), environment);
unsafe extern "C" fn prepare(_: *mut c_void) {}
let sheets = [Rc::as_ptr(&source)];
assert!(unsafe {
@@ -1714,11 +1702,7 @@ mod tests {
implicit_scope_root: root,
visit_rule: visit,
};
- let environment = FfiMediaEnvironment {
- values: std::ptr::null(),
- value_count: 0,
- length_resolution_context: std::ptr::null(),
- };
+ let environment = FfiMediaEnvironment::new(&[], None);
unsafe {
style_sheet_visit_compilation(
sheet,
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 52635bbf9c3..a48ae29f35e 100644
--- a/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs
@@ -83,15 +83,8 @@ impl DocumentMediaSnapshot {
}
/// The snapshot as the resolver reads a media environment, borrowing from it.
- fn environment(&self) -> crate::css::parser::query_parser::FfiMediaEnvironment {
- crate::css::parser::query_parser::FfiMediaEnvironment {
- values: self.values.as_ptr(),
- value_count: self.values.len(),
- length_resolution_context: self
- .length
- .as_ref()
- .map_or(std::ptr::null(), |length| std::ptr::from_ref(length).cast()),
- }
+ fn environment(&self) -> crate::css::parser::query_parser::FfiMediaEnvironment<'_> {
+ crate::css::parser::query_parser::FfiMediaEnvironment::new(&self.values, self.length.as_ref())
}
/// What lengths resolve against for a document without styled elements.
@@ -225,7 +218,7 @@ impl DocumentFunctionSnapshot {
inputs.custom_function_count = 0;
let media_environment = media.environment();
// SAFETY: The environment points into the media snapshot, which outlives the evaluation.
- let media_environment = unsafe { media_environment.borrow() };
+ let media_environment = media_environment.borrow();
for &caller_scope in self.caller_scopes.values() {
if self.scope_functions.contains_key(&caller_scope) {
continue;
@@ -349,7 +342,7 @@ fn engine_resolution_context<'a>(
inheritance_store: Option<&'a CustomPropertyStore>,
registry: &'a crate::css::custom_properties::CustomPropertyRegistry,
attributes: Option<&'a SubstitutionAttributes<'a>>,
- media_environment: &'a crate::css::parser::query_parser::FfiMediaEnvironment,
+ media_environment: &'a crate::css::parser::query_parser::FfiMediaEnvironment<'a>,
style_query: Option<&'a crate::css::cascaded_properties::FfiStyleQueryInputs>,
style_query_references: Option<&'a mut Option<Box<crate::css::custom_properties::StyleQueryDependencies>>>,
functions: Option<&'a PreparedCustomFunctions>,
diff --git a/Libraries/LibWeb/Rust/src/css/style_sheet.rs b/Libraries/LibWeb/Rust/src/css/style_sheet.rs
index afc80265b6d..a70f79e76bf 100644
--- a/Libraries/LibWeb/Rust/src/css/style_sheet.rs
+++ b/Libraries/LibWeb/Rust/src/css/style_sheet.rs
@@ -519,19 +519,15 @@ pub extern "C" fn rust_style_sheet_reset_media_state(sheet: &NativeStyleSheet) {
/// Evaluate media queries throughout the sheet graph from one document environment snapshot, and queue whether the
/// conditions of the rules whose conditions changed hold.
-///
-/// # Safety
-/// `host` must be a live document host, on its document's thread, and the environment must contain
-/// valid media feature data.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_style_sheet_evaluate_media_queries(
+pub extern "C" fn rust_style_sheet_evaluate_media_queries(
sheet: &NativeStyleSheet,
- environment: FfiMediaEnvironment,
+ environment: FfiMediaEnvironment<'_>,
state: &mut NativeMediaEvaluationState,
host: &crate::render_state::DocumentHost,
) -> NativeStyleSheetMediaEvaluation {
let mut conditions = Vec::new();
- let result = sheet.evaluate_media_queries(unsafe { environment.borrow() }, state, &mut |identity, holds| {
+ let result = sheet.evaluate_media_queries(environment.borrow(), state, &mut |identity, holds| {
conditions.push((identity, holds));
});
write_rule_conditions(host, conditions);
@@ -539,18 +535,14 @@ pub unsafe extern "C" fn rust_style_sheet_evaluate_media_queries(
}
/// Queue inherited condition gates for the document engine.
-///
-/// # Safety
-/// `host` must be a live document host, on its document's thread, and the environment live for this
-/// call.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_style_sheet_publish_conditions(
+pub extern "C" fn rust_style_sheet_publish_conditions(
sheet: &NativeStyleSheet,
host: &crate::render_state::DocumentHost,
- environment: FfiMediaEnvironment,
+ environment: FfiMediaEnvironment<'_>,
) {
let mut conditions = Vec::new();
- sheet.visit_conditions(unsafe { environment.borrow() }, true, &mut |identity, holds| {
+ sheet.visit_conditions(environment.borrow(), true, &mut |identity, holds| {
conditions.push((identity, holds));
});
write_rule_conditions(host, conditions);
@@ -689,11 +681,7 @@ mod tests {
#[test]
fn media_cache_invalidation_reads_shared_rules_without_owners() {
- let environment = FfiMediaEnvironment {
- values: std::ptr::null(),
- value_count: 0,
- length_resolution_context: std::ptr::null(),
- };
+ let environment = FfiMediaEnvironment::new(&[], None);
for (text, reaches_cache) in [
("@media all { .target { color: red; } }", false),
("@media all { @keyframes motion { from { opacity: 0; } } }", true),
@@ -702,11 +690,11 @@ mod tests {
let sheet = sheet(&parse(text));
let owners = crate::css::rule::RULE_OWNER_ALLOCATIONS.get();
let mut state = NativeMediaEvaluationState::default();
- let initial = sheet.evaluate_media_queries(unsafe { environment.borrow() }, &mut state, &mut |_, _| {});
+ let initial = sheet.evaluate_media_queries(environment.borrow(), &mut state, &mut |_, _| {});
assert!(!initial.any_changed);
assert!(!initial.style_cache_inputs_changed);
set_media(&sheet, "not all");
- let changed = sheet.evaluate_media_queries(unsafe { environment.borrow() }, &mut state, &mut |_, _| {});
+ let changed = sheet.evaluate_media_queries(environment.borrow(), &mut state, &mut |_, _| {});
assert!(changed.sheet_changed);
assert_eq!(changed.style_cache_inputs_changed, reaches_cache);
assert_eq!(crate::css::rule::RULE_OWNER_ALLOCATIONS.get(), owners);