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::{MallocSizeOf, MallocSizeOfOps};
43use rustc_hash::FxBuildHasher;
44pub(crate) use script_bindings::trace::*;
45
46use crate::dom::bindings::cell::DomRefCell;
47use crate::dom::bindings::refcounted::{Trusted, TrustedPromise};
48use crate::dom::bindings::reflector::DomObject;
49use crate::dom::html::htmlimageelement::SourceSet;
50use crate::dom::html::htmlmediaelement::HTMLMediaElementFetchContext;
51use crate::dom::windowproxy::WindowProxyHandler;
52use crate::script_runtime::StreamConsumer;
53use crate::script_thread::IncompleteParserContexts;
54use crate::task::TaskBox;
55
56unsafe impl<T: CustomTraceable> CustomTraceable for DomRefCell<T> {
57    unsafe fn trace(&self, trc: *mut JSTracer) {
58        unsafe { (*self).borrow().trace(trc) }
59    }
60}
61
62/// Wrapper type for nop traceble
63///
64/// SAFETY: Inner type must not impl JSTraceable
65#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
66#[cfg_attr(crown, crown::trace_in_no_trace_lint::must_not_have_traceable)]
67pub(crate) struct NoTrace<T>(pub(crate) T);
68
69impl<T: Display> Display for NoTrace<T> {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        self.0.fmt(f)
72    }
73}
74
75impl<T> From<T> for NoTrace<T> {
76    fn from(item: T) -> Self {
77        Self(item)
78    }
79}
80
81#[allow(unsafe_code)]
82unsafe impl<T> JSTraceable for NoTrace<T> {
83    #[inline]
84    unsafe fn trace(&self, _: *mut ::js::jsapi::JSTracer) {}
85}
86
87impl<T: MallocSizeOf> MallocSizeOf for NoTrace<T> {
88    fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
89        self.0.size_of(ops)
90    }
91}
92
93/// HashMap wrapper, that has non-jsmanaged keys
94///
95/// Not all methods are reexposed, but you can access inner type via .0
96/// If you need cryptographic secure hashs, or your keys are arbitrary large inputs
97/// stick with the default hasher. Otherwise, stronlgy think about using FxHashBuilder
98/// with `new_fx()`
99#[cfg_attr(crown, crown::trace_in_no_trace_lint::must_not_have_traceable(0))]
100#[derive(Clone, Debug)]
101pub(crate) struct HashMapTracedValues<K, V, S = RandomState>(pub(crate) HashMap<K, V, S>);
102
103impl<K, V, S: Default> Default for HashMapTracedValues<K, V, S> {
104    fn default() -> Self {
105        Self(Default::default())
106    }
107}
108
109impl<K, V> HashMapTracedValues<K, V, RandomState> {
110    /// Wrapper for HashMap::new()
111    #[inline]
112    #[must_use]
113    pub(crate) fn new() -> HashMapTracedValues<K, V, RandomState> {
114        Self(HashMap::new())
115    }
116}
117
118impl<K, V> HashMapTracedValues<K, V, FxBuildHasher> {
119    #[inline]
120    #[must_use]
121    pub(crate) fn new_fx() -> HashMapTracedValues<K, V, FxBuildHasher> {
122        Self(HashMap::with_hasher(FxBuildHasher))
123    }
124}
125
126impl<K, V, S> HashMapTracedValues<K, V, S> {
127    #[inline]
128    pub(crate) fn iter(&self) -> std::collections::hash_map::Iter<'_, K, V> {
129        self.0.iter()
130    }
131
132    #[inline]
133    pub(crate) fn drain(&mut self) -> std::collections::hash_map::Drain<'_, K, V> {
134        self.0.drain()
135    }
136
137    #[inline]
138    pub(crate) fn is_empty(&self) -> bool {
139        self.0.is_empty()
140    }
141}
142
143impl<K, V, S> HashMapTracedValues<K, V, S>
144where
145    K: Eq + Hash,
146    S: BuildHasher,
147{
148    #[inline]
149    pub(crate) fn insert(&mut self, k: K, v: V) -> Option<V> {
150        self.0.insert(k, v)
151    }
152
153    #[inline]
154    pub(crate) fn get<Q>(&self, k: &Q) -> Option<&V>
155    where
156        K: std::borrow::Borrow<Q>,
157        Q: Hash + Eq + ?Sized,
158    {
159        self.0.get(k)
160    }
161
162    #[inline]
163    pub(crate) fn get_mut<Q: Hash + Eq + ?Sized>(&mut self, k: &Q) -> Option<&mut V>
164    where
165        K: std::borrow::Borrow<Q>,
166    {
167        self.0.get_mut(k)
168    }
169
170    #[inline]
171    pub(crate) fn contains_key<Q: Hash + Eq + ?Sized>(&self, k: &Q) -> bool
172    where
173        K: std::borrow::Borrow<Q>,
174    {
175        self.0.contains_key(k)
176    }
177
178    #[inline]
179    pub(crate) fn remove<Q: Hash + Eq + ?Sized>(&mut self, k: &Q) -> Option<V>
180    where
181        K: std::borrow::Borrow<Q>,
182    {
183        self.0.remove(k)
184    }
185
186    #[inline]
187    pub(crate) fn entry(&mut self, key: K) -> std::collections::hash_map::Entry<'_, K, V> {
188        self.0.entry(key)
189    }
190}
191
192impl<K, V, S> MallocSizeOf for HashMapTracedValues<K, V, S>
193where
194    K: Eq + Hash + MallocSizeOf,
195    V: MallocSizeOf,
196    S: BuildHasher,
197{
198    fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
199        self.0.size_of(ops)
200    }
201}
202
203#[allow(unsafe_code)]
204unsafe impl<K, V: JSTraceable, S> JSTraceable for HashMapTracedValues<K, V, S> {
205    #[inline]
206    unsafe fn trace(&self, trc: *mut ::js::jsapi::JSTracer) {
207        for v in self.0.values() {
208            unsafe { v.trace(trc) };
209        }
210    }
211}
212
213unsafe_no_jsmanaged_fields!(Box<dyn TaskBox>);
214
215unsafe_no_jsmanaged_fields!(IncompleteParserContexts);
216
217#[allow(dead_code)]
218/// Trace a `JSScript`.
219pub(crate) fn trace_script(tracer: *mut JSTracer, description: &str, script: &Heap<*mut JSScript>) {
220    unsafe {
221        trace!("tracing {}", description);
222        CallScriptTracer(
223            tracer,
224            script.ptr.get() as *mut _,
225            GCTraceKindToAscii(TraceKind::Script),
226        );
227    }
228}
229
230#[allow(dead_code)]
231/// Trace a `JSVal`.
232pub(crate) fn trace_jsval(tracer: *mut JSTracer, description: &str, val: &Heap<JSVal>) {
233    unsafe {
234        if !val.get().is_markable() {
235            return;
236        }
237
238        trace!("tracing value {}", description);
239        CallValueTracer(
240            tracer,
241            val.ptr.get() as *mut _,
242            GCTraceKindToAscii(val.get().trace_kind()),
243        );
244    }
245}
246
247#[allow(dead_code)]
248/// Trace a `JSString`.
249pub(crate) fn trace_string(tracer: *mut JSTracer, description: &str, s: &Heap<*mut JSString>) {
250    unsafe {
251        trace!("tracing {}", description);
252        CallStringTracer(
253            tracer,
254            s.ptr.get() as *mut _,
255            GCTraceKindToAscii(TraceKind::String),
256        );
257    }
258}
259
260unsafe impl<T: JSTraceable> JSTraceable for DomRefCell<T> {
261    unsafe fn trace(&self, trc: *mut JSTracer) {
262        unsafe { (*self).borrow().trace(trc) };
263    }
264}
265
266unsafe_no_jsmanaged_fields!(TrustedPromise);
267
268unsafe_no_jsmanaged_fields!(WindowProxyHandler);
269unsafe_no_jsmanaged_fields!(SourceSet);
270unsafe_no_jsmanaged_fields!(HTMLMediaElementFetchContext);
271unsafe_no_jsmanaged_fields!(StreamConsumer);
272
273unsafe impl<T: DomObject> JSTraceable for Trusted<T> {
274    #[inline]
275    unsafe fn trace(&self, _: *mut JSTracer) {
276        // Do nothing
277    }
278}