Auto merge of #23816 - marmeladema:issue-20377, r=jdm

Wrapping unsafe raw JSContext pointers in a safe struct. Part 1.

Wrapping unsafe raw JSContext pointers in a safe struct. Issue #20377.

---
<!-- Thank you for contributing to Servo! Please replace each `[ ]` by `[X]` when the step is complete, and replace `___` with appropriate data: -->
- [x] create a struct JSContext(*mut jsapi::JSContext) type
- [x] implement Deref for this new type so it's easy to obtain the inner context pointer
- [x] add an unsafe from_ptr static method that returns a new instance of the type
- [x] start by changing various Argument uses in CodegenRust.py for python classes that inherit from CGAbstractMethod
- [x] convert the python code that interacts with CGClass (CGCallback, CGCallbackFunction, CGCallbackFunctionImpl, CGCallbackInterface) and any rust code that interacts with it
- [x] update CGDictionary and any rust code that interacts with it
- [x] make the code generator declare trait methods that accept the new type instead of *mut JSContext (CGInterfaceTrait)
- [x] modify GlobalScope::get_cx to return a SafeJSContext

<!-- Also, please make sure that "Allow edits from maintainers" checkbox is checked, so that we can help you if you get stuck somewhere along the way.-->

<!-- Pull requests that do not address these steps are welcome, but they will require additional verification as part of the review process. -->

<!-- Reviewable:start -->
---
This change is [<img src="https://reviewable.io/review_button.svg" height="34" align="absmiddle" alt="Reviewable"/>](https://reviewable.io/reviews/servo/servo/23816)
<!-- Reviewable:end -->
This commit is contained in:
bors-servo 2019-07-24 11:54:47 -04:00 committed by GitHub
commit 9b14bbdc98
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
72 changed files with 974 additions and 1013 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

@ -47,7 +47,7 @@ fn main() {
let mut phf = File::create(&phf).unwrap(); let mut phf = File::create(&phf).unwrap();
write!( write!(
&mut phf, &mut phf,
"pub static MAP: phf::Map<&'static [u8], unsafe fn(*mut JSContext, HandleObject)> = " "pub static MAP: phf::Map<&'static [u8], unsafe fn(JSContext, HandleObject)> = "
) )
.unwrap(); .unwrap();
map.build(&mut phf).unwrap(); map.build(&mut phf).unwrap();

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

@ -13,6 +13,7 @@ use crate::dom::bindings::num::Finite;
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::window::Window; use crate::dom::window::Window;
use crate::script_runtime::JSContext as SafeJSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::JS_GetArrayBufferViewBuffer; use js::jsapi::JS_GetArrayBufferViewBuffer;
use js::jsapi::{Heap, JSContext, JSObject}; use js::jsapi::{Heap, JSContext, JSObject};
@ -172,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;
@ -230,22 +231,20 @@ impl AudioBufferMethods for AudioBuffer {
// https://webaudio.github.io/web-audio-api/#dom-audiobuffer-getchanneldata // https://webaudio.github.io/web-audio-api/#dom-audiobuffer-getchanneldata
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn GetChannelData( fn GetChannelData(&self, cx: SafeJSContext, channel: u32) -> Fallible<NonNull<JSObject>> {
&self,
cx: *mut JSContext,
channel: u32,
) -> Fallible<NonNull<JSObject>> {
if channel >= self.number_of_channels { if channel >= self.number_of_channels {
return Err(Error::IndexSize); return Err(Error::IndexSize);
} }
if !self.restore_js_channel_data(cx) { unsafe {
return Err(Error::JSFailed); if !self.restore_js_channel_data(*cx) {
} return Err(Error::JSFailed);
}
Ok(NonNull::new_unchecked( Ok(NonNull::new_unchecked(
self.js_channels.borrow()[channel as usize].get(), self.js_channels.borrow()[channel as usize].get(),
)) ))
}
} }
// https://webaudio.github.io/web-audio-api/#dom-audiobuffer-copyfromchannel // https://webaudio.github.io/web-audio-api/#dom-audiobuffer-copyfromchannel
@ -273,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]);
@ -308,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);
} }
@ -318,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

@ -13,6 +13,7 @@ use crate::dom::bindings::settings_stack::{AutoEntryScript, AutoIncumbentScript}
use crate::dom::bindings::utils::AsCCharPtrPtr; use crate::dom::bindings::utils::AsCCharPtrPtr;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::window::Window; use crate::dom::window::Window;
use crate::script_runtime::JSContext as SafeJSContext;
use js::jsapi::Heap; use js::jsapi::Heap;
use js::jsapi::JSAutoRealm; use js::jsapi::JSAutoRealm;
use js::jsapi::{AddRawValueRoot, IsCallable, JSContext, JSObject}; use js::jsapi::{AddRawValueRoot, IsCallable, JSContext, JSObject};
@ -112,7 +113,7 @@ impl PartialEq for CallbackObject {
/// callback interface types. /// callback interface types.
pub trait CallbackContainer { pub trait CallbackContainer {
/// Create a new CallbackContainer object for the given `JSObject`. /// Create a new CallbackContainer object for the given `JSObject`.
unsafe fn new(cx: *mut JSContext, callback: *mut JSObject) -> Rc<Self>; unsafe fn new(cx: SafeJSContext, callback: *mut JSObject) -> Rc<Self>;
/// Returns the underlying `CallbackObject`. /// Returns the underlying `CallbackObject`.
fn callback_holder(&self) -> &CallbackObject; fn callback_holder(&self) -> &CallbackObject;
/// Returns the underlying `JSObject`. /// Returns the underlying `JSObject`.
@ -151,8 +152,8 @@ impl CallbackFunction {
/// Initialize the callback function with a value. /// Initialize the callback function with a value.
/// Should be called once this object is done moving. /// Should be called once this object is done moving.
pub unsafe fn init(&mut self, cx: *mut JSContext, callback: *mut JSObject) { pub unsafe fn init(&mut self, cx: SafeJSContext, callback: *mut JSObject) {
self.object.init(cx, callback); self.object.init(*cx, callback);
} }
} }
@ -178,8 +179,8 @@ impl CallbackInterface {
/// Initialize the callback function with a value. /// Initialize the callback function with a value.
/// Should be called once this object is done moving. /// Should be called once this object is done moving.
pub unsafe fn init(&mut self, cx: *mut JSContext, callback: *mut JSObject) { pub unsafe fn init(&mut self, cx: SafeJSContext, callback: *mut JSObject) {
self.object.init(cx, callback); self.object.init(*cx, callback);
} }
/// Returns the property with the given `name`, if it is a callable object, /// Returns the property with the given `name`, if it is a callable object,
@ -254,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,

File diff suppressed because it is too large Load diff

View file

@ -76,6 +76,7 @@ use crate::dom::customelementregistry::{ConstructionStackEntry, CustomElementSta
use crate::dom::element::{Element, ElementCreator}; use crate::dom::element::{Element, ElementCreator};
use crate::dom::htmlelement::HTMLElement; use crate::dom::htmlelement::HTMLElement;
use crate::dom::window::Window; use crate::dom::window::Window;
use crate::script_runtime::JSContext as SafeJSContext;
use crate::script_thread::ScriptThread; use crate::script_thread::ScriptThread;
use html5ever::interface::QualName; use html5ever::interface::QualName;
use html5ever::LocalName; use html5ever::LocalName;
@ -99,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 => {
@ -109,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
@ -133,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(),
); );
@ -201,7 +202,7 @@ pub fn get_constructor_object_from_local_name(
) -> bool { ) -> bool {
macro_rules! get_constructor( macro_rules! get_constructor(
($binding:ident) => ({ ($binding:ident) => ({
unsafe { $binding::GetConstructorObject(cx, global, rval); } unsafe { $binding::GetConstructorObject(SafeJSContext::from_ptr(cx), global, rval); }
true true
}) })
); );

View file

@ -13,6 +13,7 @@ use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::trace::{JSTraceable, RootedTraceableBox}; use crate::dom::bindings::trace::{JSTraceable, RootedTraceableBox};
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::JSContext as SafeJSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::conversions::ToJSValConvertible; use js::conversions::ToJSValConvertible;
use js::jsapi::{Heap, JSContext, JSObject}; use js::jsapi::{Heap, JSContext, JSObject};
@ -62,7 +63,7 @@ impl<T: DomObject + JSTraceable + Iterable> IterableIterator<T> {
pub fn new( pub fn new(
iterable: &T, iterable: &T,
type_: IteratorType, type_: IteratorType,
wrap: unsafe fn(*mut JSContext, &GlobalScope, Box<IterableIterator<T>>) -> DomRoot<Self>, wrap: unsafe fn(SafeJSContext, &GlobalScope, Box<IterableIterator<T>>) -> DomRoot<Self>,
) -> DomRoot<Self> { ) -> DomRoot<Self> {
let iterator = Box::new(IterableIterator { let iterator = Box::new(IterableIterator {
reflector: Reflector::new(), reflector: Reflector::new(),
@ -75,41 +76,41 @@ impl<T: DomObject + JSTraceable + Iterable> IterableIterator<T> {
/// Return the next value from the iterable object. /// Return the next value from the iterable object.
#[allow(non_snake_case)] #[allow(non_snake_case)]
pub fn Next(&self, cx: *mut JSContext) -> Fallible<NonNull<JSObject>> { pub fn Next(&self, cx: SafeJSContext) -> Fallible<NonNull<JSObject>> {
let index = self.index.get(); let index = self.index.get();
rooted!(in(cx) let mut value = UndefinedValue()); rooted!(in(*cx) let mut value = UndefinedValue());
rooted!(in(cx) let mut rval = ptr::null_mut::<JSObject>()); rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>());
let result = if index >= self.iterable.get_iterable_length() { let result = if index >= self.iterable.get_iterable_length() {
dict_return(cx, rval.handle_mut(), true, value.handle()) dict_return(*cx, rval.handle_mut(), true, value.handle())
} else { } else {
match self.type_ { match self.type_ {
IteratorType::Keys => { IteratorType::Keys => {
unsafe { unsafe {
self.iterable self.iterable
.get_key_at_index(index) .get_key_at_index(index)
.to_jsval(cx, value.handle_mut()); .to_jsval(*cx, value.handle_mut());
} }
dict_return(cx, rval.handle_mut(), false, value.handle()) dict_return(*cx, rval.handle_mut(), false, value.handle())
}, },
IteratorType::Values => { IteratorType::Values => {
unsafe { unsafe {
self.iterable self.iterable
.get_value_at_index(index) .get_value_at_index(index)
.to_jsval(cx, value.handle_mut()); .to_jsval(*cx, value.handle_mut());
} }
dict_return(cx, rval.handle_mut(), false, value.handle()) dict_return(*cx, rval.handle_mut(), false, value.handle())
}, },
IteratorType::Entries => { IteratorType::Entries => {
rooted!(in(cx) let mut key = UndefinedValue()); rooted!(in(*cx) let mut key = UndefinedValue());
unsafe { unsafe {
self.iterable self.iterable
.get_key_at_index(index) .get_key_at_index(index)
.to_jsval(cx, key.handle_mut()); .to_jsval(*cx, key.handle_mut());
self.iterable self.iterable
.get_value_at_index(index) .get_value_at_index(index)
.to_jsval(cx, value.handle_mut()); .to_jsval(*cx, value.handle_mut());
} }
key_and_value_return(cx, rval.handle_mut(), key.handle(), value.handle()) key_and_value_return(*cx, rval.handle_mut(), key.handle(), value.handle())
}, },
} }
}; };

View file

@ -7,7 +7,8 @@
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 js::jsapi::{Heap, JSContext, JSObject}; use crate::script_runtime::JSContext;
use js::jsapi::{Heap, JSObject};
use js::rust::HandleObject; use js::rust::HandleObject;
use std::default::Default; use std::default::Default;
@ -16,7 +17,7 @@ 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(*mut JSContext, &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,

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

@ -13,6 +13,7 @@ use crate::dom::bindings::inheritance::TopTypeId;
use crate::dom::bindings::str::DOMString; use crate::dom::bindings::str::DOMString;
use crate::dom::bindings::trace::trace_object; use crate::dom::bindings::trace::trace_object;
use crate::dom::windowproxy; use crate::dom::windowproxy;
use crate::script_runtime::JSContext as SafeJSContext;
use js::glue::{CallJitGetterOp, CallJitMethodOp, CallJitSetterOp, IsWrapper}; use js::glue::{CallJitGetterOp, CallJitMethodOp, CallJitSetterOp, IsWrapper};
use js::glue::{GetCrossCompartmentWrapper, JS_GetReservedSlot, WrapperNew}; use js::glue::{GetCrossCompartmentWrapper, JS_GetReservedSlot, WrapperNew};
use js::glue::{UnwrapObjectDynamic, RUST_JSID_TO_INT, RUST_JSID_TO_STRING}; use js::glue::{UnwrapObjectDynamic, RUST_JSID_TO_INT, RUST_JSID_TO_STRING};
@ -353,7 +354,7 @@ pub unsafe extern "C" fn enumerate_global(
return false; return false;
} }
for init_fun in InterfaceObjectMap::MAP.values() { for init_fun in InterfaceObjectMap::MAP.values() {
init_fun(cx, Handle::from_raw(obj)); init_fun(SafeJSContext::from_ptr(cx), Handle::from_raw(obj));
} }
true true
} }
@ -388,7 +389,7 @@ pub unsafe extern "C" fn resolve_global(
let bytes = slice::from_raw_parts(ptr, length as usize); let bytes = slice::from_raw_parts(ptr, length as usize);
if let Some(init_fun) = InterfaceObjectMap::MAP.get(bytes) { if let Some(init_fun) = InterfaceObjectMap::MAP.get(bytes) {
init_fun(cx, Handle::from_raw(obj)); init_fun(SafeJSContext::from_ptr(cx), Handle::from_raw(obj));
*rval = true; *rval = true;
} else { } else {
*rval = false; *rval = false;

View file

@ -30,6 +30,7 @@ use crate::dom::eventtarget::EventTarget;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::permissions::{get_descriptor_permission_state, PermissionAlgorithm}; use crate::dom::permissions::{get_descriptor_permission_state, PermissionAlgorithm};
use crate::dom::promise::Promise; use crate::dom::promise::Promise;
use crate::script_runtime::JSContext as SafeJSContext;
use crate::task::TaskOnce; use crate::task::TaskOnce;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use ipc_channel::ipc::{self, IpcSender}; use ipc_channel::ipc::{self, IpcSender};
@ -625,7 +626,8 @@ impl PermissionAlgorithm for Bluetooth {
.handle_mut() .handle_mut()
.set(ObjectValue(permission_descriptor_obj)); .set(ObjectValue(permission_descriptor_obj));
unsafe { unsafe {
match BluetoothPermissionDescriptor::new(cx, property.handle()) { match BluetoothPermissionDescriptor::new(SafeJSContext::from_ptr(cx), property.handle())
{
Ok(ConversionResult::Success(descriptor)) => Ok(descriptor), Ok(ConversionResult::Success(descriptor)) => Ok(descriptor),
Ok(ConversionResult::Failure(error)) => Err(Error::Type(error.into_owned())), Ok(ConversionResult::Failure(error)) => Err(Error::Type(error.into_owned())),
Err(_) => Err(Error::Type(String::from(BT_DESC_CONVERSION_ERROR))), Err(_) => Err(Error::Type(String::from(BT_DESC_CONVERSION_ERROR))),

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

@ -9,9 +9,10 @@ use crate::dom::bindings::error::{Error, Fallible};
use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::reflector::{reflect_dom_object, 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;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::JSObject;
use js::jsapi::Type; use js::jsapi::Type;
use js::jsapi::{JSContext, JSObject};
use js::rust::CustomAutoRooterGuard; use js::rust::CustomAutoRooterGuard;
use js::typedarray::ArrayBufferView; use js::typedarray::ArrayBufferView;
use servo_rand::{Rng, ServoRng}; use servo_rand::{Rng, ServoRng};
@ -47,9 +48,9 @@ impl Crypto {
impl CryptoMethods for Crypto { impl CryptoMethods for Crypto {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#Crypto-method-getRandomValues // https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#Crypto-method-getRandomValues
unsafe fn GetRandomValues( fn GetRandomValues(
&self, &self,
_cx: *mut JSContext, _cx: JSContext,
mut input: CustomAutoRooterGuard<ArrayBufferView>, mut input: CustomAutoRooterGuard<ArrayBufferView>,
) -> Fallible<NonNull<JSObject>> { ) -> Fallible<NonNull<JSObject>> {
let array_type = input.get_array_type(); let array_type = input.get_array_type();
@ -57,14 +58,14 @@ impl CryptoMethods for Crypto {
if !is_integer_buffer(array_type) { if !is_integer_buffer(array_type) {
return Err(Error::TypeMismatch); return Err(Error::TypeMismatch);
} else { } else {
let mut data = input.as_mut_slice(); let mut data = unsafe { input.as_mut_slice() };
if data.len() > 65536 { if data.len() > 65536 {
return Err(Error::QuotaExceeded); return Err(Error::QuotaExceeded);
} }
self.rng.borrow_mut().fill_bytes(&mut data); self.rng.borrow_mut().fill_bytes(&mut data);
} }
Ok(NonNull::new_unchecked(*input.underlying_object())) unsafe { Ok(NonNull::new_unchecked(*input.underlying_object())) }
} }
} }

View file

@ -31,6 +31,7 @@ use crate::dom::node::{document_from_node, window_from_node, Node, ShadowIncludi
use crate::dom::promise::Promise; use crate::dom::promise::Promise;
use crate::dom::window::Window; use crate::dom::window::Window;
use crate::microtask::Microtask; use crate::microtask::Microtask;
use crate::script_runtime::JSContext as SafeJSContext;
use crate::script_thread::ScriptThread; use crate::script_thread::ScriptThread;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use html5ever::{LocalName, Namespace, Prefix}; use html5ever::{LocalName, Namespace, Prefix};
@ -144,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,
@ -170,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",
)?,
}) })
} }
@ -182,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(),
@ -200,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,
) )
@ -238,7 +243,10 @@ unsafe fn get_callback(
if !callback.is_object() || !IsCallable(callback.to_object()) { if !callback.is_object() || !IsCallable(callback.to_object()) {
return Err(Error::Type("Lifecycle callback is not callable".to_owned())); return Err(Error::Type("Lifecycle callback is not callable".to_owned()));
} }
Ok(Some(Function::new(cx, callback.to_object()))) Ok(Some(Function::new(
SafeJSContext::from_ptr(cx),
callback.to_object(),
)))
} else { } else {
Ok(None) Ok(None)
} }
@ -254,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.
@ -322,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);
@ -332,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) => {
@ -346,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) => {
@ -401,13 +409,13 @@ impl CustomElementRegistryMethods for CustomElementRegistry {
/// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-get> /// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-get>
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn Get(&self, cx: *mut JSContext, name: DOMString) -> JSVal { fn Get(&self, cx: SafeJSContext, name: DOMString) -> JSVal {
match self.definitions.borrow().get(&LocalName::from(&*name)) { match self.definitions.borrow().get(&LocalName::from(&*name)) {
Some(definition) => { Some(definition) => unsafe {
rooted!(in(cx) let mut constructor = UndefinedValue()); rooted!(in(*cx) let mut constructor = UndefinedValue());
definition definition
.constructor .constructor
.to_jsval(cx, constructor.handle_mut()); .to_jsval(*cx, constructor.handle_mut());
constructor.get() constructor.get()
}, },
None => UndefinedValue(), None => UndefinedValue(),
@ -519,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(
@ -623,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;
} }
@ -645,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(),
@ -668,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,
@ -859,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

@ -13,8 +13,9 @@ use crate::dom::bindings::str::DOMString;
use crate::dom::bindings::trace::RootedTraceableBox; use crate::dom::bindings::trace::RootedTraceableBox;
use crate::dom::event::Event; use crate::dom::event::Event;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext}; use js::jsapi::Heap;
use js::jsval::JSVal; use js::jsval::JSVal;
use js::rust::HandleValue; use js::rust::HandleValue;
use servo_atoms::Atom; use servo_atoms::Atom;
@ -87,17 +88,15 @@ impl CustomEvent {
} }
impl CustomEventMethods for CustomEvent { impl CustomEventMethods for CustomEvent {
#[allow(unsafe_code)]
// https://dom.spec.whatwg.org/#dom-customevent-detail // https://dom.spec.whatwg.org/#dom-customevent-detail
unsafe fn Detail(&self, _cx: *mut JSContext) -> JSVal { fn Detail(&self, _cx: JSContext) -> JSVal {
self.detail.get() self.detail.get()
} }
#[allow(unsafe_code)]
// https://dom.spec.whatwg.org/#dom-customevent-initcustomevent // https://dom.spec.whatwg.org/#dom-customevent-initcustomevent
unsafe fn InitCustomEvent( fn InitCustomEvent(
&self, &self,
_cx: *mut JSContext, _cx: JSContext,
type_: DOMString, type_: DOMString,
can_bubble: bool, can_bubble: bool,
cancelable: bool, cancelable: bool,

View file

@ -26,7 +26,9 @@ use crate::dom::worker::{TrustedWorkerAddress, Worker};
use crate::dom::workerglobalscope::WorkerGlobalScope; use crate::dom::workerglobalscope::WorkerGlobalScope;
use crate::fetch::load_whole_resource; use crate::fetch::load_whole_resource;
use crate::script_runtime::ScriptThreadEventCategory::WorkerEvent; use crate::script_runtime::ScriptThreadEventCategory::WorkerEvent;
use crate::script_runtime::{new_child_runtime, CommonScriptMsg, Runtime, ScriptChan, ScriptPort}; use crate::script_runtime::{
new_child_runtime, CommonScriptMsg, JSContext as SafeJSContext, Runtime, ScriptChan, ScriptPort,
};
use crate::task_queue::{QueuedTask, QueuedTaskConversion, TaskQueue}; use crate::task_queue::{QueuedTask, QueuedTaskConversion, TaskQueue};
use crate::task_source::TaskSourceName; use crate::task_source::TaskSourceName;
use crossbeam_channel::{unbounded, Receiver, Sender}; use crossbeam_channel::{unbounded, Receiver, Sender};
@ -283,7 +285,7 @@ impl DedicatedWorkerGlobalScope {
closing, closing,
image_cache, image_cache,
)); ));
unsafe { DedicatedWorkerGlobalScopeBinding::Wrap(cx, scope) } unsafe { DedicatedWorkerGlobalScopeBinding::Wrap(SafeJSContext::from_ptr(cx), scope) }
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
@ -403,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() {
@ -464,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);
}, },
@ -558,10 +560,9 @@ unsafe extern "C" fn interrupt_callback(cx: *mut JSContext) -> bool {
} }
impl DedicatedWorkerGlobalScopeMethods for DedicatedWorkerGlobalScope { impl DedicatedWorkerGlobalScopeMethods for DedicatedWorkerGlobalScope {
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-dedicatedworkerglobalscope-postmessage // https://html.spec.whatwg.org/multipage/#dom-dedicatedworkerglobalscope-postmessage
unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { fn PostMessage(&self, cx: SafeJSContext, message: HandleValue) -> ErrorResult {
let data = StructuredCloneData::write(cx, message)?; let data = StructuredCloneData::write(*cx, message)?;
let worker = self.worker.borrow().as_ref().unwrap().clone(); let worker = self.worker.borrow().as_ref().unwrap().clone();
let pipeline_id = self.upcast::<GlobalScope>().pipeline_id(); let pipeline_id = self.upcast::<GlobalScope>().pipeline_id();
let task = Box::new(task!(post_worker_message: move || { let task = Box::new(task!(post_worker_message: move || {

View file

@ -11,9 +11,9 @@ use crate::dom::bindings::structuredclone::StructuredCloneData;
use crate::dom::dissimilaroriginlocation::DissimilarOriginLocation; use crate::dom::dissimilaroriginlocation::DissimilarOriginLocation;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::windowproxy::WindowProxy; use crate::dom::windowproxy::WindowProxy;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use ipc_channel::ipc; use ipc_channel::ipc;
use js::jsapi::JSContext;
use js::jsval::{JSVal, UndefinedValue}; use js::jsval::{JSVal, UndefinedValue};
use js::rust::HandleValue; use js::rust::HandleValue;
use msg::constellation_msg::PipelineId; use msg::constellation_msg::PipelineId;
@ -133,14 +133,8 @@ impl DissimilarOriginWindowMethods for DissimilarOriginWindow {
false false
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-window-postmessage // https://html.spec.whatwg.org/multipage/#dom-window-postmessage
unsafe fn PostMessage( fn PostMessage(&self, cx: JSContext, message: HandleValue, origin: DOMString) -> ErrorResult {
&self,
cx: *mut JSContext,
message: HandleValue,
origin: DOMString,
) -> ErrorResult {
// Step 3-5. // Step 3-5.
let origin = match &origin[..] { let origin = match &origin[..] {
"*" => None, "*" => None,
@ -156,23 +150,21 @@ impl DissimilarOriginWindowMethods for DissimilarOriginWindow {
// Step 1-2, 6-8. // Step 1-2, 6-8.
// TODO(#12717): Should implement the `transfer` argument. // TODO(#12717): Should implement the `transfer` argument.
let data = StructuredCloneData::write(cx, message)?; let data = StructuredCloneData::write(*cx, message)?;
// Step 9. // Step 9.
self.post_message(origin, data); self.post_message(origin, data);
Ok(()) Ok(())
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-opener // https://html.spec.whatwg.org/multipage/#dom-opener
unsafe fn Opener(&self, _: *mut JSContext) -> JSVal { fn Opener(&self, _: JSContext) -> JSVal {
// TODO: Implement x-origin opener // TODO: Implement x-origin opener
UndefinedValue() UndefinedValue()
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-opener // https://html.spec.whatwg.org/multipage/#dom-opener
unsafe fn SetOpener(&self, _: *mut JSContext, _: HandleValue) { fn SetOpener(&self, _: JSContext, _: HandleValue) {
// TODO: Implement x-origin opener // TODO: Implement x-origin opener
} }

View file

@ -102,6 +102,7 @@ use crate::dom::wheelevent::WheelEvent;
use crate::dom::window::{ReflowReason, Window}; use crate::dom::window::{ReflowReason, Window};
use crate::dom::windowproxy::WindowProxy; use crate::dom::windowproxy::WindowProxy;
use crate::fetch::FetchCanceller; use crate::fetch::FetchCanceller;
use crate::script_runtime::JSContext;
use crate::script_runtime::{CommonScriptMsg, ScriptThreadEventCategory}; use crate::script_runtime::{CommonScriptMsg, ScriptThreadEventCategory};
use crate::script_thread::{MainThreadScriptMsg, ScriptThread}; use crate::script_thread::{MainThreadScriptMsg, ScriptThread};
use crate::stylesheet_set::StylesheetSetRef; use crate::stylesheet_set::StylesheetSetRef;
@ -117,7 +118,7 @@ use euclid::default::Point2D;
use html5ever::{LocalName, Namespace, QualName}; use html5ever::{LocalName, Namespace, QualName};
use hyper_serde::Serde; use hyper_serde::Serde;
use ipc_channel::ipc::{self, IpcSender}; use ipc_channel::ipc::{self, IpcSender};
use js::jsapi::{JSContext, JSObject, JSRuntime}; use js::jsapi::{JSObject, JSRuntime};
use keyboard_types::{Key, KeyState, Modifiers}; use keyboard_types::{Key, KeyState, Modifiers};
use metrics::{ use metrics::{
InteractiveFlag, InteractiveMetrics, InteractiveWindow, ProfilerMetadataFactory, InteractiveFlag, InteractiveMetrics, InteractiveWindow, ProfilerMetadataFactory,
@ -4218,11 +4219,7 @@ impl DocumentMethods for Document {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-tree-accessors:dom-document-nameditem-filter // https://html.spec.whatwg.org/multipage/#dom-tree-accessors:dom-document-nameditem-filter
unsafe fn NamedGetter( fn NamedGetter(&self, _cx: JSContext, name: DOMString) -> Option<NonNull<JSObject>> {
&self,
_cx: *mut JSContext,
name: DOMString,
) -> Option<NonNull<JSObject>> {
#[derive(JSTraceable, MallocSizeOf)] #[derive(JSTraceable, MallocSizeOf)]
struct NamedElementFilter { struct NamedElementFilter {
name: Atom, name: Atom,
@ -4270,7 +4267,7 @@ impl DocumentMethods for Document {
} }
let name = Atom::from(name); let name = Atom::from(name);
let root = self.upcast::<Node>(); let root = self.upcast::<Node>();
{ unsafe {
// Step 1. // Step 1.
let mut elements = root let mut elements = root
.traverse_preorder(ShadowIncluding::No) .traverse_preorder(ShadowIncluding::No)
@ -4291,9 +4288,11 @@ impl DocumentMethods for Document {
// Step 4. // Step 4.
let filter = NamedElementFilter { name: name }; let filter = NamedElementFilter { name: name };
let collection = HTMLCollection::create(self.window(), root, Box::new(filter)); let collection = HTMLCollection::create(self.window(), root, Box::new(filter));
Some(NonNull::new_unchecked( unsafe {
collection.reflector().get_jsobject().get(), Some(NonNull::new_unchecked(
)) collection.reflector().get_jsobject().get(),
))
}
} }
// https://html.spec.whatwg.org/multipage/#dom-tree-accessors:supported-property-names // https://html.spec.whatwg.org/multipage/#dom-tree-accessors:supported-property-names

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

@ -18,10 +18,11 @@ use crate::dom::dommatrix::DOMMatrix;
use crate::dom::dompoint::DOMPoint; use crate::dom::dompoint::DOMPoint;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::window::Window; use crate::dom::window::Window;
use crate::script_runtime::JSContext;
use cssparser::{Parser, ParserInput}; use cssparser::{Parser, ParserInput};
use dom_struct::dom_struct; use dom_struct::dom_struct;
use euclid::{default::Transform3D, Angle}; use euclid::{default::Transform3D, Angle};
use js::jsapi::{JSContext, JSObject}; use js::jsapi::JSObject;
use js::rust::CustomAutoRooterGuard; use js::rust::CustomAutoRooterGuard;
use js::typedarray::CreateWith; use js::typedarray::CreateWith;
use js::typedarray::{Float32Array, Float64Array}; use js::typedarray::{Float32Array, Float64Array};
@ -667,7 +668,7 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly {
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-tofloat32array // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-tofloat32array
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn ToFloat32Array(&self, cx: *mut JSContext) -> NonNull<JSObject> { fn ToFloat32Array(&self, cx: JSContext) -> NonNull<JSObject> {
let vec: Vec<f32> = self let vec: Vec<f32> = self
.matrix .matrix
.borrow() .borrow()
@ -675,18 +676,22 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly {
.iter() .iter()
.map(|&x| x as f32) .map(|&x| x as f32)
.collect(); .collect();
rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); unsafe {
let _ = Float32Array::create(cx, CreateWith::Slice(&vec), array.handle_mut()).unwrap(); rooted!(in (*cx) let mut array = ptr::null_mut::<JSObject>());
NonNull::new_unchecked(array.get()) let _ = Float32Array::create(*cx, CreateWith::Slice(&vec), array.handle_mut()).unwrap();
NonNull::new_unchecked(array.get())
}
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-tofloat64array // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-tofloat64array
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn ToFloat64Array(&self, cx: *mut JSContext) -> NonNull<JSObject> { fn ToFloat64Array(&self, cx: JSContext) -> NonNull<JSObject> {
let arr = self.matrix.borrow().to_row_major_array(); let arr = self.matrix.borrow().to_row_major_array();
rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); unsafe {
let _ = Float64Array::create(cx, CreateWith::Slice(&arr), array.handle_mut()).unwrap(); rooted!(in (*cx) let mut array = ptr::null_mut::<JSObject>());
NonNull::new_unchecked(array.get()) let _ = Float64Array::create(*cx, CreateWith::Slice(&arr), array.handle_mut()).unwrap();
NonNull::new_unchecked(array.get())
}
} }
} }

View file

@ -14,8 +14,9 @@ use crate::dom::bindings::str::DOMString;
use crate::dom::bindings::trace::RootedTraceableBox; use crate::dom::bindings::trace::RootedTraceableBox;
use crate::dom::event::{Event, EventBubbles, EventCancelable}; use crate::dom::event::{Event, EventBubbles, EventCancelable};
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext}; use js::jsapi::Heap;
use js::jsval::JSVal; use js::jsval::JSVal;
use js::rust::HandleValue; use js::rust::HandleValue;
use servo_atoms::Atom; use servo_atoms::Atom;
@ -135,9 +136,8 @@ impl ErrorEventMethods for ErrorEvent {
self.filename.borrow().clone() self.filename.borrow().clone()
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-errorevent-error // https://html.spec.whatwg.org/multipage/#dom-errorevent-error
unsafe fn Error(&self, _cx: *mut JSContext) -> JSVal { fn Error(&self, _cx: JSContext) -> JSVal {
self.error.get() self.error.get()
} }

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

@ -150,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,
@ -168,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(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()),
@ -180,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
{ {
@ -225,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
@ -502,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(),
@ -529,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;

View file

@ -11,8 +11,8 @@ use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString; use crate::dom::bindings::str::DOMString;
use crate::dom::event::Event; use crate::dom::event::Event;
use crate::dom::serviceworkerglobalscope::ServiceWorkerGlobalScope; use crate::dom::serviceworkerglobalscope::ServiceWorkerGlobalScope;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::JSContext;
use js::rust::HandleValue; use js::rust::HandleValue;
use servo_atoms::Atom; use servo_atoms::Atom;
@ -62,7 +62,7 @@ impl ExtendableEvent {
} }
// https://w3c.github.io/ServiceWorker/#wait-until-method // https://w3c.github.io/ServiceWorker/#wait-until-method
pub fn WaitUntil(&self, _cx: *mut JSContext, _val: HandleValue) -> ErrorResult { pub fn WaitUntil(&self, _cx: JSContext, _val: HandleValue) -> ErrorResult {
// Step 1 // Step 1
if !self.extensions_allowed { if !self.extensions_allowed {
return Err(Error::InvalidState); return Err(Error::InvalidState);

View file

@ -15,8 +15,9 @@ use crate::dom::eventtarget::EventTarget;
use crate::dom::extendableevent::ExtendableEvent; use crate::dom::extendableevent::ExtendableEvent;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::serviceworkerglobalscope::ServiceWorkerGlobalScope; use crate::dom::serviceworkerglobalscope::ServiceWorkerGlobalScope;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext}; use js::jsapi::Heap;
use js::jsval::JSVal; use js::jsval::JSVal;
use js::rust::HandleValue; use js::rust::HandleValue;
use servo_atoms::Atom; use servo_atoms::Atom;
@ -91,9 +92,8 @@ impl ExtendableMessageEvent {
} }
impl ExtendableMessageEventMethods for ExtendableMessageEvent { impl ExtendableMessageEventMethods for ExtendableMessageEvent {
#[allow(unsafe_code)]
// https://w3c.github.io/ServiceWorker/#extendablemessage-event-data-attribute // https://w3c.github.io/ServiceWorker/#extendablemessage-event-data-attribute
unsafe fn Data(&self, _cx: *mut JSContext) -> JSVal { fn Data(&self, _cx: JSContext) -> JSVal {
self.data.get() self.data.get()
} }

View file

@ -22,6 +22,7 @@ use crate::dom::event::{Event, EventBubbles, EventCancelable};
use crate::dom::eventtarget::EventTarget; use crate::dom::eventtarget::EventTarget;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::progressevent::ProgressEvent; use crate::dom::progressevent::ProgressEvent;
use crate::script_runtime::JSContext as SafeJSContext;
use crate::task::TaskCanceller; use crate::task::TaskCanceller;
use crate::task_source::file_reading::{FileReadingTask, FileReadingTaskSource}; use crate::task_source::file_reading::{FileReadingTask, FileReadingTaskSource};
use crate::task_source::{TaskSource, TaskSourceName}; use crate::task_source::{TaskSource, TaskSourceName};
@ -265,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,
) )
@ -391,12 +392,14 @@ impl FileReaderMethods for FileReader {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://w3c.github.io/FileAPI/#dfn-result // https://w3c.github.io/FileAPI/#dfn-result
unsafe fn GetResult(&self, _: *mut JSContext) -> Option<StringOrObject> { fn GetResult(&self, _: SafeJSContext) -> Option<StringOrObject> {
self.result.borrow().as_ref().map(|r| match *r { self.result.borrow().as_ref().map(|r| match *r {
FileReaderResult::String(ref string) => StringOrObject::String(string.clone()), FileReaderResult::String(ref string) => StringOrObject::String(string.clone()),
FileReaderResult::ArrayBuffer(ref arr_buffer) => { FileReaderResult::ArrayBuffer(ref arr_buffer) => {
let result = RootedTraceableBox::new(Heap::default()); let result = RootedTraceableBox::new(Heap::default());
result.set((*arr_buffer.ptr.get()).to_object()); unsafe {
result.set((*arr_buffer.ptr.get()).to_object());
}
StringOrObject::Object(result) StringOrObject::Object(result)
}, },
}) })

View file

@ -13,8 +13,9 @@ use crate::dom::bindings::str::DOMString;
use crate::dom::blob::Blob; use crate::dom::blob::Blob;
use crate::dom::filereader::FileReaderSharedFunctionality; use crate::dom::filereader::FileReaderSharedFunctionality;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{JSContext, JSObject}; use js::jsapi::JSObject;
use js::typedarray::{ArrayBuffer, CreateWith}; use js::typedarray::{ArrayBuffer, CreateWith};
use std::ptr; use std::ptr;
use std::ptr::NonNull; use std::ptr::NonNull;
@ -87,23 +88,21 @@ impl FileReaderSyncMethods for FileReaderSync {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://w3c.github.io/FileAPI/#readAsArrayBufferSyncSection // https://w3c.github.io/FileAPI/#readAsArrayBufferSyncSection
unsafe fn ReadAsArrayBuffer( fn ReadAsArrayBuffer(&self, cx: JSContext, blob: &Blob) -> Fallible<NonNull<JSObject>> {
&self,
cx: *mut JSContext,
blob: &Blob,
) -> Fallible<NonNull<JSObject>> {
// step 1 // step 1
let blob_contents = FileReaderSync::get_blob_bytes(blob)?; let blob_contents = FileReaderSync::get_blob_bytes(blob)?;
// step 2 // step 2
rooted!(in(cx) let mut array_buffer = ptr::null_mut::<JSObject>()); unsafe {
assert!(ArrayBuffer::create( rooted!(in(*cx) let mut array_buffer = ptr::null_mut::<JSObject>());
cx, assert!(ArrayBuffer::create(
CreateWith::Slice(&blob_contents), *cx,
array_buffer.handle_mut() CreateWith::Slice(&blob_contents),
) array_buffer.handle_mut()
.is_ok()); )
.is_ok());
Ok(NonNull::new_unchecked(array_buffer.get())) Ok(NonNull::new_unchecked(array_buffer.get()))
}
} }
} }

View file

@ -15,8 +15,9 @@ use crate::dom::gamepadbuttonlist::GamepadButtonList;
use crate::dom::gamepadevent::{GamepadEvent, GamepadEventType}; use crate::dom::gamepadevent::{GamepadEvent, GamepadEventType};
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::vrpose::VRPose; use crate::dom::vrpose::VRPose;
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, Float64Array}; use js::typedarray::{CreateWith, Float64Array};
use std::cell::Cell; use std::cell::Cell;
use std::ptr; use std::ptr;
@ -98,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());
@ -136,8 +137,8 @@ impl GamepadMethods for Gamepad {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://w3c.github.io/gamepad/#dom-gamepad-axes // https://w3c.github.io/gamepad/#dom-gamepad-axes
unsafe fn Axes(&self, _cx: *mut JSContext) -> NonNull<JSObject> { fn Axes(&self, _cx: JSContext) -> NonNull<JSObject> {
NonNull::new_unchecked(self.axes.get()) unsafe { NonNull::new_unchecked(self.axes.get()) }
} }
// https://w3c.github.io/gamepad/#dom-gamepad-buttons // https://w3c.github.io/gamepad/#dom-gamepad-buttons
@ -172,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

@ -18,6 +18,7 @@ use crate::dom::globalscope::GlobalScope;
use crate::dom::hashchangeevent::HashChangeEvent; use crate::dom::hashchangeevent::HashChangeEvent;
use crate::dom::popstateevent::PopStateEvent; use crate::dom::popstateevent::PopStateEvent;
use crate::dom::window::Window; use crate::dom::window::Window;
use crate::script_runtime::JSContext as SafeJSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext}; use js::jsapi::{Heap, JSContext};
use js::jsval::{JSVal, NullValue, UndefinedValue}; use js::jsval::{JSVal, NullValue, UndefinedValue};
@ -116,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());
@ -279,8 +280,7 @@ impl History {
impl HistoryMethods for History { impl HistoryMethods for History {
// https://html.spec.whatwg.org/multipage/#dom-history-state // https://html.spec.whatwg.org/multipage/#dom-history-state
#[allow(unsafe_code)] fn GetState(&self, _cx: SafeJSContext) -> Fallible<JSVal> {
unsafe fn GetState(&self, _cx: *mut JSContext) -> Fallible<JSVal> {
if !self.window.Document().is_fully_active() { if !self.window.Document().is_fully_active() {
return Err(Error::Security); return Err(Error::Security);
} }
@ -327,26 +327,24 @@ impl HistoryMethods for History {
} }
// https://html.spec.whatwg.org/multipage/#dom-history-pushstate // https://html.spec.whatwg.org/multipage/#dom-history-pushstate
#[allow(unsafe_code)] fn PushState(
unsafe fn PushState(
&self, &self,
cx: *mut JSContext, cx: SafeJSContext,
data: HandleValue, data: HandleValue,
title: DOMString, title: DOMString,
url: Option<USVString>, url: Option<USVString>,
) -> ErrorResult { ) -> ErrorResult {
self.push_or_replace_state(cx, data, title, url, PushOrReplace::Push) self.push_or_replace_state(*cx, data, title, url, PushOrReplace::Push)
} }
// https://html.spec.whatwg.org/multipage/#dom-history-replacestate // https://html.spec.whatwg.org/multipage/#dom-history-replacestate
#[allow(unsafe_code)] fn ReplaceState(
unsafe fn ReplaceState(
&self, &self,
cx: *mut JSContext, cx: SafeJSContext,
data: HandleValue, data: HandleValue,
title: DOMString, title: DOMString,
url: Option<USVString>, url: Option<USVString>,
) -> ErrorResult { ) -> ErrorResult {
self.push_or_replace_state(cx, data, title, url, PushOrReplace::Replace) self.push_or_replace_state(*cx, data, title, url, PushOrReplace::Replace)
} }
} }

View file

@ -28,6 +28,7 @@ use crate::dom::webgl2renderingcontext::WebGL2RenderingContext;
use crate::dom::webglrenderingcontext::{ use crate::dom::webglrenderingcontext::{
LayoutCanvasWebGLRenderingContextHelpers, WebGLRenderingContext, LayoutCanvasWebGLRenderingContextHelpers, WebGLRenderingContext,
}; };
use crate::script_runtime::JSContext as SafeJSContext;
use base64; use base64;
use canvas_traits::canvas::{CanvasId, CanvasMsg, FromScriptMsg}; use canvas_traits::canvas::{CanvasId, CanvasMsg, FromScriptMsg};
use canvas_traits::webgl::{GLContextAttributes, WebGLVersion}; use canvas_traits::webgl::{GLContextAttributes, WebGLVersion};
@ -263,7 +264,7 @@ impl HTMLCanvasElement {
cx: *mut JSContext, cx: *mut JSContext,
options: HandleValue, options: HandleValue,
) -> Option<GLContextAttributes> { ) -> Option<GLContextAttributes> {
match WebGLContextAttributes::new(cx, options) { match WebGLContextAttributes::new(SafeJSContext::from_ptr(cx), options) {
Ok(ConversionResult::Success(ref attrs)) => Some(From::from(attrs)), Ok(ConversionResult::Success(ref attrs)) => Some(From::from(attrs)),
Ok(ConversionResult::Failure(ref error)) => { Ok(ConversionResult::Failure(ref error)) => {
throw_type_error(cx, &error); throw_type_error(cx, &error);
@ -329,9 +330,9 @@ impl HTMLCanvasElementMethods for HTMLCanvasElement {
// https://html.spec.whatwg.org/multipage/#dom-canvas-getcontext // https://html.spec.whatwg.org/multipage/#dom-canvas-getcontext
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn GetContext( fn GetContext(
&self, &self,
cx: *mut JSContext, cx: SafeJSContext,
id: DOMString, id: DOMString,
options: HandleValue, options: HandleValue,
) -> Option<RenderingContext> { ) -> Option<RenderingContext> {
@ -339,21 +340,22 @@ impl HTMLCanvasElementMethods for HTMLCanvasElement {
"2d" => self "2d" => self
.get_or_init_2d_context() .get_or_init_2d_context()
.map(RenderingContext::CanvasRenderingContext2D), .map(RenderingContext::CanvasRenderingContext2D),
"webgl" | "experimental-webgl" => self "webgl" | "experimental-webgl" => unsafe {
.get_or_init_webgl_context(cx, options) self.get_or_init_webgl_context(*cx, options)
.map(RenderingContext::WebGLRenderingContext), .map(RenderingContext::WebGLRenderingContext)
"webgl2" | "experimental-webgl2" => self },
.get_or_init_webgl2_context(cx, options) "webgl2" | "experimental-webgl2" => unsafe {
.map(RenderingContext::WebGL2RenderingContext), self.get_or_init_webgl2_context(*cx, options)
.map(RenderingContext::WebGL2RenderingContext)
},
_ => None, _ => None,
} }
} }
// https://html.spec.whatwg.org/multipage/#dom-canvas-todataurl // https://html.spec.whatwg.org/multipage/#dom-canvas-todataurl
#[allow(unsafe_code)] fn ToDataURL(
unsafe fn ToDataURL(
&self, &self,
_context: *mut JSContext, _context: SafeJSContext,
_mime_type: Option<DOMString>, _mime_type: Option<DOMString>,
_quality: HandleValue, _quality: HandleValue,
) -> Fallible<USVString> { ) -> Fallible<USVString> {

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

@ -8,10 +8,11 @@ use crate::dom::bindings::error::{Error, Fallible};
use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::reflector::{reflect_dom_object, 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;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use euclid::default::{Rect, Size2D}; use euclid::default::{Rect, Size2D};
use ipc_channel::ipc::IpcSharedMemory; use ipc_channel::ipc::IpcSharedMemory;
use js::jsapi::{Heap, JSContext, JSObject}; use js::jsapi::{Heap, JSObject};
use js::rust::Runtime; use js::rust::Runtime;
use js::typedarray::{CreateWith, Uint8ClampedArray}; use js::typedarray::{CreateWith, Uint8ClampedArray};
use std::borrow::Cow; use std::borrow::Cow;
@ -40,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);
@ -48,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()))
} }
} }
@ -69,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())
})?; })?;
@ -109,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());
} }
@ -131,7 +132,7 @@ impl ImageData {
#[allow(unsafe_code)] #[allow(unsafe_code)]
#[allow(unused_variables)] #[allow(unused_variables)]
pub unsafe fn Constructor_( pub unsafe fn Constructor_(
cx: *mut JSContext, cx: JSContext,
global: &GlobalScope, global: &GlobalScope,
jsobject: *mut JSObject, jsobject: *mut JSObject,
width: u32, width: u32,
@ -183,9 +184,8 @@ impl ImageDataMethods for ImageData {
self.height self.height
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-imagedata-data // https://html.spec.whatwg.org/multipage/#dom-imagedata-data
unsafe fn Data(&self, _: *mut JSContext) -> NonNull<JSObject> { fn Data(&self, _: JSContext) -> NonNull<JSObject> {
NonNull::new(self.data.get()).expect("got a null pointer") NonNull::new(self.data.get()).expect("got a null pointer")
} }
} }

View file

@ -15,8 +15,9 @@ use crate::dom::event::Event;
use crate::dom::eventtarget::EventTarget; use crate::dom::eventtarget::EventTarget;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::windowproxy::WindowProxy; use crate::dom::windowproxy::WindowProxy;
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::jsval::JSVal; use js::jsval::JSVal;
use js::rust::HandleValue; use js::rust::HandleValue;
use servo_atoms::Atom; use servo_atoms::Atom;
@ -127,9 +128,8 @@ impl MessageEvent {
} }
impl MessageEventMethods for MessageEvent { impl MessageEventMethods for MessageEvent {
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-messageevent-data // https://html.spec.whatwg.org/multipage/#dom-messageevent-data
unsafe fn Data(&self, _cx: *mut JSContext) -> JSVal { fn Data(&self, _cx: JSContext) -> JSVal {
self.data.get() self.data.get()
} }
@ -139,8 +139,7 @@ impl MessageEventMethods for MessageEvent {
} }
// https://html.spec.whatwg.org/multipage/#dom-messageevent-source // https://html.spec.whatwg.org/multipage/#dom-messageevent-source
#[allow(unsafe_code)] fn GetSource(&self, _cx: JSContext) -> Option<NonNull<JSObject>> {
unsafe fn GetSource(&self, _cx: *mut JSContext) -> Option<NonNull<JSObject>> {
self.source self.source
.as_ref() .as_ref()
.and_then(|source| NonNull::new(source.reflector().get_jsobject().get())) .and_then(|source| NonNull::new(source.reflector().get_jsobject().get()))

View file

@ -60,13 +60,14 @@ use crate::dom::svgsvgelement::{LayoutSVGSVGElementHelpers, SVGSVGElement};
use crate::dom::text::Text; use crate::dom::text::Text;
use crate::dom::virtualmethods::{vtable_for, VirtualMethods}; use crate::dom::virtualmethods::{vtable_for, VirtualMethods};
use crate::dom::window::Window; use crate::dom::window::Window;
use crate::script_runtime::JSContext;
use crate::script_thread::ScriptThread; use crate::script_thread::ScriptThread;
use app_units::Au; use app_units::Au;
use devtools_traits::NodeInfo; use devtools_traits::NodeInfo;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use euclid::default::{Point2D, Rect, Size2D, Vector2D}; use euclid::default::{Point2D, Rect, Size2D, Vector2D};
use html5ever::{Namespace, Prefix, QualName}; use html5ever::{Namespace, Prefix, QualName};
use js::jsapi::{JSContext, JSObject, JSRuntime}; use js::jsapi::{JSObject, JSRuntime};
use libc::{self, c_void, uintptr_t}; use libc::{self, c_void, uintptr_t};
use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
use msg::constellation_msg::{BrowsingContextId, PipelineId}; use msg::constellation_msg::{BrowsingContextId, PipelineId};
@ -1630,7 +1631,7 @@ impl Node {
pub fn reflect_node<N>( pub fn reflect_node<N>(
node: Box<N>, node: Box<N>,
document: &Document, document: &Document,
wrap_fn: unsafe fn(*mut JSContext, &GlobalScope, Box<N>) -> DomRoot<N>, wrap_fn: unsafe fn(JSContext, &GlobalScope, Box<N>) -> DomRoot<N>,
) -> DomRoot<N> ) -> DomRoot<N>
where where
N: DerivedFrom<Node> + DomObject, N: DerivedFrom<Node> + DomObject,

View file

@ -15,9 +15,9 @@ use crate::dom::eventtarget::EventTarget;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::htmlcanvaselement::HTMLCanvasElement; use crate::dom::htmlcanvaselement::HTMLCanvasElement;
use crate::dom::offscreencanvasrenderingcontext2d::OffscreenCanvasRenderingContext2D; use crate::dom::offscreencanvasrenderingcontext2d::OffscreenCanvasRenderingContext2D;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use euclid::default::Size2D; use euclid::default::Size2D;
use js::jsapi::JSContext;
use js::rust::HandleValue; use js::rust::HandleValue;
use ref_filter_map; use ref_filter_map;
use std::cell::Cell; use std::cell::Cell;
@ -108,10 +108,9 @@ impl OffscreenCanvas {
impl OffscreenCanvasMethods for OffscreenCanvas { impl OffscreenCanvasMethods for OffscreenCanvas {
// https://html.spec.whatwg.org/multipage/#dom-offscreencanvas-getcontext // https://html.spec.whatwg.org/multipage/#dom-offscreencanvas-getcontext
#[allow(unsafe_code)] fn GetContext(
unsafe fn GetContext(
&self, &self,
_cx: *mut JSContext, _cx: JSContext,
id: DOMString, id: DOMString,
_options: HandleValue, _options: HandleValue,
) -> Option<OffscreenRenderingContext> { ) -> Option<OffscreenRenderingContext> {

View file

@ -23,6 +23,7 @@ use crate::dom::worklet::WorkletExecutor;
use crate::dom::workletglobalscope::WorkletGlobalScope; use crate::dom::workletglobalscope::WorkletGlobalScope;
use crate::dom::workletglobalscope::WorkletGlobalScopeInit; use crate::dom::workletglobalscope::WorkletGlobalScopeInit;
use crate::dom::workletglobalscope::WorkletTask; use crate::dom::workletglobalscope::WorkletTask;
use crate::script_runtime::JSContext;
use crossbeam_channel::{unbounded, Sender}; use crossbeam_channel::{unbounded, Sender};
use dom_struct::dom_struct; use dom_struct::dom_struct;
use euclid::Scale; use euclid::Scale;
@ -128,7 +129,7 @@ impl PaintWorkletGlobalScope {
missing_image_urls: Vec::new(), missing_image_urls: Vec::new(),
}), }),
}); });
unsafe { PaintWorkletGlobalScopeBinding::Wrap(runtime.cx(), global) } unsafe { PaintWorkletGlobalScopeBinding::Wrap(JSContext::from_ptr(runtime.cx()), global) }
} }
pub fn image_cache(&self) -> Arc<dyn ImageCache> { pub fn image_cache(&self) -> Arc<dyn ImageCache> {
@ -252,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.
@ -281,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()
@ -332,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()),
@ -342,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,
@ -355,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);
} }
@ -517,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);
@ -534,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()) } {
@ -555,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

@ -17,6 +17,7 @@ use crate::dom::bluetoothpermissionresult::BluetoothPermissionResult;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::permissionstatus::PermissionStatus; use crate::dom::permissionstatus::PermissionStatus;
use crate::dom::promise::Promise; use crate::dom::promise::Promise;
use crate::script_runtime::JSContext as SafeJSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::conversions::ConversionResult; use js::conversions::ConversionResult;
use js::jsapi::{JSContext, JSObject}; use js::jsapi::{JSContext, JSObject};
@ -199,22 +200,19 @@ impl Permissions {
} }
impl PermissionsMethods for Permissions { impl PermissionsMethods for Permissions {
#[allow(unsafe_code)]
// https://w3c.github.io/permissions/#dom-permissions-query // https://w3c.github.io/permissions/#dom-permissions-query
unsafe fn Query(&self, cx: *mut JSContext, permissionDesc: *mut JSObject) -> Rc<Promise> { fn Query(&self, cx: SafeJSContext, permissionDesc: *mut JSObject) -> Rc<Promise> {
self.manipulate(Operation::Query, cx, permissionDesc, None) self.manipulate(Operation::Query, *cx, permissionDesc, None)
} }
#[allow(unsafe_code)]
// https://w3c.github.io/permissions/#dom-permissions-request // https://w3c.github.io/permissions/#dom-permissions-request
unsafe fn Request(&self, cx: *mut JSContext, permissionDesc: *mut JSObject) -> Rc<Promise> { fn Request(&self, cx: SafeJSContext, permissionDesc: *mut JSObject) -> Rc<Promise> {
self.manipulate(Operation::Request, cx, permissionDesc, None) self.manipulate(Operation::Request, *cx, permissionDesc, None)
} }
#[allow(unsafe_code)]
// https://w3c.github.io/permissions/#dom-permissions-revoke // https://w3c.github.io/permissions/#dom-permissions-revoke
unsafe fn Revoke(&self, cx: *mut JSContext, permissionDesc: *mut JSObject) -> Rc<Promise> { fn Revoke(&self, cx: SafeJSContext, permissionDesc: *mut JSObject) -> Rc<Promise> {
self.manipulate(Operation::Revoke, cx, permissionDesc, None) self.manipulate(Operation::Revoke, *cx, permissionDesc, None)
} }
} }
@ -232,7 +230,7 @@ impl PermissionAlgorithm for Permissions {
.handle_mut() .handle_mut()
.set(ObjectValue(permission_descriptor_obj)); .set(ObjectValue(permission_descriptor_obj));
unsafe { unsafe {
match PermissionDescriptor::new(cx, property.handle()) { match PermissionDescriptor::new(SafeJSContext::from_ptr(cx), property.handle()) {
Ok(ConversionResult::Success(descriptor)) => Ok(descriptor), Ok(ConversionResult::Success(descriptor)) => Ok(descriptor),
Ok(ConversionResult::Failure(error)) => Err(Error::Type(error.into_owned())), Ok(ConversionResult::Failure(error)) => Err(Error::Type(error.into_owned())),
Err(_) => Err(Error::JSFailed), Err(_) => Err(Error::JSFailed),

View file

@ -14,8 +14,9 @@ use crate::dom::bindings::trace::RootedTraceableBox;
use crate::dom::event::Event; use crate::dom::event::Event;
use crate::dom::eventtarget::EventTarget; use crate::dom::eventtarget::EventTarget;
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 js::jsapi::{Heap, JSContext}; use js::jsapi::Heap;
use js::jsval::JSVal; use js::jsval::JSVal;
use js::rust::HandleValue; use js::rust::HandleValue;
use servo_atoms::Atom; use servo_atoms::Atom;
@ -81,9 +82,8 @@ impl PopStateEvent {
} }
impl PopStateEventMethods for PopStateEvent { impl PopStateEventMethods for PopStateEvent {
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-popstateevent-state // https://html.spec.whatwg.org/multipage/#dom-popstateevent-state
unsafe fn State(&self, _cx: *mut JSContext) -> JSVal { fn State(&self, _cx: JSContext) -> JSVal {
self.state.get() self.state.get()
} }

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

@ -14,8 +14,9 @@ use crate::dom::bindings::trace::RootedTraceableBox;
use crate::dom::event::{Event, EventBubbles, EventCancelable}; use crate::dom::event::{Event, EventBubbles, EventCancelable};
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 dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext}; use js::jsapi::Heap;
use js::jsval::JSVal; use js::jsval::JSVal;
use js::rust::HandleValue; use js::rust::HandleValue;
use servo_atoms::Atom; use servo_atoms::Atom;
@ -100,9 +101,8 @@ impl PromiseRejectionEventMethods for PromiseRejectionEvent {
self.promise.clone() self.promise.clone()
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-promiserejectionevent-reason // https://html.spec.whatwg.org/multipage/#dom-promiserejectionevent-reason
unsafe fn Reason(&self, _cx: *mut JSContext) -> JSVal { fn Reason(&self, _cx: JSContext) -> JSVal {
self.reason.get() self.reason.get()
} }

View file

@ -14,9 +14,10 @@ use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString; use crate::dom::bindings::str::DOMString;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
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 js::conversions::ToJSValConvertible; use js::conversions::ToJSValConvertible;
use js::jsapi::{JSContext, JSObject}; use js::jsapi::JSObject;
use js::jsval::UndefinedValue; use js::jsval::UndefinedValue;
use std::ptr::NonNull; use std::ptr::NonNull;
@ -73,13 +74,15 @@ impl RTCSessionDescriptionMethods for RTCSessionDescription {
#[allow(unsafe_code)] #[allow(unsafe_code)]
/// https://w3c.github.io/webrtc-pc/#dom-rtcsessiondescription-tojson /// https://w3c.github.io/webrtc-pc/#dom-rtcsessiondescription-tojson
unsafe fn ToJSON(&self, cx: *mut JSContext) -> NonNull<JSObject> { fn ToJSON(&self, cx: JSContext) -> NonNull<JSObject> {
let init = RTCSessionDescriptionInit { let init = RTCSessionDescriptionInit {
type_: self.ty, type_: self.ty,
sdp: self.sdp.clone(), sdp: self.sdp.clone(),
}; };
rooted!(in(cx) let mut jsval = UndefinedValue()); unsafe {
init.to_jsval(cx, jsval.handle_mut()); rooted!(in(*cx) let mut jsval = UndefinedValue());
NonNull::new(jsval.to_object()).unwrap() init.to_jsval(*cx, jsval.handle_mut());
NonNull::new(jsval.to_object()).unwrap()
}
} }
} }

View file

@ -16,9 +16,9 @@ use crate::dom::bindings::str::USVString;
use crate::dom::bindings::structuredclone::StructuredCloneData; use crate::dom::bindings::structuredclone::StructuredCloneData;
use crate::dom::eventtarget::EventTarget; use crate::dom::eventtarget::EventTarget;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::JSContext;
use crate::task::TaskOnce; use crate::task::TaskOnce;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::JSContext;
use js::rust::HandleValue; use js::rust::HandleValue;
use script_traits::{DOMMessage, ScriptMsg}; use script_traits::{DOMMessage, ScriptMsg};
use servo_url::ServoUrl; use servo_url::ServoUrl;
@ -90,15 +90,14 @@ impl ServiceWorkerMethods for ServiceWorker {
USVString(self.script_url.borrow().clone()) USVString(self.script_url.borrow().clone())
} }
#[allow(unsafe_code)]
// https://w3c.github.io/ServiceWorker/#service-worker-postmessage // https://w3c.github.io/ServiceWorker/#service-worker-postmessage
unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { fn PostMessage(&self, cx: JSContext, message: HandleValue) -> ErrorResult {
// Step 1 // Step 1
if let ServiceWorkerState::Redundant = self.state.get() { if let ServiceWorkerState::Redundant = self.state.get() {
return Err(Error::InvalidState); return Err(Error::InvalidState);
} }
// Step 7 // Step 7
let data = StructuredCloneData::write(cx, message)?; let data = StructuredCloneData::write(*cx, message)?;
let msg_vec = DOMMessage(data.move_to_arraybuffer()); let msg_vec = DOMMessage(data.move_to_arraybuffer());
let _ = self let _ = self
.global() .global()

View file

@ -21,7 +21,9 @@ use crate::dom::globalscope::GlobalScope;
use crate::dom::worker::TrustedWorkerAddress; use crate::dom::worker::TrustedWorkerAddress;
use crate::dom::workerglobalscope::WorkerGlobalScope; use crate::dom::workerglobalscope::WorkerGlobalScope;
use crate::fetch::load_whole_resource; use crate::fetch::load_whole_resource;
use crate::script_runtime::{new_rt_and_cx, CommonScriptMsg, Runtime, ScriptChan}; use crate::script_runtime::{
new_rt_and_cx, CommonScriptMsg, JSContext as SafeJSContext, Runtime, ScriptChan,
};
use crate::task_queue::{QueuedTask, QueuedTaskConversion, TaskQueue}; use crate::task_queue::{QueuedTask, QueuedTaskConversion, TaskQueue};
use crate::task_source::TaskSourceName; use crate::task_source::TaskSourceName;
use crossbeam_channel::{unbounded, Receiver, Sender}; use crossbeam_channel::{unbounded, Receiver, Sender};
@ -246,7 +248,7 @@ impl ServiceWorkerGlobalScope {
swmanager_sender, swmanager_sender,
scope_url, scope_url,
)); ));
unsafe { ServiceWorkerGlobalScopeBinding::Wrap(cx, scope) } unsafe { ServiceWorkerGlobalScopeBinding::Wrap(SafeJSContext::from_ptr(cx), scope) }
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
@ -335,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));
@ -411,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

@ -49,6 +49,7 @@ use crate::dom::globalscope::GlobalScope;
use crate::dom::promise::Promise; use crate::dom::promise::Promise;
use crate::dom::promisenativehandler::{Callback, PromiseNativeHandler}; use crate::dom::promisenativehandler::{Callback, PromiseNativeHandler};
use crate::dom::url::URL; use crate::dom::url::URL;
use crate::script_runtime::JSContext as SafeJSContext;
use crate::timers::OneshotTimerCallback; use crate::timers::OneshotTimerCallback;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext, JSObject}; use js::jsapi::{Heap, JSContext, JSObject};
@ -215,23 +216,24 @@ impl TestBindingMethods for TestBinding {
} }
fn SetUnion9Attribute(&self, _: ByteStringOrLong) {} fn SetUnion9Attribute(&self, _: ByteStringOrLong) {}
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn ArrayAttribute(&self, cx: *mut JSContext) -> NonNull<JSObject> { fn ArrayAttribute(&self, cx: SafeJSContext) -> NonNull<JSObject> {
rooted!(in(cx) let array = JS_NewUint8ClampedArray(cx, 16)); unsafe {
NonNull::new(array.get()).expect("got a null pointer") rooted!(in(*cx) let array = JS_NewUint8ClampedArray(*cx, 16));
NonNull::new(array.get()).expect("got a null pointer")
}
} }
#[allow(unsafe_code)] fn AnyAttribute(&self, _: SafeJSContext) -> JSVal {
unsafe fn AnyAttribute(&self, _: *mut JSContext) -> JSVal {
NullValue() NullValue()
} }
fn SetAnyAttribute(&self, _: SafeJSContext, _: HandleValue) {}
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn SetAnyAttribute(&self, _: *mut JSContext, _: HandleValue) {} fn ObjectAttribute(&self, cx: SafeJSContext) -> NonNull<JSObject> {
#[allow(unsafe_code)] unsafe {
unsafe fn ObjectAttribute(&self, cx: *mut JSContext) -> NonNull<JSObject> { rooted!(in(*cx) let obj = JS_NewPlainObject(*cx));
rooted!(in(cx) let obj = JS_NewPlainObject(cx)); NonNull::new(obj.get()).expect("got a null pointer")
NonNull::new(obj.get()).expect("got a null pointer") }
} }
#[allow(unsafe_code)] fn SetObjectAttribute(&self, _: SafeJSContext, _: *mut JSObject) {}
unsafe fn SetObjectAttribute(&self, _: *mut JSContext, _: *mut JSObject) {}
fn GetBooleanAttributeNullable(&self) -> Option<bool> { fn GetBooleanAttributeNullable(&self) -> Option<bool> {
Some(false) Some(false)
@ -329,12 +331,10 @@ impl TestBindingMethods for TestBinding {
fn SetInterfaceAttributeWeak(&self, url: Option<&URL>) { fn SetInterfaceAttributeWeak(&self, url: Option<&URL>) {
self.url.set(url); self.url.set(url);
} }
#[allow(unsafe_code)] fn GetObjectAttributeNullable(&self, _: SafeJSContext) -> Option<NonNull<JSObject>> {
unsafe fn GetObjectAttributeNullable(&self, _: *mut JSContext) -> Option<NonNull<JSObject>> {
None None
} }
#[allow(unsafe_code)] fn SetObjectAttributeNullable(&self, _: SafeJSContext, _: *mut JSObject) {}
unsafe fn SetObjectAttributeNullable(&self, _: *mut JSContext, _: *mut JSObject) {}
fn GetUnionAttributeNullable(&self) -> Option<HTMLElementOrLong> { fn GetUnionAttributeNullable(&self) -> Option<HTMLElementOrLong> {
Some(HTMLElementOrLong::Long(0)) Some(HTMLElementOrLong::Long(0))
} }
@ -419,12 +419,10 @@ impl TestBindingMethods for TestBinding {
"".to_owned(), "".to_owned(),
) )
} }
#[allow(unsafe_code)] fn ReceiveAny(&self, _: SafeJSContext) -> JSVal {
unsafe fn ReceiveAny(&self, _: *mut JSContext) -> JSVal {
NullValue() NullValue()
} }
#[allow(unsafe_code)] fn ReceiveObject(&self, cx: SafeJSContext) -> NonNull<JSObject> {
unsafe fn ReceiveObject(&self, cx: *mut JSContext) -> NonNull<JSObject> {
self.ObjectAttribute(cx) self.ObjectAttribute(cx)
} }
fn ReceiveUnion(&self) -> HTMLElementOrLong { fn ReceiveUnion(&self) -> HTMLElementOrLong {
@ -470,10 +468,9 @@ impl TestBindingMethods for TestBinding {
"".to_owned(), "".to_owned(),
)] )]
} }
#[allow(unsafe_code)] fn ReceiveUnionIdentity(
unsafe fn ReceiveUnionIdentity(
&self, &self,
_: *mut JSContext, _: SafeJSContext,
arg: UnionTypes::StringOrObject, arg: UnionTypes::StringOrObject,
) -> UnionTypes::StringOrObject { ) -> UnionTypes::StringOrObject {
arg arg
@ -537,8 +534,7 @@ impl TestBindingMethods for TestBinding {
"".to_owned(), "".to_owned(),
)) ))
} }
#[allow(unsafe_code)] fn ReceiveNullableObject(&self, cx: SafeJSContext) -> Option<NonNull<JSObject>> {
unsafe fn ReceiveNullableObject(&self, cx: *mut JSContext) -> Option<NonNull<JSObject>> {
self.GetObjectAttributeNullable(cx) self.GetObjectAttributeNullable(cx)
} }
fn ReceiveNullableUnion(&self) -> Option<HTMLElementOrLong> { fn ReceiveNullableUnion(&self) -> Option<HTMLElementOrLong> {
@ -666,35 +662,24 @@ impl TestBindingMethods for TestBinding {
fn PassUnion7(&self, _: StringSequenceOrUnsignedLong) {} fn PassUnion7(&self, _: StringSequenceOrUnsignedLong) {}
fn PassUnion8(&self, _: ByteStringSequenceOrLong) {} fn PassUnion8(&self, _: ByteStringSequenceOrLong) {}
fn PassUnion9(&self, _: UnionTypes::TestDictionaryOrLong) {} fn PassUnion9(&self, _: UnionTypes::TestDictionaryOrLong) {}
#[allow(unsafe_code)] fn PassUnion10(&self, _: SafeJSContext, _: UnionTypes::StringOrObject) {}
unsafe fn PassUnion10(&self, _: *mut JSContext, _: UnionTypes::StringOrObject) {}
fn PassUnion11(&self, _: UnionTypes::ArrayBufferOrArrayBufferView) {} fn PassUnion11(&self, _: UnionTypes::ArrayBufferOrArrayBufferView) {}
fn PassUnionWithTypedef(&self, _: DocumentOrTestTypedef) {} fn PassUnionWithTypedef(&self, _: DocumentOrTestTypedef) {}
fn PassUnionWithTypedef2(&self, _: LongSequenceOrTestTypedef) {} fn PassUnionWithTypedef2(&self, _: LongSequenceOrTestTypedef) {}
#[allow(unsafe_code)] fn PassAny(&self, _: SafeJSContext, _: HandleValue) {}
unsafe fn PassAny(&self, _: *mut JSContext, _: HandleValue) {} fn PassObject(&self, _: SafeJSContext, _: *mut JSObject) {}
#[allow(unsafe_code)]
unsafe fn PassObject(&self, _: *mut JSContext, _: *mut JSObject) {}
fn PassCallbackFunction(&self, _: Rc<Function>) {} fn PassCallbackFunction(&self, _: Rc<Function>) {}
fn PassCallbackInterface(&self, _: Rc<EventListener>) {} fn PassCallbackInterface(&self, _: Rc<EventListener>) {}
fn PassSequence(&self, _: Vec<i32>) {} fn PassSequence(&self, _: Vec<i32>) {}
#[allow(unsafe_code)] fn PassAnySequence(&self, _: SafeJSContext, _: CustomAutoRooterGuard<Vec<JSVal>>) {}
unsafe fn PassAnySequence(&self, _: *mut JSContext, _: CustomAutoRooterGuard<Vec<JSVal>>) {} fn AnySequencePassthrough(
#[allow(unsafe_code)]
unsafe fn AnySequencePassthrough(
&self, &self,
_: *mut JSContext, _: SafeJSContext,
seq: CustomAutoRooterGuard<Vec<JSVal>>, seq: CustomAutoRooterGuard<Vec<JSVal>>,
) -> Vec<JSVal> { ) -> Vec<JSVal> {
(*seq).clone() (*seq).clone()
} }
#[allow(unsafe_code)] fn PassObjectSequence(&self, _: SafeJSContext, _: CustomAutoRooterGuard<Vec<*mut JSObject>>) {}
unsafe fn PassObjectSequence(
&self,
_: *mut JSContext,
_: CustomAutoRooterGuard<Vec<*mut JSObject>>,
) {
}
fn PassStringSequence(&self, _: Vec<DOMString>) {} fn PassStringSequence(&self, _: Vec<DOMString>) {}
fn PassInterfaceSequence(&self, _: Vec<DomRoot<Blob>>) {} fn PassInterfaceSequence(&self, _: Vec<DomRoot<Blob>>) {}
@ -719,8 +704,7 @@ impl TestBindingMethods for TestBinding {
fn PassNullableByteString(&self, _: Option<ByteString>) {} fn PassNullableByteString(&self, _: Option<ByteString>) {}
// fn PassNullableEnum(self, _: Option<TestEnum>) {} // fn PassNullableEnum(self, _: Option<TestEnum>) {}
fn PassNullableInterface(&self, _: Option<&Blob>) {} fn PassNullableInterface(&self, _: Option<&Blob>) {}
#[allow(unsafe_code)] fn PassNullableObject(&self, _: SafeJSContext, _: *mut JSObject) {}
unsafe fn PassNullableObject(&self, _: *mut JSContext, _: *mut JSObject) {}
fn PassNullableTypedArray(&self, _: CustomAutoRooterGuard<Option<typedarray::Int8Array>>) {} fn PassNullableTypedArray(&self, _: CustomAutoRooterGuard<Option<typedarray::Int8Array>>) {}
fn PassNullableUnion(&self, _: Option<HTMLElementOrLong>) {} fn PassNullableUnion(&self, _: Option<HTMLElementOrLong>) {}
fn PassNullableUnion2(&self, _: Option<EventOrString>) {} fn PassNullableUnion2(&self, _: Option<EventOrString>) {}
@ -756,10 +740,8 @@ impl TestBindingMethods for TestBinding {
fn PassOptionalUnion4(&self, _: Option<LongSequenceOrBoolean>) {} fn PassOptionalUnion4(&self, _: Option<LongSequenceOrBoolean>) {}
fn PassOptionalUnion5(&self, _: Option<UnsignedLongOrBoolean>) {} fn PassOptionalUnion5(&self, _: Option<UnsignedLongOrBoolean>) {}
fn PassOptionalUnion6(&self, _: Option<ByteStringOrLong>) {} fn PassOptionalUnion6(&self, _: Option<ByteStringOrLong>) {}
#[allow(unsafe_code)] fn PassOptionalAny(&self, _: SafeJSContext, _: HandleValue) {}
unsafe fn PassOptionalAny(&self, _: *mut JSContext, _: HandleValue) {} fn PassOptionalObject(&self, _: SafeJSContext, _: Option<*mut JSObject>) {}
#[allow(unsafe_code)]
unsafe fn PassOptionalObject(&self, _: *mut JSContext, _: Option<*mut JSObject>) {}
fn PassOptionalCallbackFunction(&self, _: Option<Rc<Function>>) {} fn PassOptionalCallbackFunction(&self, _: Option<Rc<Function>>) {}
fn PassOptionalCallbackInterface(&self, _: Option<Rc<EventListener>>) {} fn PassOptionalCallbackInterface(&self, _: Option<Rc<EventListener>>) {}
fn PassOptionalSequence(&self, _: Option<Vec<i32>>) {} fn PassOptionalSequence(&self, _: Option<Vec<i32>>) {}
@ -782,8 +764,7 @@ impl TestBindingMethods for TestBinding {
fn PassOptionalNullableByteString(&self, _: Option<Option<ByteString>>) {} fn PassOptionalNullableByteString(&self, _: Option<Option<ByteString>>) {}
// fn PassOptionalNullableEnum(self, _: Option<Option<TestEnum>>) {} // fn PassOptionalNullableEnum(self, _: Option<Option<TestEnum>>) {}
fn PassOptionalNullableInterface(&self, _: Option<Option<&Blob>>) {} fn PassOptionalNullableInterface(&self, _: Option<Option<&Blob>>) {}
#[allow(unsafe_code)] fn PassOptionalNullableObject(&self, _: SafeJSContext, _: Option<*mut JSObject>) {}
unsafe fn PassOptionalNullableObject(&self, _: *mut JSContext, _: Option<*mut JSObject>) {}
fn PassOptionalNullableUnion(&self, _: Option<Option<HTMLElementOrLong>>) {} fn PassOptionalNullableUnion(&self, _: Option<Option<HTMLElementOrLong>>) {}
fn PassOptionalNullableUnion2(&self, _: Option<Option<EventOrString>>) {} fn PassOptionalNullableUnion2(&self, _: Option<Option<EventOrString>>) {}
fn PassOptionalNullableUnion3(&self, _: Option<Option<StringOrLongSequence>>) {} fn PassOptionalNullableUnion3(&self, _: Option<Option<StringOrLongSequence>>) {}
@ -827,14 +808,12 @@ impl TestBindingMethods for TestBinding {
fn PassOptionalNullableByteStringWithDefault(&self, _: Option<ByteString>) {} fn PassOptionalNullableByteStringWithDefault(&self, _: Option<ByteString>) {}
// fn PassOptionalNullableEnumWithDefault(self, _: Option<TestEnum>) {} // fn PassOptionalNullableEnumWithDefault(self, _: Option<TestEnum>) {}
fn PassOptionalNullableInterfaceWithDefault(&self, _: Option<&Blob>) {} fn PassOptionalNullableInterfaceWithDefault(&self, _: Option<&Blob>) {}
#[allow(unsafe_code)] fn PassOptionalNullableObjectWithDefault(&self, _: SafeJSContext, _: *mut JSObject) {}
unsafe fn PassOptionalNullableObjectWithDefault(&self, _: *mut JSContext, _: *mut JSObject) {}
fn PassOptionalNullableUnionWithDefault(&self, _: Option<HTMLElementOrLong>) {} fn PassOptionalNullableUnionWithDefault(&self, _: Option<HTMLElementOrLong>) {}
fn PassOptionalNullableUnion2WithDefault(&self, _: Option<EventOrString>) {} fn PassOptionalNullableUnion2WithDefault(&self, _: Option<EventOrString>) {}
// fn PassOptionalNullableCallbackFunctionWithDefault(self, _: Option<Function>) {} // fn PassOptionalNullableCallbackFunctionWithDefault(self, _: Option<Function>) {}
fn PassOptionalNullableCallbackInterfaceWithDefault(&self, _: Option<Rc<EventListener>>) {} fn PassOptionalNullableCallbackInterfaceWithDefault(&self, _: Option<Rc<EventListener>>) {}
#[allow(unsafe_code)] fn PassOptionalAnyWithDefault(&self, _: SafeJSContext, _: HandleValue) {}
unsafe fn PassOptionalAnyWithDefault(&self, _: *mut JSContext, _: HandleValue) {}
fn PassOptionalNullableBooleanWithNonNullDefault(&self, _: Option<bool>) {} fn PassOptionalNullableBooleanWithNonNullDefault(&self, _: Option<bool>) {}
fn PassOptionalNullableByteWithNonNullDefault(&self, _: Option<i8>) {} fn PassOptionalNullableByteWithNonNullDefault(&self, _: Option<i8>) {}
@ -883,10 +862,8 @@ impl TestBindingMethods for TestBinding {
fn PassVariadicUnion5(&self, _: Vec<StringOrUnsignedLong>) {} fn PassVariadicUnion5(&self, _: Vec<StringOrUnsignedLong>) {}
fn PassVariadicUnion6(&self, _: Vec<UnsignedLongOrBoolean>) {} fn PassVariadicUnion6(&self, _: Vec<UnsignedLongOrBoolean>) {}
fn PassVariadicUnion7(&self, _: Vec<ByteStringOrLong>) {} fn PassVariadicUnion7(&self, _: Vec<ByteStringOrLong>) {}
#[allow(unsafe_code)] fn PassVariadicAny(&self, _: SafeJSContext, _: Vec<HandleValue>) {}
unsafe fn PassVariadicAny(&self, _: *mut JSContext, _: Vec<HandleValue>) {} fn PassVariadicObject(&self, _: SafeJSContext, _: Vec<*mut JSObject>) {}
#[allow(unsafe_code)]
unsafe fn PassVariadicObject(&self, _: *mut JSContext, _: Vec<*mut JSObject>) {}
fn BooleanMozPreference(&self, pref_name: DOMString) -> bool { fn BooleanMozPreference(&self, pref_name: DOMString) -> bool {
prefs::pref_map() prefs::pref_map()
.get(pref_name.as_ref()) .get(pref_name.as_ref())
@ -965,32 +942,28 @@ impl TestBindingMethods for TestBinding {
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn ReturnResolvedPromise( fn ReturnResolvedPromise(&self, cx: SafeJSContext, v: HandleValue) -> Fallible<Rc<Promise>> {
&self, unsafe { Promise::new_resolved(&self.global(), *cx, v) }
cx: *mut JSContext,
v: HandleValue,
) -> Fallible<Rc<Promise>> {
Promise::new_resolved(&self.global(), cx, v)
} }
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn ReturnRejectedPromise( fn ReturnRejectedPromise(&self, cx: SafeJSContext, v: HandleValue) -> Fallible<Rc<Promise>> {
&self, unsafe { Promise::new_rejected(&self.global(), *cx, v) }
cx: *mut JSContext,
v: HandleValue,
) -> Fallible<Rc<Promise>> {
Promise::new_rejected(&self.global(), cx, v)
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn PromiseResolveNative(&self, cx: *mut JSContext, p: &Promise, v: HandleValue) { fn PromiseResolveNative(&self, cx: SafeJSContext, p: &Promise, v: HandleValue) {
p.resolve(cx, v); unsafe {
p.resolve(*cx, v);
}
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn PromiseRejectNative(&self, cx: *mut JSContext, p: &Promise, v: HandleValue) { fn PromiseRejectNative(&self, cx: SafeJSContext, p: &Promise, v: HandleValue) {
p.reject(cx, v); unsafe {
p.reject(*cx, v);
}
} }
fn PromiseRejectWithTypeError(&self, p: &Promise, s: USVString) { fn PromiseRejectWithTypeError(&self, p: &Promise, s: USVString) {

View file

@ -10,6 +10,7 @@ use crate::dom::bindings::str::DOMString;
use crate::dom::worklet::WorkletExecutor; use crate::dom::worklet::WorkletExecutor;
use crate::dom::workletglobalscope::WorkletGlobalScope; use crate::dom::workletglobalscope::WorkletGlobalScope;
use crate::dom::workletglobalscope::WorkletGlobalScopeInit; use crate::dom::workletglobalscope::WorkletGlobalScopeInit;
use crate::script_runtime::JSContext;
use crossbeam_channel::Sender; use crossbeam_channel::Sender;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::rust::Runtime; use js::rust::Runtime;
@ -49,7 +50,7 @@ impl TestWorkletGlobalScope {
), ),
lookup_table: Default::default(), lookup_table: Default::default(),
}); });
unsafe { TestWorkletGlobalScopeBinding::Wrap(runtime.cx(), global) } unsafe { TestWorkletGlobalScopeBinding::Wrap(JSContext::from_ptr(runtime.cx()), global) }
} }
pub fn perform_a_worklet_task(&self, task: TestWorkletTask) { pub fn perform_a_worklet_task(&self, task: TestWorkletTask) {

View file

@ -9,8 +9,9 @@ use crate::dom::bindings::reflector::{reflect_dom_object, Reflector};
use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::{DOMString, USVString}; use crate::dom::bindings::str::{DOMString, USVString};
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{JSContext, JSObject}; use js::jsapi::JSObject;
use js::typedarray::{CreateWith, Uint8Array}; use js::typedarray::{CreateWith, Uint8Array};
use std::ptr; use std::ptr;
use std::ptr::NonNull; use std::ptr::NonNull;
@ -49,14 +50,17 @@ impl TextEncoderMethods for TextEncoder {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://encoding.spec.whatwg.org/#dom-textencoder-encode // https://encoding.spec.whatwg.org/#dom-textencoder-encode
unsafe fn Encode(&self, cx: *mut JSContext, input: USVString) -> NonNull<JSObject> { fn Encode(&self, cx: JSContext, input: USVString) -> NonNull<JSObject> {
let encoded = input.0.as_bytes(); let encoded = input.0.as_bytes();
rooted!(in(cx) let mut js_object = ptr::null_mut::<JSObject>()); unsafe {
assert!( rooted!(in(*cx) let mut js_object = ptr::null_mut::<JSObject>());
Uint8Array::create(cx, CreateWith::Slice(&encoded), js_object.handle_mut()).is_ok() assert!(
); Uint8Array::create(*cx, CreateWith::Slice(&encoded), js_object.handle_mut())
.is_ok()
);
NonNull::new_unchecked(js_object.get()) NonNull::new_unchecked(js_object.get())
}
} }
} }

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

@ -9,8 +9,9 @@ use crate::dom::bindings::reflector::{reflect_dom_object, Reflector};
use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::vrfieldofview::VRFieldOfView; use crate::dom::vrfieldofview::VRFieldOfView;
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::default::Default; use std::default::Default;
use std::ptr; use std::ptr;
@ -44,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(),
); );
@ -67,8 +68,8 @@ impl VREyeParameters {
impl VREyeParametersMethods for VREyeParameters { impl VREyeParametersMethods for VREyeParameters {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vreyeparameters-offset // https://w3c.github.io/webvr/#dom-vreyeparameters-offset
unsafe fn Offset(&self, _cx: *mut JSContext) -> NonNull<JSObject> { fn Offset(&self, _cx: JSContext) -> NonNull<JSObject> {
NonNull::new_unchecked(self.offset.get()) unsafe { NonNull::new_unchecked(self.offset.get()) }
} }
// https://w3c.github.io/webvr/#dom-vreyeparameters-fieldofview // https://w3c.github.io/webvr/#dom-vreyeparameters-fieldofview

View file

@ -11,8 +11,9 @@ use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::vrpose::VRPose; use crate::dom::vrpose::VRPose;
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 js::jsapi::{Heap, JSContext, JSObject}; use js::jsapi::{Heap, JSObject};
use js::typedarray::{CreateWith, Float32Array}; use js::typedarray::{CreateWith, Float32Array};
use std::cell::Cell; use std::cell::Cell;
use std::ptr; use std::ptr;
@ -62,12 +63,10 @@ impl VRFrameData {
VRFrameDataBinding::Wrap, VRFrameDataBinding::Wrap,
); );
let cx = global.get_cx(); let cx = global.get_cx();
unsafe { 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); create_typed_array(cx, &matrix, &root.right_view);
create_typed_array(cx, &matrix, &root.right_view);
}
root root
} }
@ -79,9 +78,11 @@ impl VRFrameData {
/// FIXME(#22526) this should be in a better place /// FIXME(#22526) this should be in a better place
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub unsafe fn create_typed_array(cx: *mut JSContext, src: &[f32], dst: &Heap<*mut JSObject>) { pub fn create_typed_array(cx: JSContext, src: &[f32], dst: &Heap<*mut JSObject>) {
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(src), array.handle_mut()); unsafe {
let _ = Float32Array::create(*cx, CreateWith::Slice(src), array.handle_mut());
}
(*dst).set(array.get()); (*dst).set(array.get());
} }
@ -90,27 +91,27 @@ impl VRFrameData {
pub fn update(&self, data: &WebVRFrameData) { pub fn update(&self, data: &WebVRFrameData) {
unsafe { unsafe {
let cx = 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);
} }
typedarray!(in(cx) let left_view_array: Float32Array = self.left_view.get()); typedarray!(in(*cx) let left_view_array: Float32Array = self.left_view.get());
if let Ok(mut array) = left_view_array { if let Ok(mut array) = left_view_array {
array.update(&data.left_view_matrix); array.update(&data.left_view_matrix);
} }
typedarray!(in(cx) let right_proj_array: Float32Array = self.right_proj.get()); typedarray!(in(*cx) let right_proj_array: Float32Array = self.right_proj.get());
if let Ok(mut array) = right_proj_array { if let Ok(mut array) = right_proj_array {
array.update(&data.right_projection_matrix); array.update(&data.right_projection_matrix);
} }
typedarray!(in(cx) let right_view_array: Float32Array = self.right_view.get()); typedarray!(in(*cx) let right_view_array: Float32Array = self.right_view.get());
if let Ok(mut array) = right_view_array { if let Ok(mut array) = right_view_array {
array.update(&data.right_view_matrix); array.update(&data.right_view_matrix);
} }
} self.pose.update(&data.pose);
self.pose.update(&data.pose); self.timestamp.set(data.timestamp);
self.timestamp.set(data.timestamp); if self.first_timestamp.get() == 0.0 {
if self.first_timestamp.get() == 0.0 { self.first_timestamp.set(data.timestamp);
self.first_timestamp.set(data.timestamp); }
} }
} }
} }
@ -123,26 +124,26 @@ impl VRFrameDataMethods for VRFrameData {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrframedata-leftprojectionmatrix // https://w3c.github.io/webvr/#dom-vrframedata-leftprojectionmatrix
unsafe fn LeftProjectionMatrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> { fn LeftProjectionMatrix(&self, _cx: JSContext) -> NonNull<JSObject> {
NonNull::new_unchecked(self.left_proj.get()) unsafe { NonNull::new_unchecked(self.left_proj.get()) }
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrframedata-leftviewmatrix // https://w3c.github.io/webvr/#dom-vrframedata-leftviewmatrix
unsafe fn LeftViewMatrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> { fn LeftViewMatrix(&self, _cx: JSContext) -> NonNull<JSObject> {
NonNull::new_unchecked(self.left_view.get()) unsafe { NonNull::new_unchecked(self.left_view.get()) }
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrframedata-rightprojectionmatrix // https://w3c.github.io/webvr/#dom-vrframedata-rightprojectionmatrix
unsafe fn RightProjectionMatrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> { fn RightProjectionMatrix(&self, _cx: JSContext) -> NonNull<JSObject> {
NonNull::new_unchecked(self.right_proj.get()) unsafe { NonNull::new_unchecked(self.right_proj.get()) }
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrframedata-rightviewmatrix // https://w3c.github.io/webvr/#dom-vrframedata-rightviewmatrix
unsafe fn RightViewMatrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> { fn RightViewMatrix(&self, _cx: JSContext) -> NonNull<JSObject> {
NonNull::new_unchecked(self.right_view.get()) unsafe { NonNull::new_unchecked(self.right_view.get()) }
} }
// https://w3c.github.io/webvr/#dom-vrframedata-pose // https://w3c.github.io/webvr/#dom-vrframedata-pose

View file

@ -7,8 +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;
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;
@ -32,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) };
} }
} }
}, },
@ -95,75 +94,63 @@ 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( update_or_create_typed_array(
cx, cx,
pose.position.as_ref().map(|v| &v[..]), pose.orientation.as_ref().map(|v| &v[..]),
&self.position, &self.orientation,
); );
update_or_create_typed_array( update_or_create_typed_array(
cx, cx,
pose.orientation.as_ref().map(|v| &v[..]), pose.linear_velocity.as_ref().map(|v| &v[..]),
&self.orientation, &self.linear_vel,
); );
update_or_create_typed_array( update_or_create_typed_array(
cx, cx,
pose.linear_velocity.as_ref().map(|v| &v[..]), pose.angular_velocity.as_ref().map(|v| &v[..]),
&self.linear_vel, &self.angular_vel,
); );
update_or_create_typed_array( update_or_create_typed_array(
cx, cx,
pose.angular_velocity.as_ref().map(|v| &v[..]), pose.linear_acceleration.as_ref().map(|v| &v[..]),
&self.angular_vel, &self.linear_acc,
); );
update_or_create_typed_array( update_or_create_typed_array(
cx, cx,
pose.linear_acceleration.as_ref().map(|v| &v[..]), pose.angular_acceleration.as_ref().map(|v| &v[..]),
&self.linear_acc, &self.angular_acc,
); );
update_or_create_typed_array(
cx,
pose.angular_acceleration.as_ref().map(|v| &v[..]),
&self.angular_acc,
);
}
} }
} }
impl VRPoseMethods for VRPose { impl VRPoseMethods for VRPose {
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrpose-position // https://w3c.github.io/webvr/#dom-vrpose-position
unsafe fn GetPosition(&self, _cx: *mut JSContext) -> Option<NonNull<JSObject>> { fn GetPosition(&self, _cx: JSContext) -> Option<NonNull<JSObject>> {
heap_to_option(&self.position) heap_to_option(&self.position)
} }
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrpose-linearvelocity // https://w3c.github.io/webvr/#dom-vrpose-linearvelocity
unsafe fn GetLinearVelocity(&self, _cx: *mut JSContext) -> Option<NonNull<JSObject>> { fn GetLinearVelocity(&self, _cx: JSContext) -> Option<NonNull<JSObject>> {
heap_to_option(&self.linear_vel) heap_to_option(&self.linear_vel)
} }
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrpose-linearacceleration // https://w3c.github.io/webvr/#dom-vrpose-linearacceleration
unsafe fn GetLinearAcceleration(&self, _cx: *mut JSContext) -> Option<NonNull<JSObject>> { fn GetLinearAcceleration(&self, _cx: JSContext) -> Option<NonNull<JSObject>> {
heap_to_option(&self.linear_acc) heap_to_option(&self.linear_acc)
} }
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrpose-orientation // https://w3c.github.io/webvr/#dom-vrpose-orientation
unsafe fn GetOrientation(&self, _cx: *mut JSContext) -> Option<NonNull<JSObject>> { fn GetOrientation(&self, _cx: JSContext) -> Option<NonNull<JSObject>> {
heap_to_option(&self.orientation) heap_to_option(&self.orientation)
} }
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrpose-angularvelocity // https://w3c.github.io/webvr/#dom-vrpose-angularvelocity
unsafe fn GetAngularVelocity(&self, _cx: *mut JSContext) -> Option<NonNull<JSObject>> { fn GetAngularVelocity(&self, _cx: JSContext) -> Option<NonNull<JSObject>> {
heap_to_option(&self.angular_vel) heap_to_option(&self.angular_vel)
} }
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrpose-angularacceleration // https://w3c.github.io/webvr/#dom-vrpose-angularacceleration
unsafe fn GetAngularAcceleration(&self, _cx: *mut JSContext) -> 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

@ -9,8 +9,9 @@ use crate::dom::bindings::num::Finite;
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;
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;
@ -42,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(),
); );
@ -66,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);
} }
@ -78,8 +79,8 @@ impl VRStageParameters {
impl VRStageParametersMethods for VRStageParameters { impl VRStageParametersMethods for VRStageParameters {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrstageparameters-sittingtostandingtransform // https://w3c.github.io/webvr/#dom-vrstageparameters-sittingtostandingtransform
unsafe fn SittingToStandingTransform(&self, _cx: *mut JSContext) -> NonNull<JSObject> { fn SittingToStandingTransform(&self, _cx: JSContext) -> NonNull<JSObject> {
NonNull::new_unchecked(self.transform.get()) unsafe { NonNull::new_unchecked(self.transform.get()) }
} }
// https://w3c.github.io/webvr/#dom-vrstageparameters-sizex // https://w3c.github.io/webvr/#dom-vrstageparameters-sizex

View file

@ -29,11 +29,12 @@ use crate::dom::webglshaderprecisionformat::WebGLShaderPrecisionFormat;
use crate::dom::webgltexture::WebGLTexture; use crate::dom::webgltexture::WebGLTexture;
use crate::dom::webgluniformlocation::WebGLUniformLocation; use crate::dom::webgluniformlocation::WebGLUniformLocation;
use crate::dom::window::Window; use crate::dom::window::Window;
use crate::script_runtime::JSContext;
/// https://www.khronos.org/registry/webgl/specs/latest/2.0/webgl.idl /// https://www.khronos.org/registry/webgl/specs/latest/2.0/webgl.idl
use canvas_traits::webgl::{GLContextAttributes, WebGLVersion}; use canvas_traits::webgl::{GLContextAttributes, WebGLVersion};
use dom_struct::dom_struct; use dom_struct::dom_struct;
use euclid::default::Size2D; use euclid::default::Size2D;
use js::jsapi::{JSContext, JSObject}; use js::jsapi::JSObject;
use js::jsval::JSVal; use js::jsval::JSVal;
use js::rust::CustomAutoRooterGuard; use js::rust::CustomAutoRooterGuard;
use js::typedarray::ArrayBufferView; use js::typedarray::ArrayBufferView;
@ -109,21 +110,19 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext {
self.base.DrawingBufferHeight() self.base.DrawingBufferHeight()
} }
#[allow(unsafe_code)]
/// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5
unsafe fn GetBufferParameter(&self, _cx: *mut JSContext, target: u32, parameter: u32) -> JSVal { fn GetBufferParameter(&self, cx: JSContext, target: u32, parameter: u32) -> JSVal {
self.base.GetBufferParameter(_cx, target, parameter) self.base.GetBufferParameter(cx, target, parameter)
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
/// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3
unsafe fn GetParameter(&self, cx: *mut JSContext, parameter: u32) -> JSVal { fn GetParameter(&self, cx: JSContext, parameter: u32) -> JSVal {
self.base.GetParameter(cx, parameter) self.base.GetParameter(cx, parameter)
} }
#[allow(unsafe_code)]
/// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8
unsafe fn GetTexParameter(&self, cx: *mut JSContext, target: u32, pname: u32) -> JSVal { fn GetTexParameter(&self, cx: JSContext, target: u32, pname: u32) -> JSVal {
self.base.GetTexParameter(cx, target, pname) self.base.GetTexParameter(cx, target, pname)
} }
@ -142,21 +141,15 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext {
self.base.GetSupportedExtensions() self.base.GetSupportedExtensions()
} }
#[allow(unsafe_code)]
/// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.14 /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.14
unsafe fn GetExtension( fn GetExtension(&self, cx: JSContext, name: DOMString) -> Option<NonNull<JSObject>> {
&self,
cx: *mut JSContext,
name: DOMString,
) -> Option<NonNull<JSObject>> {
self.base.GetExtension(cx, name) self.base.GetExtension(cx, name)
} }
#[allow(unsafe_code)]
/// https://www.khronos.org/registry/webgl/specs/latest/2.0/#3.7.4 /// https://www.khronos.org/registry/webgl/specs/latest/2.0/#3.7.4
unsafe fn GetFramebufferAttachmentParameter( fn GetFramebufferAttachmentParameter(
&self, &self,
cx: *mut JSContext, cx: JSContext,
target: u32, target: u32,
attachment: u32, attachment: u32,
pname: u32, pname: u32,
@ -165,14 +158,8 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext {
.GetFramebufferAttachmentParameter(cx, target, attachment, pname) .GetFramebufferAttachmentParameter(cx, target, attachment, pname)
} }
#[allow(unsafe_code)]
/// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7 /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7
unsafe fn GetRenderbufferParameter( fn GetRenderbufferParameter(&self, cx: JSContext, target: u32, pname: u32) -> JSVal {
&self,
cx: *mut JSContext,
target: u32,
pname: u32,
) -> JSVal {
self.base.GetRenderbufferParameter(cx, target, pname) self.base.GetRenderbufferParameter(cx, target, pname)
} }
@ -505,14 +492,8 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext {
self.base.GetProgramInfoLog(program) self.base.GetProgramInfoLog(program)
} }
#[allow(unsafe_code)]
/// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9
unsafe fn GetProgramParameter( fn GetProgramParameter(&self, cx: JSContext, program: &WebGLProgram, param_id: u32) -> JSVal {
&self,
cx: *mut JSContext,
program: &WebGLProgram,
param_id: u32,
) -> JSVal {
self.base.GetProgramParameter(cx, program, param_id) self.base.GetProgramParameter(cx, program, param_id)
} }
@ -521,14 +502,8 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext {
self.base.GetShaderInfoLog(shader) self.base.GetShaderInfoLog(shader)
} }
#[allow(unsafe_code)]
/// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9
unsafe fn GetShaderParameter( fn GetShaderParameter(&self, cx: JSContext, shader: &WebGLShader, param_id: u32) -> JSVal {
&self,
cx: *mut JSContext,
shader: &WebGLShader,
param_id: u32,
) -> JSVal {
self.base.GetShaderParameter(cx, shader, param_id) self.base.GetShaderParameter(cx, shader, param_id)
} }
@ -551,9 +526,8 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext {
self.base.GetUniformLocation(program, name) self.base.GetUniformLocation(program, name)
} }
#[allow(unsafe_code)]
/// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9
unsafe fn GetVertexAttrib(&self, cx: *mut JSContext, index: u32, pname: u32) -> JSVal { fn GetVertexAttrib(&self, cx: JSContext, index: u32, pname: u32) -> JSVal {
self.base.GetVertexAttrib(cx, index, pname) self.base.GetVertexAttrib(cx, index, pname)
} }
@ -815,10 +789,9 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext {
} }
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10
#[allow(unsafe_code)] fn GetUniform(
unsafe fn GetUniform(
&self, &self,
cx: *mut JSContext, cx: JSContext,
program: &WebGLProgram, program: &WebGLProgram,
location: &WebGLUniformLocation, location: &WebGLUniformLocation,
) -> JSVal { ) -> JSVal {

View file

@ -48,6 +48,7 @@ use crate::dom::webgltexture::{TexParameterValue, WebGLTexture};
use crate::dom::webgluniformlocation::WebGLUniformLocation; use crate::dom::webgluniformlocation::WebGLUniformLocation;
use crate::dom::webglvertexarrayobjectoes::WebGLVertexArrayObjectOES; use crate::dom::webglvertexarrayobjectoes::WebGLVertexArrayObjectOES;
use crate::dom::window::Window; use crate::dom::window::Window;
use crate::script_runtime::JSContext as SafeJSContext;
#[cfg(feature = "webgl_backtrace")] #[cfg(feature = "webgl_backtrace")]
use backtrace::Backtrace; use backtrace::Backtrace;
use canvas_traits::webgl::WebGLError::*; use canvas_traits::webgl::WebGLError::*;
@ -1148,9 +1149,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
receiver.recv().unwrap() receiver.recv().unwrap()
} }
#[allow(unsafe_code)]
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5
unsafe fn GetBufferParameter(&self, _cx: *mut JSContext, target: u32, parameter: u32) -> JSVal { fn GetBufferParameter(&self, _cx: SafeJSContext, target: u32, parameter: u32) -> JSVal {
let buffer = handle_potential_webgl_error!( let buffer = handle_potential_webgl_error!(
self, self,
self.bound_buffer(target) self.bound_buffer(target)
@ -1170,7 +1170,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3
unsafe fn GetParameter(&self, cx: *mut JSContext, parameter: u32) -> JSVal { fn GetParameter(&self, cx: SafeJSContext, parameter: u32) -> JSVal {
if !self if !self
.extension_manager .extension_manager
.is_get_parameter_name_enabled(parameter) .is_get_parameter_name_enabled(parameter)
@ -1180,41 +1180,41 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
} }
match parameter { match parameter {
constants::ARRAY_BUFFER_BINDING => { constants::ARRAY_BUFFER_BINDING => unsafe {
return optional_root_object_to_js_or_null!(cx, &self.bound_buffer_array.get()); return optional_root_object_to_js_or_null!(*cx, &self.bound_buffer_array.get());
}, },
constants::CURRENT_PROGRAM => { constants::CURRENT_PROGRAM => unsafe {
return optional_root_object_to_js_or_null!(cx, &self.current_program.get()); return optional_root_object_to_js_or_null!(*cx, &self.current_program.get());
}, },
constants::ELEMENT_ARRAY_BUFFER_BINDING => { constants::ELEMENT_ARRAY_BUFFER_BINDING => unsafe {
let buffer = self.current_vao().element_array_buffer().get(); let buffer = self.current_vao().element_array_buffer().get();
return optional_root_object_to_js_or_null!(cx, buffer); return optional_root_object_to_js_or_null!(*cx, buffer);
}, },
constants::FRAMEBUFFER_BINDING => { constants::FRAMEBUFFER_BINDING => unsafe {
return optional_root_object_to_js_or_null!(cx, &self.bound_framebuffer.get()); return optional_root_object_to_js_or_null!(*cx, &self.bound_framebuffer.get());
}, },
constants::RENDERBUFFER_BINDING => { constants::RENDERBUFFER_BINDING => unsafe {
return optional_root_object_to_js_or_null!(cx, &self.bound_renderbuffer.get()); return optional_root_object_to_js_or_null!(*cx, &self.bound_renderbuffer.get());
}, },
constants::TEXTURE_BINDING_2D => { constants::TEXTURE_BINDING_2D => unsafe {
let texture = self let texture = self
.textures .textures
.active_texture_slot(constants::TEXTURE_2D) .active_texture_slot(constants::TEXTURE_2D)
.unwrap() .unwrap()
.get(); .get();
return optional_root_object_to_js_or_null!(cx, texture); return optional_root_object_to_js_or_null!(*cx, texture);
}, },
constants::TEXTURE_BINDING_CUBE_MAP => { constants::TEXTURE_BINDING_CUBE_MAP => unsafe {
let texture = self let texture = self
.textures .textures
.active_texture_slot(constants::TEXTURE_CUBE_MAP) .active_texture_slot(constants::TEXTURE_CUBE_MAP)
.unwrap() .unwrap()
.get(); .get();
return optional_root_object_to_js_or_null!(cx, texture); return optional_root_object_to_js_or_null!(*cx, texture);
}, },
OESVertexArrayObjectConstants::VERTEX_ARRAY_BINDING_OES => { OESVertexArrayObjectConstants::VERTEX_ARRAY_BINDING_OES => unsafe {
let vao = self.current_vao.get().filter(|vao| vao.id().is_some()); let vao = self.current_vao.get().filter(|vao| vao.id().is_some());
return optional_root_object_to_js_or_null!(cx, vao); return optional_root_object_to_js_or_null!(*cx, vao);
}, },
// In readPixels we currently support RGBA/UBYTE only. If // In readPixels we currently support RGBA/UBYTE only. If
// we wanted to support other formats, we could ask the // we wanted to support other formats, we could ask the
@ -1227,27 +1227,27 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
constants::IMPLEMENTATION_COLOR_READ_TYPE => { constants::IMPLEMENTATION_COLOR_READ_TYPE => {
return Int32Value(constants::UNSIGNED_BYTE as i32); return Int32Value(constants::UNSIGNED_BYTE as i32);
}, },
constants::COMPRESSED_TEXTURE_FORMATS => { constants::COMPRESSED_TEXTURE_FORMATS => unsafe {
let format_ids = self.extension_manager.get_tex_compression_ids(); let format_ids = self.extension_manager.get_tex_compression_ids();
rooted!(in(cx) let mut rval = ptr::null_mut::<JSObject>()); rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>());
let _ = Uint32Array::create(cx, CreateWith::Slice(&format_ids), rval.handle_mut()) let _ = Uint32Array::create(*cx, CreateWith::Slice(&format_ids), rval.handle_mut())
.unwrap(); .unwrap();
return ObjectValue(rval.get()); return ObjectValue(rval.get());
}, },
constants::VERSION => { constants::VERSION => unsafe {
rooted!(in(cx) let mut rval = UndefinedValue()); rooted!(in(*cx) let mut rval = UndefinedValue());
"WebGL 1.0".to_jsval(cx, rval.handle_mut()); "WebGL 1.0".to_jsval(*cx, rval.handle_mut());
return rval.get(); return rval.get();
}, },
constants::RENDERER | constants::VENDOR => { constants::RENDERER | constants::VENDOR => unsafe {
rooted!(in(cx) let mut rval = UndefinedValue()); rooted!(in(*cx) let mut rval = UndefinedValue());
"Mozilla/Servo".to_jsval(cx, rval.handle_mut()); "Mozilla/Servo".to_jsval(*cx, rval.handle_mut());
return rval.get(); return rval.get();
}, },
constants::SHADING_LANGUAGE_VERSION => { constants::SHADING_LANGUAGE_VERSION => unsafe {
rooted!(in(cx) let mut rval = UndefinedValue()); rooted!(in(*cx) let mut rval = UndefinedValue());
"WebGL GLSL ES 1.0".to_jsval(cx, rval.handle_mut()); "WebGL GLSL ES 1.0".to_jsval(*cx, rval.handle_mut());
return rval.get(); return rval.get();
}, },
constants::UNPACK_FLIP_Y_WEBGL => { constants::UNPACK_FLIP_Y_WEBGL => {
@ -1314,11 +1314,11 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
self.send_command(WebGLCommand::GetParameterBool(param, sender)); self.send_command(WebGLCommand::GetParameterBool(param, sender));
BooleanValue(receiver.recv().unwrap()) BooleanValue(receiver.recv().unwrap())
}, },
Parameter::Bool4(param) => { Parameter::Bool4(param) => unsafe {
let (sender, receiver) = webgl_channel().unwrap(); let (sender, receiver) = webgl_channel().unwrap();
self.send_command(WebGLCommand::GetParameterBool4(param, sender)); self.send_command(WebGLCommand::GetParameterBool4(param, sender));
rooted!(in(cx) let mut rval = UndefinedValue()); rooted!(in(*cx) let mut rval = UndefinedValue());
receiver.recv().unwrap().to_jsval(cx, rval.handle_mut()); receiver.recv().unwrap().to_jsval(*cx, rval.handle_mut());
rval.get() rval.get()
}, },
Parameter::Int(param) => { Parameter::Int(param) => {
@ -1326,24 +1326,24 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
self.send_command(WebGLCommand::GetParameterInt(param, sender)); self.send_command(WebGLCommand::GetParameterInt(param, sender));
Int32Value(receiver.recv().unwrap()) Int32Value(receiver.recv().unwrap())
}, },
Parameter::Int2(param) => { Parameter::Int2(param) => unsafe {
let (sender, receiver) = webgl_channel().unwrap(); let (sender, receiver) = webgl_channel().unwrap();
self.send_command(WebGLCommand::GetParameterInt2(param, sender)); self.send_command(WebGLCommand::GetParameterInt2(param, sender));
rooted!(in(cx) let mut rval = ptr::null_mut::<JSObject>()); rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>());
let _ = Int32Array::create( let _ = Int32Array::create(
cx, *cx,
CreateWith::Slice(&receiver.recv().unwrap()), CreateWith::Slice(&receiver.recv().unwrap()),
rval.handle_mut(), rval.handle_mut(),
) )
.unwrap(); .unwrap();
ObjectValue(rval.get()) ObjectValue(rval.get())
}, },
Parameter::Int4(param) => { Parameter::Int4(param) => unsafe {
let (sender, receiver) = webgl_channel().unwrap(); let (sender, receiver) = webgl_channel().unwrap();
self.send_command(WebGLCommand::GetParameterInt4(param, sender)); self.send_command(WebGLCommand::GetParameterInt4(param, sender));
rooted!(in(cx) let mut rval = ptr::null_mut::<JSObject>()); rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>());
let _ = Int32Array::create( let _ = Int32Array::create(
cx, *cx,
CreateWith::Slice(&receiver.recv().unwrap()), CreateWith::Slice(&receiver.recv().unwrap()),
rval.handle_mut(), rval.handle_mut(),
) )
@ -1355,24 +1355,24 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
self.send_command(WebGLCommand::GetParameterFloat(param, sender)); self.send_command(WebGLCommand::GetParameterFloat(param, sender));
DoubleValue(receiver.recv().unwrap() as f64) DoubleValue(receiver.recv().unwrap() as f64)
}, },
Parameter::Float2(param) => { Parameter::Float2(param) => unsafe {
let (sender, receiver) = webgl_channel().unwrap(); let (sender, receiver) = webgl_channel().unwrap();
self.send_command(WebGLCommand::GetParameterFloat2(param, sender)); self.send_command(WebGLCommand::GetParameterFloat2(param, sender));
rooted!(in(cx) let mut rval = ptr::null_mut::<JSObject>()); rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>());
let _ = Float32Array::create( let _ = Float32Array::create(
cx, *cx,
CreateWith::Slice(&receiver.recv().unwrap()), CreateWith::Slice(&receiver.recv().unwrap()),
rval.handle_mut(), rval.handle_mut(),
) )
.unwrap(); .unwrap();
ObjectValue(rval.get()) ObjectValue(rval.get())
}, },
Parameter::Float4(param) => { Parameter::Float4(param) => unsafe {
let (sender, receiver) = webgl_channel().unwrap(); let (sender, receiver) = webgl_channel().unwrap();
self.send_command(WebGLCommand::GetParameterFloat4(param, sender)); self.send_command(WebGLCommand::GetParameterFloat4(param, sender));
rooted!(in(cx) let mut rval = ptr::null_mut::<JSObject>()); rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>());
let _ = Float32Array::create( let _ = Float32Array::create(
cx, *cx,
CreateWith::Slice(&receiver.recv().unwrap()), CreateWith::Slice(&receiver.recv().unwrap()),
rval.handle_mut(), rval.handle_mut(),
) )
@ -1382,9 +1382,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
} }
} }
#[allow(unsafe_code)]
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8
unsafe fn GetTexParameter(&self, _cx: *mut JSContext, target: u32, pname: u32) -> JSVal { fn GetTexParameter(&self, _cx: SafeJSContext, target: u32, pname: u32) -> JSVal {
let texture_slot = handle_potential_webgl_error!( let texture_slot = handle_potential_webgl_error!(
self, self,
self.textures.active_texture_slot(target), self.textures.active_texture_slot(target),
@ -1484,13 +1483,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
) )
} }
#[allow(unsafe_code)]
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.14 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.14
unsafe fn GetExtension( fn GetExtension(&self, _cx: SafeJSContext, name: DOMString) -> Option<NonNull<JSObject>> {
&self,
_cx: *mut JSContext,
name: DOMString,
) -> Option<NonNull<JSObject>> {
self.extension_manager self.extension_manager
.init_once(|| self.get_gl_extensions()); .init_once(|| self.get_gl_extensions());
self.extension_manager.get_or_init_extension(&name, self) self.extension_manager.get_or_init_extension(&name, self)
@ -2326,9 +2320,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6
unsafe fn GetFramebufferAttachmentParameter( fn GetFramebufferAttachmentParameter(
&self, &self,
cx: *mut JSContext, cx: SafeJSContext,
target: u32, target: u32,
attachment: u32, attachment: u32,
pname: u32, pname: u32,
@ -2411,14 +2405,14 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
let fb = self.bound_framebuffer.get().unwrap(); let fb = self.bound_framebuffer.get().unwrap();
if let Some(webgl_attachment) = fb.attachment(attachment) { if let Some(webgl_attachment) = fb.attachment(attachment) {
match webgl_attachment { match webgl_attachment {
WebGLFramebufferAttachmentRoot::Renderbuffer(rb) => { WebGLFramebufferAttachmentRoot::Renderbuffer(rb) => unsafe {
rooted!(in(cx) let mut rval = NullValue()); rooted!(in(*cx) let mut rval = NullValue());
rb.to_jsval(cx, rval.handle_mut()); rb.to_jsval(*cx, rval.handle_mut());
return rval.get(); return rval.get();
}, },
WebGLFramebufferAttachmentRoot::Texture(texture) => { WebGLFramebufferAttachmentRoot::Texture(texture) => unsafe {
rooted!(in(cx) let mut rval = NullValue()); rooted!(in(*cx) let mut rval = NullValue());
texture.to_jsval(cx, rval.handle_mut()); texture.to_jsval(*cx, rval.handle_mut());
return rval.get(); return rval.get();
}, },
} }
@ -2435,14 +2429,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
Int32Value(receiver.recv().unwrap()) Int32Value(receiver.recv().unwrap())
} }
#[allow(unsafe_code)]
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7
unsafe fn GetRenderbufferParameter( fn GetRenderbufferParameter(&self, _cx: SafeJSContext, target: u32, pname: u32) -> JSVal {
&self,
_cx: *mut JSContext,
target: u32,
pname: u32,
) -> JSVal {
let target_matches = target == constants::RENDERBUFFER; let target_matches = target == constants::RENDERBUFFER;
let pname_matches = match pname { let pname_matches = match pname {
@ -2494,14 +2482,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
} }
} }
#[allow(unsafe_code)]
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9
unsafe fn GetProgramParameter( fn GetProgramParameter(&self, _: SafeJSContext, program: &WebGLProgram, param: u32) -> JSVal {
&self,
_: *mut JSContext,
program: &WebGLProgram,
param: u32,
) -> JSVal {
handle_potential_webgl_error!(self, self.validate_ownership(program), return NullValue()); handle_potential_webgl_error!(self, self.validate_ownership(program), return NullValue());
if program.is_deleted() { if program.is_deleted() {
self.webgl_error(InvalidOperation); self.webgl_error(InvalidOperation);
@ -2541,14 +2523,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
Some(shader.info_log()) Some(shader.info_log())
} }
#[allow(unsafe_code)]
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9
unsafe fn GetShaderParameter( fn GetShaderParameter(&self, _: SafeJSContext, shader: &WebGLShader, param: u32) -> JSVal {
&self,
_: *mut JSContext,
shader: &WebGLShader,
param: u32,
) -> JSVal {
handle_potential_webgl_error!(self, self.validate_ownership(shader), return NullValue()); handle_potential_webgl_error!(self, self.validate_ownership(shader), return NullValue());
if shader.is_deleted() { if shader.is_deleted() {
self.webgl_error(InvalidValue); self.webgl_error(InvalidValue);
@ -2620,7 +2596,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9
unsafe fn GetVertexAttrib(&self, cx: *mut JSContext, index: u32, param: u32) -> JSVal { fn GetVertexAttrib(&self, cx: SafeJSContext, index: u32, param: u32) -> JSVal {
let current_vao = self.current_vao(); let current_vao = self.current_vao();
let data = handle_potential_webgl_error!( let data = handle_potential_webgl_error!(
self, self,
@ -2636,10 +2612,12 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
self.send_command(WebGLCommand::GetCurrentVertexAttrib(index, sender)); self.send_command(WebGLCommand::GetCurrentVertexAttrib(index, sender));
receiver.recv().unwrap() receiver.recv().unwrap()
}; };
rooted!(in(cx) let mut result = ptr::null_mut::<JSObject>()); unsafe {
let _ = rooted!(in(*cx) let mut result = ptr::null_mut::<JSObject>());
Float32Array::create(cx, CreateWith::Slice(&value), result.handle_mut()).unwrap(); let _ = Float32Array::create(*cx, CreateWith::Slice(&value), result.handle_mut())
return ObjectValue(result.get()); .unwrap();
return ObjectValue(result.get());
}
} }
if !self if !self
@ -2656,10 +2634,10 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
constants::VERTEX_ATTRIB_ARRAY_TYPE => Int32Value(data.type_ as i32), constants::VERTEX_ATTRIB_ARRAY_TYPE => Int32Value(data.type_ as i32),
constants::VERTEX_ATTRIB_ARRAY_NORMALIZED => BooleanValue(data.normalized), constants::VERTEX_ATTRIB_ARRAY_NORMALIZED => BooleanValue(data.normalized),
constants::VERTEX_ATTRIB_ARRAY_STRIDE => Int32Value(data.stride as i32), constants::VERTEX_ATTRIB_ARRAY_STRIDE => Int32Value(data.stride as i32),
constants::VERTEX_ATTRIB_ARRAY_BUFFER_BINDING => { constants::VERTEX_ATTRIB_ARRAY_BUFFER_BINDING => unsafe {
rooted!(in(cx) let mut jsval = NullValue()); rooted!(in(*cx) let mut jsval = NullValue());
if let Some(buffer) = data.buffer() { if let Some(buffer) = data.buffer() {
buffer.to_jsval(cx, jsval.handle_mut()); buffer.to_jsval(*cx, jsval.handle_mut());
} }
jsval.get() jsval.get()
}, },
@ -3432,9 +3410,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn GetUniform( fn GetUniform(
&self, &self,
cx: *mut JSContext, cx: SafeJSContext,
program: &WebGLProgram, program: &WebGLProgram,
location: &WebGLUniformLocation, location: &WebGLUniformLocation,
) -> JSVal { ) -> JSVal {
@ -3477,42 +3455,48 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
match location.type_() { match location.type_() {
constants::BOOL => BooleanValue(get(triple, WebGLCommand::GetUniformBool)), constants::BOOL => BooleanValue(get(triple, WebGLCommand::GetUniformBool)),
constants::BOOL_VEC2 => { constants::BOOL_VEC2 => unsafe {
rooted!(in(cx) let mut rval = NullValue()); rooted!(in(*cx) let mut rval = NullValue());
get(triple, WebGLCommand::GetUniformBool2).to_jsval(cx, rval.handle_mut()); get(triple, WebGLCommand::GetUniformBool2).to_jsval(*cx, rval.handle_mut());
rval.get() rval.get()
}, },
constants::BOOL_VEC3 => { constants::BOOL_VEC3 => unsafe {
rooted!(in(cx) let mut rval = NullValue()); rooted!(in(*cx) let mut rval = NullValue());
get(triple, WebGLCommand::GetUniformBool3).to_jsval(cx, rval.handle_mut()); get(triple, WebGLCommand::GetUniformBool3).to_jsval(*cx, rval.handle_mut());
rval.get() rval.get()
}, },
constants::BOOL_VEC4 => { constants::BOOL_VEC4 => unsafe {
rooted!(in(cx) let mut rval = NullValue()); rooted!(in(*cx) let mut rval = NullValue());
get(triple, WebGLCommand::GetUniformBool4).to_jsval(cx, rval.handle_mut()); get(triple, WebGLCommand::GetUniformBool4).to_jsval(*cx, rval.handle_mut());
rval.get() rval.get()
}, },
constants::INT | constants::SAMPLER_2D | constants::SAMPLER_CUBE => { constants::INT | constants::SAMPLER_2D | constants::SAMPLER_CUBE => {
Int32Value(get(triple, WebGLCommand::GetUniformInt)) Int32Value(get(triple, WebGLCommand::GetUniformInt))
}, },
constants::INT_VEC2 => typed::<Int32>(cx, &get(triple, WebGLCommand::GetUniformInt2)), constants::INT_VEC2 => unsafe {
constants::INT_VEC3 => typed::<Int32>(cx, &get(triple, WebGLCommand::GetUniformInt3)), typed::<Int32>(*cx, &get(triple, WebGLCommand::GetUniformInt2))
constants::INT_VEC4 => typed::<Int32>(cx, &get(triple, WebGLCommand::GetUniformInt4)), },
constants::INT_VEC3 => unsafe {
typed::<Int32>(*cx, &get(triple, WebGLCommand::GetUniformInt3))
},
constants::INT_VEC4 => unsafe {
typed::<Int32>(*cx, &get(triple, WebGLCommand::GetUniformInt4))
},
constants::FLOAT => DoubleValue(get(triple, WebGLCommand::GetUniformFloat) as f64), constants::FLOAT => DoubleValue(get(triple, WebGLCommand::GetUniformFloat) as f64),
constants::FLOAT_VEC2 => { constants::FLOAT_VEC2 => unsafe {
typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat2)) typed::<Float32>(*cx, &get(triple, WebGLCommand::GetUniformFloat2))
}, },
constants::FLOAT_VEC3 => { constants::FLOAT_VEC3 => unsafe {
typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat3)) typed::<Float32>(*cx, &get(triple, WebGLCommand::GetUniformFloat3))
}, },
constants::FLOAT_VEC4 | constants::FLOAT_MAT2 => { constants::FLOAT_VEC4 | constants::FLOAT_MAT2 => unsafe {
typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat4)) typed::<Float32>(*cx, &get(triple, WebGLCommand::GetUniformFloat4))
}, },
constants::FLOAT_MAT3 => { constants::FLOAT_MAT3 => unsafe {
typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat9)) typed::<Float32>(*cx, &get(triple, WebGLCommand::GetUniformFloat9))
}, },
constants::FLOAT_MAT4 => { constants::FLOAT_MAT4 => unsafe {
typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat16)) typed::<Float32>(*cx, &get(triple, WebGLCommand::GetUniformFloat16))
}, },
_ => panic!("wrong uniform type"), _ => panic!("wrong uniform type"),
} }

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,7 +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, Runtime, ScriptChan, ScriptPort, ScriptThreadEventCategory, CommonScriptMsg, JSContext, Runtime, ScriptChan, ScriptPort, 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};
@ -79,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;
@ -371,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> {
@ -614,26 +614,28 @@ 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
unsafe fn Opener(&self, cx: *mut JSContext) -> JSVal { fn Opener(&self, cx: JSContext) -> JSVal {
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
unsafe fn SetOpener(&self, cx: *mut JSContext, 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();
} }
// Step 2. // Step 2.
let obj = self.reflector().get_jsobject(); let obj = self.reflector().get_jsobject();
assert!(JS_DefineProperty( unsafe {
cx, assert!(JS_DefineProperty(
obj, *cx,
"opener\0".as_ptr() as *const libc::c_char, obj,
value, "opener\0".as_ptr() as *const libc::c_char,
JSPROP_ENUMERATE as u32 value,
)); JSPROP_ENUMERATE as u32
));
}
} }
// https://html.spec.whatwg.org/multipage/#dom-window-closed // https://html.spec.whatwg.org/multipage/#dom-window-closed
@ -738,11 +740,10 @@ impl WindowMethods for Window {
self.navigator.or_init(|| Navigator::new(self)) self.navigator.or_init(|| Navigator::new(self))
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout
unsafe fn SetTimeout( fn SetTimeout(
&self, &self,
_cx: *mut JSContext, _cx: JSContext,
callback: Rc<Function>, callback: Rc<Function>,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,
@ -755,11 +756,10 @@ impl WindowMethods for Window {
) )
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout
unsafe fn SetTimeout_( fn SetTimeout_(
&self, &self,
_cx: *mut JSContext, _cx: JSContext,
callback: DOMString, callback: DOMString,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,
@ -778,11 +778,10 @@ impl WindowMethods for Window {
.clear_timeout_or_interval(handle); .clear_timeout_or_interval(handle);
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval
unsafe fn SetInterval( fn SetInterval(
&self, &self,
_cx: *mut JSContext, _cx: JSContext,
callback: Rc<Function>, callback: Rc<Function>,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,
@ -795,11 +794,10 @@ impl WindowMethods for Window {
) )
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval
unsafe fn SetInterval_( fn SetInterval_(
&self, &self,
_cx: *mut JSContext, _cx: JSContext,
callback: DOMString, callback: DOMString,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,
@ -902,14 +900,8 @@ impl WindowMethods for Window {
doc.cancel_animation_frame(ident); doc.cancel_animation_frame(ident);
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-window-postmessage // https://html.spec.whatwg.org/multipage/#dom-window-postmessage
unsafe fn PostMessage( fn PostMessage(&self, cx: JSContext, message: HandleValue, origin: DOMString) -> ErrorResult {
&self,
cx: *mut JSContext,
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();
@ -925,7 +917,7 @@ impl WindowMethods for Window {
// Step 1-2, 6-8. // Step 1-2, 6-8.
// TODO(#12717): Should implement the `transfer` argument. // TODO(#12717): Should implement the `transfer` argument.
let data = StructuredCloneData::write(cx, message)?; let data = StructuredCloneData::write(*cx, message)?;
// Step 9. // Step 9.
self.post_message(origin, &*source.window_proxy(), data); self.post_message(origin, &*source.window_proxy(), data);
@ -950,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);
} }
} }
@ -960,8 +952,8 @@ impl WindowMethods for Window {
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn WebdriverCallback(&self, cx: *mut JSContext, val: HandleValue) { fn WebdriverCallback(&self, cx: JSContext, val: HandleValue) {
let rv = 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 {
chan.send(rv).unwrap(); chan.send(rv).unwrap();
@ -2179,7 +2171,7 @@ impl Window {
player_context, player_context,
}); });
unsafe { WindowBinding::Wrap(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> {
@ -2281,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

@ -21,12 +21,13 @@ use crate::dom::eventtarget::EventTarget;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::messageevent::MessageEvent; use crate::dom::messageevent::MessageEvent;
use crate::dom::workerglobalscope::prepare_workerscope_init; use crate::dom::workerglobalscope::prepare_workerscope_init;
use crate::script_runtime::JSContext;
use crate::task::TaskOnce; use crate::task::TaskOnce;
use crossbeam_channel::{unbounded, Sender}; use crossbeam_channel::{unbounded, Sender};
use devtools_traits::{DevtoolsPageInfo, ScriptToDevtoolsControlMsg}; use devtools_traits::{DevtoolsPageInfo, ScriptToDevtoolsControlMsg};
use dom_struct::dom_struct; use dom_struct::dom_struct;
use ipc_channel::ipc; use ipc_channel::ipc;
use js::jsapi::{JSContext, JS_RequestInterruptCallback}; use js::jsapi::JS_RequestInterruptCallback;
use js::jsval::UndefinedValue; use js::jsval::UndefinedValue;
use js::rust::HandleValue; use js::rust::HandleValue;
use script_traits::WorkerScriptLoadOrigin; use script_traits::WorkerScriptLoadOrigin;
@ -146,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);
} }
@ -158,10 +159,9 @@ impl Worker {
} }
impl WorkerMethods for Worker { impl WorkerMethods for Worker {
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-worker-postmessage // https://html.spec.whatwg.org/multipage/#dom-worker-postmessage
unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { fn PostMessage(&self, cx: JSContext, message: HandleValue) -> ErrorResult {
let data = StructuredCloneData::write(cx, message)?; let data = StructuredCloneData::write(*cx, message)?;
let address = Trusted::new(self); let address = Trusted::new(self);
// NOTE: step 9 of https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage // NOTE: step 9 of https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage
@ -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,6 +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;
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;
@ -39,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};
@ -164,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 {
@ -288,11 +290,10 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope {
base64_atob(atob) base64_atob(atob)
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout
unsafe fn SetTimeout( fn SetTimeout(
&self, &self,
_cx: *mut JSContext, _cx: JSContext,
callback: Rc<Function>, callback: Rc<Function>,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,
@ -305,11 +306,10 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope {
) )
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout
unsafe fn SetTimeout_( fn SetTimeout_(
&self, &self,
_cx: *mut JSContext, _cx: JSContext,
callback: DOMString, callback: DOMString,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,
@ -328,11 +328,10 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope {
.clear_timeout_or_interval(handle); .clear_timeout_or_interval(handle);
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval
unsafe fn SetInterval( fn SetInterval(
&self, &self,
_cx: *mut JSContext, _cx: JSContext,
callback: Rc<Function>, callback: Rc<Function>,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,
@ -345,11 +344,10 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope {
) )
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval
unsafe fn SetInterval_( fn SetInterval_(
&self, &self,
_cx: *mut JSContext, _cx: JSContext,
callback: DOMString, callback: DOMString,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,
@ -480,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

@ -13,8 +13,8 @@ use crate::dom::document::{Document, DocumentSource, HasBrowsingContext, IsHTMLD
use crate::dom::location::Location; use crate::dom::location::Location;
use crate::dom::node::Node; use crate::dom::node::Node;
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 js::jsapi::JSContext;
use js::jsapi::JSObject; use js::jsapi::JSObject;
use mime::Mime; use mime::Mime;
use script_traits::DocumentActivity; use script_traits::DocumentActivity;
@ -106,13 +106,8 @@ impl XMLDocumentMethods for XMLDocument {
self.upcast::<Document>().SupportedPropertyNames() self.upcast::<Document>().SupportedPropertyNames()
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-tree-accessors:dom-document-nameditem-filter // https://html.spec.whatwg.org/multipage/#dom-tree-accessors:dom-document-nameditem-filter
unsafe fn NamedGetter( fn NamedGetter(&self, _cx: JSContext, name: DOMString) -> Option<NonNull<JSObject>> {
&self,
_cx: *mut JSContext,
name: DOMString,
) -> Option<NonNull<JSObject>> {
self.upcast::<Document>().NamedGetter(_cx, name) self.upcast::<Document>().NamedGetter(_cx, name)
} }
} }

View file

@ -38,6 +38,7 @@ use crate::dom::xmlhttprequesteventtarget::XMLHttpRequestEventTarget;
use crate::dom::xmlhttprequestupload::XMLHttpRequestUpload; use crate::dom::xmlhttprequestupload::XMLHttpRequestUpload;
use crate::fetch::FetchCanceller; use crate::fetch::FetchCanceller;
use crate::network_listener::{self, NetworkListener, PreInvoke, ResourceTimingListener}; use crate::network_listener::{self, NetworkListener, PreInvoke, ResourceTimingListener};
use crate::script_runtime::JSContext as SafeJSContext;
use crate::task_source::networking::NetworkingTaskSource; use crate::task_source::networking::NetworkingTaskSource;
use crate::task_source::TaskSourceName; use crate::task_source::TaskSourceName;
use crate::timers::{OneshotTimerCallback, OneshotTimerHandle}; use crate::timers::{OneshotTimerCallback, OneshotTimerHandle};
@ -877,19 +878,19 @@ impl XMLHttpRequestMethods for XMLHttpRequest {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://xhr.spec.whatwg.org/#the-response-attribute // https://xhr.spec.whatwg.org/#the-response-attribute
unsafe fn Response(&self, cx: *mut JSContext) -> JSVal { fn Response(&self, cx: SafeJSContext) -> JSVal {
rooted!(in(cx) let mut rval = UndefinedValue()); rooted!(in(*cx) let mut rval = UndefinedValue());
match self.response_type.get() { match self.response_type.get() {
XMLHttpRequestResponseType::_empty | XMLHttpRequestResponseType::Text => { XMLHttpRequestResponseType::_empty | XMLHttpRequestResponseType::Text => unsafe {
let ready_state = self.ready_state.get(); let ready_state = self.ready_state.get();
// Step 2 // Step 2
if ready_state == XMLHttpRequestState::Done || if ready_state == XMLHttpRequestState::Done ||
ready_state == XMLHttpRequestState::Loading ready_state == XMLHttpRequestState::Loading
{ {
self.text_response().to_jsval(cx, rval.handle_mut()); self.text_response().to_jsval(*cx, rval.handle_mut());
} else { } else {
// Step 1 // Step 1
"".to_jsval(cx, rval.handle_mut()); "".to_jsval(*cx, rval.handle_mut());
} }
}, },
// Step 1 // Step 1
@ -897,18 +898,20 @@ impl XMLHttpRequestMethods for XMLHttpRequest {
return NullValue(); return NullValue();
}, },
// Step 2 // Step 2
XMLHttpRequestResponseType::Document => { XMLHttpRequestResponseType::Document => unsafe {
self.document_response().to_jsval(cx, rval.handle_mut()); self.document_response().to_jsval(*cx, rval.handle_mut());
}, },
XMLHttpRequestResponseType::Json => { XMLHttpRequestResponseType::Json => unsafe {
self.json_response(cx).to_jsval(cx, rval.handle_mut()); self.json_response(*cx).to_jsval(*cx, rval.handle_mut());
}, },
XMLHttpRequestResponseType::Blob => { XMLHttpRequestResponseType::Blob => unsafe {
self.blob_response().to_jsval(cx, rval.handle_mut()); self.blob_response().to_jsval(*cx, rval.handle_mut());
}, },
XMLHttpRequestResponseType::Arraybuffer => match self.arraybuffer_response(cx) { XMLHttpRequestResponseType::Arraybuffer => unsafe {
Some(js_object) => js_object.to_jsval(cx, rval.handle_mut()), match self.arraybuffer_response(*cx) {
None => return NullValue(), Some(js_object) => js_object.to_jsval(*cx, rval.handle_mut()),
None => return NullValue(),
}
}, },
} }
rval.get() rval.get()

View file

@ -15,9 +15,10 @@ use crate::dom::globalscope::GlobalScope;
use crate::dom::vrframedata::create_typed_array; use crate::dom::vrframedata::create_typed_array;
use crate::dom::window::Window; use crate::dom::window::Window;
use crate::dom::xrsession::ApiRigidTransform; use crate::dom::xrsession::ApiRigidTransform;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use euclid::{RigidTransform3D, Rotation3D, Vector3D}; use euclid::{RigidTransform3D, Rotation3D, Vector3D};
use js::jsapi::{Heap, JSContext, JSObject}; use js::jsapi::{Heap, JSObject};
use std::ptr::NonNull; use std::ptr::NonNull;
#[dom_struct] #[dom_struct]
@ -118,8 +119,7 @@ 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> {
unsafe fn Matrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> {
if self.matrix.get().is_null() { if self.matrix.get().is_null() {
let cx = 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,

View file

@ -10,8 +10,9 @@ use crate::dom::globalscope::GlobalScope;
use crate::dom::vrframedata::create_typed_array; use crate::dom::vrframedata::create_typed_array;
use crate::dom::xrrigidtransform::XRRigidTransform; use crate::dom::xrrigidtransform::XRRigidTransform;
use crate::dom::xrsession::{cast_transform, ApiViewerPose, XRSession}; use crate::dom::xrsession::{cast_transform, ApiViewerPose, XRSession};
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 std::ptr::NonNull; use std::ptr::NonNull;
use webxr_api::View; use webxr_api::View;
@ -39,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,9 +65,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 = global.get_cx(); let cx = global.get_cx();
unsafe { create_typed_array(cx, &proj, &ret.proj);
create_typed_array(cx, &proj, &ret.proj);
}
ret ret
} }
@ -82,9 +80,8 @@ impl XRViewMethods for XRView {
self.eye self.eye
} }
#[allow(unsafe_code)]
/// https://immersive-web.github.io/webxr/#dom-xrview-projectionmatrix /// https://immersive-web.github.io/webxr/#dom-xrview-projectionmatrix
unsafe fn ProjectionMatrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> { fn ProjectionMatrix(&self, _cx: JSContext) -> NonNull<JSObject> {
NonNull::new(self.proj.get()).unwrap() NonNull::new(self.proj.get()).unwrap()
} }

View file

@ -12,9 +12,10 @@ use crate::dom::xrpose::XRPose;
use crate::dom::xrrigidtransform::XRRigidTransform; use crate::dom::xrrigidtransform::XRRigidTransform;
use crate::dom::xrsession::{cast_transform, ApiViewerPose, XRSession}; use crate::dom::xrsession::{cast_transform, ApiViewerPose, XRSession};
use crate::dom::xrview::XRView; use crate::dom::xrview::XRView;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::conversions::ToJSValConvertible; use js::conversions::ToJSValConvertible;
use js::jsapi::{Heap, JSContext}; use js::jsapi::Heap;
use js::jsval::{JSVal, UndefinedValue}; use js::jsval::{JSVal, UndefinedValue};
use webxr_api::Views; use webxr_api::Views;
@ -56,10 +57,10 @@ impl XRViewerPose {
XRViewerPoseBinding::Wrap, XRViewerPoseBinding::Wrap,
); );
let cx = global.get_cx();
unsafe { unsafe {
let cx = global.get_cx(); rooted!(in(*cx) let mut jsval = UndefinedValue());
rooted!(in(cx) let mut jsval = UndefinedValue()); views.to_jsval(*cx, jsval.handle_mut());
views.to_jsval(cx, jsval.handle_mut());
pose.views.set(jsval.get()); pose.views.set(jsval.get());
} }
@ -69,8 +70,7 @@ impl XRViewerPose {
impl XRViewerPoseMethods for XRViewerPose { impl XRViewerPoseMethods for XRViewerPose {
/// https://immersive-web.github.io/webxr/#dom-xrviewerpose-views /// https://immersive-web.github.io/webxr/#dom-xrviewerpose-views
#[allow(unsafe_code)] fn Views(&self, _cx: JSContext) -> JSVal {
unsafe fn Views(&self, _cx: *mut JSContext) -> JSVal {
self.views.get() self.views.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

@ -29,7 +29,7 @@ use js::glue::{CollectServoSizes, CreateJobQueue, DeleteJobQueue, JobQueueTraps,
use js::jsapi::ContextOptionsRef; use js::jsapi::ContextOptionsRef;
use js::jsapi::{BuildIdCharVector, DisableIncrementalGC, GCDescription, GCProgress}; use js::jsapi::{BuildIdCharVector, DisableIncrementalGC, GCDescription, GCProgress};
use js::jsapi::{HandleObject, Heap, JobQueue}; use js::jsapi::{HandleObject, Heap, JobQueue};
use js::jsapi::{JSContext, JSTracer, SetDOMCallbacks, SetGCSliceCallback}; use js::jsapi::{JSContext as RawJSContext, JSTracer, SetDOMCallbacks, SetGCSliceCallback};
use js::jsapi::{JSGCInvocationKind, JSGCStatus, JS_AddExtraGCRootsTracer, JS_SetGCCallback}; use js::jsapi::{JSGCInvocationKind, JSGCStatus, JS_AddExtraGCRootsTracer, JS_SetGCCallback};
use js::jsapi::{JSGCMode, JSGCParamKey, JS_SetGCParameter, JS_SetGlobalJitCompilerOption}; use js::jsapi::{JSGCMode, JSGCParamKey, JS_SetGCParameter, JS_SetGlobalJitCompilerOption};
use js::jsapi::{ use js::jsapi::{
@ -139,7 +139,7 @@ pub trait ScriptPort {
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe extern "C" fn get_incumbent_global(_: *const c_void, _: *mut JSContext) -> *mut JSObject { unsafe extern "C" fn get_incumbent_global(_: *const c_void, _: *mut RawJSContext) -> *mut JSObject {
wrap_panic( wrap_panic(
AssertUnwindSafe(|| { AssertUnwindSafe(|| {
GlobalScope::incumbent() GlobalScope::incumbent()
@ -166,7 +166,7 @@ unsafe extern "C" fn empty(extra: *const c_void) -> bool {
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe extern "C" fn enqueue_promise_job( unsafe extern "C" fn enqueue_promise_job(
extra: *const c_void, extra: *const c_void,
cx: *mut JSContext, cx: *mut RawJSContext,
_promise: HandleObject, _promise: HandleObject,
job: HandleObject, job: HandleObject,
_allocation_site: HandleObject, _allocation_site: HandleObject,
@ -179,7 +179,7 @@ unsafe extern "C" fn enqueue_promise_job(
let pipeline = global.pipeline_id(); let pipeline = global.pipeline_id();
microtask_queue.enqueue( microtask_queue.enqueue(
Microtask::Promise(EnqueuedPromiseCallback { Microtask::Promise(EnqueuedPromiseCallback {
callback: PromiseJobCallback::new(cx, job.get()), callback: PromiseJobCallback::new(JSContext::from_ptr(cx), job.get()),
pipeline, pipeline,
}), }),
cx, cx,
@ -193,7 +193,7 @@ unsafe extern "C" fn enqueue_promise_job(
#[allow(unsafe_code, unrooted_must_root)] #[allow(unsafe_code, unrooted_must_root)]
/// https://html.spec.whatwg.org/multipage/#the-hostpromiserejectiontracker-implementation /// https://html.spec.whatwg.org/multipage/#the-hostpromiserejectiontracker-implementation
unsafe extern "C" fn promise_rejection_tracker( unsafe extern "C" fn promise_rejection_tracker(
cx: *mut JSContext, cx: *mut RawJSContext,
promise: HandleObject, promise: HandleObject,
state: PromiseRejectionHandlingState, state: PromiseRejectionHandlingState,
_data: *mut c_void, _data: *mut c_void,
@ -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) {
let cx = global.get_cx();
unsafe { unsafe {
let cx = global.get_cx();
// 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(),
@ -401,7 +400,7 @@ unsafe fn new_rt_and_cx_with_parent(parent: Option<ParentRuntime>) -> Runtime {
SetGCSliceCallback(cx, Some(gc_slice_callback)); SetGCSliceCallback(cx, Some(gc_slice_callback));
} }
unsafe extern "C" fn empty_wrapper_callback(_: *mut JSContext, _: HandleObject) -> bool { unsafe extern "C" fn empty_wrapper_callback(_: *mut RawJSContext, _: HandleObject) -> bool {
true true
} }
SetDOMCallbacks(cx, &DOM_CALLBACKS); SetDOMCallbacks(cx, &DOM_CALLBACKS);
@ -589,7 +588,7 @@ unsafe extern "C" fn get_size(obj: *mut JSObject) -> usize {
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn get_reports(cx: *mut JSContext, path_seg: String) -> Vec<Report> { pub fn get_reports(cx: *mut RawJSContext, path_seg: String) -> Vec<Report> {
let mut reports = vec![]; let mut reports = vec![];
unsafe { unsafe {
@ -655,7 +654,7 @@ thread_local!(static GC_SLICE_START: Cell<Option<Tm>> = Cell::new(None));
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe extern "C" fn gc_slice_callback( unsafe extern "C" fn gc_slice_callback(
_cx: *mut JSContext, _cx: *mut RawJSContext,
progress: GCProgress, progress: GCProgress,
desc: *const GCDescription, desc: *const GCDescription,
) { ) {
@ -695,7 +694,7 @@ unsafe extern "C" fn gc_slice_callback(
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe extern "C" fn debug_gc_callback( unsafe extern "C" fn debug_gc_callback(
_cx: *mut JSContext, _cx: *mut RawJSContext,
status: JSGCStatus, status: JSGCStatus,
_data: *mut os::raw::c_void, _data: *mut os::raw::c_void,
) { ) {
@ -731,7 +730,7 @@ unsafe extern "C" fn servo_build_id(build_id: *mut BuildIdCharVector) -> bool {
#[allow(unsafe_code)] #[allow(unsafe_code)]
#[cfg(feature = "debugmozjs")] #[cfg(feature = "debugmozjs")]
unsafe fn set_gc_zeal_options(cx: *mut JSContext) { unsafe fn set_gc_zeal_options(cx: *mut RawJSContext) {
use js::jsapi::{JS_SetGCZeal, JS_DEFAULT_ZEAL_FREQ}; use js::jsapi::{JS_SetGCZeal, JS_DEFAULT_ZEAL_FREQ};
let level = match pref!(js.mem.gc.zeal.level) { let level = match pref!(js.mem.gc.zeal.level) {
@ -747,4 +746,23 @@ unsafe fn set_gc_zeal_options(cx: *mut JSContext) {
#[allow(unsafe_code)] #[allow(unsafe_code)]
#[cfg(not(feature = "debugmozjs"))] #[cfg(not(feature = "debugmozjs"))]
unsafe fn set_gc_zeal_options(_: *mut JSContext) {} unsafe fn set_gc_zeal_options(_: *mut RawJSContext) {}
#[derive(Clone, Copy)]
pub struct JSContext(*mut RawJSContext);
#[allow(unsafe_code)]
impl JSContext {
pub unsafe fn from_ptr(raw_js_context: *mut RawJSContext) -> Self {
JSContext(raw_js_context)
}
}
#[allow(unsafe_code)]
impl Deref for JSContext {
type Target = *mut RawJSContext;
fn deref(&self) -> &Self::Target {
&self.0
}
}

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)
}, },
} }