1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
use crate::dom::bindings::conversions::ToJSValConvertible;
use crate::dom::bindings::error::Error;
use crate::dom::bindings::reflector::{DomObject, Reflector};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::trace::trace_reflector;
use crate::dom::promise::Promise;
use crate::task::TaskOnce;
use js::jsapi::JSTracer;
use std::cell::RefCell;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::hash_map::HashMap;
use std::hash::Hash;
use std::marker::PhantomData;
use std::rc::Rc;
use std::sync::{Arc, Weak};
#[allow(missing_docs)] mod dummy {
use super::LiveDOMReferences;
use std::cell::RefCell;
use std::rc::Rc;
thread_local!(pub static LIVE_REFERENCES: Rc<RefCell<Option<LiveDOMReferences>>> =
Rc::new(RefCell::new(None)));
}
pub use self::dummy::LIVE_REFERENCES;
struct TrustedReference(*const libc::c_void);
unsafe impl Send for TrustedReference {}
impl TrustedReference {
unsafe fn new(ptr: *const libc::c_void) -> TrustedReference {
TrustedReference(ptr)
}
}
pub struct TrustedPromise {
dom_object: *const Promise,
owner_thread: *const libc::c_void,
}
unsafe impl Send for TrustedPromise {}
impl TrustedPromise {
#[allow(unrooted_must_root)]
pub fn new(promise: Rc<Promise>) -> TrustedPromise {
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let ptr = &*promise as *const Promise;
live_references.addref_promise(promise);
TrustedPromise {
dom_object: ptr,
owner_thread: (&*live_references) as *const _ as *const libc::c_void,
}
})
}
pub fn root(self) -> Rc<Promise> {
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
assert_eq!(
self.owner_thread,
(&*live_references) as *const _ as *const libc::c_void
);
let promise = match live_references
.promise_table
.borrow_mut()
.entry(self.dom_object)
{
Occupied(mut entry) => {
let promise = {
let promises = entry.get_mut();
promises
.pop()
.expect("rooted promise list unexpectedly empty")
};
if entry.get().is_empty() {
entry.remove();
}
promise
},
Vacant(_) => unreachable!(),
};
promise
})
}
#[allow(unrooted_must_root)]
pub fn reject_task(self, error: Error) -> impl TaskOnce {
let this = self;
task!(reject_promise: move || {
debug!("Rejecting promise.");
this.root().reject_error(error);
})
}
#[allow(unrooted_must_root)]
pub fn resolve_task<T>(self, value: T) -> impl TaskOnce
where
T: ToJSValConvertible + Send,
{
let this = self;
task!(resolve_promise: move || {
debug!("Resolving promise.");
this.root().resolve_native(&value);
})
}
}
#[unrooted_must_root_lint::allow_unrooted_interior]
pub struct Trusted<T: DomObject> {
refcount: Arc<TrustedReference>,
owner_thread: *const LiveDOMReferences,
phantom: PhantomData<T>,
}
unsafe impl<T: DomObject> Send for Trusted<T> {}
impl<T: DomObject> Trusted<T> {
pub fn new(ptr: &T) -> Trusted<T> {
fn add_live_reference(
ptr: *const libc::c_void,
) -> (Arc<TrustedReference>, *const LiveDOMReferences) {
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let refcount = unsafe { live_references.addref(ptr) };
(refcount, live_references as *const _)
})
}
let (refcount, owner_thread) = add_live_reference(ptr as *const T as *const _);
Trusted {
refcount,
owner_thread,
phantom: PhantomData,
}
}
pub fn root(&self) -> DomRoot<T> {
fn validate(owner_thread: *const LiveDOMReferences) {
assert!(LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
owner_thread == live_references
}));
}
validate(self.owner_thread);
unsafe { DomRoot::from_ref(&*(self.refcount.0 as *const T)) }
}
}
impl<T: DomObject> Clone for Trusted<T> {
fn clone(&self) -> Trusted<T> {
Trusted {
refcount: self.refcount.clone(),
owner_thread: self.owner_thread,
phantom: PhantomData,
}
}
}
#[allow(unrooted_must_root)]
pub struct LiveDOMReferences {
reflectable_table: RefCell<HashMap<*const libc::c_void, Weak<TrustedReference>>>,
promise_table: RefCell<HashMap<*const Promise, Vec<Rc<Promise>>>>,
}
impl LiveDOMReferences {
pub fn initialize() {
LIVE_REFERENCES.with(|ref r| {
*r.borrow_mut() = Some(LiveDOMReferences {
reflectable_table: RefCell::new(HashMap::new()),
promise_table: RefCell::new(HashMap::new()),
})
});
}
pub fn destruct() {
LIVE_REFERENCES.with(|ref r| {
*r.borrow_mut() = None;
});
}
#[allow(unrooted_must_root)]
fn addref_promise(&self, promise: Rc<Promise>) {
let mut table = self.promise_table.borrow_mut();
table.entry(&*promise).or_insert(vec![]).push(promise)
}
unsafe fn addref(&self, ptr: *const libc::c_void) -> Arc<TrustedReference> {
let mut table = self.reflectable_table.borrow_mut();
let capacity = table.capacity();
let len = table.len();
if (0 < capacity) && (capacity <= len) {
info!("growing refcounted references by {}", len);
remove_nulls(&mut table);
table.reserve(len);
}
match table.entry(ptr) {
Occupied(mut entry) => match entry.get().upgrade() {
Some(refcount) => refcount,
None => {
let refcount = Arc::new(TrustedReference::new(ptr));
entry.insert(Arc::downgrade(&refcount));
refcount
},
},
Vacant(entry) => {
let refcount = Arc::new(TrustedReference::new(ptr));
entry.insert(Arc::downgrade(&refcount));
refcount
},
}
}
}
fn remove_nulls<K: Eq + Hash + Clone, V>(table: &mut HashMap<K, Weak<V>>) {
let to_remove: Vec<K> = table
.iter()
.filter(|&(_, value)| Weak::upgrade(value).is_none())
.map(|(key, _)| key.clone())
.collect();
info!("removing {} refcounted references", to_remove.len());
for key in to_remove {
table.remove(&key);
}
}
#[allow(unrooted_must_root)]
pub unsafe fn trace_refcounted_objects(tracer: *mut JSTracer) {
info!("tracing live refcounted references");
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
{
let mut table = live_references.reflectable_table.borrow_mut();
remove_nulls(&mut table);
for obj in table.keys() {
let reflectable = &*(*obj as *const Reflector);
trace_reflector(tracer, "refcounted", reflectable);
}
}
{
let table = live_references.promise_table.borrow_mut();
for promise in table.keys() {
trace_reflector(tracer, "refcounted", (**promise).reflector());
}
}
});
}