script/dom/bindings/
refcounted.rs1use 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 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#[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 unsafe fn new(ptr: *const libc::c_void) -> TrustedReference {
73 TrustedReference(ptr)
74 }
75}
76
77pub 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 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 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 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 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#[cfg_attr(crown, crown::unrooted_must_root_lint::allow_unrooted_interior)]
163#[derive(MallocSizeOf)]
164pub(crate) struct Trusted<T: DomObject> {
165 #[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 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 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
231pub(crate) struct LiveDOMReferences {
234 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 #[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
284fn 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
297pub(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}