Skip to content

Truly independent web browser

LibWeb: Run render jobs a host waits for on the host's own thread

Andreas Klingcb3046552756
diff --git a/Libraries/LibWeb/Layout/RenderDocument.cpp b/Libraries/LibWeb/Layout/RenderDocument.cpp
index 4743c20d179..930a81e2832 100644
--- a/Libraries/LibWeb/Layout/RenderDocument.cpp
+++ b/Libraries/LibWeb/Layout/RenderDocument.cpp
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/StackInfo.h>
#include <LibWeb/CSS/StyleComputer.h>
#include <LibWeb/CSS/StyleEngineBridge.h>
#include <LibWeb/DOM/Document.h>
@@ -35,3 +36,11 @@ ForcedReadScope::ForcedReadScope(DOM::Document const& document)
}
}
+
+// The lowest address of the calling thread's stack, which the render state asks for before it runs a job on a host's
+// thread rather than the StyleLayout thread's larger stack.
+extern "C" FlatPtr web_current_thread_stack_base();
+extern "C" FlatPtr web_current_thread_stack_base()
+{
+ return AK::StackInfo {}.base();
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs b/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs
index 47c2e47ba06..2e6ffc5eecc 100644
--- a/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs
@@ -145,6 +145,11 @@ pub(crate) struct StagedInput {
}
impl StagedInput {
+ /// How many tree deltas the batch holds, each of which may deepen the tree by a level.
+ pub(crate) fn tree_delta_count(&self) -> usize {
+ self.tree.len()
+ }
+
fn is_empty(&self) -> bool {
self.tree.is_empty()
&& self.arrivals.is_empty()
diff --git a/Libraries/LibWeb/Rust/src/css/style/inputs.rs b/Libraries/LibWeb/Rust/src/css/style/inputs.rs
index 4d2a445b23f..4835cd43197 100644
--- a/Libraries/LibWeb/Rust/src/css/style/inputs.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/inputs.rs
@@ -2581,6 +2581,25 @@ impl StyleEngine {
.resize_required_to(&mut self.retained.memory, bytes);
}
+ /// Raises `deepest_element` to the depth of the deepest element the tree holds, and keeps `staged_rows` at how many
+ /// relation rows are staged and not settled yet, both of which the document's host reads, rather than counts of
+ /// the engine's own. Nothing is staged yet.
+ pub(crate) fn share_tree_depth(
+ &mut self,
+ deepest_element: std::sync::Arc<std::sync::atomic::AtomicU32>,
+ staged_rows: std::sync::Arc<std::sync::atomic::AtomicU32>,
+ ) {
+ self.retained.tree.share_deepest_element(deepest_element);
+ self.host.tree_staging.share_staged_rows(staged_rows);
+ }
+
+ /// Gives a fork counts of the tree's depth of its own in place of those it shares with the host, holding what they
+ /// hold now.
+ pub(crate) fn detach_tree_depth_for_fork(&mut self) {
+ self.retained.tree.detach_deepest_element_for_fork();
+ self.host.tree_staging.detach_staged_rows_for_fork();
+ }
+
/// Install final staged relation rows at the transaction barrier.
pub(super) fn apply_staged_tree_deltas(&mut self) {
if self.host.tree_staging.is_empty() || self.host.tree_staging.is_applied() {
diff --git a/Libraries/LibWeb/Rust/src/css/style/tree.rs b/Libraries/LibWeb/Rust/src/css/style/tree.rs
index a2c8a839652..06ab2c840cc 100644
--- a/Libraries/LibWeb/Rust/src/css/style/tree.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/tree.rs
@@ -26,6 +26,8 @@ use super::fast_hash::FastSet as HashSet;
use smallvec::SmallVec;
use std::cmp::Ordering;
use std::num::NonZeroU32;
+use std::sync::Arc;
+use std::sync::atomic::AtomicU32;
use super::capacity::capacity_bytes;
use super::column::BitColumn;
@@ -255,6 +257,8 @@ pub(super) struct TreeRelationStaging {
touched_first_children: Vec<StyleNodeID>,
dirty_first_children: Vec<StyleNodeID>,
applied: bool,
+ /// How many rows are staged, which the document's host reads: each may deepen the tree by a level once settled.
+ staged_rows: Arc<AtomicU32>,
}
type StagedTreeRows = Vec<(StyleNodeID, Option<TreeRelations>, Option<TreeRelations>)>;
@@ -321,10 +325,27 @@ impl TreeRelationStaging {
);
self.touched_rows.push(node);
self.dirty_rows.push(node);
+ self.staged_rows.store(
+ u32::try_from(self.touched_rows.len()).unwrap_or(u32::MAX),
+ std::sync::atomic::Ordering::Relaxed,
+ );
}
}
}
+ /// Gives a fork a count of staged rows of its own in place of the one it shares with the host.
+ pub(super) fn detach_staged_rows_for_fork(&mut self) {
+ let staged = self.staged_rows.load(std::sync::atomic::Ordering::Relaxed);
+ self.staged_rows = Arc::new(AtomicU32::new(staged));
+ }
+
+ /// Keeps `staged_rows`, which the document's host reads, at how many rows are staged, rather than a count of the
+ /// staging's own. Nothing is staged yet.
+ pub(super) fn share_staged_rows(&mut self, staged_rows: Arc<AtomicU32>) {
+ debug_assert!(self.touched_rows.is_empty());
+ self.staged_rows = staged_rows;
+ }
+
pub(super) fn stage_first_child(
&mut self,
parent: StyleNodeID,
@@ -427,7 +448,12 @@ impl TreeRelationStaging {
}
pub(super) fn clear(&mut self) {
- *self = Self::default();
+ let staged_rows = std::mem::take(&mut self.staged_rows);
+ staged_rows.store(0, std::sync::atomic::Ordering::Relaxed);
+ *self = Self {
+ staged_rows,
+ ..Self::default()
+ };
}
pub(super) fn capacity_bytes(&self) -> u64 {
@@ -700,9 +726,36 @@ pub struct StyleNodeTree {
#[cfg(test)]
depth_recompute_visits: usize,
+ /// The depth of the deepest element the tree ever held, which the document's host reads.
+ deepest_element: Arc<AtomicU32>,
}
impl StyleNodeTree {
+ /// Raises `deepest_element`, which the document's host reads, to the depth of the deepest element the tree holds
+ /// from now on, rather than a count of the tree's own.
+ pub(super) fn share_deepest_element(&mut self, deepest_element: Arc<AtomicU32>) {
+ deepest_element.fetch_max(
+ self.deepest_element.load(std::sync::atomic::Ordering::Relaxed),
+ std::sync::atomic::Ordering::Relaxed,
+ );
+ self.deepest_element = deepest_element;
+ }
+
+ /// Gives a fork a depth of its own in place of the one it shares with the host.
+ pub(super) fn detach_deepest_element_for_fork(&mut self) {
+ let deepest = self.deepest_element.load(std::sync::atomic::Ordering::Relaxed);
+ self.deepest_element = Arc::new(AtomicU32::new(deepest));
+ }
+
+ /// Notes that an element of the tree is `depth` deep.
+ #[inline]
+ fn note_element_depth(&self, depth: u32) {
+ if depth > self.deepest_element.load(std::sync::atomic::Ordering::Relaxed) {
+ self.deepest_element
+ .fetch_max(depth, std::sync::atomic::Ordering::Relaxed);
+ }
+ }
+
pub(super) fn collect_atoms(&self, atoms: &mut HashSet<StyleAtomID>) -> u64 {
let mut visited = 0_u64;
if let Some(shadow) = &self.shadow {
@@ -749,6 +802,7 @@ impl StyleNodeTree {
dom_order_version: 0,
#[cfg(test)]
depth_recompute_visits: 0,
+ deepest_element: Arc::default(),
};
// Slot 0 is never a valid identity; reserving it keeps column indexing direct.
tree.parent.push(None);
@@ -1337,8 +1391,10 @@ impl StyleNodeTree {
let mut next = Some(node);
while let Some(descendant) = next {
let descendant_index = self.live_element_index(descendant);
- self.depth[descendant_index] = u32::try_from(i64::from(self.depth[descendant_index]) + adjustment)
+ let depth = u32::try_from(i64::from(self.depth[descendant_index]) + adjustment)
.expect("style tree depth exhausted");
+ self.note_element_depth(depth);
+ self.depth[descendant_index] = depth;
next = self.first_element_child[descendant_index].or_else(|| {
let mut candidate = descendant;
loop {
@@ -1371,9 +1427,11 @@ impl StyleNodeTree {
self.depth_recompute_visits += 1;
}
let index = self.live_element_index(node);
- self.depth[index] = self.parent[index].map_or(0, |parent| {
+ let depth = self.parent[index].map_or(0, |parent| {
self.depth(parent).checked_add(1).expect("style tree depth exhausted")
});
+ self.note_element_depth(depth);
+ self.depth[index] = depth;
next = self.first_element_child[index].or_else(|| {
let mut candidate = node;
loop {
diff --git a/Libraries/LibWeb/Rust/src/render_state.rs b/Libraries/LibWeb/Rust/src/render_state.rs
index 97c290df2f6..355e33d89ca 100644
--- a/Libraries/LibWeb/Rust/src/render_state.rs
+++ b/Libraries/LibWeb/Rust/src/render_state.rs
@@ -61,6 +61,7 @@ impl RenderState {
engine.share_element_random_base_values_exist(shared.element_random_base_values_exist);
engine.share_declaration_block_versions(shared.declaration_block_versions);
engine.share_container_effects_held(shared.container_effects_held);
+ engine.share_tree_depth(shared.deepest_element, shared.staged_tree_rows);
let engine = StyleEngineHandle::create(engine);
arena
.arena_mut()
@@ -108,6 +109,7 @@ impl RenderState {
pub(crate) fn fork(&self) -> RenderFork {
let mut engine = Box::new(self.engine_ref().clone());
engine.detach_host_flags_for_fork();
+ engine.detach_tree_depth_for_fork();
let engine = StyleEngineHandle::create(engine);
let arena = Box::new(self.arena.fork(engine));
RenderFork(std::mem::ManuallyDrop::new(Self {
@@ -729,14 +731,73 @@ impl ChangeQueue {
}
}
-/// Runs `job` on the render owner, the StyleLayout thread, and waits for it, so it may borrow from the calling frame. A
-/// job handed from that thread itself, as a host callback's while the owner runs another job, runs right there, and a
-/// unit test's jobs run on the test's own thread.
-fn on_render_side<R: Send>(job: impl FnOnce() -> R + Send) -> R {
+/// Runs `job` on the render owner and waits for it, so it may borrow from the calling frame. A job handed from the
+/// owner itself, as a host callback's while the owner runs another job, runs right there, and a unit test's jobs run on
+/// the test's own thread.
+///
+/// The calling thread becomes the owner for the job where it waits for nothing the StyleLayout thread runs: that thread
+/// has run every job the calling thread made for it, so the job comes after them as it would there, and the calling
+/// thread's stack has room for the job to recurse through a tree `tree_depth` levels deep. Otherwise the StyleLayout
+/// thread runs it.
+fn on_render_side<R: Send>(tree_depth: u32, job: impl FnOnce() -> R + Send) -> R {
if cfg!(test) {
return job();
}
- crate::stage_thread::style_layout_thread().run(job)
+ let thread = crate::stage_thread::style_layout_thread();
+ if thread.is_current() || owner::is_held_here() {
+ return job();
+ }
+ // OPTIMIZATION: A host waits for a job it hands the StyleLayout thread anyway, so running it right here saves both
+ // threads a hand-off, which costs more than a small job such as a forced layout read takes.
+ if thread.ran_every_job_handed_from_here() && stack_has_room_for_render_job(tree_depth) {
+ return owner::hold(job);
+ }
+ thread.run(job)
+}
+
+/// Waits until the StyleLayout thread has run the jobs handed to it before. A thread that holds the render owner's slot
+/// waits for nothing: no job on the render states runs elsewhere meanwhile, and one waiting for the slot waits for it.
+fn wait_for_render_side() {
+ if cfg!(test) || owner::is_held_here() {
+ return;
+ }
+ crate::stage_thread::style_layout_thread().run(|| ());
+}
+
+/// Whether the calling thread's stack has room for a job on a render state that recurses through a tree `tree_depth`
+/// levels deep. Only the StyleLayout thread's stack is large enough for any tree.
+#[cfg(not(test))]
+fn stack_has_room_for_render_job(tree_depth: u32) -> bool {
+ /// The stack a job on a render state takes at most per level of the tree it recurses through, as it builds and
+ /// lays out boxes, with room to spare for the boxes a level adds: release builds took about 1.5 KiB per element,
+ /// and debug builds about 2 KiB.
+ const STACK_PER_TREE_LEVEL: usize = 16 * 1024;
+ /// The stack a job on a render state takes beside its recursion through the tree, with room to spare.
+ const STACK_BESIDE_RECURSION: usize = 1024 * 1024;
+ unsafe extern "C" {
+ fn web_current_thread_stack_base() -> usize;
+ }
+ thread_local! {
+ static STACK_BASE: Cell<usize> = const { Cell::new(0) };
+ }
+ let mut base = STACK_BASE.get();
+ if base == 0 {
+ // SAFETY: The function only reads the calling thread's stack bounds.
+ base = unsafe { web_current_thread_stack_base() };
+ STACK_BASE.set(base);
+ }
+ let here = 0u8;
+ let free = std::ptr::from_ref(&here).addr().saturating_sub(base);
+ usize::try_from(tree_depth)
+ .ok()
+ .and_then(|depth| depth.checked_mul(STACK_PER_TREE_LEVEL))
+ .and_then(|recursion| recursion.checked_add(STACK_BESIDE_RECURSION))
+ .is_some_and(|needed| free > needed)
+}
+
+#[cfg(test)]
+fn stack_has_room_for_render_job(_: u32) -> bool {
+ false
}
/// Posts `job` to the render owner, which runs it after the jobs handed to it before, and goes on. A unit test's job
diff --git a/Libraries/LibWeb/Rust/src/render_state/clock.rs b/Libraries/LibWeb/Rust/src/render_state/clock.rs
index 4bd3edff4cd..d07fda237fc 100644
--- a/Libraries/LibWeb/Rust/src/render_state/clock.rs
+++ b/Libraries/LibWeb/Rust/src/render_state/clock.rs
@@ -731,7 +731,7 @@ impl ClockTicks {
if cfg!(test) {
return;
}
- crate::stage_thread::style_layout_thread().run(|| ());
+ super::wait_for_render_side();
crate::paint_stage::paint_thread().run(|| ());
}
@@ -1767,7 +1767,7 @@ pub(super) fn settle_lanes_for_testing() {
}
};
settle_paint();
- crate::stage_thread::style_layout_thread().run(|| ());
+ super::wait_for_render_side();
settle_paint();
}
@@ -1786,7 +1786,7 @@ pub unsafe extern "C" fn document_host_presented_color(
generated_for: u8,
color: *mut u32,
) -> bool {
- crate::stage_thread::style_layout_thread().run(|| ());
+ super::wait_for_render_side();
let Some(presented) =
StyleNodeID::from_raw(element).and_then(|element| host.clock_ticks().presented_color(element, generated_for))
else {
@@ -1825,7 +1825,7 @@ pub unsafe extern "C" fn document_host_presented_compositor_animation_count(
element: u32,
count: *mut u32,
) -> bool {
- crate::stage_thread::style_layout_thread().run(|| ());
+ super::wait_for_render_side();
let Some(presented) = StyleNodeID::from_raw(element)
.and_then(|element| host.clock_ticks().presented_compositor_animation_count(element))
else {
@@ -1845,7 +1845,7 @@ pub unsafe extern "C" fn document_host_presented_compositor_animation_count(
/// be valid for writes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn document_host_presented_opacity(host: &DocumentHost, element: u32, opacity: *mut f32) -> bool {
- crate::stage_thread::style_layout_thread().run(|| ());
+ super::wait_for_render_side();
let Some(presented) =
StyleNodeID::from_raw(element).and_then(|element| host.clock_ticks().presented_opacity(element))
else {
@@ -1869,7 +1869,7 @@ pub unsafe extern "C" fn document_host_presented_border_box(
element: u32,
rect: *mut FfiCssPixelRect,
) -> bool {
- crate::stage_thread::style_layout_thread().run(|| ());
+ super::wait_for_render_side();
let Some(presented) =
StyleNodeID::from_raw(element).and_then(|element| host.clock_ticks().presented_border_box(element))
else {
diff --git a/Libraries/LibWeb/Rust/src/render_state/document_host.rs b/Libraries/LibWeb/Rust/src/render_state/document_host.rs
index 3106addc534..caad2ad4344 100644
--- a/Libraries/LibWeb/Rust/src/render_state/document_host.rs
+++ b/Libraries/LibWeb/Rust/src/render_state/document_host.rs
@@ -728,7 +728,7 @@ impl DocumentHost {
});
None
}
- None => Some(on_render_side(move || super::clock::take_lanes_in(&ticks, update))),
+ None => Some(on_render_side(0, move || super::clock::take_lanes_in(&ticks, update))),
};
// A same-process iframe's lanes hear of the pointer from the lanes of the document around it, which handed them
// nothing of a newer move the compositor told that document of: the pointer may have gone elsewhere, and the
@@ -960,7 +960,8 @@ impl DocumentHost {
.as_slice()
.iter()
.any(|change| !change.keeps_the_presented_frame());
- let answer = on_render_side(move || {
+ let tree_depth = self.tree_depth_bound(changes.as_slice());
+ let answer = on_render_side(tree_depth, move || {
if moves_state {
super::clock::note_host_write(document);
}
@@ -986,6 +987,26 @@ impl DocumentHost {
answer
}
+ /// How deep the document's style tree may be once a job applies `changes`: as deep as its deepest element ever was,
+ /// and a level deeper for each relation row the engine staged and has not settled, and for each tree delta of
+ /// `changes`.
+ fn tree_depth_bound(&self, changes: &[ArenaChange]) -> u32 {
+ let queued_tree_deltas = changes
+ .iter()
+ .map(|change| match change {
+ ArenaChange::Engine(crate::css::style::engine_calls::EngineWrite::ApplyTransaction(input)) => {
+ input.tree_delta_count()
+ }
+ _ => 0,
+ })
+ .sum::<usize>();
+ self.shared
+ .deepest_element
+ .load(Ordering::Relaxed)
+ .saturating_add(self.shared.staged_tree_rows.load(Ordering::Relaxed))
+ .saturating_add(u32::try_from(queued_tree_deltas).unwrap_or(u32::MAX))
+ }
+
/// Answers `read` of the document's render state, spending `wait`, as of every write the host queued. A read leaves
/// the paint and hit testing properties prepared from the state current: what it brings up to date first, a
/// preparation leaves up to date, or only a layout round reads, but for overflow it measures first, which can
diff --git a/Libraries/LibWeb/Rust/src/render_state/owner.rs b/Libraries/LibWeb/Rust/src/render_state/owner.rs
index cd6bb8800c9..4d89278db3d 100644
--- a/Libraries/LibWeb/Rust/src/render_state/owner.rs
+++ b/Libraries/LibWeb/Rust/src/render_state/owner.rs
@@ -6,11 +6,12 @@
//! The render owner: whichever thread holds the slot every document's render state lives in.
//!
-//! The StyleLayout thread holds the slot for the jobs it runs. A thread holds the slot only for the length of a job,
-//! never between them, so no thread waits for another to run script. The host names its document's state by the
-//! [`DocumentId`] it minted, and reaches it only with a job. The owner makes a state the first time a job reaches it,
-//! from what the host's [`StateSeed`] says, so a document that never sends its state anything never makes one, and
-//! drops it with the job that retires it.
+//! The StyleLayout thread holds the slot for the jobs it runs, and a host's thread holds it for a job it runs itself,
+//! while it waits for nothing the StyleLayout thread runs (see [`super::on_render_side`]). A thread holds the slot only
+//! for the length of a job, never between them, so no thread waits for another to run script. The host names its
+//! document's state by the [`DocumentId`] it minted, and reaches it only with a job. The owner makes a state the first
+//! time a job reaches it, from what the host's [`StateSeed`] says, so a document that never sends its state anything
+//! never makes one, and drops it with the job that retires it.
use super::RenderState;
use std::cell::{Cell, RefCell, UnsafeCell};
@@ -46,6 +47,11 @@ pub(crate) struct SharedWithHost {
pub(super) container_effects_held: Arc<AtomicBool>,
/// The versions the state's style engine mints declaration blocks from, which the host mints from as well.
pub(super) declaration_block_versions: Arc<AtomicU32>,
+ /// The depth of the deepest element the state's style tree ever held.
+ pub(super) deepest_element: Arc<AtomicU32>,
+ /// How many relation rows the state's style engine staged and has not settled yet, each of which may deepen the
+ /// tree by a level.
+ pub(super) staged_tree_rows: Arc<AtomicU32>,
}
impl SharedWithHost {
diff --git a/Libraries/LibWeb/Rust/src/stage_thread.rs b/Libraries/LibWeb/Rust/src/stage_thread.rs
index b8787536495..f8d58244831 100644
--- a/Libraries/LibWeb/Rust/src/stage_thread.rs
+++ b/Libraries/LibWeb/Rust/src/stage_thread.rs
@@ -4,8 +4,9 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! The threads a document's rendering runs on beside the host's: the StyleLayout thread, which every document's
-//! render state lives on, and the Paint thread, which records display lists from the frames the render states publish.
+//! The threads a document's rendering runs on beside the host's: the StyleLayout thread, which runs the jobs on every
+//! document's render state that the host does not run itself, and the Paint thread, which records display lists from
+//! the frames the render states publish.
//!
//! There is one of each per process, spawned the first time it is handed a job. A WebContent process runs every
//! document it hosts on its one main thread, so a thread per process is also a thread per event loop. The host waits
@@ -19,11 +20,12 @@
//! threads that run.
use crate::render_state::TaskBoundary;
-use std::cell::{Cell, UnsafeCell};
+use smallvec::SmallVec;
+use std::cell::{Cell, RefCell, UnsafeCell};
use std::marker::PhantomData;
use std::panic::AssertUnwindSafe;
use std::ptr::NonNull;
-use std::sync::atomic::{AtomicBool, AtomicPtr, Ordering};
+use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, OnceLock, PoisonError};
use std::thread::Thread;
@@ -70,6 +72,26 @@ struct Shared {
tsan_key: AtomicBool,
}
+impl Shared {
+ /// Notes that a job has run, which `unfinished` counted among those its thread made, before the thread tells
+ /// whoever waits for it.
+ fn note_ran(&self, unfinished: Option<Arc<AtomicUsize>>) {
+ tsan::release(&self.tsan_key);
+ if let Some(unfinished) = unfinished {
+ unfinished.fetch_sub(1, Ordering::Release);
+ }
+ }
+}
+
+/// How many of the jobs a thread made for each stage thread have yet to run, by the address of what the stage thread
+/// shares.
+type UnfinishedJobCounts = SmallVec<[(usize, Arc<AtomicUsize>); 2]>;
+
+thread_local! {
+ /// How many of the jobs the calling thread made for each stage thread have yet to run.
+ static UNFINISHED_HANDED: RefCell<UnfinishedJobCounts> = RefCell::new(SmallVec::new());
+}
+
static THREAD_SETUP: OnceLock<extern "C" fn()> = OnceLock::new();
/// Makes each stage thread run `setup` first thing once it starts. Call it before any is handed a job; the first setup
@@ -117,7 +139,7 @@ impl StageThread {
// it runs, as the thread that handed it may leave the frame it is in once it is done.
unsafe {
next = job.as_ref().next.get();
- (job.as_ref().run)(job, &shared.tsan_key);
+ (job.as_ref().run)(job, shared);
}
}
}
@@ -142,7 +164,10 @@ impl StageThread {
return job();
}
let mut answer = None;
- let job = JobInFrame::new(|| answer = Some(std::panic::catch_unwind(AssertUnwindSafe(job))));
+ let job = JobInFrame::new(
+ || answer = Some(std::panic::catch_unwind(AssertUnwindSafe(job))),
+ self.count_unfinished(),
+ );
self.hand(NonNull::from(&job).cast());
wait_for(|| job.done.load(Ordering::Acquire).then_some(()));
tsan::acquire(&self.shared.tsan_key);
@@ -174,7 +199,7 @@ impl StageThread {
let flight = Flight::pending();
let parked = ParkedJob {
thread: self,
- header: SubmittedJob::give_up(job, Arc::clone(&flight)),
+ header: SubmittedJob::give_up(job, Arc::clone(&flight), self.count_unfinished()),
};
let flight = InFlight {
flight,
@@ -186,7 +211,7 @@ impl StageThread {
/// Posts `job` to this thread and goes on: the job owns what it reads, runs after the jobs handed to the thread
/// before it, and answers nothing. A job posted from this thread runs once the job it is posted from is done.
pub(crate) fn post(&self, job: impl FnOnce() + Send + 'static) {
- self.hand(PostedJob::give_up(job));
+ self.hand(PostedJob::give_up(job, self.count_unfinished()));
}
/// Hands the job `header` heads to this thread, which runs it after the jobs handed to it before.
@@ -206,6 +231,45 @@ impl StageThread {
self.thread.unpark();
}
}
+
+ /// Counts a job the calling thread makes for this thread among those that have yet to run, which the job uncounts
+ /// once it has run.
+ fn count_unfinished(&self) -> Arc<AtomicUsize> {
+ let key = self.key();
+ UNFINISHED_HANDED.with_borrow_mut(|unfinished| {
+ let count = match unfinished.iter().find(|(of, _)| *of == key) {
+ Some((_, count)) => Arc::clone(count),
+ None => {
+ let count = Arc::new(AtomicUsize::new(0));
+ unfinished.push((key, Arc::clone(&count)));
+ count
+ }
+ };
+ count.fetch_add(1, Ordering::Relaxed);
+ count
+ })
+ }
+
+ /// Whether this thread has run every job the calling thread made for it, so that nothing the calling thread asked
+ /// of it waits to run.
+ pub(crate) fn ran_every_job_handed_from_here(&self) -> bool {
+ let key = self.key();
+ let done = UNFINISHED_HANDED.with_borrow(|unfinished| {
+ unfinished
+ .iter()
+ .find(|(of, _)| *of == key)
+ .is_none_or(|(_, count)| count.load(Ordering::Acquire) == 0)
+ });
+ if done {
+ tsan::acquire(&self.shared.tsan_key);
+ }
+ done
+ }
+
+ /// The key the calling thread counts the jobs it made for this thread by.
+ fn key(&self) -> usize {
+ std::ptr::from_ref(self.shared).addr()
+ }
}
/// Relinks the jobs a stage thread took, the last one handed `last` and each linked to the one handed before it, so
@@ -222,9 +286,11 @@ fn in_handed_order(last: NonNull<JobHeader>) -> NonNull<JobHeader> {
/// What a stage thread knows of a job handed to it: how to run it, which the job's kind says.
struct JobHeader {
- /// Runs the job this header heads, and tells whoever takes its answer that it is done, after it has released the
- /// thread's ThreadSanitizer key it is handed.
- run: unsafe fn(NonNull<JobHeader>, &AtomicBool),
+ /// Runs the job this header heads, and tells whoever takes its answer that it is done, after it has noted on the
+ /// thread's shared state that it ran.
+ run: unsafe fn(NonNull<JobHeader>, &Shared),
+ /// The count of unfinished jobs of the thread that made the job, which the job is counted in until it has run.
+ unfinished: Cell<Option<Arc<AtomicUsize>>>,
/// Until the stage thread takes the job, the job handed to it before this one and not taken yet; then, the job it
/// runs after this one.
next: Cell<Option<NonNull<JobHeader>>>,
@@ -243,10 +309,11 @@ struct JobInFrame<F> {
impl<F: FnOnce() + Send> JobInFrame<F> {
/// A job the calling thread is to hand out and wait for.
- fn new(job: F) -> Self {
+ fn new(job: F, unfinished: Arc<AtomicUsize>) -> Self {
Self {
header: JobHeader {
run: Self::run_handed,
+ unfinished: Cell::new(Some(unfinished)),
next: Cell::new(None),
},
waiting: UnsafeCell::new(Some(std::thread::current())),
@@ -261,16 +328,18 @@ impl<F: FnOnce() + Send> JobInFrame<F> {
///
/// `header` must head a live `JobInFrame<F>` that was handed out to the calling thread and is not done yet, which
/// nothing else reaches meanwhile.
- unsafe fn run_handed(header: NonNull<JobHeader>, tsan_key: &AtomicBool) {
+ unsafe fn run_handed(header: NonNull<JobHeader>, shared: &Shared) {
let job = header.cast::<Self>();
// SAFETY: Guaranteed by the caller: the thread that handed the job out reaches none of it until `done`.
+ let unfinished = unsafe { job.as_ref() }.header.unfinished.take();
+ // SAFETY: As above.
let waiting = unsafe {
if let Some(run) = (*job.as_ref().job.get()).take() {
run();
}
(*job.as_ref().waiting.get()).take()
};
- tsan::release(tsan_key);
+ shared.note_ran(unfinished);
// SAFETY: As above. The waiting thread may leave the frame the job is in as soon as it sees `done`.
unsafe { job.as_ref() }.done.store(true, Ordering::Release);
if let Some(waiting) = waiting {
@@ -305,10 +374,11 @@ struct SubmittedJob<F, R> {
impl<F: FnOnce(&StopWord) -> R + Send, R: Send> SubmittedJob<F, R> {
/// The header of `job` on the heap, which the stage thread it is handed to frees, and lands in `flight`.
- fn give_up(job: F, flight: Arc<Flight<R>>) -> NonNull<JobHeader> {
+ fn give_up(job: F, flight: Arc<Flight<R>>, unfinished: Arc<AtomicUsize>) -> NonNull<JobHeader> {
let job = Box::new(Self {
header: JobHeader {
run: Self::run_submitted,
+ unfinished: Cell::new(Some(unfinished)),
next: Cell::new(None),
},
job,
@@ -322,12 +392,12 @@ impl<F: FnOnce(&StopWord) -> R + Send, R: Send> SubmittedJob<F, R> {
/// # Safety
///
/// `header` must come from [`Self::give_up`], and be handed out to the calling thread only.
- unsafe fn run_submitted(header: NonNull<JobHeader>, tsan_key: &AtomicBool) {
+ unsafe fn run_submitted(header: NonNull<JobHeader>, shared: &Shared) {
// SAFETY: Guaranteed by the caller: the submitting thread gave the job up.
let job = unsafe { Box::from_raw(header.cast::<Self>().as_ptr()) };
- let Self { job, flight, .. } = *job;
+ let Self { header, job, flight } = *job;
let answer = std::panic::catch_unwind(AssertUnwindSafe(|| job(&flight.stop)));
- tsan::release(tsan_key);
+ shared.note_ran(header.unfinished.take());
flight.land(answer);
if let Some(finished) = FLIGHT_FINISHED.get() {
finished();
@@ -345,10 +415,11 @@ struct PostedJob<F> {
impl<F: FnOnce() + Send> PostedJob<F> {
/// The header of `job` on the heap, which the stage thread it is handed to frees.
- fn give_up(job: F) -> NonNull<JobHeader> {
+ fn give_up(job: F, unfinished: Arc<AtomicUsize>) -> NonNull<JobHeader> {
let job = Box::new(Self {
header: JobHeader {
run: Self::run_posted,
+ unfinished: Cell::new(Some(unfinished)),
next: Cell::new(None),
},
job,
@@ -361,13 +432,14 @@ impl<F: FnOnce() + Send> PostedJob<F> {
/// # Safety
///
/// `header` must come from [`Self::give_up`], and be handed out to the calling thread only.
- unsafe fn run_posted(header: NonNull<JobHeader>, tsan_key: &AtomicBool) {
+ unsafe fn run_posted(header: NonNull<JobHeader>, shared: &Shared) {
// SAFETY: Guaranteed by the caller: the posting thread gave the job up.
let job = unsafe { Box::from_raw(header.cast::<Self>().as_ptr()) };
- if std::panic::catch_unwind(AssertUnwindSafe(job.job)).is_err() {
+ let Self { header, job } = *job;
+ if std::panic::catch_unwind(AssertUnwindSafe(job)).is_err() {
std::process::abort();
}
- tsan::release(tsan_key);
+ shared.note_ran(header.unfinished.take());
}
}
@@ -619,7 +691,7 @@ fn wait_for<T>(mut ready: impl FnMut() -> Option<T>) -> T {
static STYLE_LAYOUT_THREAD: OnceLock<StageThread> = OnceLock::new();
-/// The StyleLayout thread, which every document's render state lives on.
+/// The StyleLayout thread, which runs the jobs on every document's render state that the host does not run itself.
pub(crate) fn style_layout_thread() -> &'static StageThread {
STYLE_LAYOUT_THREAD.get_or_init(|| StageThread::spawn("StyleLayout"))
}
@@ -706,6 +778,40 @@ mod tests {
assert_eq!(test_thread().run(|| ran.load(Ordering::Relaxed)), 1);
}
+ #[test]
+ fn a_thread_knows_whether_the_jobs_it_handed_have_run() {
+ let (open, wait) = gate();
+ test_thread().post(wait);
+ test_thread().post(|| ());
+ assert!(
+ !test_thread().ran_every_job_handed_from_here(),
+ "a posted job waits behind the gate"
+ );
+ let other = std::thread::spawn(|| test_thread().ran_every_job_handed_from_here());
+ assert!(
+ other.join().unwrap_or_default(),
+ "another thread handed the stage thread nothing"
+ );
+ open.store(true, Ordering::Release);
+ while !test_thread().ran_every_job_handed_from_here() {
+ std::thread::yield_now();
+ }
+ test_thread().post(|| ());
+ test_thread().run(|| ());
+ assert!(
+ test_thread().ran_every_job_handed_from_here(),
+ "a job the thread waited for ran after the jobs it handed before"
+ );
+ let (flight, parked) = test_thread().park(|_| 7u32);
+ assert!(
+ !test_thread().ran_every_job_handed_from_here(),
+ "a parked job counts for the thread that made it"
+ );
+ let _ = std::thread::spawn(move || drop(parked)).join();
+ assert_eq!(flight.join(()), 7);
+ assert!(test_thread().ran_every_job_handed_from_here());
+ }
+
#[test]
fn a_job_that_panics_panics_in_the_thread_that_waits_for_it() {
let panicked = std::panic::catch_unwind(|| test_thread().run(|| panic!("the job panicked")));
diff --git a/Meta/Linters/check_rust_process_wide_state.py b/Meta/Linters/check_rust_process_wide_state.py
index 52c9a96dec2..e5bbc899d18 100755
--- a/Meta/Linters/check_rust_process_wide_state.py
+++ b/Meta/Linters/check_rust_process_wide_state.py
@@ -136,6 +136,8 @@ RENDER_STATE_ALLOWED = {
"per-thread count of the holds of the render owner's slot the thread is in",
["render_state/owner.rs:HOLDS"],
),
+ f"{RENDER_STATE_CRATE}/src/render_state.rs:STACK_BASE": "per-thread cache of the thread's own stack bounds",
+ f"{RENDER_STATE_CRATE}/src/stage_thread.rs:UNFINISHED_HANDED": "per-thread count of the jobs the thread made for each stage thread that have yet to run",
**render_state_entries(
BUILT_ONCE,
[
diff --git a/Tests/LibWeb/Crash/Layout/deep-tree-inserted-before-forced-layout.html b/Tests/LibWeb/Crash/Layout/deep-tree-inserted-before-forced-layout.html
new file mode 100644
index 00000000000..bd5936ed1ed
--- /dev/null
+++ b/Tests/LibWeb/Crash/Layout/deep-tree-inserted-before-forced-layout.html
@@ -0,0 +1,10 @@
+<!DOCTYPE html>
+<!-- A forced layout right after a deep tree is inserted in one write lays out all of it. 8000 levels overflowed an
+ 8 MiB stack. -->
+<body>
+<script>
+ document.body.offsetHeight;
+ document.body.innerHTML = "<div>".repeat(8000) + "leaf";
+ document.body.offsetHeight;
+</script>
+</body>