Truly independent web browser
/*
* Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
use super::syntax_parser::ParsedStyleSheet;
use super::value_parser::{FfiValueParsingContext, ParseContext, RandomFunctionIndex};
use crate::css::css_tokenizer::TokenizerInput;
use crate::css::ffi_support::FfiUtf16View;
use crate::css::style_compute::{FfiFontMetrics, FfiLengthResolutionContext};
use std::cell::Cell;
use std::collections::{HashMap, HashSet, hash_map::RandomState};
use std::hash::{BuildHasher, Hash, Hasher};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, Weak};
#[derive(PartialEq, Eq, Hash)]
struct LengthResolutionKey {
viewport: [u64; 2],
font: [u64; 5],
root_font: [u64; 5],
container: [u64; 2],
zoom: u64,
flags: [bool; 7],
}
impl LengthResolutionKey {
fn new(context: &FfiLengthResolutionContext) -> Option<Self> {
let FfiLengthResolutionContext {
viewport_width,
viewport_height,
font_metrics,
root_font_metrics,
font_metrics_depend_on_viewport_metrics,
root_font_metrics_depend_on_viewport_metrics,
has_container_width_basis,
has_container_height_basis,
container_width_basis,
container_height_basis,
container_width_basis_depends_on_viewport_metrics,
container_height_basis_depends_on_viewport_metrics,
subject_inline_axis_is_horizontal,
resolved_viewport_relative_length,
zoom,
} = *context;
// A cache hit cannot reproduce writes to an external dependency-tracking flag.
if !resolved_viewport_relative_length.is_null() {
return None;
}
let font_key = |font: &FfiFontMetrics| {
let FfiFontMetrics {
font_size,
x_height,
cap_height,
zero_advance,
line_height,
} = *font;
[
font_size.to_bits(),
x_height.to_bits(),
cap_height.to_bits(),
zero_advance.to_bits(),
line_height.to_bits(),
]
};
Some(Self {
viewport: [viewport_width.to_bits(), viewport_height.to_bits()],
font: font_key(&font_metrics),
root_font: font_key(&root_font_metrics),
container: [container_width_basis.to_bits(), container_height_basis.to_bits()],
zoom: zoom.to_bits(),
flags: [
font_metrics_depend_on_viewport_metrics,
root_font_metrics_depend_on_viewport_metrics,
has_container_width_basis,
has_container_height_basis,
container_width_basis_depends_on_viewport_metrics,
container_height_basis_depends_on_viewport_metrics,
subject_inline_axis_is_horizontal,
],
})
}
}
#[derive(PartialEq, Eq, Hash)]
struct ValueContextKey {
kind: u8,
value: u16,
secondary_value: u16,
name: Box<[u16]>,
}
#[derive(PartialEq, Eq, Hash)]
struct ParsingInputs {
flags: [bool; 5],
value_contexts: Vec<ValueContextKey>,
declared_namespaces: Vec<Box<[u16]>>,
random_function_index: Option<usize>,
}
struct ContextKey {
inputs: ParsingInputs,
document_base_url: Box<[u16]>,
length_resolution: Option<LengthResolutionKey>,
}
#[derive(Clone, Copy, Default)]
struct ParseDependencies {
base_url: bool,
length_resolution: bool,
}
impl ParseDependencies {
fn index(self) -> usize {
usize::from(self.base_url) | (usize::from(self.length_resolution) << 1)
}
fn record(self) {
let previous = PARSE_DEPENDENCIES.get();
PARSE_DEPENDENCIES.set(Self {
base_url: previous.base_url || self.base_url,
length_resolution: previous.length_resolution || self.length_resolution,
});
}
}
thread_local! {
static PARSE_DEPENDENCIES: Cell<ParseDependencies> = const { Cell::new(ParseDependencies {
base_url: false,
length_resolution: false,
}) };
}
pub(super) fn record_length_resolution_dependency() {
ParseDependencies {
length_resolution: true,
..Default::default()
}
.record();
}
struct ParseDependencyScope {
previous: ParseDependencies,
}
impl ParseDependencyScope {
fn new() -> Self {
Self {
previous: PARSE_DEPENDENCIES.replace(ParseDependencies::default()),
}
}
fn dependencies(&self) -> ParseDependencies {
PARSE_DEPENDENCIES.get()
}
}
impl Drop for ParseDependencyScope {
fn drop(&mut self) {
// Propagate dependencies if a parser invokes another cached parse on this thread.
self.previous.record();
}
}
fn own_text(source: TokenizerInput<'_>) -> Box<[u16]> {
let mut text = Vec::with_capacity(source.len());
source.append_to(&mut text);
text.into_boxed_slice()
}
fn own_view(view: FfiUtf16View) -> Option<Box<[u16]>> {
Some(own_text(view.units()?))
}
fn own_url(bytes: &[u8]) -> Option<Box<[u16]>> {
if bytes.is_empty() {
return Some(Box::default());
}
// The legacy URL context is UTF-8. Keep the cache's owned strings in native UTF-16.
Some(std::str::from_utf8(bytes).ok()?.encode_utf16().collect())
}
impl ContextKey {
fn new(context: &ParseContext) -> Option<Self> {
// Keep this exhaustive so new parsing inputs cannot silently bypass the cache key.
let ParseContext {
in_quirks_mode,
is_svg_presentation_attribute,
is_substituted_value,
contains_attr_tainted_values,
is_ua_style_sheet,
value_contexts: borrowed_value_contexts,
declared_namespaces,
// Parsed values do not use the document URL. Image values capture the base URL.
document_url: _,
document_base_url,
length_resolution_context,
random_function_index,
} = *context;
let mut value_contexts = Vec::with_capacity(borrowed_value_contexts.as_slice().len());
for &FfiValueParsingContext {
kind,
value,
secondary_value,
name,
} in borrowed_value_contexts.as_slice()
{
value_contexts.push(ValueContextKey {
kind: kind as u8,
value,
secondary_value,
name: own_view(name)?,
});
}
let declared_namespaces = declared_namespaces
.into_iter()
.flat_map(|namespaces| namespaces.prefixes.iter())
.map(|namespace| namespace.units().into())
.collect();
let length_resolution = match length_resolution_context {
Some(context) => Some(LengthResolutionKey::new(context)?),
None => None,
};
Some(Self {
inputs: ParsingInputs {
flags: [
in_quirks_mode,
is_svg_presentation_attribute,
is_substituted_value,
contains_attr_tainted_values,
is_ua_style_sheet,
],
value_contexts,
declared_namespaces,
random_function_index: random_function_index.map(RandomFunctionIndex::get),
},
document_base_url: own_url(document_base_url.as_slice())?,
length_resolution,
})
}
}
/// Identifies a sheet's text without keeping a copy of it: its length and two keyed hashes of its code units. The
/// keys are random for each process, so a page cannot make two different texts collide.
#[derive(PartialEq, Eq, Hash)]
struct TextDigest {
length: usize,
hashes: [u64; 2],
}
impl TextDigest {
fn new(source: TokenizerInput<'_>) -> Self {
const CHUNK_BYTES: usize = 4096;
static KEYS: OnceLock<[RandomState; 2]> = OnceLock::new();
let mut hashers = KEYS
.get_or_init(|| [RandomState::new(), RandomState::new()])
.each_ref()
.map(RandomState::build_hasher);
let mut write = |bytes: &[u8]| hashers.iter_mut().for_each(|hasher| hasher.write(bytes));
// NB: Equal texts hash equally whether they arrive as Latin-1 or as UTF-16, so UTF-16 text that is all Latin-1 is
// hashed as Latin-1. The first byte keeps the two forms apart otherwise.
let mut chunk = [0u8; CHUNK_BYTES];
match source {
TokenizerInput::Latin1(units) => {
write(&[0]);
write(units);
}
TokenizerInput::Utf16(units) if units.iter().all(|&unit| unit <= 0xFF) => {
write(&[0]);
for part in units.chunks(CHUNK_BYTES) {
for (byte, &unit) in chunk.iter_mut().zip(part) {
*byte = unit as u8;
}
write(&chunk[..part.len()]);
}
}
TokenizerInput::Utf16(units) => {
write(&[1]);
for part in units.chunks(CHUNK_BYTES / 2) {
for (bytes, &unit) in chunk.as_chunks_mut::<2>().0.iter_mut().zip(part) {
bytes.copy_from_slice(&unit.to_ne_bytes());
}
write(&chunk[..part.len() * 2]);
}
}
}
Self {
length: source.len(),
hashes: hashers.map(|hasher| hasher.finish()),
}
}
}
struct StyleSheetKey {
text: TextDigest,
context: Option<ContextKey>,
}
impl Hash for StyleSheetKey {
fn hash<H: Hasher>(&self, state: &mut H) {
self.text.hash(state);
self.context.as_ref().map(|context| &context.inputs).hash(state);
}
}
impl StyleSheetKey {
fn matches(&self, other: &Self, dependencies: ParseDependencies) -> bool {
self.text == other.text
&& match (&self.context, &other.context) {
(None, None) => true,
(Some(left), Some(right)) => {
left.inputs == right.inputs
&& (!dependencies.base_url || left.document_base_url == right.document_base_url)
&& (!dependencies.length_resolution || left.length_resolution == right.length_resolution)
}
_ => false,
}
}
}
/// The scheme and host of a document's URL, keyed for each process, which a parse only the process still keeps is
/// handed out to alone: a hit is about 20 ms faster than a parse, so a page must not be able to tell what the pages
/// of another site parsed.
#[derive(Clone, Copy, PartialEq, Eq)]
struct SitePartition(u64);
impl SitePartition {
fn of_document(context: Option<&ParseContext>) -> Self {
let url = context.map_or(&[][..], |context| context.document_url.as_slice());
let end_of_host = match url.windows(3).position(|bytes| bytes == b"://") {
Some(separator) => url[separator + 3..]
.iter()
.position(|&byte| matches!(byte, b'/' | b'?' | b'#'))
.map_or(url.len(), |end| separator + 3 + end),
None => url.iter().position(|&byte| byte == b':').unwrap_or(url.len()),
};
static HASHER: OnceLock<RandomState> = OnceLock::new();
Self(HASHER.get_or_init(RandomState::new).hash_one(&url[..end_of_host]))
}
}
pub(super) struct CachedParseMetadata {
key: StyleSheetKey,
dependencies: ParseDependencies,
final_random_function_index: Option<usize>,
/// The partition of the document that last asked for the parse.
partition: AtomicU64,
/// Whether the process keeps the parse past its last document.
kept: AtomicBool,
}
type Entries = HashMap<u64, Vec<Weak<ParsedStyleSheet>>>;
#[derive(Default)]
struct Cache {
entries: Entries,
/// The common hashes of the sheets a worker is parsing right now. A worker whose sheet is among them waits for
/// that parse to publish rather than parsing the same sheet again: documents that load one sheet at the same
/// time (a page's frames, e.g.) would otherwise each parse it in full, and all but one throw the result away.
in_flight: HashSet<u64>,
}
struct SharedCache {
cache: Mutex<Cache>,
/// Signaled whenever a parse leaves `in_flight`, published or not.
parse_finished: Condvar,
}
impl SharedCache {
fn the() -> &'static Self {
static CACHE: OnceLock<SharedCache> = OnceLock::new();
CACHE.get_or_init(|| SharedCache {
cache: Mutex::default(),
parse_finished: Condvar::new(),
})
}
fn lock(&self) -> MutexGuard<'_, Cache> {
self.cache.lock().unwrap()
}
}
/// Marks a sheet's parse as in flight for as long as it lives, so that the mark comes off however the parse ends.
struct InFlightParse {
hash: u64,
}
impl Drop for InFlightParse {
fn drop(&mut self) {
let shared = SharedCache::the();
shared.lock().in_flight.remove(&self.hash);
shared.parse_finished.notify_all();
}
}
fn find(entries: &Entries, hash: u64, key: &StyleSheetKey, partition: SitePartition) -> Option<Arc<ParsedStyleSheet>> {
entries.get(&hash)?.iter().filter_map(Weak::upgrade).find(|sheet| {
sheet.cache_metadata.as_ref().is_some_and(|metadata| {
// NB: Only the upgrade and what the process keeps hold a parse no document holds.
let only_kept = metadata.kept.load(Ordering::Relaxed) && Arc::strong_count(sheet) == 2;
metadata.key.matches(key, metadata.dependencies)
&& (!only_kept || metadata.partition.load(Ordering::Relaxed) == partition.0)
})
})
}
/// Have the process keep `sheet`, a parse just published, which holds about `bytes`.
fn keep_past_release(sheet: &Arc<ParsedStyleSheet>, bytes: usize) {
let metadata = sheet
.cache_metadata
.as_ref()
.expect("a published parse has its metadata");
metadata.kept.store(true, Ordering::Relaxed);
crate::render_state::process_style().keep_parsed_sheet(sheet, bytes);
}
pub(super) fn parse_with_cache(
source: TokenizerInput<'_>,
context: Option<&ParseContext>,
parse: impl FnOnce() -> ParsedStyleSheet,
) -> Arc<ParsedStyleSheet> {
let context_key = match context {
Some(context) => match ContextKey::new(context) {
Some(key) => Some(key),
None => return Arc::new(parse()),
},
None => None,
};
let partition = SitePartition::of_document(context);
let key = StyleSheetKey {
text: TextDigest::new(source),
context: context_key,
};
static HASHER: OnceLock<RandomState> = OnceLock::new();
let hash = HASHER.get_or_init(RandomState::new).hash_one(&key);
// Keep context-dependent variants in separate buckets so many documents using one
// contextual sheet do not create a linear scan. Independent sheets use the common key.
let hasher = HASHER.get().unwrap();
let base_url = key.context.as_ref().map(|context| &context.document_base_url);
let lengths = key.context.as_ref().map(|context| &context.length_resolution);
let hashes = [
hash,
hasher.hash_one((hash, 1_u8, base_url)),
hasher.hash_one((hash, 2_u8, lengths)),
hasher.hash_one((hash, 3_u8, base_url, lengths)),
];
let shared = SharedCache::the();
let cached = {
let mut cache = shared.lock();
loop {
if let Some(sheet) = hashes
.iter()
.find_map(|&hash| find(&cache.entries, hash, &key, partition))
{
break Some(sheet);
}
// The parse in flight may publish under a context-dependent hash that this key doesn't match; the
// lookup above misses again then, and this worker parses for itself.
if cache.in_flight.insert(hash) {
break None;
}
cache = shared.parse_finished.wait(cache).unwrap();
}
};
if let Some(sheet) = cached {
let metadata = sheet.cache_metadata.as_ref().unwrap();
metadata.partition.store(partition.0, Ordering::Relaxed);
crate::render_state::process_style().note_parsed_sheet_use(&sheet);
metadata.dependencies.record();
if let Some(counter) = context.and_then(|context| context.random_function_index) {
counter.set(
sheet
.cache_metadata
.as_ref()
.unwrap()
.final_random_function_index
.unwrap(),
);
}
return sheet;
}
// Never hold the cache lock while parsing. Workers parsing different sheets run independently.
let in_flight = InFlightParse { hash };
let dependency_scope = ParseDependencyScope::new();
let mut sheet = parse();
let dependencies = dependency_scope.dependencies();
drop(dependency_scope);
let hash = hashes[dependencies.index()];
let mut cache = shared.lock();
let entries = &mut cache.entries;
// A worker whose context matched this key under another dependency may have published while this one parsed.
if let Some(sheet) = find(entries, hash, &key, partition) {
drop(cache);
drop(in_flight);
return sheet;
}
entries.retain(|_, bucket| {
bucket.retain(|sheet| sheet.strong_count() != 0);
!bucket.is_empty()
});
sheet.cache_metadata = Some(CachedParseMetadata {
key,
dependencies,
final_random_function_index: context
.and_then(|context| context.random_function_index)
.map(RandomFunctionIndex::get),
partition: AtomicU64::new(partition.0),
kept: AtomicBool::new(false),
});
let bytes = source.len() + sheet.bytes_kept_past_release();
let sheet = Arc::new(sheet);
entries.entry(hash).or_default().push(Arc::downgrade(&sheet));
drop(cache);
drop(in_flight);
// NB: Unit tests of parsing count what a parse holds, and that it goes with its last holder.
#[cfg(not(test))]
keep_past_release(&sheet, bytes);
#[cfg(test)]
let _ = bytes;
sheet
}
#[cfg(test)]
mod tests {
use super::*;
fn parsed_for_document(source: &str, document_url: &'static str) -> Arc<ParsedStyleSheet> {
let units: Vec<u16> = source.encode_utf16().collect();
let context = ParseContext {
document_url: ak::Span::new(document_url.as_bytes()),
..Default::default()
};
crate::css::parser::syntax_parser::parse_shared_stylesheet(TokenizerInput::Utf16(&units), Some(&context))
}
#[test]
fn a_page_of_the_same_site_finds_a_parse_no_document_holds_and_another_sites_does_not() {
let source = ".kept-past-release { width: 11.75px }";
let first = parsed_for_document(source, "https://one.example/a");
keep_past_release(&first, 0);
let pointer = Arc::as_ptr(&first);
drop(first);
let second = parsed_for_document(source, "https://one.example/b");
assert_eq!(Arc::as_ptr(&second), pointer);
drop(second);
let other_site = parsed_for_document(source, "https://other.example/a");
assert_ne!(Arc::as_ptr(&other_site), pointer);
// While a document holds a parse, any document finds it, as a frame of another site does.
let frame = parsed_for_document(source, "https://third.example/a");
assert!(Arc::ptr_eq(&frame, &other_site));
}
#[test]
fn text_digests_agree_for_ascii_and_utf16_forms_of_one_text() {
let utf16 = |text: &str| text.encode_utf16().collect::<Vec<_>>();
let long = "a { color: red }\n".repeat(1000);
for text in ["", "a{}", long.as_str()] {
let ascii = TextDigest::new(TokenizerInput::Latin1(text.as_bytes()));
assert!(ascii == TextDigest::new(TokenizerInput::Utf16(&utf16(text))));
}
let ascii = TextDigest::new(TokenizerInput::Latin1(b"a{}"));
assert!(ascii != TextDigest::new(TokenizerInput::Latin1(b"b{}")));
let wide = TextDigest::new(TokenizerInput::Utf16(&utf16("\u{e9}{}")));
assert!(wide == TextDigest::new(TokenizerInput::Utf16(&utf16("\u{e9}{}"))));
assert!(wide != TextDigest::new(TokenizerInput::Utf16(&utf16("\u{e8}{}"))));
}
}