Skip to main content

script/dom/bindings/
trace.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//! Utilities for tracing JS-managed values.
6//!
7//! The lifetime of DOM objects is managed by the SpiderMonkey Garbage
8//! Collector. A rooted DOM object implementing the interface `Foo` is traced
9//! as follows:
10//!
11//! 1. The GC calls `_trace` defined in `FooBinding` during the marking
12//!    phase. (This happens through `JSClass.trace` for non-proxy bindings, and
13//!    through `ProxyTraps.trace` otherwise.)
14//! 2. `_trace` calls `Foo::trace()` (an implementation of `JSTraceable`).
15//!    This is typically derived via a `#[dom_struct]`
16//!    (implies `#[derive(JSTraceable)]`) annotation.
17//!    Non-JS-managed types have an empty inline `trace()` method,
18//!    achieved via `unsafe_no_jsmanaged_fields!` or similar.
19//! 3. For all fields, `Foo::trace()`
20//!    calls `trace()` on the field.
21//!    For example, for fields of type `Dom<T>`, `Dom<T>::trace()` calls
22//!    `trace_reflector()`.
23//! 4. `trace_reflector()` calls `Dom::TraceEdge()` with a
24//!    pointer to the `JSObject` for the reflector. This notifies the GC, which
25//!    will add the object to the graph, and will trace that object as well.
26//! 5. When the GC finishes tracing, it [`finalizes`](../index.html#destruction)
27//!    any reflectors that were not reachable.
28//!
29//! The `unsafe_no_jsmanaged_fields!()` macro adds an empty implementation of
30//! `JSTraceable` to a datatype.
31
32use std::collections::HashMap;
33use std::collections::hash_map::RandomState;
34use std::fmt::Display;
35use std::hash::{BuildHasher, Hash};
36
37/// A trait to allow tracing (only) DOM objects.
38pub(crate) use js::gc::Traceable as JSTraceable;
39use js::glue::{CallScriptTracer, CallStringTracer, CallValueTracer};
40use js::jsapi::{GCTraceKindToAscii, Heap, JSScript, JSString, JSTracer, TraceKind};
41use js::jsval::JSVal;
42use malloc_size_of::{MallocConditionalSizeOf, MallocSizeOf, MallocSizeOfOps};
43use rustc_hash::FxBuildHasher;
44pub(crate) use script_bindings::trace::*;
45
46use crate::dom::bindings::refcounted::TrustedPromise;
47use crate::dom::html::htmlmediaelement::HTMLMediaElementFetchContext;
48use crate::dom::srcset::SourceSet;
49use crate::dom::windowproxy::WindowProxyHandler;
50use crate::event_loop::script_thread::IncompleteParserContexts;
51use crate::runtime::script_runtime::StreamConsumer;
52
53/// Wrapper type for nop traceble
54///
55/// SAFETY: Inner type must not impl JSTraceable
56#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
57#[cfg_attr(crown, crown::trace_in_no_trace_lint::must_not_have_traceable)]
58pub(crate) struct NoTrace<T>(pub(crate) T);
59
60impl<T: Display> Display for NoTrace<T> {
61    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62        self.0.fmt(f)
63    }
64}
65
66impl<T> From<T> for NoTrace<T> {
67    fn from(item: T) -> Self {
68        Self(item)
69    }
70}
71
72#[expect(unsafe_code)]
73unsafe impl<T> JSTraceable for NoTrace<T> {
74    #[inline]
75    unsafe fn trace(&self, _: *mut ::js::jsapi::JSTracer) {}
76}
77
78impl<T: MallocSizeOf> MallocSizeOf for NoTrace<T> {
79    fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
80        self.0.size_of(ops)
81    }
82}
83
84/// HashMap wrapper, that has non-jsmanaged keys
85///
86/// Not all methods are reexposed, but you can access inner type via .0
87/// If you need cryptographic secure hashs, or your keys are arbitrary large inputs
88/// stick with the default hasher. Otherwise, stronlgy think about using FxHashBuilder
89/// with `new_fx()`
90#[cfg_attr(crown, crown::trace_in_no_trace_lint::must_not_have_traceable(0))]
91#[derive(Clone, Debug)]
92pub(crate) struct HashMapTracedValues<K, V, S = RandomState>(pub(crate) HashMap<K, V, S>);
93
94impl<K, V, S: Default> Default for HashMapTracedValues<K, V, S> {
95    fn default() -> Self {
96        Self(Default::default())
97    }
98}
99
100impl<K, V> HashMapTracedValues<K, V, RandomState> {
101    /// Wrapper for HashMap::new()
102    #[inline]
103    #[must_use]
104    pub(crate) fn new() -> HashMapTracedValues<K, V, RandomState> {
105        Self(HashMap::new())
106    }
107}
108
109impl<K, V> HashMapTracedValues<K, V, FxBuildHasher> {
110    #[inline]
111    #[must_use]
112    pub(crate) fn new_fx() -> HashMapTracedValues<K, V, FxBuildHasher> {
113        Self(HashMap::with_hasher(FxBuildHasher))
114    }
115}
116
117impl<K, V, S> HashMapTracedValues<K, V, S> {
118    #[inline]
119    pub(crate) fn iter(&self) -> std::collections::hash_map::Iter<'_, K, V> {
120        self.0.iter()
121    }
122
123    #[inline]
124    pub(crate) fn iter_mut(&mut self) -> std::collections::hash_map::IterMut<'_, K, V> {
125        self.0.iter_mut()
126    }
127
128    #[inline]
129    pub(crate) fn drain(&mut self) -> std::collections::hash_map::Drain<'_, K, V> {
130        self.0.drain()
131    }
132
133    #[inline]
134    pub(crate) fn is_empty(&self) -> bool {
135        self.0.is_empty()
136    }
137
138    #[inline]
139    pub(crate) fn values(&self) -> std::collections::hash_map::Values<'_, K, V> {
140        self.0.values()
141    }
142}
143
144impl<K, V, S> HashMapTracedValues<K, V, S>
145where
146    K: Eq + Hash,
147    S: BuildHasher,
148{
149    #[inline]
150    pub(crate) fn insert(&mut self, k: K, v: V) -> Option<V> {
151        self.0.insert(k, v)
152    }
153
154    #[inline]
155    pub(crate) fn get<Q>(&self, k: &Q) -> Option<&V>
156    where
157        K: std::borrow::Borrow<Q>,
158        Q: Hash + Eq + ?Sized,
159    {
160        self.0.get(k)
161    }
162
163    #[inline]
164    pub(crate) fn get_mut<Q: Hash + Eq + ?Sized>(&mut self, k: &Q) -> Option<&mut V>
165    where
166        K: std::borrow::Borrow<Q>,
167    {
168        self.0.get_mut(k)
169    }
170
171    #[inline]
172    pub(crate) fn contains_key<Q: Hash + Eq + ?Sized>(&self, k: &Q) -> bool
173    where
174        K: std::borrow::Borrow<Q>,
175    {
176        self.0.contains_key(k)
177    }
178
179    #[inline]
180    pub(crate) fn remove<Q: Hash + Eq + ?Sized>(&mut self, k: &Q) -> Option<V>
181    where
182        K: std::borrow::Borrow<Q>,
183    {
184        self.0.remove(k)
185    }
186
187    #[inline]
188    pub(crate) fn entry(&mut self, key: K) -> std::collections::hash_map::Entry<'_, K, V> {
189        self.0.entry(key)
190    }
191}
192
193impl<K, V, S> MallocSizeOf for HashMapTracedValues<K, V, S>
194where
195    K: Eq + Hash + MallocSizeOf,
196    V: MallocSizeOf,
197    S: BuildHasher,
198{
199    fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
200        self.0.size_of(ops)
201    }
202}
203
204impl<K, V, S> MallocConditionalSizeOf for HashMapTracedValues<K, V, S>
205where
206    K: Eq + Hash + MallocSizeOf,
207    V: MallocConditionalSizeOf,
208    S: BuildHasher,
209{
210    fn conditional_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
211        self.0.conditional_size_of(ops)
212    }
213}
214
215#[expect(unsafe_code)]
216unsafe impl<K, V: JSTraceable, S> JSTraceable for HashMapTracedValues<K, V, S> {
217    #[inline]
218    unsafe fn trace(&self, trc: *mut ::js::jsapi::JSTracer) {
219        for v in self.0.values() {
220            unsafe { v.trace(trc) };
221        }
222    }
223}
224
225unsafe_no_jsmanaged_fields!(IncompleteParserContexts);
226
227#[expect(dead_code)]
228/// Trace a `JSScript`.
229pub(crate) fn trace_script(tracer: *mut JSTracer, description: &str, script: &Heap<*mut JSScript>) {
230    unsafe {
231        trace!("tracing {}", description);
232        CallScriptTracer(
233            tracer,
234            script.ptr.get() as *mut _,
235            GCTraceKindToAscii(TraceKind::Script),
236        );
237    }
238}
239
240#[expect(dead_code)]
241/// Trace a `JSVal`.
242pub(crate) fn trace_jsval(tracer: *mut JSTracer, description: &str, val: &Heap<JSVal>) {
243    unsafe {
244        if !val.get().is_markable() {
245            return;
246        }
247
248        trace!("tracing value {}", description);
249        CallValueTracer(
250            tracer,
251            val.ptr.get() as *mut _,
252            GCTraceKindToAscii(val.get().trace_kind()),
253        );
254    }
255}
256
257#[expect(dead_code)]
258/// Trace a `JSString`.
259pub(crate) fn trace_string(tracer: *mut JSTracer, description: &str, s: &Heap<*mut JSString>) {
260    unsafe {
261        trace!("tracing {}", description);
262        CallStringTracer(
263            tracer,
264            s.ptr.get() as *mut _,
265            GCTraceKindToAscii(TraceKind::String),
266        );
267    }
268}
269
270unsafe_no_jsmanaged_fields!(TrustedPromise);
271
272unsafe_no_jsmanaged_fields!(WindowProxyHandler);
273unsafe_no_jsmanaged_fields!(SourceSet);
274unsafe_no_jsmanaged_fields!(HTMLMediaElementFetchContext);
275unsafe_no_jsmanaged_fields!(StreamConsumer);