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, RootedPromise};
41use crate::tasks::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 From<RootedPromise> for TrustedPromise {
89 fn from(promise: RootedPromise) -> Self {
90 TrustedPromise::new((*promise).clone())
91 }
92}
93
94impl TrustedPromise {
95 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 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 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 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#[cfg_attr(crown, crown::unrooted_must_root_lint::allow_unrooted_interior)]
169#[derive(MallocSizeOf)]
170pub(crate) struct Trusted<T: DomObject> {
171 #[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 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 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
237pub(crate) struct LiveDOMReferences {
240 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 #[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
290fn 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
303pub(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}