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, RootedPromise};
41use crate::tasks::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 From<RootedPromise> for TrustedPromise {
89    fn from(promise: RootedPromise) -> Self {
90        TrustedPromise::new((*promise).clone())
91    }
92}
93
94impl TrustedPromise {
95    /// Create a new `TrustedPromise` instance from an existing DOM object. The object will
96    /// be prevented from being GCed for the duration of the resulting `TrustedPromise` object's
97    /// lifetime.
98    pub(crate) fn new(promise: Rc<Promise>) -> TrustedPromise {
99        LIVE_REFERENCES.with(|r| {
100            let live_references = &*r.borrow();
101            let ptr = &raw const *promise;
102            live_references.addref_promise(promise);
103            TrustedPromise {
104                dom_object: ptr,
105                owner_thread: (live_references) as *const _ as *const libc::c_void,
106            }
107        })
108    }
109
110    /// Obtain a usable DOM Promise from a pinned `TrustedPromise` value. Fails if used on
111    /// a different thread than the original value from which this `TrustedPromise` was
112    /// obtained.
113    pub(crate) fn root(self) -> Rc<Promise> {
114        LIVE_REFERENCES.with(|r| {
115            let live_references = &*r.borrow();
116            assert_eq!(
117                self.owner_thread,
118                live_references as *const _ as *const libc::c_void
119            );
120            match live_references
121                .promise_table
122                .borrow_mut()
123                .entry(self.dom_object)
124            {
125                Occupied(mut entry) => {
126                    let promise = {
127                        let promises = entry.get_mut();
128                        promises
129                            .pop()
130                            .expect("rooted promise list unexpectedly empty")
131                    };
132                    if entry.get().is_empty() {
133                        entry.remove();
134                    }
135                    promise
136                },
137                Vacant(_) => unreachable!(),
138            }
139        })
140    }
141
142    /// A task which will reject the promise.
143    pub(crate) fn reject_task(self, error: Error) -> impl TaskOnce {
144        let this = self;
145        task!(reject_promise: move |cx| {
146            debug!("Rejecting promise.");
147            this.root().reject_error(cx, error);
148        })
149    }
150
151    /// A task which will resolve the promise.
152    pub(crate) fn resolve_task<T>(self, value: T) -> impl TaskOnce
153    where
154        T: ToJSValConvertible + Send,
155    {
156        let this = self;
157        task!(resolve_promise: move |cx| {
158            debug!("Resolving promise.");
159            this.root().resolve_native(cx, &value);
160        })
161    }
162}
163
164/// A safe wrapper around a raw pointer to a DOM object that can be
165/// shared among threads for use in asynchronous operations. The underlying
166/// DOM object is guaranteed to live at least as long as the last outstanding
167/// `Trusted<T>` instance.
168#[cfg_attr(crown, crown::unrooted_must_root_lint::allow_unrooted_interior)]
169#[derive(MallocSizeOf)]
170pub(crate) struct Trusted<T: DomObject> {
171    /// A pointer to the Rust DOM object of type T, but void to allow
172    /// sending `Trusted<T>` between threads, regardless of T's sendability.
173    #[conditional_malloc_size_of]
174    refcount: Arc<TrustedReference>,
175    #[ignore_malloc_size_of = "These are shared by all `Trusted` types."]
176    owner_thread: *const LiveDOMReferences,
177    phantom: PhantomData<T>,
178}
179
180impl<T: DomObject> std::fmt::Debug for Trusted<T> {
181    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
182        f.write_str("...")
183    }
184}
185
186unsafe impl<T: DomObject> Send for Trusted<T> {}
187
188impl<T: DomObject> Trusted<T> {
189    /// Create a new `Trusted<T>` instance from an existing DOM pointer. The DOM object will
190    /// be prevented from being GCed for the duration of the resulting `Trusted<T>` object's
191    /// lifetime.
192    pub(crate) fn new(ptr: &T) -> Trusted<T> {
193        fn add_live_reference(
194            ptr: *const libc::c_void,
195        ) -> (Arc<TrustedReference>, *const LiveDOMReferences) {
196            LIVE_REFERENCES.with(|r| {
197                let live_references = &*r.borrow();
198                let refcount = unsafe { live_references.addref(ptr) };
199                (refcount, live_references as *const _)
200            })
201        }
202
203        let (refcount, owner_thread) = add_live_reference(ptr as *const T as *const _);
204        Trusted {
205            refcount,
206            owner_thread,
207            phantom: PhantomData,
208        }
209    }
210
211    /// Obtain a usable DOM pointer from a pinned `Trusted<T>` value. Fails if used on
212    /// a different thread than the original value from which this `Trusted<T>` was
213    /// obtained.
214    pub(crate) fn root(&self) -> DomRoot<T> {
215        fn validate(owner_thread: *const LiveDOMReferences) {
216            assert!(LIVE_REFERENCES.with(|r| {
217                let r = r.borrow();
218                let live_references = &*r;
219                owner_thread == live_references
220            }));
221        }
222        validate(self.owner_thread);
223        unsafe { DomRoot::from_ref(&*(self.refcount.0 as *const T)) }
224    }
225}
226
227impl<T: DomObject> Clone for Trusted<T> {
228    fn clone(&self) -> Trusted<T> {
229        Trusted {
230            refcount: self.refcount.clone(),
231            owner_thread: self.owner_thread,
232            phantom: PhantomData,
233        }
234    }
235}
236
237/// The set of live, pinned DOM objects that are currently prevented
238/// from being garbage collected due to outstanding references.
239pub(crate) struct LiveDOMReferences {
240    // keyed on pointer to Rust DOM object
241    reflectable_table: RefCell<FxHashMap<*const libc::c_void, Weak<TrustedReference>>>,
242    promise_table: RefCell<FxHashMap<*const Promise, Vec<Rc<Promise>>>>,
243}
244
245impl LiveDOMReferences {
246    pub(crate) fn destruct() {
247        LIVE_REFERENCES.with(|r| {
248            let live_references = r.borrow_mut();
249            let _ = live_references.promise_table.take();
250            let _ = live_references.reflectable_table.take();
251        });
252    }
253
254    fn addref_promise(&self, promise: Rc<Promise>) {
255        let mut table = self.promise_table.borrow_mut();
256        table.entry(&*promise).or_default().push(promise)
257    }
258
259    /// ptr must be a pointer to a type that implements DOMObject.
260    /// This is not enforced by the type system to reduce duplicated generic code,
261    /// which is acceptable since this method is internal to this module.
262    #[expect(clippy::arc_with_non_send_sync)]
263    unsafe fn addref(&self, ptr: *const libc::c_void) -> Arc<TrustedReference> {
264        let mut table = self.reflectable_table.borrow_mut();
265        let capacity = table.capacity();
266        let len = table.len();
267        if (0 < capacity) && (capacity <= len) {
268            trace!("growing refcounted references by {}", len);
269            remove_nulls(&mut table);
270            table.reserve(len);
271        }
272        match table.entry(ptr) {
273            Occupied(mut entry) => match entry.get().upgrade() {
274                Some(refcount) => refcount,
275                None => {
276                    let refcount = Arc::new(unsafe { TrustedReference::new(ptr) });
277                    entry.insert(Arc::downgrade(&refcount));
278                    refcount
279                },
280            },
281            Vacant(entry) => {
282                let refcount = Arc::new(unsafe { TrustedReference::new(ptr) });
283                entry.insert(Arc::downgrade(&refcount));
284                refcount
285            },
286        }
287    }
288}
289
290/// Remove null entries from the live references table
291fn remove_nulls<K: Eq + Hash + Clone, V>(table: &mut FxHashMap<K, Weak<V>>) {
292    let to_remove: Vec<K> = table
293        .iter()
294        .filter(|&(_, value)| Weak::upgrade(value).is_none())
295        .map(|(key, _)| key.clone())
296        .collect();
297    trace!("removing {} refcounted references", to_remove.len());
298    for key in to_remove {
299        table.remove(&key);
300    }
301}
302
303/// A JSTraceDataOp for tracing reflectors held in LIVE_REFERENCES
304pub(crate) unsafe fn trace_refcounted_objects(tracer: *mut JSTracer) {
305    trace!("tracing live refcounted references");
306    LIVE_REFERENCES.with(|r| {
307        let live_references = &*r.borrow();
308        {
309            let mut table = live_references.reflectable_table.borrow_mut();
310            remove_nulls(&mut table);
311            for obj in table.keys() {
312                unsafe {
313                    trace_reflector(tracer, "refcounted", &*(*obj as *const Reflector));
314                }
315            }
316        }
317
318        {
319            let table = live_references.promise_table.borrow_mut();
320            for promise in table.keys() {
321                unsafe {
322                    trace_reflector(tracer, "refcounted", (**promise).reflector());
323                }
324            }
325        }
326    });
327}