Nacre/vendor/servo-script/event_loop/document_loader.rs
astar76 0ecfd0f573 S031: root due timers in vendored servo-script (R5-01 SIGSEGV), crash-adblock regression smoke
fire_timer moved due timers into an unrooted Vec; a GC inside one callback swept
the functions of the timers still waiting. Heavy-web reruns and cargo test still pending.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:38:47 -06:00

180 lines
5.6 KiB
Rust

/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Tracking of pending loads in a document.
//!
//! <https://html.spec.whatwg.org/multipage/#the-end>
#![cfg_attr(crown, allow(crown::jscontext_first_arg))]
use std::collections::HashMap;
use net_traits::ResourceThreads;
use script_bindings::cell::DomRefCell;
use script_bindings::script_runtime::{during_gc_collection, runtime_is_alive};
use servo_url::ServoUrl;
use crate::dom::bindings::root::Dom;
use crate::dom::document::Document;
#[derive(Clone, Debug, Eq, Hash, JSTraceable, MallocSizeOf, PartialEq)]
pub(crate) enum LoadType {
Image(#[no_trace] ServoUrl),
Script(#[no_trace] ServoUrl),
Subframe(#[no_trace] ServoUrl),
Stylesheet(#[no_trace] ServoUrl),
PageSource(#[no_trace] ServoUrl),
Media,
}
/// Canary value ensuring that manually added blocking loads are always removed by the
/// time that the owner is destroyed.
#[derive(JSTraceable, MallocSizeOf)]
#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
pub(crate) struct LoadBlocker {
/// The document whose load event is blocked by this object existing.
doc: Dom<Document>,
/// The load that is blocking the document's load event.
load: Option<LoadType>,
}
impl LoadBlocker {
/// Mark the document's load event as blocked on this new load.
pub(crate) fn new(doc: &Document, load: LoadType) -> LoadBlocker {
doc.loader_mut().add_blocking_load(load.clone());
LoadBlocker {
doc: Dom::from_ref(doc),
load: Some(load),
}
}
/// Remove this load from the associated document's list of blocking loads.
pub(crate) fn terminate(
blocker: &DomRefCell<Option<LoadBlocker>>,
cx: &mut js::context::JSContext,
) {
let Some(load) = blocker
.safe_borrow_mut(cx.no_gc())
.as_mut()
.and_then(|blocker| blocker.load.take())
else {
return;
};
if let Some(blocker) = blocker.borrow().as_ref() {
blocker.doc.finish_load(load, cx);
}
*blocker.safe_borrow_mut(cx.no_gc()) = None;
}
}
impl Drop for LoadBlocker {
fn drop(&mut self) {
// We need to check here if the whole runtime is alive, otherwise
// we interact with a document that is also being dropped. That
// would panic, since we should no longer schedule a task for
// a dropped runtime. Therefore, we should only run the drop logic
// in case this element is dropped, but its containing document
// is still alive.
//
// This destructor can also run from during GC (see #46207), which can lead to
// accessing already freed memory if we run `finish_load_for_dropped_blocker`.
if runtime_is_alive() &&
!during_gc_collection() &&
let Some(load) = self.load.take()
{
self.doc.finish_load_for_dropped_blocker(load);
}
}
}
#[derive(JSTraceable, MallocSizeOf)]
pub(crate) struct DocumentLoader {
#[no_trace]
resource_threads: ResourceThreads,
/// A map from [`LoadType`] to the number of blocking loads. When a particular [`LoadType`]
/// reaches zero, it is removed from the map and no longer blocks the load.
blocking_loads: HashMap<LoadType, u32>,
events_inhibited: bool,
}
impl DocumentLoader {
pub(crate) fn new(existing: &DocumentLoader) -> DocumentLoader {
DocumentLoader::new_with_threads(existing.resource_threads.clone(), None)
}
pub(crate) fn new_with_threads(
resource_threads: ResourceThreads,
initial_load: Option<ServoUrl>,
) -> DocumentLoader {
debug!("Initial blocking load {:?}.", initial_load);
let initial_loads = initial_load
.into_iter()
.map(|url| (LoadType::PageSource(url), 1))
.collect();
DocumentLoader {
resource_threads,
blocking_loads: initial_loads,
events_inhibited: false,
}
}
/// Add a load to the list of blocking loads.
pub(crate) fn add_blocking_load(&mut self, load: LoadType) {
debug!(
"Adding blocking load {:?} ({}).",
load,
self.blocking_loads.len()
);
self.blocking_loads
.entry(load)
.and_modify(|load_number| *load_number += 1)
.or_insert(1);
}
/// Mark an in-progress network request complete.
pub(crate) fn finish_load(&mut self, load: &LoadType) {
debug!(
"Removing blocking load {:?} ({}).",
load,
self.blocking_loads.len()
);
let Some(entry) = self.blocking_loads.get_mut(load) else {
warn!("unknown completed load {load:?}");
return;
};
*entry = entry.saturating_sub(1);
if *entry == 0 {
self.blocking_loads.remove(load);
}
}
pub(crate) fn is_blocked(&self) -> bool {
// TODO: Ensure that we report blocked if parsing is still ongoing.
!self.blocking_loads.is_empty()
}
pub(crate) fn is_only_blocked_by_iframes(&self) -> bool {
self.blocking_loads
.keys()
.all(|load| matches!(*load, LoadType::Subframe(_)))
}
pub(crate) fn inhibit_events(&mut self) {
self.events_inhibited = true;
}
pub(crate) fn events_inhibited(&self) -> bool {
self.events_inhibited
}
pub(crate) fn resource_threads(&self) -> &ResourceThreads {
&self.resource_threads
}
}