Auto merge of #11872 - eddyb:back-to-roots, r=Ms2ger

Replace return_address usage for rooting with stack guards and convenience macros.

The existing `Rooted` and `RootedVec` users were migrated the the following two macros:
```rust
let x = Rooted::new(cx, value);
// Was changed to:
rooted!(in(cx) let x = value);
// Which expands to:
let mut __root = Rooted::new_unrooted(value);
let x = RootedGuard::new(cx, &mut __root);
```
```rust
let mut v = RootedVec::new();
v.extend(iterator);
// Was changed to:
rooted_vec!(let v <- iterator);
// Which expands to:
let mut __root = RootableVec::new();
let v = RootedVec::new(&mut __root, iterator);
```

The `rooted!` macro depends on servo/rust-mozjs#272.
These APIs based on two types, a container to be rooted and a rooting guard, allow implementing both `Rooted`-style rooting and `Traceable`-based rooting in stable Rust, without abusing `return_address`.

Such macros may have been tried before, but in 1.9 their hygiene is broken, they work only since 1.10.

Sadly, `Rooted` is a FFI type and completely exposed, so I cannot prevent anyone from creating their own, although all fields but the value get overwritten by `RootedGuard::new` anyway.
`RootableVec` OTOH is *guaranteed* to be empty when not rooted, which makes it harmless AFAICT.

By fixing rust-lang/rust#34227, this PR enables Servo to build with `-Zorbit`.

---
- [x] `./mach build -d` does not report any errors
- [x] `./mach test-tidy` does not report any errors
- [x] These changes fix rust-lang/rust#34227
- [x] These changes do not require tests because they are not functional changes

<!-- Reviewable:start -->
---
This change is [<img src="https://reviewable.io/review_button.svg" height="35" align="absmiddle" alt="Reviewable"/>](https://reviewable.io/reviews/servo/servo/11872)
<!-- Reviewable:end -->
This commit is contained in:
bors-servo 2016-07-04 11:03:35 -07:00 committed by GitHub
commit 80cb0cf821
33 changed files with 315 additions and 308 deletions

View file

@ -9,14 +9,14 @@ use dom::bindings::global::global_root_from_object;
use dom::bindings::reflector::Reflectable;
use js::jsapi::GetGlobalForObjectCrossCompartment;
use js::jsapi::JSAutoCompartment;
use js::jsapi::{Heap, MutableHandleObject, RootedObject, RootedValue};
use js::jsapi::{Heap, MutableHandleObject, RootedObject};
use js::jsapi::{IsCallable, JSContext, JSObject, JS_WrapObject};
use js::jsapi::{JSCompartment, JS_EnterCompartment, JS_LeaveCompartment};
use js::jsapi::{JS_GetProperty, JS_IsExceptionPending, JS_ReportPendingException};
use js::jsval::{JSVal, UndefinedValue};
use js::rust::RootedGuard;
use std::default::Default;
use std::ffi::CString;
use std::intrinsics::return_address;
use std::ptr;
use std::rc::Rc;
@ -114,20 +114,20 @@ impl CallbackInterface {
/// Returns the property with the given `name`, if it is a callable object,
/// or an error otherwise.
pub fn get_callable_property(&self, cx: *mut JSContext, name: &str) -> Fallible<JSVal> {
let mut callable = RootedValue::new(cx, UndefinedValue());
let obj = RootedObject::new(cx, self.callback());
rooted!(in(cx) let mut callable = UndefinedValue());
rooted!(in(cx) let obj = self.callback());
unsafe {
let c_name = CString::new(name).unwrap();
if !JS_GetProperty(cx, obj.handle(), c_name.as_ptr(), callable.handle_mut()) {
return Err(Error::JSFailed);
}
if !callable.ptr.is_object() || !IsCallable(callable.ptr.to_object()) {
if !callable.is_object() || !IsCallable(callable.to_object()) {
return Err(Error::Type(format!("The value of the {} property is not callable",
name)));
}
}
Ok(callable.ptr)
Ok(callable.get())
}
}
@ -147,11 +147,9 @@ pub fn wrap_call_this_object<T: Reflectable>(cx: *mut JSContext,
/// A class that performs whatever setup we need to safely make a call while
/// this class is on the stack. After `new` returns, the call is safe to make.
pub struct CallSetup {
pub struct CallSetup<'a> {
/// The compartment for reporting exceptions.
/// As a RootedObject, this must be the first field in order to
/// determine the final address on the stack correctly.
exception_compartment: RootedObject,
exception_compartment: RootedGuard<'a, *mut JSObject>,
/// The `JSContext` used for the call.
cx: *mut JSContext,
/// The compartment we were in before the call.
@ -160,20 +158,21 @@ pub struct CallSetup {
handling: ExceptionHandling,
}
impl CallSetup {
impl<'a> CallSetup<'a> {
/// Performs the setup needed to make a call.
#[allow(unrooted_must_root)]
pub fn new<T: CallbackContainer>(callback: &T, handling: ExceptionHandling) -> CallSetup {
pub fn new<T: CallbackContainer>(exception_compartment: &'a mut RootedObject,
callback: &T,
handling: ExceptionHandling)
-> CallSetup<'a> {
let global = unsafe { global_root_from_object(callback.callback()) };
let cx = global.r().get_cx();
let exception_compartment = unsafe {
exception_compartment.ptr = unsafe {
GetGlobalForObjectCrossCompartment(callback.callback())
};
CallSetup {
exception_compartment: RootedObject::new_with_addr(cx,
exception_compartment,
unsafe { return_address() }),
exception_compartment: RootedGuard::new(cx, exception_compartment),
cx: cx,
old_compartment: unsafe { JS_EnterCompartment(cx, callback.callback()) },
handling: handling,
@ -186,7 +185,7 @@ impl CallSetup {
}
}
impl Drop for CallSetup {
impl<'a> Drop for CallSetup<'a> {
fn drop(&mut self) {
unsafe {
JS_LeaveCompartment(self.cx, self.old_compartment);
@ -195,7 +194,7 @@ impl Drop for CallSetup {
unsafe { JS_IsExceptionPending(self.cx) };
if need_to_deal_with_exception {
unsafe {
let _ac = JSAutoCompartment::new(self.cx, self.exception_compartment.ptr);
let _ac = JSAutoCompartment::new(self.cx, *self.exception_compartment);
JS_ReportPendingException(self.cx);
}
}

View file

@ -1166,23 +1166,22 @@ class CGArgumentConverter(CGThing):
template, variadicConversion, declType, "slot")]
arg = "arg%d" % index
if argument.type.isGeckoInterface():
vec = "RootedVec::new()"
init = "rooted_vec!(let mut %s)" % arg
innerConverter.append(CGGeneric("%s.push(JS::from_ref(&*slot));" % arg))
else:
vec = "vec![]"
init = "let mut %s = vec![]" % arg
innerConverter.append(CGGeneric("%s.push(slot);" % arg))
inner = CGIndenter(CGList(innerConverter, "\n"), 8).define()
self.converter = CGGeneric("""\
let mut %(arg)s = %(vec)s;
%(init)s;
if %(argc)s > %(index)s {
%(arg)s.reserve(%(argc)s as usize - %(index)s);
for variadicArg in %(index)s..%(argc)s {
%(inner)s
}
}""" % {'arg': arg, 'argc': argc, 'index': index, 'inner': inner, 'vec': vec})
}""" % {'arg': arg, 'argc': argc, 'index': index, 'inner': inner, 'init': init})
def define(self):
return self.converter.define()
@ -2278,34 +2277,33 @@ def CreateBindingJSObject(descriptor, parent=None):
assert not descriptor.isGlobal()
create += """
let handler = RegisterBindings::proxy_handlers[PrototypeList::Proxies::%s as usize];
let private = RootedValue::new(cx, PrivateValue(raw as *const libc::c_void));
rooted!(in(cx) let private = PrivateValue(raw as *const libc::c_void));
let obj = NewProxyObject(cx, handler,
private.handle(),
proto.ptr, %s.get(),
proto.get(), %s.get(),
ptr::null_mut(), ptr::null_mut());
assert!(!obj.is_null());
let obj = RootedObject::new(cx, obj);\
rooted!(in(cx) let obj = obj);\
""" % (descriptor.name, parent)
elif descriptor.isGlobal():
create += ("let obj = RootedObject::new(\n"
" cx,\n"
create += ("rooted!(in(cx) let obj =\n"
" create_dom_global(\n"
" cx,\n"
" &Class.base as *const js::jsapi::Class as *const JSClass,\n"
" raw as *const libc::c_void,\n"
" Some(%s))\n"
");\n"
"assert!(!obj.ptr.is_null());" % TRACE_HOOK_NAME)
"assert!(!obj.is_null());" % TRACE_HOOK_NAME)
else:
create += ("let obj = RootedObject::new(cx, JS_NewObjectWithGivenProto(\n"
create += ("rooted!(in(cx) let obj = JS_NewObjectWithGivenProto(\n"
" cx, &Class.base as *const js::jsapi::Class as *const JSClass, proto.handle()));\n"
"assert!(!obj.ptr.is_null());\n"
"assert!(!obj.is_null());\n"
"\n"
"JS_SetReservedSlot(obj.ptr, DOM_OBJECT_SLOT,\n"
"JS_SetReservedSlot(obj.get(), DOM_OBJECT_SLOT,\n"
" PrivateValue(raw as *const libc::c_void));")
if descriptor.weakReferenceable:
create += """
JS_SetReservedSlot(obj.ptr, DOM_WEAK_SLOT, PrivateValue(ptr::null()));"""
JS_SetReservedSlot(obj.get(), DOM_WEAK_SLOT, PrivateValue(ptr::null()));"""
return create
@ -2344,7 +2342,7 @@ def CopyUnforgeablePropertiesToInstance(descriptor):
# reflector, so we can make sure we don't get confused by named getters.
if descriptor.proxy:
copyCode += """\
let expando = RootedObject::new(cx, ensure_expando_object(cx, obj.handle()));
rooted!(in(cx) let expando = ensure_expando_object(cx, obj.handle()));
"""
obj = "expando"
else:
@ -2358,9 +2356,9 @@ let expando = RootedObject::new(cx, ensure_expando_object(cx, obj.handle()));
else:
copyFunc = "JS_InitializePropertiesFromCompatibleNativeObject"
copyCode += """\
let mut unforgeable_holder = RootedObject::new(cx, ptr::null_mut());
rooted!(in(cx) let mut unforgeable_holder = ptr::null_mut());
unforgeable_holder.handle_mut().set(
JS_GetReservedSlot(proto.ptr, DOM_PROTO_UNFORGEABLE_HOLDER_SLOT).to_object());
JS_GetReservedSlot(proto.get(), DOM_PROTO_UNFORGEABLE_HOLDER_SLOT).to_object());
assert!(%(copyFunc)s(cx, %(obj)s.handle(), unforgeable_holder.handle()));
""" % {'copyFunc': copyFunc, 'obj': obj}
@ -2393,25 +2391,25 @@ let scope = scope.reflector().get_jsobject();
assert!(!scope.get().is_null());
assert!(((*JS_GetClass(scope.get())).flags & JSCLASS_IS_GLOBAL) != 0);
let mut proto = RootedObject::new(cx, ptr::null_mut());
rooted!(in(cx) let mut proto = ptr::null_mut());
let _ac = JSAutoCompartment::new(cx, scope.get());
GetProtoObject(cx, scope, proto.handle_mut());
assert!(!proto.ptr.is_null());
assert!(!proto.is_null());
%(createObject)s
%(copyUnforgeable)s
(*raw).init_reflector(obj.ptr);
(*raw).init_reflector(obj.get());
Root::from_ref(&*raw)""" % {'copyUnforgeable': unforgeable, 'createObject': create})
else:
create = CreateBindingJSObject(self.descriptor)
return CGGeneric("""\
%(createObject)s
(*raw).init_reflector(obj.ptr);
(*raw).init_reflector(obj.get());
let _ac = JSAutoCompartment::new(cx, obj.ptr);
let mut proto = RootedObject::new(cx, ptr::null_mut());
let _ac = JSAutoCompartment::new(cx, obj.get());
rooted!(in(cx) let mut proto = ptr::null_mut());
GetProtoObject(cx, obj.handle(), proto.handle_mut());
JS_SetPrototype(cx, obj.handle(), proto.handle());
@ -2525,29 +2523,29 @@ class CGCreateInterfaceObjectsMethod(CGAbstractMethod):
if self.descriptor.interface.isCallback():
assert not self.descriptor.interface.ctor() and self.descriptor.interface.hasConstants()
return CGGeneric("""\
let mut interface = RootedObject::new(cx, ptr::null_mut());
rooted!(in(cx) let mut interface = ptr::null_mut());
create_callback_interface_object(cx, global, sConstants, %(name)s, interface.handle_mut());
assert!(!interface.ptr.is_null());
assert!(!interface.is_null());
assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null());
(*cache)[PrototypeList::Constructor::%(id)s as usize] = interface.ptr;
(*cache)[PrototypeList::Constructor::%(id)s as usize] = interface.get();
<*mut JSObject>::post_barrier((*cache).as_mut_ptr().offset(PrototypeList::Constructor::%(id)s as isize),
ptr::null_mut(),
interface.ptr);
interface.get());
""" % {"id": name, "name": str_to_const_array(name)})
if len(self.descriptor.prototypeChain) == 1:
if self.descriptor.interface.getExtendedAttribute("ExceptionClass"):
getPrototypeProto = "prototype_proto.ptr = JS_GetErrorPrototype(cx)"
getPrototypeProto = "prototype_proto.set(JS_GetErrorPrototype(cx))"
else:
getPrototypeProto = "prototype_proto.ptr = JS_GetObjectPrototype(cx, global)"
getPrototypeProto = "prototype_proto.set(JS_GetObjectPrototype(cx, global))"
else:
getPrototypeProto = ("%s::GetProtoObject(cx, global, prototype_proto.handle_mut())" %
toBindingNamespace(self.descriptor.prototypeChain[-2]))
code = [CGGeneric("""\
let mut prototype_proto = RootedObject::new(cx, ptr::null_mut());
rooted!(in(cx) let mut prototype_proto = ptr::null_mut());
%s;
assert!(!prototype_proto.ptr.is_null());""" % getPrototypeProto)]
assert!(!prototype_proto.is_null());""" % getPrototypeProto)]
properties = {
"id": name,
@ -2561,7 +2559,7 @@ assert!(!prototype_proto.ptr.is_null());""" % getPrototypeProto)]
properties[arrayName] = "&[]"
code.append(CGGeneric("""
let mut prototype = RootedObject::new(cx, ptr::null_mut());
rooted!(in(cx) let mut prototype = ptr::null_mut());
create_interface_prototype_object(cx,
prototype_proto.handle(),
&PrototypeClass,
@ -2570,12 +2568,12 @@ create_interface_prototype_object(cx,
%(consts)s,
%(unscopables)s,
prototype.handle_mut());
assert!(!prototype.ptr.is_null());
assert!(!prototype.is_null());
assert!((*cache)[PrototypeList::ID::%(id)s as usize].is_null());
(*cache)[PrototypeList::ID::%(id)s as usize] = prototype.ptr;
(*cache)[PrototypeList::ID::%(id)s as usize] = prototype.get();
<*mut JSObject>::post_barrier((*cache).as_mut_ptr().offset(PrototypeList::ID::%(id)s as isize),
ptr::null_mut(),
prototype.ptr);
prototype.get());
""" % properties))
if self.descriptor.interface.hasInterfaceObject():
@ -2587,15 +2585,15 @@ assert!((*cache)[PrototypeList::ID::%(id)s as usize].is_null());
if self.descriptor.interface.parent:
parentName = toBindingNamespace(self.descriptor.getParentName())
code.append(CGGeneric("""
let mut interface_proto = RootedObject::new(cx, ptr::null_mut());
rooted!(in(cx) let mut interface_proto = ptr::null_mut());
%s::GetConstructorObject(cx, global, interface_proto.handle_mut());""" % parentName))
else:
code.append(CGGeneric("""
let interface_proto = RootedObject::new(cx, JS_GetFunctionPrototype(cx, global));"""))
rooted!(in(cx) let interface_proto = JS_GetFunctionPrototype(cx, global));"""))
code.append(CGGeneric("""\
assert!(!interface_proto.ptr.is_null());
assert!(!interface_proto.is_null());
let mut interface = RootedObject::new(cx, ptr::null_mut());
rooted!(in(cx) let mut interface = ptr::null_mut());
create_noncallback_interface_object(cx,
global,
interface_proto.handle(),
@ -2607,14 +2605,14 @@ create_noncallback_interface_object(cx,
%(name)s,
%(length)s,
interface.handle_mut());
assert!(!interface.ptr.is_null());""" % properties))
assert!(!interface.is_null());""" % properties))
if self.descriptor.hasDescendants():
code.append(CGGeneric("""\
assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null());
(*cache)[PrototypeList::Constructor::%(id)s as usize] = interface.ptr;
(*cache)[PrototypeList::Constructor::%(id)s as usize] = interface.get();
<*mut JSObject>::post_barrier((*cache).as_mut_ptr().offset(PrototypeList::Constructor::%(id)s as isize),
ptr::null_mut(),
interface.ptr);
interface.get());
""" % properties))
constructors = self.descriptor.interface.namedConstructors
@ -2649,15 +2647,15 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null());
holderClass = "&Class.base as *const js::jsapi::Class as *const JSClass"
holderProto = "prototype.handle()"
code.append(CGGeneric("""
let mut unforgeable_holder = RootedObject::new(cx, ptr::null_mut());
rooted!(in(cx) let mut unforgeable_holder = ptr::null_mut());
unforgeable_holder.handle_mut().set(
JS_NewObjectWithoutMetadata(cx, %(holderClass)s, %(holderProto)s));
assert!(!unforgeable_holder.ptr.is_null());
assert!(!unforgeable_holder.is_null());
""" % {'holderClass': holderClass, 'holderProto': holderProto}))
code.append(InitUnforgeablePropertiesOnHolder(self.descriptor, self.properties))
code.append(CGGeneric("""\
JS_SetReservedSlot(prototype.ptr, DOM_PROTO_UNFORGEABLE_HOLDER_SLOT,
ObjectValue(&*unforgeable_holder.ptr))"""))
JS_SetReservedSlot(prototype.get(), DOM_PROTO_UNFORGEABLE_HOLDER_SLOT,
ObjectValue(&*unforgeable_holder.get()))"""))
return CGList(code, "\n")
@ -2826,9 +2824,9 @@ class CGDefineDOMInterfaceMethod(CGAbstractMethod):
return CGGeneric("""\
assert!(!global.get().is_null());
%s
let mut proto = RootedObject::new(cx, ptr::null_mut());
rooted!(in(cx) let mut proto = ptr::null_mut());
%s(cx, global, proto.handle_mut());
assert!(!proto.ptr.is_null());""" % (getCheck(self.descriptor), function))
assert!(!proto.is_null());""" % (getCheck(self.descriptor), function))
def needCx(returnType, arguments, considerTypes):
@ -3277,15 +3275,15 @@ class CGSpecializedForwardingSetter(CGSpecializedSetter):
assert all(ord(c) < 128 for c in attrName)
assert all(ord(c) < 128 for c in forwardToAttrName)
return CGGeneric("""\
let mut v = RootedValue::new(cx, UndefinedValue());
rooted!(in(cx) let mut v = UndefinedValue());
if !JS_GetProperty(cx, obj, %s as *const u8 as *const libc::c_char, v.handle_mut()) {
return false;
}
if !v.ptr.is_object() {
if !v.is_object() {
throw_type_error(cx, "Value.%s is not an object.");
return false;
}
let target_obj = RootedObject::new(cx, v.ptr.to_object());
rooted!(in(cx) let target_obj = v.to_object());
JS_SetProperty(cx, target_obj.handle(), %s as *const u8 as *const libc::c_char, args.get(0))
""" % (str_to_const_array(attrName), attrName, str_to_const_array(forwardToAttrName)))
@ -4342,7 +4340,7 @@ class CGProxySpecialOperation(CGPerSignatureCall):
}
self.cgRoot.prepend(instantiateJSToNativeConversionTemplate(
template, templateValues, declType, argument.identifier.name))
self.cgRoot.prepend(CGGeneric("let value = RootedValue::new(cx, desc.get().value);"))
self.cgRoot.prepend(CGGeneric("rooted!(in(cx) let value = desc.value);"))
elif operation.isGetter():
self.cgRoot.prepend(CGGeneric("let mut found = false;"))
@ -4450,7 +4448,7 @@ class CGProxyUnwrap(CGAbstractMethod):
obj = js::UnwrapObject(obj);
}*/
//MOZ_ASSERT(IsProxy(obj));
let box_ = GetProxyPrivate(*obj.ptr).to_private() as *const %s;
let box_ = GetProxyPrivate(obj.get()).to_private() as *const %s;
return box_;""" % self.descriptor.concreteType)
@ -4458,7 +4456,7 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod):
def __init__(self, descriptor):
args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', 'proxy'),
Argument('HandleId', 'id'),
Argument('MutableHandle<PropertyDescriptor>', 'desc')]
Argument('MutableHandle<PropertyDescriptor>', 'desc', mutable=True)]
CGAbstractExternMethod.__init__(self, descriptor, "getOwnPropertyDescriptor",
"bool", args)
self.descriptor = descriptor
@ -4475,13 +4473,14 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod):
attrs = "JSPROP_ENUMERATE"
if self.descriptor.operations['IndexedSetter'] is None:
attrs += " | JSPROP_READONLY"
fillDescriptor = ("desc.get().value = result_root.ptr;\n"
"fill_property_descriptor(&mut *desc.ptr, *proxy.ptr, %s);\n"
# FIXME(#11868) Should assign to desc.value, desc.get() is a copy.
fillDescriptor = ("desc.get().value = result_root.get();\n"
"fill_property_descriptor(&mut desc, proxy.get(), %s);\n"
"return true;" % attrs)
templateValues = {
'jsvalRef': 'result_root.handle_mut()',
'successCode': fillDescriptor,
'pre': 'let mut result_root = RootedValue::new(cx, UndefinedValue());'
'pre': 'rooted!(in(cx) let mut result_root = UndefinedValue());'
}
get += ("if let Some(index) = index {\n" +
" let this = UnwrapProxy(proxy);\n" +
@ -4500,13 +4499,14 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod):
attrs = " | ".join(attrs)
else:
attrs = "0"
fillDescriptor = ("desc.get().value = result_root.ptr;\n"
"fill_property_descriptor(&mut *desc.ptr, *proxy.ptr, %s);\n"
# FIXME(#11868) Should assign to desc.value, desc.get() is a copy.
fillDescriptor = ("desc.get().value = result_root.get();\n"
"fill_property_descriptor(&mut desc, proxy.get(), %s);\n"
"return true;" % attrs)
templateValues = {
'jsvalRef': 'result_root.handle_mut()',
'successCode': fillDescriptor,
'pre': 'let mut result_root = RootedValue::new(cx, UndefinedValue());'
'pre': 'rooted!(in(cx) let mut result_root = UndefinedValue());'
}
# Once we start supporting OverrideBuiltins we need to make
# ResolveOwnProperty or EnumerateOwnProperties filter out named
@ -4518,16 +4518,17 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod):
else:
namedGet = ""
# FIXME(#11868) Should assign to desc.obj, desc.get() is a copy.
return get + """\
let expando = RootedObject::new(cx, get_expando_object(proxy));
rooted!(in(cx) let expando = get_expando_object(proxy));
//if (!xpc::WrapperFactory::IsXrayWrapper(proxy) && (expando = GetExpandoObject(proxy))) {
if !expando.ptr.is_null() {
if !expando.is_null() {
if !JS_GetPropertyDescriptorById(cx, expando.handle(), id, desc) {
return false;
}
if !desc.get().obj.is_null() {
if !desc.obj.is_null() {
// Pretend the property lives on the wrapper.
desc.get().obj = *proxy.ptr;
desc.get().obj = proxy.get();
return true;
}
}
@ -4637,7 +4638,7 @@ class CGDOMJSProxyHandler_ownPropertyKeys(CGAbstractExternMethod):
body += dedent(
"""
for i in 0..(*unwrapped_proxy).Length() {
let rooted_jsid = RootedId::new(cx, int_to_jsid(i as i32));
rooted!(in(cx) let rooted_jsid = int_to_jsid(i as i32));
AppendToAutoIdVector(props, rooted_jsid.handle().get());
}
""")
@ -4648,9 +4649,9 @@ class CGDOMJSProxyHandler_ownPropertyKeys(CGAbstractExternMethod):
for name in (*unwrapped_proxy).SupportedPropertyNames() {
let cstring = CString::new(name).unwrap();
let jsstring = JS_AtomizeAndPinString(cx, cstring.as_ptr());
let rooted = RootedString::new(cx, jsstring);
rooted!(in(cx) let rooted = jsstring);
let jsid = INTERNED_STRING_TO_JSID(cx, rooted.handle().get());
let rooted_jsid = RootedId::new(cx, jsid);
rooted!(in(cx) let rooted_jsid = jsid);
AppendToAutoIdVector(props, rooted_jsid.handle().get());
}
""")
@ -4659,7 +4660,7 @@ class CGDOMJSProxyHandler_ownPropertyKeys(CGAbstractExternMethod):
"""
let expando = get_expando_object(proxy);
if !expando.is_null() {
let rooted_expando = RootedObject::new(cx, expando);
rooted!(in(cx) let rooted_expando = expando);
GetPropertyKeys(cx, rooted_expando.handle(), JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, props);
}
@ -4693,7 +4694,7 @@ class CGDOMJSProxyHandler_getOwnEnumerablePropertyKeys(CGAbstractExternMethod):
body += dedent(
"""
for i in 0..(*unwrapped_proxy).Length() {
let rooted_jsid = RootedId::new(cx, int_to_jsid(i as i32));
rooted!(in(cx) let rooted_jsid = int_to_jsid(i as i32));
AppendToAutoIdVector(props, rooted_jsid.handle().get());
}
""")
@ -4702,7 +4703,7 @@ class CGDOMJSProxyHandler_getOwnEnumerablePropertyKeys(CGAbstractExternMethod):
"""
let expando = get_expando_object(proxy);
if !expando.is_null() {
let rooted_expando = RootedObject::new(cx, expando);
rooted!(in(cx) let rooted_expando = expando);
GetPropertyKeys(cx, rooted_expando.handle(), JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, props);
}
@ -4748,8 +4749,8 @@ class CGDOMJSProxyHandler_hasOwn(CGAbstractExternMethod):
named = ""
return indexed + """\
let expando = RootedObject::new(cx, get_expando_object(proxy));
if !expando.ptr.is_null() {
rooted!(in(cx) let expando = get_expando_object(proxy));
if !expando.is_null() {
let ok = JS_HasPropertyById(cx, expando.handle(), id, bp);
if !ok || *bp {
return ok;
@ -4773,8 +4774,8 @@ class CGDOMJSProxyHandler_get(CGAbstractExternMethod):
def getBody(self):
getFromExpando = """\
let expando = RootedObject::new(cx, get_expando_object(proxy));
if !expando.ptr.is_null() {
rooted!(in(cx) let expando = get_expando_object(proxy));
if !expando.is_null() {
let mut hasProp = false;
if !JS_HasPropertyById(cx, expando.handle(), id, &mut hasProp) {
return false;
@ -4829,7 +4830,7 @@ if found {
return true;
}
%s
*vp.ptr = UndefinedValue();
vp.set(UndefinedValue());
return true;""" % (getIndexedOrExpando, getNamed)
def definition_body(self):
@ -5297,7 +5298,7 @@ class CGDictionary(CGThing):
return CGGeneric("%s: %s,\n" % (name, conversion.define()))
def varInsert(varName, dictionaryName):
insertion = ("let mut %s_js = RootedValue::new(cx, UndefinedValue());\n"
insertion = ("rooted!(in(cx) let mut %s_js = UndefinedValue());\n"
"%s.to_jsval(cx, %s_js.handle_mut());\n"
"set_dictionary_property(cx, obj.handle(), \"%s\", %s_js.handle()).unwrap();"
% (varName, varName, varName, dictionaryName, varName))
@ -5324,13 +5325,14 @@ class CGDictionary(CGThing):
" }\n"
" pub unsafe fn new(cx: *mut JSContext, val: HandleValue) -> Result<${selfName}, ()> {\n"
" let object = if val.get().is_null_or_undefined() {\n"
" RootedObject::new(cx, ptr::null_mut())\n"
" ptr::null_mut()\n"
" } else if val.get().is_object() {\n"
" RootedObject::new(cx, val.get().to_object())\n"
" val.get().to_object()\n"
" } else {\n"
" throw_type_error(cx, \"Value not an object.\");\n"
" return Err(());\n"
" };\n"
" rooted!(in(cx) let object = object);\n"
" Ok(${selfName} {\n"
"${initParent}"
"${initMembers}"
@ -5348,9 +5350,9 @@ class CGDictionary(CGThing):
"\n"
"impl ToJSValConvertible for ${selfName} {\n"
" unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {\n"
" let obj = RootedObject::new(cx, JS_NewObject(cx, ptr::null()));\n"
" rooted!(in(cx) let obj = JS_NewObject(cx, ptr::null()));\n"
"${insertMembers}"
" rval.set(ObjectOrNullValue(obj.ptr))\n"
" rval.set(ObjectOrNullValue(obj.get()))\n"
" }\n"
"}\n").substitute({
"selfName": self.makeClassName(d),
@ -5400,7 +5402,7 @@ class CGDictionary(CGThing):
conversion = (
"{\n"
"let mut rval = RootedValue::new(cx, UndefinedValue());\n"
"rooted!(in(cx) let mut rval = UndefinedValue());\n"
"match try!(get_dictionary_property(cx, object.handle(), \"%s\", rval.handle_mut())) {\n"
" true => {\n"
"%s\n"
@ -5548,8 +5550,8 @@ class CGBindingRoot(CGThing):
'js::jsapi::{JSNative, JSObject, JSNativeWrapper, JSPropertySpec}',
'js::jsapi::{JSString, JSTracer, JSType, JSTypedMethodJitInfo, JSValueType}',
'js::jsapi::{ObjectOpResult, JSJitInfo_OpType, MutableHandle, MutableHandleObject}',
'js::jsapi::{MutableHandleValue, PropertyDescriptor, RootedId, RootedObject}',
'js::jsapi::{RootedString, RootedValue, SymbolCode, jsid}',
'js::jsapi::{MutableHandleValue, PropertyDescriptor, RootedObject}',
'js::jsapi::{SymbolCode, jsid}',
'js::jsval::JSVal',
'js::jsval::{ObjectValue, ObjectOrNullValue, PrivateValue}',
'js::jsval::{NullValue, UndefinedValue}',
@ -5600,7 +5602,6 @@ class CGBindingRoot(CGThing):
'dom::bindings::proxyhandler::{get_expando_object, get_property_descriptor}',
'dom::bindings::num::Finite',
'dom::bindings::str::{ByteString, DOMString, USVString}',
'dom::bindings::trace::RootedVec',
'dom::bindings::weakref::{DOM_WEAK_SLOT, WeakBox, WeakReferenceable}',
'dom::browsingcontext::BrowsingContext',
'mem::heap_size_of_raw_self_and_children',
@ -5769,16 +5770,17 @@ class CGCallback(CGClass):
args.insert(0, Argument(None, "&self"))
argsWithoutThis.insert(0, Argument(None, "&self"))
setupCall = ("let s = CallSetup::new(self, aExceptionHandling);\n"
setupCall = ("let mut s_ec = RootedObject::new_unrooted(ptr::null_mut());\n"
"let s = CallSetup::new(&mut s_ec, self, aExceptionHandling);\n"
"if s.get_context().is_null() {\n"
" return Err(JSFailed);\n"
"}\n")
bodyWithThis = string.Template(
setupCall +
"let mut thisObjJS = RootedObject::new(s.get_context(), ptr::null_mut());\n"
"rooted!(in(s.get_context()) let mut thisObjJS = ptr::null_mut());\n"
"wrap_call_this_object(s.get_context(), thisObj, thisObjJS.handle_mut());\n"
"if thisObjJS.ptr.is_null() {\n"
"if thisObjJS.is_null() {\n"
" return Err(JSFailed);\n"
"}\n"
"return ${methodName}(${callArgs});").substitute({
@ -5787,7 +5789,7 @@ class CGCallback(CGClass):
})
bodyWithoutThis = string.Template(
setupCall +
"let thisObjJS = RootedObject::new(s.get_context(), ptr::null_mut());"
"rooted!(in(s.get_context()) let thisObjJS = ptr::null_mut());"
"return ${methodName}(${callArgs});").substitute({
"callArgs": ", ".join(argnamesWithoutThis),
"methodName": 'self.' + method.name,
@ -6006,8 +6008,8 @@ class CallbackMember(CGNativeMember):
conversion = wrapForType(
"argv_root.handle_mut()", result=argval,
successCode="argv[%s] = argv_root.ptr;" % jsvalIndex,
pre="let mut argv_root = RootedValue::new(cx, UndefinedValue());")
successCode="argv[%s] = argv_root.get();" % jsvalIndex,
pre="rooted!(in(cx) let mut argv_root = UndefinedValue());")
if arg.variadic:
conversion = string.Template(
"for idx in 0..${arg}.len() {\n" +
@ -6077,7 +6079,7 @@ class CallbackMethod(CallbackMember):
needThisHandling)
def getRvalDecl(self):
return "let mut rval = RootedValue::new(cx, UndefinedValue());\n"
return "rooted!(in(cx) let mut rval = UndefinedValue());\n"
def getCall(self):
replacements = {
@ -6092,7 +6094,7 @@ class CallbackMethod(CallbackMember):
replacements["argc"] = "0"
return string.Template(
"${getCallable}"
"let rootedThis = RootedObject::new(cx, ${thisObj});\n"
"rooted!(in(cx) let rootedThis = ${thisObj});\n"
"let ok = JS_CallFunctionValue(\n"
" cx, rootedThis.handle(), callable.handle(),\n"
" &HandleValueArray {\n"
@ -6116,7 +6118,7 @@ class CallCallback(CallbackMethod):
return "aThisObj.get()"
def getCallableDecl(self):
return "let callable = RootedValue::new(cx, ObjectValue(&*self.parent.callback()));\n"
return "rooted!(in(cx) let callable = ObjectValue(&*self.parent.callback()));\n"
class CallbackOperationBase(CallbackMethod):
@ -6141,17 +6143,17 @@ class CallbackOperationBase(CallbackMethod):
"methodName": self.methodName
}
getCallableFromProp = string.Template(
'RootedValue::new(cx, try!(self.parent.get_callable_property(cx, "${methodName}")))'
'try!(self.parent.get_callable_property(cx, "${methodName}"))'
).substitute(replacements)
if not self.singleOperation:
return 'JS::Rooted<JS::Value> callable(cx);\n' + getCallableFromProp
return 'rooted!(in(cx) let callable =\n' + getCallableFromProp + ');\n'
return (
'let isCallable = IsCallable(self.parent.callback());\n'
'let callable =\n' +
'rooted!(in(cx) let callable =\n' +
CGIndenter(
CGIfElseWrapper('isCallable',
CGGeneric('RootedValue::new(cx, ObjectValue(&*self.parent.callback()))'),
CGGeneric(getCallableFromProp))).define() + ';\n')
CGGeneric('ObjectValue(&*self.parent.callback())'),
CGGeneric(getCallableFromProp))).define() + ');\n')
class CallbackOperation(CallbackOperationBase):

View file

@ -10,7 +10,7 @@ use dom::bindings::global::GlobalRef;
use dom::domexception::{DOMErrorName, DOMException};
use js::error::{throw_range_error, throw_type_error};
use js::jsapi::JSAutoCompartment;
use js::jsapi::{JSContext, JSObject, RootedValue};
use js::jsapi::{JSContext, JSObject};
use js::jsapi::{JS_IsExceptionPending, JS_ReportPendingException, JS_SetPendingException};
use js::jsval::UndefinedValue;
@ -115,7 +115,7 @@ pub unsafe fn throw_dom_exception(cx: *mut JSContext, global: GlobalRef, result:
assert!(!JS_IsExceptionPending(cx));
let exception = DOMException::new(global, code);
let mut thrown = RootedValue::new(cx, UndefinedValue());
rooted!(in(cx) let mut thrown = UndefinedValue());
exception.to_jsval(cx, thrown.handle_mut());
JS_SetPendingException(cx, thrown.handle());
}

View file

@ -19,8 +19,8 @@ use js::jsapi::{JS_DefineProperty2, JS_DefineProperty4, JS_DefinePropertyById3};
use js::jsapi::{JS_GetClass, JS_GetFunctionObject, JS_GetPrototype, JS_LinkConstructorAndPrototype};
use js::jsapi::{JS_NewFunction, JS_NewObject, JS_NewObjectWithUniqueType};
use js::jsapi::{JS_NewPlainObject, JS_NewStringCopyN, MutableHandleObject};
use js::jsapi::{MutableHandleValue, ObjectOps, RootedId, RootedObject};
use js::jsapi::{RootedString, RootedValue, SymbolCode, TrueHandleValue, Value};
use js::jsapi::{MutableHandleValue, ObjectOps};
use js::jsapi::{SymbolCode, TrueHandleValue, Value};
use js::jsval::{BooleanValue, DoubleValue, Int32Value, JSVal, NullValue, UInt32Value};
use js::rust::{define_methods, define_properties};
use libc;
@ -74,7 +74,7 @@ fn define_constants(
obj: HandleObject,
constants: &[ConstantSpec]) {
for spec in constants {
let value = RootedValue::new(cx, spec.get_value());
rooted!(in(cx) let value = spec.get_value());
unsafe {
assert!(JS_DefineProperty(cx,
obj,
@ -243,13 +243,13 @@ pub unsafe fn create_interface_prototype_object(
create_object(cx, proto, class, regular_methods, regular_properties, constants, rval);
if !unscopable_names.is_empty() {
let mut unscopable_obj = RootedObject::new(cx, ptr::null_mut());
rooted!(in(cx) let mut unscopable_obj = ptr::null_mut());
create_unscopable_object(cx, unscopable_names, unscopable_obj.handle_mut());
let unscopable_symbol = GetWellKnownSymbol(cx, SymbolCode::unscopables);
assert!(!unscopable_symbol.is_null());
let unscopable_id = RootedId::new(cx, RUST_SYMBOL_TO_JSID(unscopable_symbol));
rooted!(in(cx) let unscopable_id = RUST_SYMBOL_TO_JSID(unscopable_symbol));
assert!(JS_DefinePropertyById3(
cx, rval.handle(), unscopable_id.handle(), unscopable_obj.handle(),
JSPROP_READONLY, None, None))
@ -288,7 +288,7 @@ pub unsafe fn create_named_constructors(
global: HandleObject,
named_constructors: &[(NonNullJSNative, &[u8], u32)],
interface_prototype_object: HandleObject) {
let mut constructor = RootedObject::new(cx, ptr::null_mut());
rooted!(in(cx) let mut constructor = ptr::null_mut());
for &(native, name, arity) in named_constructors {
assert!(*name.last().unwrap() == b'\0');
@ -299,8 +299,8 @@ pub unsafe fn create_named_constructors(
JSFUN_CONSTRUCTOR,
name.as_ptr() as *const libc::c_char);
assert!(!fun.is_null());
constructor.ptr = JS_GetFunctionObject(fun);
assert!(!constructor.ptr.is_null());
constructor.set(JS_GetFunctionObject(fun));
assert!(!constructor.is_null());
assert!(JS_DefineProperty1(cx,
constructor.handle(),
@ -339,12 +339,13 @@ unsafe fn has_instance(
// Step 1.
return Ok(false);
}
let mut value = RootedObject::new(cx, value.to_object());
rooted!(in(cx) let mut value = value.to_object());
let js_class = JS_GetClass(interface_object.get());
let object_class = &*(js_class as *const NonCallbackInterfaceObjectClass);
if let Ok(dom_class) = get_dom_class(UncheckedUnwrapObject(value.ptr, /* stopAtWindowProxy = */ 0)) {
if let Ok(dom_class) = get_dom_class(UncheckedUnwrapObject(value.get(),
/* stopAtWindowProxy = */ 0)) {
if dom_class.interface_chain[object_class.proto_depth as usize] == object_class.proto_id {
// Step 4.
return Ok(true);
@ -355,15 +356,15 @@ unsafe fn has_instance(
let global = GetGlobalForObjectCrossCompartment(interface_object.get());
assert!(!global.is_null());
let proto_or_iface_array = get_proto_or_iface_array(global);
let prototype = RootedObject::new(cx, (*proto_or_iface_array)[object_class.proto_id as usize]);
assert!(!prototype.ptr.is_null());
rooted!(in(cx) let prototype = (*proto_or_iface_array)[object_class.proto_id as usize]);
assert!(!prototype.is_null());
// Step 3 only concern legacy callback interface objects (i.e. NodeFilter).
while JS_GetPrototype(cx, value.handle(), value.handle_mut()) {
if value.ptr.is_null() {
if value.is_null() {
// Step 5.2.
return Ok(false);
} else if value.ptr as *const _ == prototype.ptr {
} else if value.get() as *const _ == prototype.get() {
// Step 5.3.
return Ok(true);
}
@ -433,9 +434,8 @@ pub unsafe fn define_guarded_properties(
unsafe fn define_name(cx: *mut JSContext, obj: HandleObject, name: &[u8]) {
assert!(*name.last().unwrap() == b'\0');
let name = RootedString::new(
cx, JS_AtomizeAndPinString(cx, name.as_ptr() as *const libc::c_char));
assert!(!name.ptr.is_null());
rooted!(in(cx) let name = JS_AtomizeAndPinString(cx, name.as_ptr() as *const libc::c_char));
assert!(!name.is_null());
assert!(JS_DefineProperty2(cx,
obj,
b"name\0".as_ptr() as *const libc::c_char,

View file

@ -13,7 +13,7 @@ use js::glue::InvokeGetOwnPropertyDescriptor;
use js::glue::{GetProxyHandler, SetProxyExtra};
use js::jsapi::GetObjectProto;
use js::jsapi::JS_GetPropertyDescriptorById;
use js::jsapi::{Handle, HandleId, HandleObject, MutableHandle, ObjectOpResult, RootedObject};
use js::jsapi::{Handle, HandleId, HandleObject, MutableHandle, ObjectOpResult};
use js::jsapi::{JSContext, JSObject, JSPROP_GETTER, PropertyDescriptor};
use js::jsapi::{JSErrNum, JS_StrictPropertyStub};
use js::jsapi::{JS_DefinePropertyById, JS_NewObjectWithGivenProto};
@ -36,12 +36,13 @@ pub unsafe extern "C" fn get_property_descriptor(cx: *mut JSContext,
if !InvokeGetOwnPropertyDescriptor(handler, cx, proxy, id, desc) {
return false;
}
if !desc.get().obj.is_null() {
if !desc.obj.is_null() {
return true;
}
let mut proto = RootedObject::new(cx, ptr::null_mut());
rooted!(in(cx) let mut proto = ptr::null_mut());
if !GetObjectProto(cx, proxy, proto.handle_mut()) {
// FIXME(#11868) Should assign to desc.obj, desc.get() is a copy.
desc.get().obj = ptr::null_mut();
return true;
}
@ -65,7 +66,7 @@ pub unsafe extern "C" fn define_property(cx: *mut JSContext,
return true;
}
let expando = RootedObject::new(cx, ensure_expando_object(cx, proxy));
rooted!(in(cx) let expando = ensure_expando_object(cx, proxy));
JS_DefinePropertyById(cx, expando.handle(), id, desc, result)
}
@ -75,8 +76,8 @@ pub unsafe extern "C" fn delete(cx: *mut JSContext,
id: HandleId,
bp: *mut ObjectOpResult)
-> bool {
let expando = RootedObject::new(cx, get_expando_object(proxy));
if expando.ptr.is_null() {
rooted!(in(cx) let expando = get_expando_object(proxy));
if expando.is_null() {
(*bp).code_ = 0 /* OkCode */;
return true;
}

View file

@ -77,8 +77,6 @@ use std::boxed::FnBox;
use std::cell::{Cell, UnsafeCell};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::hash::{BuildHasher, Hash};
use std::intrinsics::return_address;
use std::iter::{FromIterator, IntoIterator};
use std::mem;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
@ -466,8 +464,8 @@ impl RootedTraceableSet {
/// Roots any JSTraceable thing
///
/// If you have a valid Reflectable, use Root.
/// If you have GC things like *mut JSObject or JSVal, use jsapi::Rooted.
/// If you have an arbitrary number of Reflectables to root, use RootedVec<JS<T>>
/// If you have GC things like *mut JSObject or JSVal, use rooted!.
/// If you have an arbitrary number of Reflectables to root, use rooted_vec!.
/// If you know what you're doing, use this.
#[derive(JSTraceable)]
pub struct RootedTraceable<'a, T: 'a + JSTraceable> {
@ -494,73 +492,73 @@ impl<'a, T: JSTraceable> Drop for RootedTraceable<'a, T> {
}
}
/// A vector of items that are rooted for the lifetime of this struct.
/// A vector of items to be rooted with `RootedVec`.
/// Guaranteed to be empty when not rooted.
/// Usage: `rooted_vec!(let mut v);` or if you have an
/// iterator of `Root`s, `rooted_vec!(let v <- iterator);`.
#[allow(unrooted_must_root)]
#[no_move]
#[derive(JSTraceable)]
#[allow_unrooted_interior]
pub struct RootedVec<T: JSTraceable> {
pub struct RootableVec<T: JSTraceable> {
v: Vec<T>,
}
impl<T: JSTraceable> RootedVec<T> {
/// Create a vector of items of type T that is rooted for
/// the lifetime of this struct
pub fn new() -> RootedVec<T> {
let addr = unsafe { return_address() as *const libc::c_void };
unsafe { RootedVec::new_with_destination_address(addr) }
}
/// Create a vector of items of type T. This constructor is specific
/// for RootTraceableSet.
pub unsafe fn new_with_destination_address(addr: *const libc::c_void) -> RootedVec<T> {
RootedTraceableSet::add::<RootedVec<T>>(&*(addr as *const _));
RootedVec::<T> {
impl<T: JSTraceable> RootableVec<T> {
/// Create a vector of items of type T that can be rooted later.
pub fn new_unrooted() -> RootableVec<T> {
RootableVec {
v: vec![],
}
}
}
}
impl<T: JSTraceable + Reflectable> RootedVec<JS<T>> {
/// Obtain a safe slice of references that can't outlive that RootedVec.
pub fn r(&self) -> &[&T] {
unsafe { mem::transmute(&self.v[..]) }
}
/// A vector of items that are rooted for the lifetime 'a.
#[allow_unrooted_interior]
pub struct RootedVec<'a, T: 'a + JSTraceable> {
root: &'a mut RootableVec<T>,
}
impl<T: JSTraceable> Drop for RootedVec<T> {
fn drop(&mut self) {
impl<'a, T: JSTraceable + Reflectable> RootedVec<'a, JS<T>> {
/// Create a vector of items of type T that is rooted for
/// the lifetime of this struct
pub fn new<I: Iterator<Item = Root<T>>>(root: &'a mut RootableVec<JS<T>>, iter: I)
-> RootedVec<'a, JS<T>> {
unsafe {
RootedTraceableSet::remove(self);
RootedTraceableSet::add(root);
}
root.v.extend(iter.map(|item| JS::from_ref(&*item)));
RootedVec {
root: root,
}
}
}
impl<T: JSTraceable> Deref for RootedVec<T> {
impl<'a, T: JSTraceable + Reflectable> RootedVec<'a, JS<T>> {
/// Obtain a safe slice of references that can't outlive that RootedVec.
pub fn r(&self) -> &[&T] {
unsafe { mem::transmute(&self[..]) }
}
}
impl<'a, T: JSTraceable> Drop for RootedVec<'a, T> {
fn drop(&mut self) {
self.clear();
unsafe {
RootedTraceableSet::remove(self.root);
}
}
}
impl<'a, T: JSTraceable> Deref for RootedVec<'a, T> {
type Target = Vec<T>;
fn deref(&self) -> &Vec<T> {
&self.v
&self.root.v
}
}
impl<T: JSTraceable> DerefMut for RootedVec<T> {
impl<'a, T: JSTraceable> DerefMut for RootedVec<'a, T> {
fn deref_mut(&mut self) -> &mut Vec<T> {
&mut self.v
}
}
impl<A: JSTraceable + Reflectable> FromIterator<Root<A>> for RootedVec<JS<A>> {
#[allow(moved_no_move)]
fn from_iter<T>(iterable: T) -> RootedVec<JS<A>>
where T: IntoIterator<Item = Root<A>>
{
let mut vec = unsafe {
RootedVec::new_with_destination_address(return_address() as *const libc::c_void)
};
vec.extend(iterable.into_iter().map(|item| JS::from_ref(&*item)));
vec
&mut self.root.v
}
}

View file

@ -29,8 +29,8 @@ use js::jsapi::{JS_ForwardGetPropertyTo, JS_GetClass, JS_GetLatin1StringCharsAnd
use js::jsapi::{JS_GetProperty, JS_GetPrototype, JS_GetReservedSlot, JS_HasProperty};
use js::jsapi::{JS_HasPropertyById, JS_IsExceptionPending, JS_IsGlobalObject, JS_NewGlobalObject};
use js::jsapi::{JS_ResolveStandardClass, JS_SetProperty, ToWindowProxyIfWindow};
use js::jsapi::{JS_SetReservedSlot, JS_StringHasLatin1Chars, MutableHandleValue, ObjectOpResult};
use js::jsapi::{OnNewGlobalHookOption, RootedObject, RootedValue};
use js::jsapi::{JS_SetReservedSlot, JS_StringHasLatin1Chars, MutableHandleValue};
use js::jsapi::{ObjectOpResult, OnNewGlobalHookOption};
use js::jsval::{JSVal, ObjectValue, PrivateValue, UndefinedValue};
use js::rust::{GCMethods, ToString};
use libc;
@ -135,8 +135,8 @@ pub fn get_property_on_prototype(cx: *mut JSContext,
-> bool {
unsafe {
// let proto = GetObjectProto(proxy);
let mut proto = RootedObject::new(cx, ptr::null_mut());
if !JS_GetPrototype(cx, proxy, proto.handle_mut()) || proto.ptr.is_null() {
rooted!(in(cx) let mut proto = ptr::null_mut());
if !JS_GetPrototype(cx, proxy, proto.handle_mut()) || proto.is_null() {
*found = false;
return true;
}
@ -150,7 +150,7 @@ pub fn get_property_on_prototype(cx: *mut JSContext,
return true;
}
let receiver = RootedValue::new(cx, ObjectValue(&**proxy.ptr));
rooted!(in(cx) let receiver = ObjectValue(&*proxy.get()));
JS_ForwardGetPropertyTo(cx, proto.handle(), id, receiver.handle(), vp)
}
}
@ -305,29 +305,28 @@ pub fn create_dom_global(cx: *mut JSContext,
options.creationOptions_.traceGlobal_ = trace;
options.creationOptions_.sharedMemoryAndAtomics_ = true;
let obj =
RootedObject::new(cx,
JS_NewGlobalObject(cx,
class,
ptr::null_mut(),
OnNewGlobalHookOption::DontFireOnNewGlobalHook,
&options));
if obj.ptr.is_null() {
rooted!(in(cx) let obj =
JS_NewGlobalObject(cx,
class,
ptr::null_mut(),
OnNewGlobalHookOption::DontFireOnNewGlobalHook,
&options));
if obj.is_null() {
return ptr::null_mut();
}
// Initialize the reserved slots before doing amything that can GC, to
// avoid getting trace hooks called on a partially initialized object.
JS_SetReservedSlot(obj.ptr, DOM_OBJECT_SLOT, PrivateValue(private));
JS_SetReservedSlot(obj.get(), DOM_OBJECT_SLOT, PrivateValue(private));
let proto_array: Box<ProtoOrIfaceArray> =
box [0 as *mut JSObject; PROTO_OR_IFACE_LENGTH];
JS_SetReservedSlot(obj.ptr,
JS_SetReservedSlot(obj.get(),
DOM_PROTOTYPE_SLOT,
PrivateValue(Box::into_raw(proto_array) as *const libc::c_void));
let _ac = JSAutoCompartment::new(cx, obj.ptr);
let _ac = JSAutoCompartment::new(cx, obj.get());
JS_FireOnNewGlobalObject(cx, obj.handle());
obj.ptr
obj.get()
}
}
@ -459,14 +458,14 @@ unsafe fn generic_call(cx: *mut JSContext,
} else {
GetGlobalForObjectCrossCompartment(JS_CALLEE(cx, vp).to_object_or_null())
};
let obj = RootedObject::new(cx, obj);
rooted!(in(cx) let obj = obj);
let info = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx, vp));
let proto_id = (*info).protoID;
let depth = (*info).depth;
let proto_check = |class: &'static DOMClass| {
class.interface_chain[depth as usize] as u16 == proto_id
};
let this = match private_from_proto_check(obj.ptr, proto_check) {
let this = match private_from_proto_check(obj.get(), proto_check) {
Ok(val) => val,
Err(()) => {
if is_lenient {