Allow refcounting arbitrary DOM objects in concert with the GC to enable safe, asynchronous/cross-task references to pinned objects.

This commit is contained in:
Josh Matthews 2014-11-20 17:17:02 -05:00
parent c4b93d30e4
commit 2f059c15e7
8 changed files with 210 additions and 154 deletions

View file

@ -48,8 +48,6 @@
use dom::bindings::trace::JSTraceable;
use dom::bindings::utils::{Reflector, Reflectable};
use dom::node::Node;
use dom::xmlhttprequest::{XMLHttpRequest, TrustedXHRAddress};
use dom::worker::{Worker, TrustedWorkerAddress};
use js::jsapi::JSObject;
use js::jsval::JSVal;
use layout_interface::TrustedNodeAddress;
@ -142,24 +140,6 @@ impl JS<Node> {
}
}
impl JS<XMLHttpRequest> {
pub unsafe fn from_trusted_xhr_address(inner: TrustedXHRAddress) -> JS<XMLHttpRequest> {
let TrustedXHRAddress(addr) = inner;
JS {
ptr: addr as *const XMLHttpRequest
}
}
}
impl JS<Worker> {
pub unsafe fn from_trusted_worker_address(inner: TrustedWorkerAddress) -> JS<Worker> {
let TrustedWorkerAddress(addr) = inner;
JS {
ptr: addr as *const Worker
}
}
}
impl<T: Reflectable> JS<T> {
/// Create a new JS-owned value wrapped from a raw Rust pointer.
pub unsafe fn from_raw(raw: *const T) -> JS<T> {

View file

@ -0,0 +1,174 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![deny(missing_docs)]
//! A generic, safe mechnanism by which DOM objects can be pinned and transferred
//! between tasks (or intra-task for asynchronous events). Akin to Gecko's
//! nsMainThreadPtrHandle, this uses thread-safe reference counting and ensures
//! that the actual SpiderMonkey GC integration occurs on the script task via
//! message passing. Ownership of a `Trusted<T>` object means the DOM object of
//! type T to which it points remains alive. Any other behaviour is undefined.
//! To guarantee the lifetime of a DOM object when performing asynchronous operations,
//! obtain a `Trusted<T>` from that object and pass it along with each operation.
//! A usable pointer to the original DOM object can be obtained on the script task
//! from a `Trusted<T>` via the `to_temporary` method.
//!
//! The implementation of Trusted<T> is as follows:
//! A hashtable resides in the script task, keyed on the pointer to the Rust DOM object.
//! The values in this hashtable are atomic reference counts. When a Trusted<T> object is
//! created or cloned, this count is increased. When a Trusted<T> is dropped, the count
//! decreases. If the count hits zero, a message is dispatched to the script task to remove
//! the entry from the hashmap if the count is still zero. The JS reflector for the DOM object
//! is rooted when a hashmap entry is first created, and unrooted when the hashmap entry
//! is removed.
use dom::bindings::js::{Temporary, JS, JSRef};
use dom::bindings::utils::{Reflector, Reflectable};
use script_task::{ScriptMsg, ScriptChan};
use js::jsapi::{JS_AddObjectRoot, JS_RemoveObjectRoot, JSContext};
use libc;
use std::cell::RefCell;
use std::collections::hash_map::{HashMap, Vacant, Occupied};
use std::sync::{Arc, Mutex};
local_data_key!(pub LiveReferences: LiveDOMReferences)
/// A safe wrapper around a raw pointer to a DOM object that can be
/// shared among tasks for use in asynchronous operations. The underlying
/// DOM object is guaranteed to live at least as long as the last outstanding
/// `Trusted<T>` instance.
pub struct Trusted<T> {
cx: *mut JSContext,
/// A pointer to the Rust DOM object of type T, but void to allow
/// sending `Trusted<T>` between tasks, regardless of T's sendability.
ptr: *const libc::c_void,
refcount: Arc<Mutex<uint>>,
script_chan: ScriptChan,
}
impl<T: Reflectable> Trusted<T> {
/// Create a new `Trusted<T>` instance from an existing DOM pointer. The DOM object will
/// be prevented from being GCed for the duration of the resulting `Trusted<T>` object's
/// lifetime.
pub fn new(cx: *mut JSContext, ptr: JSRef<T>, script_chan: ScriptChan) -> Trusted<T> {
let live_references = LiveReferences.get().unwrap();
let refcount = live_references.addref(cx, &*ptr as *const T);
Trusted {
cx: cx,
ptr: &*ptr as *const T as *const libc::c_void,
refcount: refcount,
script_chan: script_chan,
}
}
/// Obtain a usable DOM pointer from a pinned `Trusted<T>` value. Attempts to use the
/// resulting `Temporary<T>` off of the script thread will fail.
pub fn to_temporary(&self) -> Temporary<T> {
unsafe {
Temporary::new(JS::from_raw(self.ptr as *const T))
}
}
}
impl<T: Reflectable> Clone for Trusted<T> {
fn clone(&self) -> Trusted<T> {
{
let mut refcount = self.refcount.lock();
*refcount += 1;
}
Trusted {
cx: self.cx,
ptr: self.ptr,
refcount: self.refcount.clone(),
script_chan: self.script_chan.clone(),
}
}
}
#[unsafe_destructor]
impl<T: Reflectable> Drop for Trusted<T> {
fn drop(&mut self) {
let mut refcount = self.refcount.lock();
assert!(*refcount > 0);
*refcount -= 1;
if *refcount == 0 {
let ScriptChan(ref chan) = self.script_chan;
chan.send(ScriptMsg::RefcountCleanup(self.ptr));
}
}
}
/// The set of live, pinned DOM objects that are currently prevented
/// from being garbage collected due to outstanding references.
pub struct LiveDOMReferences {
// keyed on pointer to Rust DOM object
table: RefCell<HashMap<*const libc::c_void, Arc<Mutex<uint>>>>
}
impl LiveDOMReferences {
/// Set up the task-local data required for storing the outstanding DOM references.
pub fn initialize() {
LiveReferences.replace(Some(LiveDOMReferences {
table: RefCell::new(HashMap::new()),
}));
}
fn addref<T: Reflectable>(&self, cx: *mut JSContext, ptr: *const T) -> Arc<Mutex<uint>> {
let mut table = self.table.borrow_mut();
match table.entry(ptr as *const libc::c_void) {
Occupied(mut entry) => {
let refcount = entry.get_mut();
*refcount.lock() += 1;
refcount.clone()
}
Vacant(entry) => {
unsafe {
let rootable = (*ptr).reflector().rootable();
JS_AddObjectRoot(cx, rootable);
}
let refcount = Arc::new(Mutex::new(1));
entry.set(refcount.clone());
refcount
}
}
}
/// Unpin the given DOM object if its refcount is 0.
pub fn cleanup(cx: *mut JSContext, raw_reflectable: *const libc::c_void) {
let live_references = LiveReferences.get().unwrap();
let reflectable = raw_reflectable as *const Reflector;
let mut table = live_references.table.borrow_mut();
match table.entry(raw_reflectable) {
Occupied(entry) => {
if *entry.get().lock() != 0 {
// there could have been a new reference taken since
// this message was dispatched.
return;
}
unsafe {
JS_RemoveObjectRoot(cx, (*reflectable).rootable());
}
let _ = entry.take();
}
Vacant(_) => {
// there could be a cleanup message dispatched, then a new
// pinned reference obtained and released before the message
// is processed, at which point there would be no matching
// hashtable entry.
info!("attempt to cleanup an unrecognized reflector");
}
}
}
}
impl Drop for LiveDOMReferences {
fn drop(&mut self) {
assert!(self.table.borrow().keys().count() == 0);
}
}

View file

@ -28,6 +28,7 @@
//! a datatype.
use dom::bindings::js::JS;
use dom::bindings::refcounted::Trusted;
use dom::bindings::utils::{Reflectable, Reflector, WindowProxyHandler};
use dom::node::{Node, TrustedNodeAddress};
@ -203,6 +204,7 @@ no_jsmanaged_fields!(Receiver<T>)
no_jsmanaged_fields!(Rect<T>)
no_jsmanaged_fields!(ImageCacheTask, ScriptControlChan)
no_jsmanaged_fields!(Atom, Namespace, Timer)
no_jsmanaged_fields!(Trusted<T>)
no_jsmanaged_fields!(PropertyDeclarationBlock)
// These three are interdependent, if you plan to put jsmanaged data
// in one of these make sure it is propagated properly to containing structs