Skip to main content

script/event_loop/
document_loader.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! Tracking of pending loads in a document.
6//!
7//! <https://html.spec.whatwg.org/multipage/#the-end>
8
9use std::collections::HashMap;
10
11use js::context::JSContext;
12use net_traits::ResourceThreads;
13use script_bindings::cell::DomRefCell;
14use script_bindings::script_runtime::{during_gc_collection, runtime_is_alive};
15use servo_url::ServoUrl;
16
17use crate::dom::bindings::root::Dom;
18use crate::dom::document::Document;
19
20#[derive(Clone, Debug, Eq, Hash, JSTraceable, MallocSizeOf, PartialEq)]
21pub(crate) enum LoadType {
22    Image(#[no_trace] ServoUrl),
23    Script(#[no_trace] ServoUrl),
24    Subframe(#[no_trace] ServoUrl),
25    Stylesheet(#[no_trace] ServoUrl),
26    PageSource(#[no_trace] ServoUrl),
27    Media,
28}
29
30/// Canary value ensuring that manually added blocking loads are always removed by the
31/// time that the owner is destroyed.
32#[derive(JSTraceable, MallocSizeOf)]
33#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
34pub(crate) struct LoadBlocker {
35    /// The document whose load event is blocked by this object existing.
36    doc: Dom<Document>,
37    /// The load that is blocking the document's load event.
38    load: Option<LoadType>,
39}
40
41impl LoadBlocker {
42    /// Mark the document's load event as blocked on this new load.
43    pub(crate) fn new(doc: &Document, load: LoadType) -> LoadBlocker {
44        doc.loader_mut().add_blocking_load(load.clone());
45        LoadBlocker {
46            doc: Dom::from_ref(doc),
47            load: Some(load),
48        }
49    }
50
51    /// Remove this load from the associated document's list of blocking loads.
52    pub(crate) fn terminate(cx: &mut JSContext, blocker: &DomRefCell<Option<LoadBlocker>>) {
53        let Some(load) = blocker
54            .safe_borrow_mut(cx.no_gc())
55            .as_mut()
56            .and_then(|blocker| blocker.load.take())
57        else {
58            return;
59        };
60
61        if let Some(blocker) = blocker.borrow().as_ref() {
62            blocker.doc.finish_load(load, cx);
63        }
64
65        *blocker.safe_borrow_mut(cx.no_gc()) = None;
66    }
67}
68
69impl Drop for LoadBlocker {
70    fn drop(&mut self) {
71        // We need to check here if the whole runtime is alive, otherwise
72        // we interact with a document that is also being dropped. That
73        // would panic, since we should no longer schedule a task for
74        // a dropped runtime. Therefore, we should only run the drop logic
75        // in case this element is dropped, but its containing document
76        // is still alive.
77        //
78        // This destructor can also run from during GC (see #46207), which can lead to
79        // accessing already freed memory if we run `finish_load_for_dropped_blocker`.
80        if runtime_is_alive() &&
81            !during_gc_collection() &&
82            let Some(load) = self.load.take()
83        {
84            self.doc.finish_load_for_dropped_blocker(load);
85        }
86    }
87}
88
89#[derive(JSTraceable, MallocSizeOf)]
90pub(crate) struct DocumentLoader {
91    #[no_trace]
92    resource_threads: ResourceThreads,
93    /// A map from [`LoadType`] to the number of blocking loads. When a particular [`LoadType`]
94    /// reaches zero, it is removed from the map and no longer blocks the load.
95    blocking_loads: HashMap<LoadType, u32>,
96    events_inhibited: bool,
97    /// Whether or not the load was aborted via [`Document::abort`].
98    aborted: bool,
99}
100
101impl DocumentLoader {
102    pub(crate) fn new(existing: &DocumentLoader) -> DocumentLoader {
103        DocumentLoader::new_with_threads(existing.resource_threads.clone(), None)
104    }
105
106    pub(crate) fn new_with_threads(
107        resource_threads: ResourceThreads,
108        initial_load: Option<ServoUrl>,
109    ) -> DocumentLoader {
110        debug!("Initial blocking load {:?}.", initial_load);
111
112        let initial_loads = initial_load
113            .into_iter()
114            .map(|url| (LoadType::PageSource(url), 1))
115            .collect();
116
117        DocumentLoader {
118            resource_threads,
119            blocking_loads: initial_loads,
120            events_inhibited: false,
121            aborted: false,
122        }
123    }
124
125    /// Add a load to the list of blocking loads.
126    pub(crate) fn add_blocking_load(&mut self, load: LoadType) {
127        debug!(
128            "Adding blocking load {:?} ({}).",
129            load,
130            self.blocking_loads.len()
131        );
132        self.blocking_loads
133            .entry(load)
134            .and_modify(|load_number| *load_number += 1)
135            .or_insert(1);
136    }
137
138    /// Mark an in-progress network request complete.
139    pub(crate) fn finish_load(&mut self, load: &LoadType) {
140        debug!(
141            "Removing blocking load {:?} ({}).",
142            load,
143            self.blocking_loads.len()
144        );
145
146        let Some(entry) = self.blocking_loads.get_mut(load) else {
147            warn!("unknown completed load {load:?}");
148            return;
149        };
150
151        *entry = entry.saturating_sub(1);
152        if *entry == 0 {
153            self.blocking_loads.remove(load);
154        }
155    }
156
157    pub(crate) fn is_blocked(&self) -> bool {
158        // TODO: Ensure that we report blocked if parsing is still ongoing.
159        !self.blocking_loads.is_empty()
160    }
161
162    pub(crate) fn is_only_blocked_by_iframes(&self) -> bool {
163        self.blocking_loads
164            .keys()
165            .all(|load| matches!(*load, LoadType::Subframe(_)))
166    }
167
168    pub(crate) fn inhibit_events(&mut self) {
169        self.events_inhibited = true;
170    }
171
172    pub(crate) fn events_inhibited(&self) -> bool {
173        self.events_inhibited
174    }
175
176    pub(crate) fn abort(&mut self) {
177        self.aborted = true;
178        self.events_inhibited = true;
179    }
180
181    pub(crate) fn aborted(&self) -> bool {
182        self.aborted
183    }
184
185    pub(crate) fn resource_threads(&self) -> &ResourceThreads {
186        &self.resource_threads
187    }
188}