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 http://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 
25 use dom::bindings::conversions::ToJSValConvertible;
26 use dom::bindings::error::Error;
27 use dom::bindings::reflector::{DomObject, Reflector};
28 use dom::bindings::root::DomRoot;
29 use dom::bindings::trace::trace_reflector;
30 use dom::promise::Promise;
31 use js::jsapi::JSTracer;
32 use libc;
33 use std::cell::RefCell;
34 use std::collections::hash_map::Entry::{Occupied, Vacant};
35 use std::collections::hash_map::HashMap;
36 use std::hash::Hash;
37 use std::marker::PhantomData;
38 use std::rc::Rc;
39 use std::sync::{Arc, Weak};
40 use task::TaskOnce;
41 
42 
43 #[allow(missing_docs)]  // FIXME
44 mod dummy {  // Attributes don’t apply through the macro.
45     use std::cell::RefCell;
46     use std::rc::Rc;
47     use super::LiveDOMReferences;
48     thread_local!(pub static LIVE_REFERENCES: Rc<RefCell<Option<LiveDOMReferences>>> =
49             Rc::new(RefCell::new(None)));
50 }
51 pub use self::dummy::LIVE_REFERENCES;
52 
53 
54 /// A pointer to a Rust DOM object that needs to be destroyed.
55 pub struct TrustedReference(*const libc::c_void);
56 unsafe impl Send for TrustedReference {}
57 
58 impl TrustedReference {
new<T: DomObject>(ptr: *const T) -> TrustedReference59     fn new<T: DomObject>(ptr: *const T) -> TrustedReference {
60         TrustedReference(ptr as *const libc::c_void)
61     }
62 }
63 
64 /// A safe wrapper around a DOM Promise object that can be shared among threads for use
65 /// in asynchronous operations. The underlying DOM object is guaranteed to live at least
66 /// as long as the last outstanding `TrustedPromise` instance. These values cannot be cloned,
67 /// only created from existing Rc<Promise> values.
68 pub struct TrustedPromise {
69     dom_object: *const Promise,
70     owner_thread: *const libc::c_void,
71 }
72 
73 unsafe impl Send for TrustedPromise {}
74 
75 impl TrustedPromise {
76     /// Create a new `TrustedPromise` instance from an existing DOM object. The object will
77     /// be prevented from being GCed for the duration of the resulting `TrustedPromise` object's
78     /// lifetime.
79     #[allow(unrooted_must_root)]
new(promise: Rc<Promise>) -> TrustedPromise80     pub fn new(promise: Rc<Promise>) -> TrustedPromise {
81         LIVE_REFERENCES.with(|ref r| {
82             let r = r.borrow();
83             let live_references = r.as_ref().unwrap();
84             let ptr = &*promise as *const Promise;
85             live_references.addref_promise(promise);
86             TrustedPromise {
87                 dom_object: ptr,
88                 owner_thread: (&*live_references) as *const _ as *const libc::c_void,
89             }
90         })
91     }
92 
93     /// Obtain a usable DOM Promise from a pinned `TrustedPromise` value. Fails if used on
94     /// a different thread than the original value from which this `TrustedPromise` was
95     /// obtained.
96     #[allow(unrooted_must_root)]
root(self) -> Rc<Promise>97     pub fn root(self) -> Rc<Promise> {
98         LIVE_REFERENCES.with(|ref r| {
99             let r = r.borrow();
100             let live_references = r.as_ref().unwrap();
101             assert_eq!(self.owner_thread, (&*live_references) as *const _ as *const libc::c_void);
102             // Borrow-check error requires the redundant `let promise = ...; promise` here.
103             let promise = match live_references.promise_table.borrow_mut().entry(self.dom_object) {
104                 Occupied(mut entry) => {
105                     let promise = {
106                         let promises = entry.get_mut();
107                         promises.pop().expect("rooted promise list unexpectedly empty")
108                     };
109                     if entry.get().is_empty() {
110                         entry.remove();
111                     }
112                     promise
113                 }
114                 Vacant(_) => unreachable!(),
115             };
116             promise
117         })
118     }
119 
120     /// A task which will reject the promise.
121     #[allow(unrooted_must_root)]
reject_task(self, error: Error) -> impl TaskOnce122     pub fn reject_task(self, error: Error) -> impl TaskOnce {
123         let this = self;
124         task!(reject_promise: move || {
125             debug!("Rejecting promise.");
126             this.root().reject_error(error);
127         })
128     }
129 
130     /// A task which will resolve the promise.
131     #[allow(unrooted_must_root)]
resolve_task<T>(self, value: T) -> impl TaskOnce where T: ToJSValConvertible + Send,132     pub fn resolve_task<T>(self, value: T) -> impl TaskOnce
133     where
134         T: ToJSValConvertible + Send,
135     {
136         let this = self;
137         task!(resolve_promise: move || {
138             debug!("Resolving promise.");
139             this.root().resolve_native(&value);
140         })
141     }
142 }
143 
144 /// A safe wrapper around a raw pointer to a DOM object that can be
145 /// shared among threads for use in asynchronous operations. The underlying
146 /// DOM object is guaranteed to live at least as long as the last outstanding
147 /// `Trusted<T>` instance.
148 #[allow_unrooted_interior]
149 pub struct Trusted<T: DomObject> {
150     /// A pointer to the Rust DOM object of type T, but void to allow
151     /// sending `Trusted<T>` between threads, regardless of T's sendability.
152     refcount: Arc<TrustedReference>,
153     owner_thread: *const libc::c_void,
154     phantom: PhantomData<T>,
155 }
156 
157 unsafe impl<T: DomObject> Send for Trusted<T> {}
158 
159 impl<T: DomObject> Trusted<T> {
160     /// Create a new `Trusted<T>` instance from an existing DOM pointer. The DOM object will
161     /// be prevented from being GCed for the duration of the resulting `Trusted<T>` object's
162     /// lifetime.
new(ptr: &T) -> Trusted<T>163     pub fn new(ptr: &T) -> Trusted<T> {
164         LIVE_REFERENCES.with(|ref r| {
165             let r = r.borrow();
166             let live_references = r.as_ref().unwrap();
167             let refcount = live_references.addref(&*ptr as *const T);
168             Trusted {
169                 refcount: refcount,
170                 owner_thread: (&*live_references) as *const _ as *const libc::c_void,
171                 phantom: PhantomData,
172             }
173         })
174     }
175 
176     /// Obtain a usable DOM pointer from a pinned `Trusted<T>` value. Fails if used on
177     /// a different thread than the original value from which this `Trusted<T>` was
178     /// obtained.
root(&self) -> DomRoot<T>179     pub fn root(&self) -> DomRoot<T> {
180         assert!(LIVE_REFERENCES.with(|ref r| {
181             let r = r.borrow();
182             let live_references = r.as_ref().unwrap();
183             self.owner_thread == (&*live_references) as *const _ as *const libc::c_void
184         }));
185         unsafe {
186             DomRoot::from_ref(&*(self.refcount.0 as *const T))
187         }
188     }
189 }
190 
191 impl<T: DomObject> Clone for Trusted<T> {
clone(&self) -> Trusted<T>192     fn clone(&self) -> Trusted<T> {
193         Trusted {
194             refcount: self.refcount.clone(),
195             owner_thread: self.owner_thread,
196             phantom: PhantomData,
197         }
198     }
199 }
200 
201 /// The set of live, pinned DOM objects that are currently prevented
202 /// from being garbage collected due to outstanding references.
203 #[allow(unrooted_must_root)]
204 pub struct LiveDOMReferences {
205     // keyed on pointer to Rust DOM object
206     reflectable_table: RefCell<HashMap<*const libc::c_void, Weak<TrustedReference>>>,
207     promise_table: RefCell<HashMap<*const Promise, Vec<Rc<Promise>>>>,
208 }
209 
210 impl LiveDOMReferences {
211     /// Set up the thread-local data required for storing the outstanding DOM references.
initialize()212     pub fn initialize() {
213         LIVE_REFERENCES.with(|ref r| {
214             *r.borrow_mut() = Some(LiveDOMReferences {
215                 reflectable_table: RefCell::new(HashMap::new()),
216                 promise_table: RefCell::new(HashMap::new()),
217             })
218         });
219     }
220 
221     #[allow(unrooted_must_root)]
addref_promise(&self, promise: Rc<Promise>)222     fn addref_promise(&self, promise: Rc<Promise>) {
223         let mut table = self.promise_table.borrow_mut();
224         table.entry(&*promise).or_insert(vec![]).push(promise)
225     }
226 
addref<T: DomObject>(&self, ptr: *const T) -> Arc<TrustedReference>227     fn addref<T: DomObject>(&self, ptr: *const T) -> Arc<TrustedReference> {
228         let mut table = self.reflectable_table.borrow_mut();
229         let capacity = table.capacity();
230         let len = table.len();
231         if (0 < capacity) && (capacity <= len) {
232             info!("growing refcounted references by {}", len);
233             remove_nulls(&mut table);
234             table.reserve(len);
235         }
236         match table.entry(ptr as *const libc::c_void) {
237             Occupied(mut entry) => match entry.get().upgrade() {
238                 Some(refcount) => refcount,
239                 None => {
240                     let refcount = Arc::new(TrustedReference::new(ptr));
241                     entry.insert(Arc::downgrade(&refcount));
242                     refcount
243                 },
244             },
245             Vacant(entry) => {
246                 let refcount = Arc::new(TrustedReference::new(ptr));
247                 entry.insert(Arc::downgrade(&refcount));
248                 refcount
249             }
250         }
251     }
252 }
253 
254 /// Remove null entries from the live references table
remove_nulls<K: Eq + Hash + Clone, V> (table: &mut HashMap<K, Weak<V>>)255 fn remove_nulls<K: Eq + Hash + Clone, V> (table: &mut HashMap<K, Weak<V>>) {
256     let to_remove: Vec<K> =
257         table.iter()
258         .filter(|&(_, value)| Weak::upgrade(value).is_none())
259         .map(|(key, _)| key.clone())
260         .collect();
261     info!("removing {} refcounted references", to_remove.len());
262     for key in to_remove {
263         table.remove(&key);
264     }
265 }
266 
267 /// A JSTraceDataOp for tracing reflectors held in LIVE_REFERENCES
268 #[allow(unrooted_must_root)]
trace_refcounted_objects(tracer: *mut JSTracer)269 pub unsafe fn trace_refcounted_objects(tracer: *mut JSTracer) {
270     info!("tracing live refcounted references");
271     LIVE_REFERENCES.with(|ref r| {
272         let r = r.borrow();
273         let live_references = r.as_ref().unwrap();
274         {
275             let mut table = live_references.reflectable_table.borrow_mut();
276             remove_nulls(&mut table);
277             for obj in table.keys() {
278                 let reflectable = &*(*obj as *const Reflector);
279                 trace_reflector(tracer, "refcounted", reflectable);
280             }
281         }
282 
283         {
284             let table = live_references.promise_table.borrow_mut();
285             for promise in table.keys() {
286                 trace_reflector(tracer, "refcounted", (**promise).reflector());
287             }
288         }
289     });
290 }
291