Modify *::get_cx methods to return a safe JSContext instead of a raw one

This commit is contained in:
marmeladema 2019-07-22 22:14:11 +01:00
parent 2c5d0a6ebc
commit 88cacfb009
43 changed files with 306 additions and 321 deletions

View file

@ -13,8 +13,8 @@ use crate::dom::blob::{Blob, BlobImpl};
use crate::dom::formdata::FormData; use crate::dom::formdata::FormData;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::promise::Promise; use crate::dom::promise::Promise;
use crate::script_runtime::JSContext;
use js::jsapi::Heap; use js::jsapi::Heap;
use js::jsapi::JSContext;
use js::jsapi::JSObject; use js::jsapi::JSObject;
use js::jsapi::JS_ClearPendingException; use js::jsapi::JS_ClearPendingException;
use js::jsapi::Value as JSValue; use js::jsapi::Value as JSValue;
@ -122,7 +122,7 @@ fn run_package_data_algorithm<T: BodyOperations + DomObject>(
BodyType::Json => run_json_data_algorithm(cx, bytes), BodyType::Json => run_json_data_algorithm(cx, bytes),
BodyType::Blob => run_blob_data_algorithm(&global, bytes, mime), BodyType::Blob => run_blob_data_algorithm(&global, bytes, mime),
BodyType::FormData => run_form_data_algorithm(&global, bytes, mime), BodyType::FormData => run_form_data_algorithm(&global, bytes, mime),
BodyType::ArrayBuffer => unsafe { run_array_buffer_data_algorithm(cx, bytes) }, BodyType::ArrayBuffer => run_array_buffer_data_algorithm(cx, bytes),
} }
} }
@ -133,20 +133,20 @@ fn run_text_data_algorithm(bytes: Vec<u8>) -> Fallible<FetchedData> {
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
fn run_json_data_algorithm(cx: *mut JSContext, bytes: Vec<u8>) -> Fallible<FetchedData> { fn run_json_data_algorithm(cx: JSContext, bytes: Vec<u8>) -> Fallible<FetchedData> {
let json_text = String::from_utf8_lossy(&bytes); let json_text = String::from_utf8_lossy(&bytes);
let json_text: Vec<u16> = json_text.encode_utf16().collect(); let json_text: Vec<u16> = json_text.encode_utf16().collect();
rooted!(in(cx) let mut rval = UndefinedValue()); rooted!(in(*cx) let mut rval = UndefinedValue());
unsafe { unsafe {
if !JS_ParseJSON( if !JS_ParseJSON(
cx, *cx,
json_text.as_ptr(), json_text.as_ptr(),
json_text.len() as u32, json_text.len() as u32,
rval.handle_mut(), rval.handle_mut(),
) { ) {
rooted!(in(cx) let mut exception = UndefinedValue()); rooted!(in(*cx) let mut exception = UndefinedValue());
assert!(JS_GetPendingException(cx, exception.handle_mut())); assert!(JS_GetPendingException(*cx, exception.handle_mut()));
JS_ClearPendingException(cx); JS_ClearPendingException(*cx);
return Ok(FetchedData::JSException(RootedTraceableBox::from_box( return Ok(FetchedData::JSException(RootedTraceableBox::from_box(
Heap::boxed(exception.get()), Heap::boxed(exception.get()),
))); )));
@ -200,13 +200,15 @@ fn run_form_data_algorithm(
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn run_array_buffer_data_algorithm( fn run_array_buffer_data_algorithm(cx: JSContext, bytes: Vec<u8>) -> Fallible<FetchedData> {
cx: *mut JSContext, rooted!(in(*cx) let mut array_buffer_ptr = ptr::null_mut::<JSObject>());
bytes: Vec<u8>, let arraybuffer = unsafe {
) -> Fallible<FetchedData> { ArrayBuffer::create(
rooted!(in(cx) let mut array_buffer_ptr = ptr::null_mut::<JSObject>()); *cx,
let arraybuffer = CreateWith::Slice(&bytes),
ArrayBuffer::create(cx, CreateWith::Slice(&bytes), array_buffer_ptr.handle_mut()); array_buffer_ptr.handle_mut(),
)
};
if arraybuffer.is_err() { if arraybuffer.is_err() {
return Err(Error::JSFailed); return Err(Error::JSFailed);
} }

View file

@ -12,7 +12,7 @@ impl AlreadyInCompartment {
#![allow(unsafe_code)] #![allow(unsafe_code)]
pub fn assert(global: &GlobalScope) -> AlreadyInCompartment { pub fn assert(global: &GlobalScope) -> AlreadyInCompartment {
unsafe { unsafe {
assert!(!GetCurrentRealmOrNull(global.get_cx()).is_null()); assert!(!GetCurrentRealmOrNull(*global.get_cx()).is_null());
} }
AlreadyInCompartment(()) AlreadyInCompartment(())
} }
@ -43,7 +43,7 @@ impl<'a> InCompartment<'a> {
pub fn enter_realm(object: &impl DomObject) -> JSAutoRealm { pub fn enter_realm(object: &impl DomObject) -> JSAutoRealm {
JSAutoRealm::new( JSAutoRealm::new(
object.global().get_cx(), *object.global().get_cx(),
object.reflector().get_jsobject().get(), object.reflector().get_jsobject().get(),
) )
} }

View file

@ -36,7 +36,7 @@ pub fn handle_evaluate_js(global: &GlobalScope, eval: String, reply: IpcSender<E
let result = unsafe { let result = unsafe {
let cx = global.get_cx(); let cx = global.get_cx();
let _ac = enter_realm(global); let _ac = enter_realm(global);
rooted!(in(cx) let mut rval = UndefinedValue()); rooted!(in(*cx) let mut rval = UndefinedValue());
global.evaluate_js_on_global_with_result(&eval, rval.handle_mut()); global.evaluate_js_on_global_with_result(&eval, rval.handle_mut());
if rval.is_undefined() { if rval.is_undefined() {
@ -45,20 +45,20 @@ pub fn handle_evaluate_js(global: &GlobalScope, eval: String, reply: IpcSender<E
EvaluateJSReply::BooleanValue(rval.to_boolean()) EvaluateJSReply::BooleanValue(rval.to_boolean())
} else if rval.is_double() || rval.is_int32() { } else if rval.is_double() || rval.is_int32() {
EvaluateJSReply::NumberValue( EvaluateJSReply::NumberValue(
match FromJSValConvertible::from_jsval(cx, rval.handle(), ()) { match FromJSValConvertible::from_jsval(*cx, rval.handle(), ()) {
Ok(ConversionResult::Success(v)) => v, Ok(ConversionResult::Success(v)) => v,
_ => unreachable!(), _ => unreachable!(),
}, },
) )
} else if rval.is_string() { } else if rval.is_string() {
EvaluateJSReply::StringValue(String::from(jsstring_to_str(cx, rval.to_string()))) EvaluateJSReply::StringValue(String::from(jsstring_to_str(*cx, rval.to_string())))
} else if rval.is_null() { } else if rval.is_null() {
EvaluateJSReply::NullValue EvaluateJSReply::NullValue
} else { } else {
assert!(rval.is_object()); assert!(rval.is_object());
rooted!(in(cx) let obj = rval.to_object()); rooted!(in(*cx) let obj = rval.to_object());
let class_name = CStr::from_ptr(ObjectClassName(cx, obj.handle())); let class_name = CStr::from_ptr(ObjectClassName(*cx, obj.handle()));
let class_name = str::from_utf8(class_name.to_bytes()).unwrap(); let class_name = str::from_utf8(class_name.to_bytes()).unwrap();
EvaluateJSReply::ActorValue { EvaluateJSReply::ActorValue {

View file

@ -173,15 +173,15 @@ impl AudioBuffer {
// Step 2. // Step 2.
let channel_data = unsafe { let channel_data = unsafe {
typedarray!(in(cx) let array: Float32Array = channel.get()); typedarray!(in(*cx) let array: Float32Array = channel.get());
if let Ok(array) = array { if let Ok(array) = array {
let data = array.to_vec(); let data = array.to_vec();
let mut is_shared = false; let mut is_shared = false;
rooted!(in (cx) let view_buffer = rooted!(in (*cx) let view_buffer =
JS_GetArrayBufferViewBuffer(cx, channel.handle(), &mut is_shared)); JS_GetArrayBufferViewBuffer(*cx, channel.handle(), &mut is_shared));
// This buffer is always created unshared // This buffer is always created unshared
debug_assert!(!is_shared); debug_assert!(!is_shared);
let _ = DetachArrayBuffer(cx, view_buffer.handle()); let _ = DetachArrayBuffer(*cx, view_buffer.handle());
data data
} else { } else {
return None; return None;
@ -272,7 +272,7 @@ impl AudioBufferMethods for AudioBuffer {
// We either copy form js_channels or shared_channels. // We either copy form js_channels or shared_channels.
let js_channel = self.js_channels.borrow()[channel_number].get(); let js_channel = self.js_channels.borrow()[channel_number].get();
if !js_channel.is_null() { if !js_channel.is_null() {
typedarray!(in(cx) let array: Float32Array = js_channel); typedarray!(in(*cx) let array: Float32Array = js_channel);
if let Ok(array) = array { if let Ok(array) = array {
let data = unsafe { array.as_slice() }; let data = unsafe { array.as_slice() };
dest.extend_from_slice(&data[offset..offset + bytes_to_copy]); dest.extend_from_slice(&data[offset..offset + bytes_to_copy]);
@ -307,7 +307,7 @@ impl AudioBufferMethods for AudioBuffer {
} }
let cx = self.global().get_cx(); let cx = self.global().get_cx();
if unsafe { !self.restore_js_channel_data(cx) } { if unsafe { !self.restore_js_channel_data(*cx) } {
return Err(Error::JSFailed); return Err(Error::JSFailed);
} }
@ -317,7 +317,7 @@ impl AudioBufferMethods for AudioBuffer {
return Err(Error::IndexSize); return Err(Error::IndexSize);
} }
typedarray!(in(cx) let js_channel: Float32Array = js_channel); typedarray!(in(*cx) let js_channel: Float32Array = js_channel);
if let Ok(mut js_channel) = js_channel { if let Ok(mut js_channel) = js_channel {
let bytes_to_copy = min(self.length - start_in_channel, source.len() as u32) as usize; let bytes_to_copy = min(self.length - start_in_channel, source.len() as u32) as usize;
let js_channel_data = unsafe { js_channel.as_mut_slice() }; let js_channel_data = unsafe { js_channel.as_mut_slice() };

View file

@ -255,8 +255,8 @@ impl CallSetup {
let ais = callback.incumbent().map(AutoIncumbentScript::new); let ais = callback.incumbent().map(AutoIncumbentScript::new);
CallSetup { CallSetup {
exception_global: global, exception_global: global,
cx: cx, cx: *cx,
old_realm: unsafe { EnterRealm(cx, callback.callback()) }, old_realm: unsafe { EnterRealm(*cx, callback.callback()) },
handling: handling, handling: handling,
entry_script: Some(aes), entry_script: Some(aes),
incumbent_script: ais, incumbent_script: ais,

View file

@ -100,7 +100,7 @@ where
// Step 2 is checked in the generated caller code // Step 2 is checked in the generated caller code
// Step 3 // Step 3
rooted!(in(window.get_cx()) let new_target = call_args.new_target().to_object()); rooted!(in(*window.get_cx()) let new_target = call_args.new_target().to_object());
let definition = match registry.lookup_definition_by_constructor(new_target.handle()) { let definition = match registry.lookup_definition_by_constructor(new_target.handle()) {
Some(definition) => definition, Some(definition) => definition,
None => { None => {
@ -110,15 +110,15 @@ where
}, },
}; };
rooted!(in(window.get_cx()) let callee = UnwrapObjectStatic(call_args.callee())); rooted!(in(*window.get_cx()) let callee = UnwrapObjectStatic(call_args.callee()));
if callee.is_null() { if callee.is_null() {
return Err(Error::Security); return Err(Error::Security);
} }
{ {
let _ac = JSAutoRealm::new(window.get_cx(), callee.get()); let _ac = JSAutoRealm::new(*window.get_cx(), callee.get());
rooted!(in(window.get_cx()) let mut constructor = ptr::null_mut::<JSObject>()); rooted!(in(*window.get_cx()) let mut constructor = ptr::null_mut::<JSObject>());
rooted!(in(window.get_cx()) let global_object = CurrentGlobalOrNull(window.get_cx())); rooted!(in(*window.get_cx()) let global_object = CurrentGlobalOrNull(*window.get_cx()));
if definition.is_autonomous() { if definition.is_autonomous() {
// Step 4 // Step 4
@ -126,7 +126,7 @@ where
// Retrieve the constructor object for HTMLElement // Retrieve the constructor object for HTMLElement
HTMLElementBinding::GetConstructorObject( HTMLElementBinding::GetConstructorObject(
SafeJSContext::from_ptr(window.get_cx()), window.get_cx(),
global_object.handle(), global_object.handle(),
constructor.handle_mut(), constructor.handle_mut(),
); );
@ -134,7 +134,7 @@ where
// Step 5 // Step 5
get_constructor_object_from_local_name( get_constructor_object_from_local_name(
definition.local_name.clone(), definition.local_name.clone(),
window.get_cx(), *window.get_cx(),
global_object.handle(), global_object.handle(),
constructor.handle_mut(), constructor.handle_mut(),
); );

View file

@ -7,7 +7,7 @@
use crate::dom::bindings::conversions::DerivedFrom; use crate::dom::bindings::conversions::DerivedFrom;
use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::root::DomRoot;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::JSContext as SafeJSContext; use crate::script_runtime::JSContext;
use js::jsapi::{Heap, JSObject}; use js::jsapi::{Heap, JSObject};
use js::rust::HandleObject; use js::rust::HandleObject;
use std::default::Default; use std::default::Default;
@ -17,20 +17,14 @@ use std::default::Default;
pub fn reflect_dom_object<T, U>( pub fn reflect_dom_object<T, U>(
obj: Box<T>, obj: Box<T>,
global: &U, global: &U,
wrap_fn: unsafe fn(SafeJSContext, &GlobalScope, Box<T>) -> DomRoot<T>, wrap_fn: unsafe fn(JSContext, &GlobalScope, Box<T>) -> DomRoot<T>,
) -> DomRoot<T> ) -> DomRoot<T>
where where
T: DomObject, T: DomObject,
U: DerivedFrom<GlobalScope>, U: DerivedFrom<GlobalScope>,
{ {
let global_scope = global.upcast(); let global_scope = global.upcast();
unsafe { unsafe { wrap_fn(global_scope.get_cx(), global_scope, obj) }
wrap_fn(
SafeJSContext::from_ptr(global_scope.get_cx()),
global_scope,
obj,
)
}
} }
/// A struct to store a reference to the reflector of a DOM object. /// A struct to store a reference to the reflector of a DOM object.

View file

@ -321,7 +321,7 @@ impl StructuredCloneData {
WriteBytesToJSStructuredCloneData(data as *const u8, nbytes, scdata); WriteBytesToJSStructuredCloneData(data as *const u8, nbytes, scdata);
assert!(JS_ReadStructuredClone( assert!(JS_ReadStructuredClone(
cx, *cx,
scdata, scdata,
JS_STRUCTURED_CLONE_VERSION, JS_STRUCTURED_CLONE_VERSION,
StructuredCloneScope::DifferentProcess, StructuredCloneScope::DifferentProcess,

View file

@ -157,9 +157,9 @@ fn create_html_element(
// Step 6.1.1 // Step 6.1.1
unsafe { unsafe {
let _ac = let _ac =
JSAutoRealm::new(cx, global.reflector().get_jsobject().get()); JSAutoRealm::new(*cx, global.reflector().get_jsobject().get());
throw_dom_exception(cx, &global, error); throw_dom_exception(*cx, &global, error);
report_pending_exception(cx, true); report_pending_exception(*cx, true);
} }
// Step 6.1.2 // Step 6.1.2

View file

@ -145,7 +145,7 @@ impl CustomElementRegistry {
unsafe { unsafe {
// Step 10.1 // Step 10.1
if !JS_GetProperty( if !JS_GetProperty(
global_scope.get_cx(), *global_scope.get_cx(),
constructor, constructor,
b"prototype\0".as_ptr() as *const _, b"prototype\0".as_ptr() as *const _,
prototype, prototype,
@ -171,10 +171,14 @@ impl CustomElementRegistry {
// Step 4 // Step 4
Ok(LifecycleCallbacks { Ok(LifecycleCallbacks {
connected_callback: get_callback(cx, prototype, b"connectedCallback\0")?, connected_callback: get_callback(*cx, prototype, b"connectedCallback\0")?,
disconnected_callback: get_callback(cx, prototype, b"disconnectedCallback\0")?, disconnected_callback: get_callback(*cx, prototype, b"disconnectedCallback\0")?,
adopted_callback: get_callback(cx, prototype, b"adoptedCallback\0")?, adopted_callback: get_callback(*cx, prototype, b"adoptedCallback\0")?,
attribute_changed_callback: get_callback(cx, prototype, b"attributeChangedCallback\0")?, attribute_changed_callback: get_callback(
*cx,
prototype,
b"attributeChangedCallback\0",
)?,
}) })
} }
@ -183,10 +187,10 @@ impl CustomElementRegistry {
#[allow(unsafe_code)] #[allow(unsafe_code)]
fn get_observed_attributes(&self, constructor: HandleObject) -> Fallible<Vec<DOMString>> { fn get_observed_attributes(&self, constructor: HandleObject) -> Fallible<Vec<DOMString>> {
let cx = self.window.get_cx(); let cx = self.window.get_cx();
rooted!(in(cx) let mut observed_attributes = UndefinedValue()); rooted!(in(*cx) let mut observed_attributes = UndefinedValue());
if unsafe { if unsafe {
!JS_GetProperty( !JS_GetProperty(
cx, *cx,
constructor, constructor,
b"observedAttributes\0".as_ptr() as *const _, b"observedAttributes\0".as_ptr() as *const _,
observed_attributes.handle_mut(), observed_attributes.handle_mut(),
@ -201,7 +205,7 @@ impl CustomElementRegistry {
let conversion = unsafe { let conversion = unsafe {
FromJSValConvertible::from_jsval( FromJSValConvertible::from_jsval(
cx, *cx,
observed_attributes.handle(), observed_attributes.handle(),
StringificationBehavior::Default, StringificationBehavior::Default,
) )
@ -258,12 +262,12 @@ impl CustomElementRegistryMethods for CustomElementRegistry {
options: &ElementDefinitionOptions, options: &ElementDefinitionOptions,
) -> ErrorResult { ) -> ErrorResult {
let cx = self.window.get_cx(); let cx = self.window.get_cx();
rooted!(in(cx) let constructor = constructor_.callback()); rooted!(in(*cx) let constructor = constructor_.callback());
let name = LocalName::from(&*name); let name = LocalName::from(&*name);
// Step 1 // Step 1
// We must unwrap the constructor as all wrappers are constructable if they are callable. // We must unwrap the constructor as all wrappers are constructable if they are callable.
rooted!(in(cx) let unwrapped_constructor = unsafe { UnwrapObjectStatic(constructor.get()) }); rooted!(in(*cx) let unwrapped_constructor = unsafe { UnwrapObjectStatic(constructor.get()) });
if unwrapped_constructor.is_null() { if unwrapped_constructor.is_null() {
// We do not have permission to access the unwrapped constructor. // We do not have permission to access the unwrapped constructor.
@ -326,9 +330,9 @@ impl CustomElementRegistryMethods for CustomElementRegistry {
self.element_definition_is_running.set(true); self.element_definition_is_running.set(true);
// Steps 10.1 - 10.2 // Steps 10.1 - 10.2
rooted!(in(cx) let mut prototype = UndefinedValue()); rooted!(in(*cx) let mut prototype = UndefinedValue());
{ {
let _ac = JSAutoRealm::new(cx, constructor.get()); let _ac = JSAutoRealm::new(*cx, constructor.get());
if let Err(error) = self.check_prototype(constructor.handle(), prototype.handle_mut()) { if let Err(error) = self.check_prototype(constructor.handle(), prototype.handle_mut()) {
self.element_definition_is_running.set(false); self.element_definition_is_running.set(false);
return Err(error); return Err(error);
@ -336,9 +340,9 @@ impl CustomElementRegistryMethods for CustomElementRegistry {
}; };
// Steps 10.3 - 10.4 // Steps 10.3 - 10.4
rooted!(in(cx) let proto_object = prototype.to_object()); rooted!(in(*cx) let proto_object = prototype.to_object());
let callbacks = { let callbacks = {
let _ac = JSAutoRealm::new(cx, proto_object.get()); let _ac = JSAutoRealm::new(*cx, proto_object.get());
match unsafe { self.get_callbacks(proto_object.handle()) } { match unsafe { self.get_callbacks(proto_object.handle()) } {
Ok(callbacks) => callbacks, Ok(callbacks) => callbacks,
Err(error) => { Err(error) => {
@ -350,7 +354,7 @@ impl CustomElementRegistryMethods for CustomElementRegistry {
// Step 10.5 - 10.6 // Step 10.5 - 10.6
let observed_attributes = if callbacks.attribute_changed_callback.is_some() { let observed_attributes = if callbacks.attribute_changed_callback.is_some() {
let _ac = JSAutoRealm::new(cx, constructor.get()); let _ac = JSAutoRealm::new(*cx, constructor.get());
match self.get_observed_attributes(constructor.handle()) { match self.get_observed_attributes(constructor.handle()) {
Ok(attributes) => attributes, Ok(attributes) => attributes,
Err(error) => { Err(error) => {
@ -523,20 +527,20 @@ impl CustomElementDefinition {
let window = document.window(); let window = document.window();
let cx = window.get_cx(); let cx = window.get_cx();
// Step 2 // Step 2
rooted!(in(cx) let constructor = ObjectValue(self.constructor.callback())); rooted!(in(*cx) let constructor = ObjectValue(self.constructor.callback()));
rooted!(in(cx) let mut element = ptr::null_mut::<JSObject>()); rooted!(in(*cx) let mut element = ptr::null_mut::<JSObject>());
{ {
// Go into the constructor's compartment // Go into the constructor's compartment
let _ac = JSAutoRealm::new(cx, self.constructor.callback()); let _ac = JSAutoRealm::new(*cx, self.constructor.callback());
let args = HandleValueArray::new(); let args = HandleValueArray::new();
if unsafe { !Construct1(cx, constructor.handle(), &args, element.handle_mut()) } { if unsafe { !Construct1(*cx, constructor.handle(), &args, element.handle_mut()) } {
return Err(Error::JSFailed); return Err(Error::JSFailed);
} }
} }
rooted!(in(cx) let element_val = ObjectValue(element.get())); rooted!(in(*cx) let element_val = ObjectValue(element.get()));
let element: DomRoot<Element> = let element: DomRoot<Element> =
match unsafe { DomRoot::from_jsval(cx, element_val.handle(), ()) } { match unsafe { DomRoot::from_jsval(*cx, element_val.handle(), ()) } {
Ok(ConversionResult::Success(element)) => element, Ok(ConversionResult::Success(element)) => element,
Ok(ConversionResult::Failure(..)) => { Ok(ConversionResult::Failure(..)) => {
return Err(Error::Type( return Err(Error::Type(
@ -627,8 +631,8 @@ pub fn upgrade_element(definition: Rc<CustomElementDefinition>, element: &Elemen
let global = GlobalScope::current().expect("No current global"); let global = GlobalScope::current().expect("No current global");
let cx = global.get_cx(); let cx = global.get_cx();
unsafe { unsafe {
throw_dom_exception(cx, &global, error); throw_dom_exception(*cx, &global, error);
report_pending_exception(cx, true); report_pending_exception(*cx, true);
} }
return; return;
} }
@ -649,20 +653,20 @@ fn run_upgrade_constructor(
) -> ErrorResult { ) -> ErrorResult {
let window = window_from_node(element); let window = window_from_node(element);
let cx = window.get_cx(); let cx = window.get_cx();
rooted!(in(cx) let constructor_val = ObjectValue(constructor.callback())); rooted!(in(*cx) let constructor_val = ObjectValue(constructor.callback()));
rooted!(in(cx) let mut element_val = UndefinedValue()); rooted!(in(*cx) let mut element_val = UndefinedValue());
unsafe { unsafe {
element.to_jsval(cx, element_val.handle_mut()); element.to_jsval(*cx, element_val.handle_mut());
} }
rooted!(in(cx) let mut construct_result = ptr::null_mut::<JSObject>()); rooted!(in(*cx) let mut construct_result = ptr::null_mut::<JSObject>());
{ {
// Go into the constructor's compartment // Go into the constructor's compartment
let _ac = JSAutoRealm::new(cx, constructor.callback()); let _ac = JSAutoRealm::new(*cx, constructor.callback());
let args = HandleValueArray::new(); let args = HandleValueArray::new();
// Step 7.1 // Step 7.1
if unsafe { if unsafe {
!Construct1( !Construct1(
cx, *cx,
constructor_val.handle(), constructor_val.handle(),
&args, &args,
construct_result.handle_mut(), construct_result.handle_mut(),
@ -672,10 +676,10 @@ fn run_upgrade_constructor(
} }
// Step 7.2 // Step 7.2
let mut same = false; let mut same = false;
rooted!(in(cx) let construct_result_val = ObjectValue(construct_result.get())); rooted!(in(*cx) let construct_result_val = ObjectValue(construct_result.get()));
if unsafe { if unsafe {
!SameValue( !SameValue(
cx, *cx,
construct_result_val.handle(), construct_result_val.handle(),
element_val.handle(), element_val.handle(),
&mut same, &mut same,
@ -863,30 +867,30 @@ impl CustomElementReactionStack {
let cx = element.global().get_cx(); let cx = element.global().get_cx();
let local_name = DOMString::from(&*local_name); let local_name = DOMString::from(&*local_name);
rooted!(in(cx) let mut name_value = UndefinedValue()); rooted!(in(*cx) let mut name_value = UndefinedValue());
unsafe { unsafe {
local_name.to_jsval(cx, name_value.handle_mut()); local_name.to_jsval(*cx, name_value.handle_mut());
} }
rooted!(in(cx) let mut old_value = NullValue()); rooted!(in(*cx) let mut old_value = NullValue());
if let Some(old_val) = old_val { if let Some(old_val) = old_val {
unsafe { unsafe {
old_val.to_jsval(cx, old_value.handle_mut()); old_val.to_jsval(*cx, old_value.handle_mut());
} }
} }
rooted!(in(cx) let mut value = NullValue()); rooted!(in(*cx) let mut value = NullValue());
if let Some(val) = val { if let Some(val) = val {
unsafe { unsafe {
val.to_jsval(cx, value.handle_mut()); val.to_jsval(*cx, value.handle_mut());
} }
} }
rooted!(in(cx) let mut namespace_value = NullValue()); rooted!(in(*cx) let mut namespace_value = NullValue());
if namespace != ns!() { if namespace != ns!() {
let namespace = DOMString::from(&*namespace); let namespace = DOMString::from(&*namespace);
unsafe { unsafe {
namespace.to_jsval(cx, namespace_value.handle_mut()); namespace.to_jsval(*cx, namespace_value.handle_mut());
} }
} }

View file

@ -405,7 +405,7 @@ impl DedicatedWorkerGlobalScope {
unsafe { unsafe {
// Handle interrupt requests // Handle interrupt requests
JS_AddInterruptCallback(scope.get_cx(), Some(interrupt_callback)); JS_AddInterruptCallback(*scope.get_cx(), Some(interrupt_callback));
} }
if scope.is_closing() { if scope.is_closing() {
@ -466,7 +466,7 @@ impl DedicatedWorkerGlobalScope {
let scope = self.upcast::<WorkerGlobalScope>(); let scope = self.upcast::<WorkerGlobalScope>();
let target = self.upcast(); let target = self.upcast();
let _ac = enter_realm(self); let _ac = enter_realm(self);
rooted!(in(scope.get_cx()) let mut message = UndefinedValue()); rooted!(in(*scope.get_cx()) let mut message = UndefinedValue());
data.read(scope.upcast(), message.handle_mut()); data.read(scope.upcast(), message.handle_mut());
MessageEvent::dispatch_jsval(target, scope.upcast(), message.handle(), None, None); MessageEvent::dispatch_jsval(target, scope.upcast(), message.handle(), None, None);
}, },

View file

@ -68,7 +68,7 @@ impl DissimilarOriginWindow {
window_proxy: Dom::from_ref(window_proxy), window_proxy: Dom::from_ref(window_proxy),
location: Default::default(), location: Default::default(),
}); });
unsafe { DissimilarOriginWindowBinding::Wrap(JSContext::from_ptr(cx), win) } unsafe { DissimilarOriginWindowBinding::Wrap(cx, win) }
} }
pub fn window_proxy(&self) -> DomRoot<WindowProxy> { pub fn window_proxy(&self) -> DomRoot<WindowProxy> {

View file

@ -131,7 +131,7 @@ impl DocumentOrShadowRoot {
.first() .first()
{ {
Some(address) => { Some(address) => {
let js_runtime = unsafe { JS_GetRuntime(self.window.get_cx()) }; let js_runtime = unsafe { JS_GetRuntime(*self.window.get_cx()) };
let node = unsafe { node::from_untrusted_node_address(js_runtime, *address) }; let node = unsafe { node::from_untrusted_node_address(js_runtime, *address) };
let parent_node = node.GetParentNode().unwrap(); let parent_node = node.GetParentNode().unwrap();
let element_ref = node let element_ref = node
@ -167,7 +167,7 @@ impl DocumentOrShadowRoot {
return vec![]; return vec![];
} }
let js_runtime = unsafe { JS_GetRuntime(self.window.get_cx()) }; let js_runtime = unsafe { JS_GetRuntime(*self.window.get_cx()) };
// Step 1 and Step 3 // Step 1 and Step 3
let nodes = self.nodes_from_point(point, NodesFromPointQueryType::All); let nodes = self.nodes_from_point(point, NodesFromPointQueryType::All);

View file

@ -223,10 +223,10 @@ impl EventSourceContext {
// Steps 4-5 // Steps 4-5
let event = { let event = {
let _ac = enter_realm(&*event_source); let _ac = enter_realm(&*event_source);
rooted!(in(event_source.global().get_cx()) let mut data = UndefinedValue()); rooted!(in(*event_source.global().get_cx()) let mut data = UndefinedValue());
unsafe { unsafe {
self.data self.data
.to_jsval(event_source.global().get_cx(), data.handle_mut()) .to_jsval(*event_source.global().get_cx(), data.handle_mut())
}; };
MessageEvent::new( MessageEvent::new(
&*event_source.global(), &*event_source.global(),

View file

@ -33,7 +33,6 @@ use crate::dom::globalscope::GlobalScope;
use crate::dom::node::document_from_node; use crate::dom::node::document_from_node;
use crate::dom::virtualmethods::VirtualMethods; use crate::dom::virtualmethods::VirtualMethods;
use crate::dom::window::Window; use crate::dom::window::Window;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use fnv::FnvHasher; use fnv::FnvHasher;
use js::jsapi::{JSAutoRealm, JSFunction, JS_GetFunctionObject, SourceText}; use js::jsapi::{JSAutoRealm, JSFunction, JS_GetFunctionObject, SourceText};
@ -151,7 +150,6 @@ pub enum CompiledEventListener {
} }
impl CompiledEventListener { impl CompiledEventListener {
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#the-event-handler-processing-algorithm // https://html.spec.whatwg.org/multipage/#the-event-handler-processing-algorithm
pub fn call_or_handle_event<T: DomObject>( pub fn call_or_handle_event<T: DomObject>(
&self, &self,
@ -169,7 +167,7 @@ impl CompiledEventListener {
CommonEventHandler::ErrorEventHandler(ref handler) => { CommonEventHandler::ErrorEventHandler(ref handler) => {
if let Some(event) = event.downcast::<ErrorEvent>() { if let Some(event) = event.downcast::<ErrorEvent>() {
let cx = object.global().get_cx(); let cx = object.global().get_cx();
rooted!(in(cx) let error = unsafe { event.Error(JSContext::from_ptr(cx)) }); rooted!(in(*cx) let error = event.Error(cx));
let return_value = handler.Call_( let return_value = handler.Call_(
object, object,
EventOrString::String(event.Message()), EventOrString::String(event.Message()),
@ -181,7 +179,7 @@ impl CompiledEventListener {
); );
// Step 4 // Step 4
if let Ok(return_value) = return_value { if let Ok(return_value) = return_value {
rooted!(in(cx) let return_value = return_value); rooted!(in(*cx) let return_value = return_value);
if return_value.handle().is_boolean() && if return_value.handle().is_boolean() &&
return_value.handle().to_boolean() == true return_value.handle().to_boolean() == true
{ {
@ -226,7 +224,7 @@ impl CompiledEventListener {
CommonEventHandler::EventHandler(ref handler) => { CommonEventHandler::EventHandler(ref handler) => {
if let Ok(value) = handler.Call_(object, event, exception_handle) { if let Ok(value) = handler.Call_(object, event, exception_handle) {
let cx = object.global().get_cx(); let cx = object.global().get_cx();
rooted!(in(cx) let value = value); rooted!(in(*cx) let value = value);
let value = value.handle(); let value = value.handle();
//Step 4 //Step 4
@ -503,16 +501,16 @@ impl EventTarget {
}; };
let cx = window.get_cx(); let cx = window.get_cx();
let options = CompileOptionsWrapper::new(cx, url_serialized.as_ptr(), handler.line as u32); let options = CompileOptionsWrapper::new(*cx, url_serialized.as_ptr(), handler.line as u32);
// TODO step 1.10.1-3 (document, form owner, element in scope chain) // TODO step 1.10.1-3 (document, form owner, element in scope chain)
let scopechain = AutoObjectVectorWrapper::new(cx); let scopechain = AutoObjectVectorWrapper::new(*cx);
let _ac = enter_realm(&*window); let _ac = enter_realm(&*window);
rooted!(in(cx) let mut handler = ptr::null_mut::<JSFunction>()); rooted!(in(*cx) let mut handler = ptr::null_mut::<JSFunction>());
let rv = unsafe { let rv = unsafe {
CompileFunction( CompileFunction(
cx, *cx,
scopechain.ptr, scopechain.ptr,
options.ptr, options.ptr,
name.as_ptr(), name.as_ptr(),
@ -530,9 +528,9 @@ impl EventTarget {
if !rv || handler.get().is_null() { if !rv || handler.get().is_null() {
// Step 1.8.2 // Step 1.8.2
unsafe { unsafe {
let _ac = JSAutoRealm::new(cx, self.reflector().get_jsobject().get()); let _ac = JSAutoRealm::new(*cx, self.reflector().get_jsobject().get());
// FIXME(#13152): dispatch error event. // FIXME(#13152): dispatch error event.
report_pending_exception(cx, false); report_pending_exception(*cx, false);
} }
// Step 1.8.1 / 1.8.3 // Step 1.8.1 / 1.8.3
return None; return None;
@ -544,16 +542,16 @@ impl EventTarget {
// Step 1.14 // Step 1.14
if is_error { if is_error {
Some(CommonEventHandler::ErrorEventHandler(unsafe { Some(CommonEventHandler::ErrorEventHandler(unsafe {
OnErrorEventHandlerNonNull::new(JSContext::from_ptr(cx), funobj) OnErrorEventHandlerNonNull::new(cx, funobj)
})) }))
} else { } else {
if ty == &atom!("beforeunload") { if ty == &atom!("beforeunload") {
Some(CommonEventHandler::BeforeUnloadEventHandler(unsafe { Some(CommonEventHandler::BeforeUnloadEventHandler(unsafe {
OnBeforeUnloadEventHandlerNonNull::new(JSContext::from_ptr(cx), funobj) OnBeforeUnloadEventHandlerNonNull::new(cx, funobj)
})) }))
} else { } else {
Some(CommonEventHandler::EventHandler(unsafe { Some(CommonEventHandler::EventHandler(unsafe {
EventHandlerNonNull::new(JSContext::from_ptr(cx), funobj) EventHandlerNonNull::new(cx, funobj)
})) }))
} }
} }
@ -568,7 +566,7 @@ impl EventTarget {
let event_listener = listener.map(|listener| { let event_listener = listener.map(|listener| {
InlineEventListener::Compiled(CommonEventHandler::EventHandler(unsafe { InlineEventListener::Compiled(CommonEventHandler::EventHandler(unsafe {
EventHandlerNonNull::new(JSContext::from_ptr(cx), listener.callback()) EventHandlerNonNull::new(cx, listener.callback())
})) }))
}); });
self.set_inline_event_listener(Atom::from(ty), event_listener); self.set_inline_event_listener(Atom::from(ty), event_listener);
@ -583,7 +581,7 @@ impl EventTarget {
let event_listener = listener.map(|listener| { let event_listener = listener.map(|listener| {
InlineEventListener::Compiled(CommonEventHandler::ErrorEventHandler(unsafe { InlineEventListener::Compiled(CommonEventHandler::ErrorEventHandler(unsafe {
OnErrorEventHandlerNonNull::new(JSContext::from_ptr(cx), listener.callback()) OnErrorEventHandlerNonNull::new(cx, listener.callback())
})) }))
}); });
self.set_inline_event_listener(Atom::from(ty), event_listener); self.set_inline_event_listener(Atom::from(ty), event_listener);
@ -601,7 +599,7 @@ impl EventTarget {
let event_listener = listener.map(|listener| { let event_listener = listener.map(|listener| {
InlineEventListener::Compiled(CommonEventHandler::BeforeUnloadEventHandler(unsafe { InlineEventListener::Compiled(CommonEventHandler::BeforeUnloadEventHandler(unsafe {
OnBeforeUnloadEventHandlerNonNull::new(JSContext::from_ptr(cx), listener.callback()) OnBeforeUnloadEventHandlerNonNull::new(cx, listener.callback())
})) }))
}); });
self.set_inline_event_listener(Atom::from(ty), event_listener); self.set_inline_event_listener(Atom::from(ty), event_listener);
@ -613,10 +611,7 @@ impl EventTarget {
let listener = self.get_inline_event_listener(&Atom::from(ty)); let listener = self.get_inline_event_listener(&Atom::from(ty));
unsafe { unsafe {
listener.map(|listener| { listener.map(|listener| {
CallbackContainer::new( CallbackContainer::new(cx, listener.parent().callback_holder().get())
JSContext::from_ptr(cx),
listener.parent().callback_holder().get(),
)
}) })
} }
} }

View file

@ -266,7 +266,7 @@ impl FileReader {
let _ac = enter_realm(&*fr); let _ac = enter_realm(&*fr);
FileReader::perform_readasarraybuffer( FileReader::perform_readasarraybuffer(
&fr.result, &fr.result,
fr.global().get_cx(), *fr.global().get_cx(),
data, data,
&blob_contents, &blob_contents,
) )

View file

@ -99,9 +99,9 @@ impl Gamepad {
); );
let cx = global.get_cx(); let cx = global.get_cx();
rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); rooted!(in (*cx) let mut array = ptr::null_mut::<JSObject>());
unsafe { unsafe {
let _ = Float64Array::create(cx, CreateWith::Slice(&state.axes), array.handle_mut()); let _ = Float64Array::create(*cx, CreateWith::Slice(&state.axes), array.handle_mut());
} }
gamepad.axes.set(array.get()); gamepad.axes.set(array.get());
@ -173,7 +173,7 @@ impl Gamepad {
self.timestamp.set(state.timestamp); self.timestamp.set(state.timestamp);
unsafe { unsafe {
let cx = self.global().get_cx(); let cx = self.global().get_cx();
typedarray!(in(cx) let axes: Float64Array = self.axes.get()); typedarray!(in(*cx) let axes: Float64Array = self.axes.get());
if let Ok(mut array) = axes { if let Ok(mut array) = axes {
array.update(&state.axes); array.update(&state.axes);
} }

View file

@ -26,7 +26,7 @@ use crate::dom::window::Window;
use crate::dom::workerglobalscope::WorkerGlobalScope; use crate::dom::workerglobalscope::WorkerGlobalScope;
use crate::dom::workletglobalscope::WorkletGlobalScope; use crate::dom::workletglobalscope::WorkletGlobalScope;
use crate::microtask::{Microtask, MicrotaskQueue}; use crate::microtask::{Microtask, MicrotaskQueue};
use crate::script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort}; use crate::script_runtime::{CommonScriptMsg, JSContext as SafeJSContext, ScriptChan, ScriptPort};
use crate::script_thread::{MainThreadScriptChan, ScriptThread}; use crate::script_thread::{MainThreadScriptChan, ScriptThread};
use crate::task::TaskCanceller; use crate::task::TaskCanceller;
use crate::task_source::dom_manipulation::DOMManipulationTaskSource; use crate::task_source::dom_manipulation::DOMManipulationTaskSource;
@ -311,8 +311,8 @@ impl GlobalScope {
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn get_cx(&self) -> *mut JSContext { pub fn get_cx(&self) -> SafeJSContext {
Runtime::get() unsafe { SafeJSContext::from_ptr(Runtime::get()) }
} }
pub fn crypto(&self) -> DomRoot<Crypto> { pub fn crypto(&self) -> DomRoot<Crypto> {
@ -571,14 +571,14 @@ impl GlobalScope {
let globalhandle = self.reflector().get_jsobject(); let globalhandle = self.reflector().get_jsobject();
let filename = CString::new(filename).unwrap(); let filename = CString::new(filename).unwrap();
let _ac = JSAutoRealm::new(cx, globalhandle.get()); let _ac = JSAutoRealm::new(*cx, globalhandle.get());
let _aes = AutoEntryScript::new(self); let _aes = AutoEntryScript::new(self);
let options = CompileOptionsWrapper::new(cx, filename.as_ptr(), line_number); let options = CompileOptionsWrapper::new(*cx, filename.as_ptr(), line_number);
debug!("evaluating Dom string"); debug!("evaluating Dom string");
let result = unsafe { let result = unsafe {
EvaluateUtf8( EvaluateUtf8(
cx, *cx,
options.ptr, options.ptr,
code.as_ptr() as *const _, code.as_ptr() as *const _,
code.len() as libc::size_t, code.len() as libc::size_t,
@ -588,7 +588,7 @@ impl GlobalScope {
if !result { if !result {
debug!("error evaluating Dom string"); debug!("error evaluating Dom string");
unsafe { report_pending_exception(cx, true) }; unsafe { report_pending_exception(*cx, true) };
} }
maybe_resume_unwind(); maybe_resume_unwind();
@ -681,7 +681,7 @@ impl GlobalScope {
pub fn perform_a_microtask_checkpoint(&self) { pub fn perform_a_microtask_checkpoint(&self) {
unsafe { unsafe {
self.microtask_queue.checkpoint( self.microtask_queue.checkpoint(
self.get_cx(), *self.get_cx(),
|_| Some(DomRoot::from_ref(self)), |_| Some(DomRoot::from_ref(self)),
vec![DomRoot::from_ref(self)], vec![DomRoot::from_ref(self)],
); );
@ -692,7 +692,7 @@ impl GlobalScope {
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn enqueue_microtask(&self, job: Microtask) { pub fn enqueue_microtask(&self, job: Microtask) {
unsafe { unsafe {
self.microtask_queue.enqueue(job, self.get_cx()); self.microtask_queue.enqueue(job, *self.get_cx());
} }
} }

View file

@ -117,7 +117,7 @@ impl History {
match serialized_data { match serialized_data {
Some(serialized_data) => { Some(serialized_data) => {
let global_scope = self.window.upcast::<GlobalScope>(); let global_scope = self.window.upcast::<GlobalScope>();
rooted!(in(global_scope.get_cx()) let mut state = UndefinedValue()); rooted!(in(*global_scope.get_cx()) let mut state = UndefinedValue());
StructuredCloneData::Vector(serialized_data) StructuredCloneData::Vector(serialized_data)
.read(&global_scope, state.handle_mut()); .read(&global_scope, state.handle_mut());
self.state.set(state.get()); self.state.set(state.get());

View file

@ -654,7 +654,7 @@ impl HTMLScriptElement {
} else { } else {
self.line_number as u32 self.line_number as u32
}; };
rooted!(in(window.get_cx()) let mut rval = UndefinedValue()); rooted!(in(*window.get_cx()) let mut rval = UndefinedValue());
let global = window.upcast::<GlobalScope>(); let global = window.upcast::<GlobalScope>();
global.evaluate_script_on_global_with_result( global.evaluate_script_on_global_with_result(
&script.text, &script.text,

View file

@ -41,7 +41,7 @@ impl ImageData {
let len = width * height * 4; let len = width * height * 4;
unsafe { unsafe {
let cx = global.get_cx(); let cx = global.get_cx();
rooted!(in (cx) let mut js_object = ptr::null_mut::<JSObject>()); rooted!(in (*cx) let mut js_object = ptr::null_mut::<JSObject>());
let data = match data { let data = match data {
Some(ref mut d) => { Some(ref mut d) => {
d.resize(len as usize, 0); d.resize(len as usize, 0);
@ -49,7 +49,7 @@ impl ImageData {
}, },
None => CreateWith::Length(len), None => CreateWith::Length(len),
}; };
Uint8ClampedArray::create(cx, data, js_object.handle_mut()).unwrap(); Uint8ClampedArray::create(*cx, data, js_object.handle_mut()).unwrap();
Self::new_with_jsobject(global, width, Some(height), Some(js_object.get())) Self::new_with_jsobject(global, width, Some(height), Some(js_object.get()))
} }
} }
@ -70,7 +70,7 @@ impl ImageData {
// checking jsobject type and verifying (height * width * 4 == jsobject.byte_len()) // checking jsobject type and verifying (height * width * 4 == jsobject.byte_len())
if let Some(jsobject) = opt_jsobject { if let Some(jsobject) = opt_jsobject {
let cx = global.get_cx(); let cx = global.get_cx();
typedarray!(in(cx) let array_res: Uint8ClampedArray = jsobject); typedarray!(in(*cx) let array_res: Uint8ClampedArray = jsobject);
let array = array_res.map_err(|_| { let array = array_res.map_err(|_| {
Error::Type("Argument to Image data is not an Uint8ClampedArray".to_owned()) Error::Type("Argument to Image data is not an Uint8ClampedArray".to_owned())
})?; })?;
@ -110,8 +110,8 @@ impl ImageData {
} else { } else {
let len = width * height * 4; let len = width * height * 4;
let cx = global.get_cx(); let cx = global.get_cx();
rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); rooted!(in (*cx) let mut array = ptr::null_mut::<JSObject>());
Uint8ClampedArray::create(cx, CreateWith::Length(len), array.handle_mut()).unwrap(); Uint8ClampedArray::create(*cx, CreateWith::Length(len), array.handle_mut()).unwrap();
(*imagedata).data.set(array.get()); (*imagedata).data.set(array.get());
} }

View file

@ -253,12 +253,12 @@ impl PaintWorkletGlobalScope {
); );
let cx = self.worklet_global.get_cx(); let cx = self.worklet_global.get_cx();
let _ac = JSAutoRealm::new(cx, self.worklet_global.reflector().get_jsobject().get()); let _ac = JSAutoRealm::new(*cx, self.worklet_global.reflector().get_jsobject().get());
// TODO: Steps 1-2.1. // TODO: Steps 1-2.1.
// Step 2.2-5.1. // Step 2.2-5.1.
rooted!(in(cx) let mut class_constructor = UndefinedValue()); rooted!(in(*cx) let mut class_constructor = UndefinedValue());
rooted!(in(cx) let mut paint_function = UndefinedValue()); rooted!(in(*cx) let mut paint_function = UndefinedValue());
let rendering_context = match self.paint_definitions.borrow().get(name) { let rendering_context = match self.paint_definitions.borrow().get(name) {
None => { None => {
// Step 2.2. // Step 2.2.
@ -282,21 +282,21 @@ impl PaintWorkletGlobalScope {
// prepopulate the paint instance in `RegisterPaint`, to avoid calling it in // prepopulate the paint instance in `RegisterPaint`, to avoid calling it in
// the primary worklet thread. // the primary worklet thread.
// https://github.com/servo/servo/issues/17377 // https://github.com/servo/servo/issues/17377
rooted!(in(cx) let mut paint_instance = UndefinedValue()); rooted!(in(*cx) let mut paint_instance = UndefinedValue());
match self.paint_class_instances.borrow_mut().entry(name.clone()) { match self.paint_class_instances.borrow_mut().entry(name.clone()) {
Entry::Occupied(entry) => paint_instance.set(entry.get().get()), Entry::Occupied(entry) => paint_instance.set(entry.get().get()),
Entry::Vacant(entry) => { Entry::Vacant(entry) => {
// Step 5.2-5.3 // Step 5.2-5.3
let args = HandleValueArray::new(); let args = HandleValueArray::new();
rooted!(in(cx) let mut result = null_mut::<JSObject>()); rooted!(in(*cx) let mut result = null_mut::<JSObject>());
unsafe { unsafe {
Construct1(cx, class_constructor.handle(), &args, result.handle_mut()); Construct1(*cx, class_constructor.handle(), &args, result.handle_mut());
} }
paint_instance.set(ObjectValue(result.get())); paint_instance.set(ObjectValue(result.get()));
if unsafe { JS_IsExceptionPending(cx) } { if unsafe { JS_IsExceptionPending(*cx) } {
debug!("Paint constructor threw an exception {}.", name); debug!("Paint constructor threw an exception {}.", name);
unsafe { unsafe {
JS_ClearPendingException(cx); JS_ClearPendingException(*cx);
} }
self.paint_definitions self.paint_definitions
.borrow_mut() .borrow_mut()
@ -333,7 +333,7 @@ impl PaintWorkletGlobalScope {
.collect(); .collect();
let arguments_value_array = let arguments_value_array =
unsafe { HandleValueArray::from_rooted_slice(&*arguments_value_vec) }; unsafe { HandleValueArray::from_rooted_slice(&*arguments_value_vec) };
rooted!(in(cx) let argument_object = unsafe { JS_NewArrayObject(cx, &arguments_value_array) }); rooted!(in(*cx) let argument_object = unsafe { JS_NewArrayObject(*cx, &arguments_value_array) });
let args_slice = [ let args_slice = [
ObjectValue(rendering_context.reflector().get_jsobject().get()), ObjectValue(rendering_context.reflector().get_jsobject().get()),
@ -343,10 +343,10 @@ impl PaintWorkletGlobalScope {
]; ];
let args = unsafe { HandleValueArray::from_rooted_slice(&args_slice) }; let args = unsafe { HandleValueArray::from_rooted_slice(&args_slice) };
rooted!(in(cx) let mut result = UndefinedValue()); rooted!(in(*cx) let mut result = UndefinedValue());
unsafe { unsafe {
Call( Call(
cx, *cx,
paint_instance.handle(), paint_instance.handle(),
paint_function.handle(), paint_function.handle(),
&args, &args,
@ -356,10 +356,10 @@ impl PaintWorkletGlobalScope {
let missing_image_urls = rendering_context.take_missing_image_urls(); let missing_image_urls = rendering_context.take_missing_image_urls();
// Step 13. // Step 13.
if unsafe { JS_IsExceptionPending(cx) } { if unsafe { JS_IsExceptionPending(*cx) } {
debug!("Paint function threw an exception {}.", name); debug!("Paint function threw an exception {}.", name);
unsafe { unsafe {
JS_ClearPendingException(cx); JS_ClearPendingException(*cx);
} }
return self.invalid_image(size_in_dpx, missing_image_urls); return self.invalid_image(size_in_dpx, missing_image_urls);
} }
@ -518,8 +518,8 @@ impl PaintWorkletGlobalScopeMethods for PaintWorkletGlobalScope {
fn RegisterPaint(&self, name: DOMString, paint_ctor: Rc<VoidFunction>) -> Fallible<()> { fn RegisterPaint(&self, name: DOMString, paint_ctor: Rc<VoidFunction>) -> Fallible<()> {
let name = Atom::from(name); let name = Atom::from(name);
let cx = self.worklet_global.get_cx(); let cx = self.worklet_global.get_cx();
rooted!(in(cx) let paint_obj = paint_ctor.callback_holder().get()); rooted!(in(*cx) let paint_obj = paint_ctor.callback_holder().get());
rooted!(in(cx) let paint_val = ObjectValue(paint_obj.get())); rooted!(in(*cx) let paint_val = ObjectValue(paint_obj.get()));
debug!("Registering paint image name {}.", name); debug!("Registering paint image name {}.", name);
@ -535,20 +535,20 @@ impl PaintWorkletGlobalScopeMethods for PaintWorkletGlobalScope {
// Step 4-6. // Step 4-6.
let mut property_names: Vec<String> = let mut property_names: Vec<String> =
unsafe { get_property(cx, paint_obj.handle(), "inputProperties", ()) }? unsafe { get_property(*cx, paint_obj.handle(), "inputProperties", ()) }?
.unwrap_or_default(); .unwrap_or_default();
let properties = property_names.drain(..).map(Atom::from).collect(); let properties = property_names.drain(..).map(Atom::from).collect();
// Step 7-9. // Step 7-9.
let input_arguments: Vec<String> = let input_arguments: Vec<String> =
unsafe { get_property(cx, paint_obj.handle(), "inputArguments", ()) }? unsafe { get_property(*cx, paint_obj.handle(), "inputArguments", ()) }?
.unwrap_or_default(); .unwrap_or_default();
// TODO: Steps 10-11. // TODO: Steps 10-11.
// Steps 12-13. // Steps 12-13.
let alpha: bool = let alpha: bool =
unsafe { get_property(cx, paint_obj.handle(), "alpha", ()) }?.unwrap_or(true); unsafe { get_property(*cx, paint_obj.handle(), "alpha", ()) }?.unwrap_or(true);
// Step 14 // Step 14
if unsafe { !IsConstructor(paint_obj.get()) } { if unsafe { !IsConstructor(paint_obj.get()) } {
@ -556,19 +556,24 @@ impl PaintWorkletGlobalScopeMethods for PaintWorkletGlobalScope {
} }
// Steps 15-16 // Steps 15-16
rooted!(in(cx) let mut prototype = UndefinedValue()); rooted!(in(*cx) let mut prototype = UndefinedValue());
unsafe { unsafe {
get_property_jsval(cx, paint_obj.handle(), "prototype", prototype.handle_mut())?; get_property_jsval(*cx, paint_obj.handle(), "prototype", prototype.handle_mut())?;
} }
if !prototype.is_object() { if !prototype.is_object() {
return Err(Error::Type(String::from("Prototype is not an object."))); return Err(Error::Type(String::from("Prototype is not an object.")));
} }
rooted!(in(cx) let prototype = prototype.to_object()); rooted!(in(*cx) let prototype = prototype.to_object());
// Steps 17-18 // Steps 17-18
rooted!(in(cx) let mut paint_function = UndefinedValue()); rooted!(in(*cx) let mut paint_function = UndefinedValue());
unsafe { unsafe {
get_property_jsval(cx, prototype.handle(), "paint", paint_function.handle_mut())?; get_property_jsval(
*cx,
prototype.handle(),
"paint",
paint_function.handle_mut(),
)?;
} }
if !paint_function.is_object() || unsafe { !IsCallable(paint_function.to_object()) } { if !paint_function.is_object() || unsafe { !IsCallable(paint_function.to_object()) } {
return Err(Error::Type(String::from("Paint function is not callable."))); return Err(Error::Type(String::from("Paint function is not callable.")));

View file

@ -89,17 +89,17 @@ impl Promise {
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn new_in_current_compartment(global: &GlobalScope, _comp: InCompartment) -> Rc<Promise> { pub fn new_in_current_compartment(global: &GlobalScope, _comp: InCompartment) -> Rc<Promise> {
let cx = global.get_cx(); let cx = global.get_cx();
rooted!(in(cx) let mut obj = ptr::null_mut::<JSObject>()); rooted!(in(*cx) let mut obj = ptr::null_mut::<JSObject>());
unsafe { unsafe {
Promise::create_js_promise(cx, HandleObject::null(), obj.handle_mut()); Promise::create_js_promise(*cx, HandleObject::null(), obj.handle_mut());
Promise::new_with_js_promise(obj.handle(), cx) Promise::new_with_js_promise(obj.handle(), *cx)
} }
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn duplicate(&self) -> Rc<Promise> { pub fn duplicate(&self) -> Rc<Promise> {
let cx = self.global().get_cx(); let cx = self.global().get_cx();
unsafe { Promise::new_with_js_promise(self.reflector().get_jsobject(), cx) } unsafe { Promise::new_with_js_promise(self.reflector().get_jsobject(), *cx) }
} }
#[allow(unsafe_code, unrooted_must_root)] #[allow(unsafe_code, unrooted_must_root)]
@ -166,10 +166,10 @@ impl Promise {
{ {
let cx = self.global().get_cx(); let cx = self.global().get_cx();
let _ac = enter_realm(&*self); let _ac = enter_realm(&*self);
rooted!(in(cx) let mut v = UndefinedValue()); rooted!(in(*cx) let mut v = UndefinedValue());
unsafe { unsafe {
val.to_jsval(cx, v.handle_mut()); val.to_jsval(*cx, v.handle_mut());
self.resolve(cx, v.handle()); self.resolve(*cx, v.handle());
} }
} }
@ -187,10 +187,10 @@ impl Promise {
{ {
let cx = self.global().get_cx(); let cx = self.global().get_cx();
let _ac = enter_realm(&*self); let _ac = enter_realm(&*self);
rooted!(in(cx) let mut v = UndefinedValue()); rooted!(in(*cx) let mut v = UndefinedValue());
unsafe { unsafe {
val.to_jsval(cx, v.handle_mut()); val.to_jsval(*cx, v.handle_mut());
self.reject(cx, v.handle()); self.reject(*cx, v.handle());
} }
} }
@ -198,10 +198,10 @@ impl Promise {
pub fn reject_error(&self, error: Error) { pub fn reject_error(&self, error: Error) {
let cx = self.global().get_cx(); let cx = self.global().get_cx();
let _ac = enter_realm(&*self); let _ac = enter_realm(&*self);
rooted!(in(cx) let mut v = UndefinedValue()); rooted!(in(*cx) let mut v = UndefinedValue());
unsafe { unsafe {
error.to_jsval(cx, &self.global(), v.handle_mut()); error.to_jsval(*cx, &self.global(), v.handle_mut());
self.reject(cx, v.handle()); self.reject(*cx, v.handle());
} }
} }
@ -233,19 +233,19 @@ impl Promise {
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn append_native_handler(&self, handler: &PromiseNativeHandler) { pub fn append_native_handler(&self, handler: &PromiseNativeHandler) {
let cx = self.global().get_cx(); let cx = self.global().get_cx();
rooted!(in(cx) let resolve_func = rooted!(in(*cx) let resolve_func =
create_native_handler_function(cx, create_native_handler_function(*cx,
handler.reflector().get_jsobject(), handler.reflector().get_jsobject(),
NativeHandlerTask::Resolve)); NativeHandlerTask::Resolve));
rooted!(in(cx) let reject_func = rooted!(in(*cx) let reject_func =
create_native_handler_function(cx, create_native_handler_function(*cx,
handler.reflector().get_jsobject(), handler.reflector().get_jsobject(),
NativeHandlerTask::Reject)); NativeHandlerTask::Reject));
unsafe { unsafe {
let ok = AddPromiseReactions( let ok = AddPromiseReactions(
cx, *cx,
self.promise_obj(), self.promise_obj(),
resolve_func.handle(), resolve_func.handle(),
reject_func.handle(), reject_func.handle(),

View file

@ -337,7 +337,7 @@ impl ServiceWorkerGlobalScope {
unsafe { unsafe {
// Handle interrupt requests // Handle interrupt requests
JS_AddInterruptCallback(scope.get_cx(), Some(interrupt_callback)); JS_AddInterruptCallback(*scope.get_cx(), Some(interrupt_callback));
} }
scope.execute_script(DOMString::from(source)); scope.execute_script(DOMString::from(source));
@ -413,7 +413,7 @@ impl ServiceWorkerGlobalScope {
let scope = self.upcast::<WorkerGlobalScope>(); let scope = self.upcast::<WorkerGlobalScope>();
let target = self.upcast(); let target = self.upcast();
let _ac = enter_realm(&*scope); let _ac = enter_realm(&*scope);
rooted!(in(scope.get_cx()) let mut message = UndefinedValue()); rooted!(in(*scope.get_cx()) let mut message = UndefinedValue());
data.read(scope.upcast(), message.handle_mut()); data.read(scope.upcast(), message.handle_mut());
ExtendableMessageEvent::dispatch_jsval(target, scope.upcast(), message.handle()); ExtendableMessageEvent::dispatch_jsval(target, scope.upcast(), message.handle());
}, },

View file

@ -22,7 +22,7 @@ pub fn load_script(head: &HTMLHeadElement) {
doc.add_delayed_task(task!(UserScriptExecute: move || { doc.add_delayed_task(task!(UserScriptExecute: move || {
let win = win.root(); let win = win.root();
let cx = win.get_cx(); let cx = win.get_cx();
rooted!(in(cx) let mut rval = UndefinedValue()); rooted!(in(*cx) let mut rval = UndefinedValue());
let path = PathBuf::from(&path_str); let path = PathBuf::from(&path_str);
let mut files = read_dir(&path) let mut files = read_dir(&path)

View file

@ -45,10 +45,10 @@ impl VREyeParameters {
let fov = VRFieldOfView::new(&global, parameters.field_of_view.clone()); let fov = VRFieldOfView::new(&global, parameters.field_of_view.clone());
let cx = global.get_cx(); let cx = global.get_cx();
rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); rooted!(in (*cx) let mut array = ptr::null_mut::<JSObject>());
unsafe { unsafe {
let _ = Float32Array::create( let _ = Float32Array::create(
cx, *cx,
CreateWith::Slice(&parameters.offset), CreateWith::Slice(&parameters.offset),
array.handle_mut(), array.handle_mut(),
); );

View file

@ -62,7 +62,7 @@ impl VRFrameData {
global, global,
VRFrameDataBinding::Wrap, VRFrameDataBinding::Wrap,
); );
let cx = unsafe { JSContext::from_ptr(global.get_cx()) }; let cx = global.get_cx();
create_typed_array(cx, &matrix, &root.left_proj); create_typed_array(cx, &matrix, &root.left_proj);
create_typed_array(cx, &matrix, &root.left_view); create_typed_array(cx, &matrix, &root.left_view);
create_typed_array(cx, &matrix, &root.right_proj); create_typed_array(cx, &matrix, &root.right_proj);
@ -90,7 +90,7 @@ impl VRFrameData {
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn update(&self, data: &WebVRFrameData) { pub fn update(&self, data: &WebVRFrameData) {
unsafe { unsafe {
let cx = JSContext::from_ptr(self.global().get_cx()); let cx = self.global().get_cx();
typedarray!(in(*cx) let left_proj_array: Float32Array = self.left_proj.get()); typedarray!(in(*cx) let left_proj_array: Float32Array = self.left_proj.get());
if let Ok(mut array) = left_proj_array { if let Ok(mut array) = left_proj_array {
array.update(&data.left_projection_matrix); array.update(&data.left_projection_matrix);

View file

@ -7,9 +7,9 @@ use crate::dom::bindings::codegen::Bindings::VRPoseBinding::VRPoseMethods;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::root::DomRoot;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::JSContext as SafeJSContext; use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext, JSObject}; use js::jsapi::{Heap, JSObject};
use js::typedarray::{CreateWith, Float32Array}; use js::typedarray::{CreateWith, Float32Array};
use std::ptr; use std::ptr;
use std::ptr::NonNull; use std::ptr::NonNull;
@ -33,21 +33,19 @@ pub struct VRPose {
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn update_or_create_typed_array( fn update_or_create_typed_array(cx: JSContext, src: Option<&[f32]>, dst: &Heap<*mut JSObject>) {
cx: *mut JSContext,
src: Option<&[f32]>,
dst: &Heap<*mut JSObject>,
) {
match src { match src {
Some(data) => { Some(data) => {
if dst.get().is_null() { if dst.get().is_null() {
rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); rooted!(in (*cx) let mut array = ptr::null_mut::<JSObject>());
let _ = Float32Array::create(cx, CreateWith::Slice(data), array.handle_mut()); let _ = unsafe {
Float32Array::create(*cx, CreateWith::Slice(data), array.handle_mut())
};
(*dst).set(array.get()); (*dst).set(array.get());
} else { } else {
typedarray!(in(cx) let array: Float32Array = dst.get()); typedarray!(in(*cx) let array: Float32Array = dst.get());
if let Ok(mut array) = array { if let Ok(mut array) = array {
array.update(data); unsafe { array.update(data) };
} }
} }
}, },
@ -96,12 +94,7 @@ impl VRPose {
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn update(&self, pose: &webvr::VRPose) { pub fn update(&self, pose: &webvr::VRPose) {
let cx = self.global().get_cx(); let cx = self.global().get_cx();
unsafe { update_or_create_typed_array(cx, pose.position.as_ref().map(|v| &v[..]), &self.position);
update_or_create_typed_array(
cx,
pose.position.as_ref().map(|v| &v[..]),
&self.position,
);
update_or_create_typed_array( update_or_create_typed_array(
cx, cx,
pose.orientation.as_ref().map(|v| &v[..]), pose.orientation.as_ref().map(|v| &v[..]),
@ -129,36 +122,35 @@ impl VRPose {
); );
} }
} }
}
impl VRPoseMethods for VRPose { impl VRPoseMethods for VRPose {
// https://w3c.github.io/webvr/#dom-vrpose-position // https://w3c.github.io/webvr/#dom-vrpose-position
fn GetPosition(&self, _cx: SafeJSContext) -> Option<NonNull<JSObject>> { fn GetPosition(&self, _cx: JSContext) -> Option<NonNull<JSObject>> {
heap_to_option(&self.position) heap_to_option(&self.position)
} }
// https://w3c.github.io/webvr/#dom-vrpose-linearvelocity // https://w3c.github.io/webvr/#dom-vrpose-linearvelocity
fn GetLinearVelocity(&self, _cx: SafeJSContext) -> Option<NonNull<JSObject>> { fn GetLinearVelocity(&self, _cx: JSContext) -> Option<NonNull<JSObject>> {
heap_to_option(&self.linear_vel) heap_to_option(&self.linear_vel)
} }
// https://w3c.github.io/webvr/#dom-vrpose-linearacceleration // https://w3c.github.io/webvr/#dom-vrpose-linearacceleration
fn GetLinearAcceleration(&self, _cx: SafeJSContext) -> Option<NonNull<JSObject>> { fn GetLinearAcceleration(&self, _cx: JSContext) -> Option<NonNull<JSObject>> {
heap_to_option(&self.linear_acc) heap_to_option(&self.linear_acc)
} }
// https://w3c.github.io/webvr/#dom-vrpose-orientation // https://w3c.github.io/webvr/#dom-vrpose-orientation
fn GetOrientation(&self, _cx: SafeJSContext) -> Option<NonNull<JSObject>> { fn GetOrientation(&self, _cx: JSContext) -> Option<NonNull<JSObject>> {
heap_to_option(&self.orientation) heap_to_option(&self.orientation)
} }
// https://w3c.github.io/webvr/#dom-vrpose-angularvelocity // https://w3c.github.io/webvr/#dom-vrpose-angularvelocity
fn GetAngularVelocity(&self, _cx: SafeJSContext) -> Option<NonNull<JSObject>> { fn GetAngularVelocity(&self, _cx: JSContext) -> Option<NonNull<JSObject>> {
heap_to_option(&self.angular_vel) heap_to_option(&self.angular_vel)
} }
// https://w3c.github.io/webvr/#dom-vrpose-angularacceleration // https://w3c.github.io/webvr/#dom-vrpose-angularacceleration
fn GetAngularAcceleration(&self, _cx: SafeJSContext) -> Option<NonNull<JSObject>> { fn GetAngularAcceleration(&self, _cx: JSContext) -> Option<NonNull<JSObject>> {
heap_to_option(&self.angular_acc) heap_to_option(&self.angular_acc)
} }
} }

View file

@ -43,10 +43,10 @@ impl VRStageParameters {
global: &GlobalScope, global: &GlobalScope,
) -> DomRoot<VRStageParameters> { ) -> DomRoot<VRStageParameters> {
let cx = global.get_cx(); let cx = global.get_cx();
rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); rooted!(in (*cx) let mut array = ptr::null_mut::<JSObject>());
unsafe { unsafe {
let _ = Float32Array::create( let _ = Float32Array::create(
cx, *cx,
CreateWith::Slice(&parameters.sitting_to_standing_transform), CreateWith::Slice(&parameters.sitting_to_standing_transform),
array.handle_mut(), array.handle_mut(),
); );
@ -67,7 +67,7 @@ impl VRStageParameters {
pub fn update(&self, parameters: &WebVRStageParameters) { pub fn update(&self, parameters: &WebVRStageParameters) {
unsafe { unsafe {
let cx = self.global().get_cx(); let cx = self.global().get_cx();
typedarray!(in(cx) let array: Float32Array = self.transform.get()); typedarray!(in(*cx) let array: Float32Array = self.transform.get());
if let Ok(mut array) = array { if let Ok(mut array) = array {
array.update(&parameters.sitting_to_standing_transform); array.update(&parameters.sitting_to_standing_transform);
} }

View file

@ -569,26 +569,26 @@ impl TaskOnce for MessageReceivedTask {
// global.get_cx() returns a valid `JSContext` pointer, so this is safe. // global.get_cx() returns a valid `JSContext` pointer, so this is safe.
unsafe { unsafe {
let cx = global.get_cx(); let cx = global.get_cx();
let _ac = JSAutoRealm::new(cx, ws.reflector().get_jsobject().get()); let _ac = JSAutoRealm::new(*cx, ws.reflector().get_jsobject().get());
rooted!(in(cx) let mut message = UndefinedValue()); rooted!(in(*cx) let mut message = UndefinedValue());
match self.message { match self.message {
MessageData::Text(text) => text.to_jsval(cx, message.handle_mut()), MessageData::Text(text) => text.to_jsval(*cx, message.handle_mut()),
MessageData::Binary(data) => match ws.binary_type.get() { MessageData::Binary(data) => match ws.binary_type.get() {
BinaryType::Blob => { BinaryType::Blob => {
let blob = let blob =
Blob::new(&global, BlobImpl::new_from_bytes(data), "".to_owned()); Blob::new(&global, BlobImpl::new_from_bytes(data), "".to_owned());
blob.to_jsval(cx, message.handle_mut()); blob.to_jsval(*cx, message.handle_mut());
}, },
BinaryType::Arraybuffer => { BinaryType::Arraybuffer => {
rooted!(in(cx) let mut array_buffer = ptr::null_mut::<JSObject>()); rooted!(in(*cx) let mut array_buffer = ptr::null_mut::<JSObject>());
assert!(ArrayBuffer::create( assert!(ArrayBuffer::create(
cx, *cx,
CreateWith::Slice(&data), CreateWith::Slice(&data),
array_buffer.handle_mut() array_buffer.handle_mut()
) )
.is_ok()); .is_ok());
(*array_buffer).to_jsval(cx, message.handle_mut()); (*array_buffer).to_jsval(*cx, message.handle_mut());
}, },
}, },
} }

View file

@ -57,8 +57,7 @@ use crate::fetch;
use crate::layout_image::fetch_image_for_layout; use crate::layout_image::fetch_image_for_layout;
use crate::microtask::MicrotaskQueue; use crate::microtask::MicrotaskQueue;
use crate::script_runtime::{ use crate::script_runtime::{
CommonScriptMsg, JSContext as SafeJSContext, Runtime, ScriptChan, ScriptPort, CommonScriptMsg, JSContext, Runtime, ScriptChan, ScriptPort, ScriptThreadEventCategory,
ScriptThreadEventCategory,
}; };
use crate::script_thread::{ImageCacheMsg, MainThreadScriptChan, MainThreadScriptMsg}; use crate::script_thread::{ImageCacheMsg, MainThreadScriptChan, MainThreadScriptMsg};
use crate::script_thread::{ScriptThread, SendableMainThreadScriptChan}; use crate::script_thread::{ScriptThread, SendableMainThreadScriptChan};
@ -80,7 +79,6 @@ use euclid::{Point2D, Rect, Scale, Size2D, Vector2D};
use ipc_channel::ipc::{channel, IpcSender}; use ipc_channel::ipc::{channel, IpcSender};
use ipc_channel::router::ROUTER; use ipc_channel::router::ROUTER;
use js::jsapi::JSAutoRealm; use js::jsapi::JSAutoRealm;
use js::jsapi::JSContext;
use js::jsapi::JSPROP_ENUMERATE; use js::jsapi::JSPROP_ENUMERATE;
use js::jsapi::{GCReason, JS_GC}; use js::jsapi::{GCReason, JS_GC};
use js::jsval::JSVal; use js::jsval::JSVal;
@ -372,8 +370,9 @@ impl Window {
self.globalscope.origin() self.globalscope.origin()
} }
pub fn get_cx(&self) -> *mut JSContext { #[allow(unsafe_code)]
self.js_runtime.borrow().as_ref().unwrap().cx() pub fn get_cx(&self) -> JSContext {
unsafe { JSContext::from_ptr(self.js_runtime.borrow().as_ref().unwrap().cx()) }
} }
pub fn main_thread_script_chan(&self) -> &Sender<MainThreadScriptMsg> { pub fn main_thread_script_chan(&self) -> &Sender<MainThreadScriptMsg> {
@ -615,13 +614,13 @@ impl WindowMethods for Window {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-opener // https://html.spec.whatwg.org/multipage/#dom-opener
fn Opener(&self, cx: SafeJSContext) -> JSVal { fn Opener(&self, cx: JSContext) -> JSVal {
unsafe { self.window_proxy().opener(*cx) } unsafe { self.window_proxy().opener(*cx) }
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-opener // https://html.spec.whatwg.org/multipage/#dom-opener
fn SetOpener(&self, cx: SafeJSContext, value: HandleValue) { fn SetOpener(&self, cx: JSContext, value: HandleValue) {
// Step 1. // Step 1.
if value.is_null() { if value.is_null() {
return self.window_proxy().disown(); return self.window_proxy().disown();
@ -744,7 +743,7 @@ impl WindowMethods for Window {
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout
fn SetTimeout( fn SetTimeout(
&self, &self,
_cx: SafeJSContext, _cx: JSContext,
callback: Rc<Function>, callback: Rc<Function>,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,
@ -760,7 +759,7 @@ impl WindowMethods for Window {
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout
fn SetTimeout_( fn SetTimeout_(
&self, &self,
_cx: SafeJSContext, _cx: JSContext,
callback: DOMString, callback: DOMString,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,
@ -782,7 +781,7 @@ impl WindowMethods for Window {
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval
fn SetInterval( fn SetInterval(
&self, &self,
_cx: SafeJSContext, _cx: JSContext,
callback: Rc<Function>, callback: Rc<Function>,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,
@ -798,7 +797,7 @@ impl WindowMethods for Window {
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval
fn SetInterval_( fn SetInterval_(
&self, &self,
_cx: SafeJSContext, _cx: JSContext,
callback: DOMString, callback: DOMString,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,
@ -902,12 +901,7 @@ impl WindowMethods for Window {
} }
// https://html.spec.whatwg.org/multipage/#dom-window-postmessage // https://html.spec.whatwg.org/multipage/#dom-window-postmessage
fn PostMessage( fn PostMessage(&self, cx: JSContext, message: HandleValue, origin: DOMString) -> ErrorResult {
&self,
cx: SafeJSContext,
message: HandleValue,
origin: DOMString,
) -> ErrorResult {
let source_global = GlobalScope::incumbent().expect("no incumbent global??"); let source_global = GlobalScope::incumbent().expect("no incumbent global??");
let source = source_global.as_window(); let source = source_global.as_window();
@ -948,7 +942,7 @@ impl WindowMethods for Window {
#[allow(unsafe_code)] #[allow(unsafe_code)]
fn Gc(&self) { fn Gc(&self) {
unsafe { unsafe {
JS_GC(self.get_cx(), GCReason::API); JS_GC(*self.get_cx(), GCReason::API);
} }
} }
@ -958,7 +952,7 @@ impl WindowMethods for Window {
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
fn WebdriverCallback(&self, cx: SafeJSContext, val: HandleValue) { fn WebdriverCallback(&self, cx: JSContext, val: HandleValue) {
let rv = unsafe { jsval_to_webdriver(*cx, val) }; let rv = unsafe { jsval_to_webdriver(*cx, val) };
let opt_chan = self.webdriver_script_chan.borrow_mut().take(); let opt_chan = self.webdriver_script_chan.borrow_mut().take();
if let Some(chan) = opt_chan { if let Some(chan) = opt_chan {
@ -2177,7 +2171,7 @@ impl Window {
player_context, player_context,
}); });
unsafe { WindowBinding::Wrap(SafeJSContext::from_ptr(runtime.cx()), win) } unsafe { WindowBinding::Wrap(JSContext::from_ptr(runtime.cx()), win) }
} }
pub fn pipeline_id(&self) -> Option<PipelineId> { pub fn pipeline_id(&self) -> Option<PipelineId> {
@ -2279,8 +2273,8 @@ impl Window {
// Steps 7.2.-7.5. // Steps 7.2.-7.5.
let cx = this.get_cx(); let cx = this.get_cx();
let obj = this.reflector().get_jsobject(); let obj = this.reflector().get_jsobject();
let _ac = JSAutoRealm::new(cx, obj.get()); let _ac = JSAutoRealm::new(*cx, obj.get());
rooted!(in(cx) let mut message_clone = UndefinedValue()); rooted!(in(*cx) let mut message_clone = UndefinedValue());
serialize_with_transfer_result.read( serialize_with_transfer_result.read(
this.upcast(), this.upcast(),
message_clone.handle_mut(), message_clone.handle_mut(),

View file

@ -152,10 +152,10 @@ impl WindowProxy {
((*get_object_class(window_jsobject.get())).flags & JSCLASS_IS_GLOBAL), ((*get_object_class(window_jsobject.get())).flags & JSCLASS_IS_GLOBAL),
0 0
); );
let _ac = JSAutoRealm::new(cx, window_jsobject.get()); let _ac = JSAutoRealm::new(*cx, window_jsobject.get());
// Create a new window proxy. // Create a new window proxy.
rooted!(in(cx) let js_proxy = NewWindowProxy(cx, window_jsobject, handler)); rooted!(in(*cx) let js_proxy = NewWindowProxy(*cx, window_jsobject, handler));
assert!(!js_proxy.is_null()); assert!(!js_proxy.is_null());
// Create a new browsing context. // Create a new browsing context.
@ -178,7 +178,7 @@ impl WindowProxy {
); );
// Notify the JS engine about the new window proxy binding. // Notify the JS engine about the new window proxy binding.
SetWindowProxy(cx, window_jsobject, js_proxy.handle()); SetWindowProxy(*cx, window_jsobject, js_proxy.handle());
// Set the reflector. // Set the reflector.
debug!( debug!(
@ -223,10 +223,10 @@ impl WindowProxy {
((*get_object_class(window_jsobject.get())).flags & JSCLASS_IS_GLOBAL), ((*get_object_class(window_jsobject.get())).flags & JSCLASS_IS_GLOBAL),
0 0
); );
let _ac = JSAutoRealm::new(cx, window_jsobject.get()); let _ac = JSAutoRealm::new(*cx, window_jsobject.get());
// Create a new window proxy. // Create a new window proxy.
rooted!(in(cx) let js_proxy = NewWindowProxy(cx, window_jsobject, handler)); rooted!(in(*cx) let js_proxy = NewWindowProxy(*cx, window_jsobject, handler));
assert!(!js_proxy.is_null()); assert!(!js_proxy.is_null());
// The window proxy owns the browsing context. // The window proxy owns the browsing context.
@ -238,7 +238,7 @@ impl WindowProxy {
); );
// Notify the JS engine about the new window proxy binding. // Notify the JS engine about the new window proxy binding.
SetWindowProxy(cx, window_jsobject, js_proxy.handle()); SetWindowProxy(*cx, window_jsobject, js_proxy.handle());
// Set the reflector. // Set the reflector.
debug!( debug!(
@ -576,20 +576,20 @@ impl WindowProxy {
// of the old window proxy to the new window proxy, then // of the old window proxy to the new window proxy, then
// making the old window proxy a cross-compartment wrapper // making the old window proxy a cross-compartment wrapper
// pointing to the new window proxy. // pointing to the new window proxy.
rooted!(in(cx) let new_js_proxy = NewWindowProxy(cx, window_jsobject, handler)); rooted!(in(*cx) let new_js_proxy = NewWindowProxy(*cx, window_jsobject, handler));
debug!( debug!(
"Transplanting proxy from {:p} to {:p}.", "Transplanting proxy from {:p} to {:p}.",
old_js_proxy.get(), old_js_proxy.get(),
new_js_proxy.get() new_js_proxy.get()
); );
rooted!(in(cx) let new_js_proxy = JS_TransplantObject(cx, old_js_proxy, new_js_proxy.handle())); rooted!(in(*cx) let new_js_proxy = JS_TransplantObject(*cx, old_js_proxy, new_js_proxy.handle()));
debug!("Transplanted proxy is {:p}.", new_js_proxy.get()); debug!("Transplanted proxy is {:p}.", new_js_proxy.get());
// Transfer ownership of this browsing context from the old window proxy to the new one. // Transfer ownership of this browsing context from the old window proxy to the new one.
SetProxyReservedSlot(new_js_proxy.get(), 0, &PrivateValue(self.as_void_ptr())); SetProxyReservedSlot(new_js_proxy.get(), 0, &PrivateValue(self.as_void_ptr()));
// Notify the JS engine about the new window proxy binding. // Notify the JS engine about the new window proxy binding.
SetWindowProxy(cx, window_jsobject, new_js_proxy.handle()); SetWindowProxy(*cx, window_jsobject, new_js_proxy.handle());
// Update the reflector. // Update the reflector.
debug!( debug!(

View file

@ -147,7 +147,7 @@ impl Worker {
let global = worker.global(); let global = worker.global();
let target = worker.upcast(); let target = worker.upcast();
let _ac = enter_realm(target); let _ac = enter_realm(target);
rooted!(in(global.get_cx()) let mut message = UndefinedValue()); rooted!(in(*global.get_cx()) let mut message = UndefinedValue());
data.read(&global, message.handle_mut()); data.read(&global, message.handle_mut());
MessageEvent::dispatch_jsval(target, &global, message.handle(), None, None); MessageEvent::dispatch_jsval(target, &global, message.handle(), None, None);
} }
@ -186,7 +186,7 @@ impl WorkerMethods for Worker {
// Step 3 // Step 3
let cx = self.global().get_cx(); let cx = self.global().get_cx();
unsafe { JS_RequestInterruptCallback(cx) }; unsafe { JS_RequestInterruptCallback(*cx) };
} }
// https://html.spec.whatwg.org/multipage/#handler-worker-onmessage // https://html.spec.whatwg.org/multipage/#handler-worker-onmessage

View file

@ -26,7 +26,7 @@ use crate::dom::window::{base64_atob, base64_btoa};
use crate::dom::workerlocation::WorkerLocation; use crate::dom::workerlocation::WorkerLocation;
use crate::dom::workernavigator::WorkerNavigator; use crate::dom::workernavigator::WorkerNavigator;
use crate::fetch; use crate::fetch;
use crate::script_runtime::JSContext as SafeJSContext; use crate::script_runtime::JSContext;
use crate::script_runtime::{get_reports, CommonScriptMsg, Runtime, ScriptChan, ScriptPort}; use crate::script_runtime::{get_reports, CommonScriptMsg, Runtime, ScriptChan, ScriptPort};
use crate::task::TaskCanceller; use crate::task::TaskCanceller;
use crate::task_source::dom_manipulation::DOMManipulationTaskSource; use crate::task_source::dom_manipulation::DOMManipulationTaskSource;
@ -40,7 +40,7 @@ use crossbeam_channel::Receiver;
use devtools_traits::{DevtoolScriptControlMsg, WorkerId}; use devtools_traits::{DevtoolScriptControlMsg, WorkerId};
use dom_struct::dom_struct; use dom_struct::dom_struct;
use ipc_channel::ipc::IpcSender; use ipc_channel::ipc::IpcSender;
use js::jsapi::{JSAutoRealm, JSContext}; use js::jsapi::JSAutoRealm;
use js::jsval::UndefinedValue; use js::jsval::UndefinedValue;
use js::panic::maybe_resume_unwind; use js::panic::maybe_resume_unwind;
use js::rust::{HandleValue, ParentRuntime}; use js::rust::{HandleValue, ParentRuntime};
@ -165,8 +165,9 @@ impl WorkerGlobalScope {
&self.from_devtools_receiver &self.from_devtools_receiver
} }
pub fn get_cx(&self) -> *mut JSContext { #[allow(unsafe_code)]
self.runtime.cx() pub fn get_cx(&self) -> JSContext {
unsafe { JSContext::from_ptr(self.runtime.cx()) }
} }
pub fn is_closing(&self) -> bool { pub fn is_closing(&self) -> bool {
@ -292,7 +293,7 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope {
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout
fn SetTimeout( fn SetTimeout(
&self, &self,
_cx: SafeJSContext, _cx: JSContext,
callback: Rc<Function>, callback: Rc<Function>,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,
@ -308,7 +309,7 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope {
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout
fn SetTimeout_( fn SetTimeout_(
&self, &self,
_cx: SafeJSContext, _cx: JSContext,
callback: DOMString, callback: DOMString,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,
@ -330,7 +331,7 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope {
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval
fn SetInterval( fn SetInterval(
&self, &self,
_cx: SafeJSContext, _cx: JSContext,
callback: Rc<Function>, callback: Rc<Function>,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,
@ -346,7 +347,7 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope {
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval
fn SetInterval_( fn SetInterval_(
&self, &self,
_cx: SafeJSContext, _cx: JSContext,
callback: DOMString, callback: DOMString,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,
@ -477,7 +478,7 @@ impl WorkerGlobalScope {
CommonScriptMsg::CollectReports(reports_chan) => { CommonScriptMsg::CollectReports(reports_chan) => {
let cx = self.get_cx(); let cx = self.get_cx();
let path_seg = format!("url({})", self.get_url()); let path_seg = format!("url({})", self.get_url());
let reports = get_reports(cx, path_seg); let reports = get_reports(*cx, path_seg);
reports_chan.send(reports); reports_chan.send(reports);
}, },
} }

View file

@ -10,13 +10,13 @@ use crate::dom::paintworkletglobalscope::PaintWorkletTask;
use crate::dom::testworkletglobalscope::TestWorkletGlobalScope; use crate::dom::testworkletglobalscope::TestWorkletGlobalScope;
use crate::dom::testworkletglobalscope::TestWorkletTask; use crate::dom::testworkletglobalscope::TestWorkletTask;
use crate::dom::worklet::WorkletExecutor; use crate::dom::worklet::WorkletExecutor;
use crate::script_runtime::JSContext;
use crate::script_thread::MainThreadScriptMsg; use crate::script_thread::MainThreadScriptMsg;
use crossbeam_channel::Sender; use crossbeam_channel::Sender;
use devtools_traits::ScriptToDevtoolsControlMsg; use devtools_traits::ScriptToDevtoolsControlMsg;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use ipc_channel::ipc; use ipc_channel::ipc;
use ipc_channel::ipc::IpcSender; use ipc_channel::ipc::IpcSender;
use js::jsapi::JSContext;
use js::jsval::UndefinedValue; use js::jsval::UndefinedValue;
use js::rust::Runtime; use js::rust::Runtime;
use msg::constellation_msg::PipelineId; use msg::constellation_msg::PipelineId;
@ -83,14 +83,14 @@ impl WorkletGlobalScope {
} }
/// Get the JS context. /// Get the JS context.
pub fn get_cx(&self) -> *mut JSContext { pub fn get_cx(&self) -> JSContext {
self.globalscope.get_cx() self.globalscope.get_cx()
} }
/// Evaluate a JS script in this global. /// Evaluate a JS script in this global.
pub fn evaluate_js(&self, script: &str) -> bool { pub fn evaluate_js(&self, script: &str) -> bool {
debug!("Evaluating Dom."); debug!("Evaluating Dom.");
rooted!(in (self.globalscope.get_cx()) let mut rval = UndefinedValue()); rooted!(in (*self.globalscope.get_cx()) let mut rval = UndefinedValue());
self.globalscope self.globalscope
.evaluate_js_on_global_with_result(&*script, rval.handle_mut()) .evaluate_js_on_global_with_result(&*script, rval.handle_mut())
} }

View file

@ -119,10 +119,9 @@ impl XRRigidTransformMethods for XRRigidTransform {
}) })
} }
// https://immersive-web.github.io/webxr/#dom-xrrigidtransform-matrix // https://immersive-web.github.io/webxr/#dom-xrrigidtransform-matrix
#[allow(unsafe_code)]
fn Matrix(&self, _cx: JSContext) -> NonNull<JSObject> { fn Matrix(&self, _cx: JSContext) -> NonNull<JSObject> {
if self.matrix.get().is_null() { if self.matrix.get().is_null() {
let cx = unsafe { JSContext::from_ptr(self.global().get_cx()) }; let cx = self.global().get_cx();
// According to the spec all matrices are column-major, // According to the spec all matrices are column-major,
// however euclid uses row vectors so we use .to_row_major_array() // however euclid uses row vectors so we use .to_row_major_array()
let arr = self.transform.to_transform().to_row_major_array(); let arr = self.transform.to_transform().to_row_major_array();

View file

@ -40,7 +40,6 @@ impl XRView {
} }
} }
#[allow(unsafe_code)]
pub fn new<V: Copy>( pub fn new<V: Copy>(
global: &GlobalScope, global: &GlobalScope,
session: &XRSession, session: &XRSession,
@ -65,7 +64,7 @@ impl XRView {
// row_major since euclid uses row vectors // row_major since euclid uses row vectors
let proj = view.projection.to_row_major_array(); let proj = view.projection.to_row_major_array();
let cx = unsafe { JSContext::from_ptr(global.get_cx()) }; let cx = global.get_cx();
create_typed_array(cx, &proj, &ret.proj); create_typed_array(cx, &proj, &ret.proj);
ret ret
} }

View file

@ -57,10 +57,10 @@ impl XRViewerPose {
XRViewerPoseBinding::Wrap, XRViewerPoseBinding::Wrap,
); );
unsafe {
let cx = global.get_cx(); let cx = global.get_cx();
rooted!(in(cx) let mut jsval = UndefinedValue()); unsafe {
views.to_jsval(cx, jsval.handle_mut()); rooted!(in(*cx) let mut jsval = UndefinedValue());
views.to_jsval(*cx, jsval.handle_mut());
pose.views.set(jsval.get()); pose.views.set(jsval.get());
} }

View file

@ -115,7 +115,7 @@ impl XRWebGLLayer {
0, 0,
constants::RGBA, constants::RGBA,
constants::UNSIGNED_BYTE, constants::UNSIGNED_BYTE,
pixels.root(cx), pixels.root(*cx),
); );
// Bind the new texture to the framebuffer // Bind the new texture to the framebuffer

View file

@ -245,7 +245,7 @@ unsafe extern "C" fn promise_rejection_tracker(
let cx = target.global().get_cx(); let cx = target.global().get_cx();
let root_promise = trusted_promise.root(); let root_promise = trusted_promise.root();
rooted!(in(cx) let reason = GetPromiseResult(root_promise.reflector().get_jsobject())); rooted!(in(*cx) let reason = GetPromiseResult(root_promise.reflector().get_jsobject()));
let event = PromiseRejectionEvent::new( let event = PromiseRejectionEvent::new(
&target.global(), &target.global(),
@ -270,9 +270,8 @@ unsafe extern "C" fn promise_rejection_tracker(
#[allow(unsafe_code, unrooted_must_root)] #[allow(unsafe_code, unrooted_must_root)]
/// https://html.spec.whatwg.org/multipage/#notify-about-rejected-promises /// https://html.spec.whatwg.org/multipage/#notify-about-rejected-promises
pub fn notify_about_rejected_promises(global: &GlobalScope) { pub fn notify_about_rejected_promises(global: &GlobalScope) {
unsafe {
let cx = global.get_cx(); let cx = global.get_cx();
unsafe {
// Step 2. // Step 2.
if global.get_uncaught_rejections().borrow().len() > 0 { if global.get_uncaught_rejections().borrow().len() > 0 {
// Step 1. // Step 1.
@ -282,7 +281,7 @@ pub fn notify_about_rejected_promises(global: &GlobalScope) {
.iter() .iter()
.map(|promise| { .map(|promise| {
let promise = let promise =
Promise::new_with_js_promise(Handle::from_raw(promise.handle()), cx); Promise::new_with_js_promise(Handle::from_raw(promise.handle()), *cx);
TrustedPromise::new(promise) TrustedPromise::new(promise)
}) })
@ -309,7 +308,7 @@ pub fn notify_about_rejected_promises(global: &GlobalScope) {
} }
// Step 4-2. // Step 4-2.
rooted!(in(cx) let reason = GetPromiseResult(promise.reflector().get_jsobject())); rooted!(in(*cx) let reason = GetPromiseResult(promise.reflector().get_jsobject()));
let event = PromiseRejectionEvent::new( let event = PromiseRejectionEvent::new(
&target.global(), &target.global(),

View file

@ -70,7 +70,7 @@ use crate::dom::worklet::WorkletThreadPool;
use crate::dom::workletglobalscope::WorkletGlobalScopeInit; use crate::dom::workletglobalscope::WorkletGlobalScopeInit;
use crate::fetch::FetchCanceller; use crate::fetch::FetchCanceller;
use crate::microtask::{Microtask, MicrotaskQueue}; use crate::microtask::{Microtask, MicrotaskQueue};
use crate::script_runtime::{get_reports, new_rt_and_cx, Runtime, ScriptPort}; use crate::script_runtime::{get_reports, new_rt_and_cx, JSContext, Runtime, ScriptPort};
use crate::script_runtime::{CommonScriptMsg, ScriptChan, ScriptThreadEventCategory}; use crate::script_runtime::{CommonScriptMsg, ScriptChan, ScriptThreadEventCategory};
use crate::serviceworkerjob::{Job, JobQueue}; use crate::serviceworkerjob::{Job, JobQueue};
use crate::task_manager::TaskManager; use crate::task_manager::TaskManager;
@ -102,7 +102,7 @@ use hyper_serde::Serde;
use ipc_channel::ipc::{self, IpcSender}; use ipc_channel::ipc::{self, IpcSender};
use ipc_channel::router::ROUTER; use ipc_channel::router::ROUTER;
use js::glue::GetWindowProxyClass; use js::glue::GetWindowProxyClass;
use js::jsapi::{JSContext, JS_SetWrapObjectCallbacks}; use js::jsapi::JS_SetWrapObjectCallbacks;
use js::jsapi::{JSTracer, SetWindowProxyClass}; use js::jsapi::{JSTracer, SetWindowProxyClass};
use js::jsval::UndefinedValue; use js::jsval::UndefinedValue;
use js::rust::ParentRuntime; use js::rust::ParentRuntime;
@ -915,7 +915,7 @@ impl ScriptThread {
let script_thread = &*script_thread; let script_thread = &*script_thread;
script_thread script_thread
.microtask_queue .microtask_queue
.enqueue(task, script_thread.get_cx()); .enqueue(task, *script_thread.get_cx());
} }
} }
}); });
@ -1317,8 +1317,9 @@ impl ScriptThread {
} }
} }
pub fn get_cx(&self) -> *mut JSContext { #[allow(unsafe_code)]
self.js_runtime.cx() pub fn get_cx(&self) -> JSContext {
unsafe { JSContext::from_ptr(self.js_runtime.cx()) }
} }
/// Starts the script thread. After calling this method, the script thread will loop receiving /// Starts the script thread. After calling this method, the script thread will loop receiving
@ -2349,7 +2350,7 @@ impl ScriptThread {
let path_seg = format!("url({})", urls); let path_seg = format!("url({})", urls);
let mut reports = vec![]; let mut reports = vec![];
reports.extend(get_reports(self.get_cx(), path_seg)); reports.extend(get_reports(*self.get_cx(), path_seg));
reports_chan.send(reports); reports_chan.send(reports);
} }
@ -3540,13 +3541,13 @@ impl ScriptThread {
// Script source is ready to be evaluated (11.) // Script source is ready to be evaluated (11.)
let _ac = enter_realm(global_scope); let _ac = enter_realm(global_scope);
rooted!(in(global_scope.get_cx()) let mut jsval = UndefinedValue()); rooted!(in(*global_scope.get_cx()) let mut jsval = UndefinedValue());
global_scope.evaluate_js_on_global_with_result(&script_source, jsval.handle_mut()); global_scope.evaluate_js_on_global_with_result(&script_source, jsval.handle_mut());
load_data.js_eval_result = if jsval.get().is_string() { load_data.js_eval_result = if jsval.get().is_string() {
unsafe { unsafe {
let strval = DOMString::from_jsval( let strval = DOMString::from_jsval(
global_scope.get_cx(), *global_scope.get_cx(),
jsval.handle(), jsval.handle(),
StringificationBehavior::Empty, StringificationBehavior::Empty,
); );
@ -3776,7 +3777,7 @@ impl ScriptThread {
let script_thread = &*root.get().unwrap(); let script_thread = &*root.get().unwrap();
script_thread script_thread
.microtask_queue .microtask_queue
.enqueue(job, script_thread.get_cx()); .enqueue(job, *script_thread.get_cx());
}); });
} }
@ -3791,7 +3792,7 @@ impl ScriptThread {
unsafe { unsafe {
self.microtask_queue.checkpoint( self.microtask_queue.checkpoint(
self.get_cx(), *self.get_cx(),
|id| self.documents.borrow().find_global(id), |id| self.documents.borrow().find_global(id),
globals, globals,
) )

View file

@ -517,7 +517,7 @@ impl JsTimerTask {
InternalTimerCallback::StringTimerCallback(ref code_str) => { InternalTimerCallback::StringTimerCallback(ref code_str) => {
let global = this.global(); let global = this.global();
let cx = global.get_cx(); let cx = global.get_cx();
rooted!(in(cx) let mut rval = UndefinedValue()); rooted!(in(*cx) let mut rval = UndefinedValue());
global.evaluate_js_on_global_with_result(code_str, rval.handle_mut()); global.evaluate_js_on_global_with_result(code_str, rval.handle_mut());
}, },

View file

@ -145,11 +145,11 @@ pub fn handle_execute_script(
Some(window) => { Some(window) => {
let result = unsafe { let result = unsafe {
let cx = window.get_cx(); let cx = window.get_cx();
rooted!(in(cx) let mut rval = UndefinedValue()); rooted!(in(*cx) let mut rval = UndefinedValue());
window window
.upcast::<GlobalScope>() .upcast::<GlobalScope>()
.evaluate_js_on_global_with_result(&eval, rval.handle_mut()); .evaluate_js_on_global_with_result(&eval, rval.handle_mut());
jsval_to_webdriver(cx, rval.handle()) jsval_to_webdriver(*cx, rval.handle())
}; };
reply.send(result).unwrap(); reply.send(result).unwrap();
@ -171,7 +171,7 @@ pub fn handle_execute_async_script(
Some(window) => { Some(window) => {
let cx = window.get_cx(); let cx = window.get_cx();
window.set_webdriver_script_chan(Some(reply)); window.set_webdriver_script_chan(Some(reply));
rooted!(in(cx) let mut rval = UndefinedValue()); rooted!(in(*cx) let mut rval = UndefinedValue());
window window
.upcast::<GlobalScope>() .upcast::<GlobalScope>()
.evaluate_js_on_global_with_result(&eval, rval.handle_mut()); .evaluate_js_on_global_with_result(&eval, rval.handle_mut());
@ -725,21 +725,21 @@ pub fn handle_get_property(
Some(node) => { Some(node) => {
let cx = documents.find_document(pipeline).unwrap().window().get_cx(); let cx = documents.find_document(pipeline).unwrap().window().get_cx();
rooted!(in(cx) let mut property = UndefinedValue()); rooted!(in(*cx) let mut property = UndefinedValue());
match unsafe { match unsafe {
get_property_jsval( get_property_jsval(
cx, *cx,
node.reflector().get_jsobject(), node.reflector().get_jsobject(),
&name, &name,
property.handle_mut(), property.handle_mut(),
) )
} { } {
Ok(_) => match unsafe { jsval_to_webdriver(cx, property.handle()) } { Ok(_) => match unsafe { jsval_to_webdriver(*cx, property.handle()) } {
Ok(property) => Ok(property), Ok(property) => Ok(property),
Err(_) => Ok(WebDriverJSValue::Undefined), Err(_) => Ok(WebDriverJSValue::Undefined),
}, },
Err(error) => { Err(error) => {
unsafe { throw_dom_exception(cx, &node.reflector().global(), error) }; unsafe { throw_dom_exception(*cx, &node.reflector().global(), error) };
Ok(WebDriverJSValue::Undefined) Ok(WebDriverJSValue::Undefined)
}, },
} }