Skip to main content

script/dom/bindings/
refcounted.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//! A generic, safe mechanism by which DOM objects can be pinned and transferred
6//! between threads (or intra-thread for asynchronous events). Akin to Gecko's
7//! nsMainThreadPtrHandle, this uses thread-safe reference counting and ensures
8//! that the actual SpiderMonkey GC integration occurs on the script thread via
9//! weak refcounts. Ownership of a `Trusted<T>` object means the DOM object of
10//! type T to which it points remains alive. Any other behaviour is undefined.
11//! To guarantee the lifetime of a DOM object when performing asynchronous operations,
12//! obtain a `Trusted<T>` from that object and pass it along with each operation.
13//! A usable pointer to the original DOM object can be obtained on the script thread
14//! from a `Trusted<T>` via the `root` method.
15//!
16//! The implementation of `Trusted<T>` is as follows:
17//! The `Trusted<T>` object contains an atomic reference counted pointer to the Rust DOM object.
18//! A hashtable resides in the script thread, keyed on the pointer.
19//! The values in this hashtable are weak reference counts. When a `Trusted<T>` object is
20//! created or cloned, the reference count is increased. When a `Trusted<T>` is dropped, the count
21//! decreases. If the count hits zero, the weak reference is emptied, and is removed from
22//! its hash table during the next GC. During GC, the entries of the hash table are counted
23//! as JS roots.
24
25use std::cell::RefCell;
26use std::collections::hash_map::Entry::{Occupied, Vacant};
27use std::hash::Hash;
28use std::marker::PhantomData;
29use std::rc::Rc;
30use std::sync::{Arc, Weak};
31
32use js::jsapi::JSTracer;
33use rustc_hash::FxHashMap;
34use script_bindings::reflector::{DomObject, Reflector};
35
36use crate::dom::bindings::conversions::ToJSValConvertible;
37use crate::dom::bindings::error::Error;
38use crate::dom::bindings::root::DomRoot;
39use crate::dom::bindings::trace::trace_reflector;
40use crate::dom::promise::Promise;
41use crate::task::TaskOnce;
42
43mod dummy {
44    // Attributes don’t apply through the macro.
45    use std::cell::RefCell;
46    use std::rc::Rc;
47
48    use rustc_hash::FxHashMap;
49
50    use super::LiveDOMReferences;
51    thread_local!(pub(crate) static LIVE_REFERENCES: Rc<RefCell<LiveDOMReferences>> =
52        Rc::new(RefCell::new(
53        LiveDOMReferences {
54            reflectable_table: RefCell::new(FxHashMap::default()),
55            promise_table: RefCell::new(FxHashMap::default()),
56        }
57    )));
58}
59pub(crate) use self::dummy::LIVE_REFERENCES;
60
61/// A pointer to a Rust DOM object that needs to be destroyed.
62#[derive(MallocSizeOf)]
63struct TrustedReference(
64    #[ignore_malloc_size_of = "This is a shared reference."] *const libc::c_void,
65);
66unsafe impl Send for TrustedReference {}
67
68impl TrustedReference {
69    /// Creates a new TrustedReference from a pointer to a value that impements DOMObject.
70    /// This is not enforced by the type system to reduce duplicated generic code,
71    /// which is acceptable since this method is internal to this module.
72    unsafe fn new(ptr: *const libc::c_void) -> TrustedReference {
73        TrustedReference(ptr)
74    }
75}
76
77/// A safe wrapper around a DOM Promise object that can be shared among threads for use
78/// in asynchronous operations. The underlying DOM object is guaranteed to live at least
79/// as long as the last outstanding `TrustedPromise` instance. These values cannot be cloned,
80/// only created from existing `Rc<Promise>` values.
81pub struct TrustedPromise {
82    dom_object: *const Promise,
83    owner_thread: *const libc::c_void,
84}
85
86unsafe impl Send for TrustedPromise {}
87
88impl TrustedPromise {
89    /// Create a new `TrustedPromise` instance from an existing DOM object. The object will
90    /// be prevented from being GCed for the duration of the resulting `TrustedPromise` object's
91    /// lifetime.
92    pub(crate) fn new(promise: Rc<Promise>) -> TrustedPromise {
93        LIVE_REFERENCES.with(|r| {
94            let live_references = &*r.borrow();
95            let ptr = &raw const *promise;
96            live_references.addref_promise(promise);
97            TrustedPromise {
98                dom_object: ptr,
99                owner_thread: (live_references) as *const _ as *const libc::c_void,
100            }
101        })
102    }
103
104    /// Obtain a usable DOM Promise from a pinned `TrustedPromise` value. Fails if used on
105    /// a different thread than the original value from which this `TrustedPromise` was
106    /// obtained.
107    pub(crate) fn root(self) -> Rc<Promise> {
108        LIVE_REFERENCES.with(|r| {
109            let live_references = &*r.borrow();
110            assert_eq!(
111                self.owner_thread,
112                live_references as *const _ as *const libc::c_void
113            );
114            match live_references
115                .promise_table
116                .borrow_mut()
117                .entry(self.dom_object)
118            {
119                Occupied(mut entry) => {
120                    let promise = {
121                        let promises = entry.get_mut();
122                        promises
123                            .pop()
124                            .expect("rooted promise list unexpectedly empty")
125                    };
126                    if entry.get().is_empty() {
127                        entry.remove();
128                    }
129                    promise
130                },
131                Vacant(_) => unreachable!(),
132            }
133        })
134    }
135
136    /// A task which will reject the promise.
137    pub(crate) fn reject_task(self, error: Error) -> impl TaskOnce {
138        let this = self;
139        task!(reject_promise: move |cx| {
140            debug!("Rejecting promise.");
141            this.root().reject_error_with_cx(cx, error);
142        })
143    }
144
145    /// A task which will resolve the promise.
146    pub(crate) fn resolve_task<T>(self, value: T) -> impl TaskOnce
147    where
148        T: ToJSValConvertible + Send,
149    {
150        let this = self;
151        task!(resolve_promise: move |cx| {
152            debug!("Resolving promise.");
153            this.root().resolve_native_with_cx(cx, &value);
154        })
155    }
156}
157
158/// A safe wrapper around a raw pointer to a DOM object that can be
159/// shared among threads for use in asynchronous operations. The underlying
160/// DOM object is guaranteed to live at least as long as the last outstanding
161/// `Trusted<T>` instance.
162#[cfg_attr(crown, crown::unrooted_must_root_lint::allow_unrooted_interior)]
163#[derive(MallocSizeOf)]
164pub(crate) struct Trusted<T: DomObject> {
165    /// A pointer to the Rust DOM object of type T, but void to allow
166    /// sending `Trusted<T>` between threads, regardless of T's sendability.
167    #[conditional_malloc_size_of]
168    refcount: Arc<TrustedReference>,
169    #[ignore_malloc_size_of = "These are shared by all `Trusted` types."]
170    owner_thread: *const LiveDOMReferences,
171    phantom: PhantomData<T>,
172}
173
174impl<T: DomObject> std::fmt::Debug for Trusted<T> {
175    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
176        f.write_str("...")
177    }
178}
179
180unsafe impl<T: DomObject> Send for Trusted<T> {}
181
182impl<T: DomObject> Trusted<T> {
183    /// Create a new `Trusted<T>` instance from an existing DOM pointer. The DOM object will
184    /// be prevented from being GCed for the duration of the resulting `Trusted<T>` object's
185    /// lifetime.
186    pub(crate) fn new(ptr: &T) -> Trusted<T> {
187        fn add_live_reference(
188            ptr: *const libc::c_void,
189        ) -> (Arc<TrustedReference>, *const LiveDOMReferences) {
190            LIVE_REFERENCES.with(|r| {
191                let live_references = &*r.borrow();
192                let refcount = unsafe { live_references.addref(ptr) };
193                (refcount, live_references as *const _)
194            })
195        }
196
197        let (refcount, owner_thread) = add_live_reference(ptr as *const T as *const _);
198        Trusted {
199            refcount,
200            owner_thread,
201            phantom: PhantomData,
202        }
203    }
204
205    /// Obtain a usable DOM pointer from a pinned `Trusted<T>` value. Fails if used on
206    /// a different thread than the original value from which this `Trusted<T>` was
207    /// obtained.
208    pub(crate) fn root(&self) -> DomRoot<T> {
209        fn validate(owner_thread: *const LiveDOMReferences) {
210            assert!(LIVE_REFERENCES.with(|r| {
211                let r = r.borrow();
212                let live_references = &*r;
213                owner_thread == live_references
214            }));
215        }
216        validate(self.owner_thread);
217        unsafe { DomRoot::from_ref(&*(self.refcount.0 as *const T)) }
218    }
219}
220
221impl<T: DomObject> Clone for Trusted<T> {
222    fn clone(&self) -> Trusted<T> {
223        Trusted {
224            refcount: self.refcount.clone(),
225            owner_thread: self.owner_thread,
226            phantom: PhantomData,
227        }
228    }
229}
230
231/// The set of live, pinned DOM objects that are currently prevented
232/// from being garbage collected due to outstanding references.
233pub(crate) struct LiveDOMReferences {
234    // keyed on pointer to Rust DOM object
235    reflectable_table: RefCell<FxHashMap<*const libc::c_void, Weak<TrustedReference>>>,
236    promise_table: RefCell<FxHashMap<*const Promise, Vec<Rc<Promise>>>>,
237}
238
239impl LiveDOMReferences {
240    pub(crate) fn destruct() {
241        LIVE_REFERENCES.with(|r| {
242            let live_references = r.borrow_mut();
243            let _ = live_references.promise_table.take();
244            let _ = live_references.reflectable_table.take();
245        });
246    }
247
248    fn addref_promise(&self, promise: Rc<Promise>) {
249        let mut table = self.promise_table.borrow_mut();
250        table.entry(&*promise).or_default().push(promise)
251    }
252
253    /// ptr must be a pointer to a type that implements DOMObject.
254    /// This is not enforced by the type system to reduce duplicated generic code,
255    /// which is acceptable since this method is internal to this module.
256    #[expect(clippy::arc_with_non_send_sync)]
257    unsafe fn addref(&self, ptr: *const libc::c_void) -> Arc<TrustedReference> {
258        let mut table = self.reflectable_table.borrow_mut();
259        let capacity = table.capacity();
260        let len = table.len();
261        if (0 < capacity) && (capacity <= len) {
262            trace!("growing refcounted references by {}", len);
263            remove_nulls(&mut table);
264            table.reserve(len);
265        }
266        match table.entry(ptr) {
267            Occupied(mut entry) => match entry.get().upgrade() {
268                Some(refcount) => refcount,
269                None => {
270                    let refcount = Arc::new(unsafe { TrustedReference::new(ptr) });
271                    entry.insert(Arc::downgrade(&refcount));
272                    refcount
273                },
274            },
275            Vacant(entry) => {
276                let refcount = Arc::new(unsafe { TrustedReference::new(ptr) });
277                entry.insert(Arc::downgrade(&refcount));
278                refcount
279            },
280        }
281    }
282}
283
284/// Remove null entries from the live references table
285fn remove_nulls<K: Eq + Hash + Clone, V>(table: &mut FxHashMap<K, Weak<V>>) {
286    let to_remove: Vec<K> = table
287        .iter()
288        .filter(|&(_, value)| Weak::upgrade(value).is_none())
289        .map(|(key, _)| key.clone())
290        .collect();
291    trace!("removing {} refcounted references", to_remove.len());
292    for key in to_remove {
293        table.remove(&key);
294    }
295}
296
297/// A JSTraceDataOp for tracing reflectors held in LIVE_REFERENCES
298pub(crate) unsafe fn trace_refcounted_objects(tracer: *mut JSTracer) {
299    trace!("tracing live refcounted references");
300    LIVE_REFERENCES.with(|r| {
301        let live_references = &*r.borrow();
302        {
303            let mut table = live_references.reflectable_table.borrow_mut();
304            remove_nulls(&mut table);
305            for obj in table.keys() {
306                unsafe {
307                    trace_reflector(tracer, "refcounted", &*(*obj as *const Reflector));
308                }
309            }
310        }
311
312        {
313            let table = live_references.promise_table.borrow_mut();
314            for promise in table.keys() {
315                unsafe {
316                    trace_reflector(tracer, "refcounted", (**promise).reflector());
317                }
318            }
319        }
320    });
321}