diff options
43 files changed, 444 insertions, 529 deletions
diff --git a/components/script/dom/audiobuffer.rs b/components/script/dom/audiobuffer.rs index b3f18f319ad..a5b8dfbc8c8 100644 --- a/components/script/dom/audiobuffer.rs +++ b/components/script/dom/audiobuffer.rs @@ -13,6 +13,7 @@ use crate::dom::bindings::num::Finite; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::window::Window; +use crate::script_runtime::JSContext as SafeJSContext; use dom_struct::dom_struct; use js::jsapi::JS_GetArrayBufferViewBuffer; use js::jsapi::{Heap, JSContext, JSObject}; @@ -230,22 +231,20 @@ impl AudioBufferMethods for AudioBuffer { // https://webaudio.github.io/web-audio-api/#dom-audiobuffer-getchanneldata #[allow(unsafe_code)] - unsafe fn GetChannelData( - &self, - cx: *mut JSContext, - channel: u32, - ) -> Fallible<NonNull<JSObject>> { + fn GetChannelData(&self, cx: SafeJSContext, channel: u32) -> Fallible<NonNull<JSObject>> { if channel >= self.number_of_channels { return Err(Error::IndexSize); } - if !self.restore_js_channel_data(cx) { - return Err(Error::JSFailed); - } + unsafe { + if !self.restore_js_channel_data(*cx) { + return Err(Error::JSFailed); + } - Ok(NonNull::new_unchecked( - self.js_channels.borrow()[channel as usize].get(), - )) + Ok(NonNull::new_unchecked( + self.js_channels.borrow()[channel as usize].get(), + )) + } } // https://webaudio.github.io/web-audio-api/#dom-audiobuffer-copyfromchannel diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 70da52b765e..343b8e6596d 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -3332,7 +3332,7 @@ class CGCallGenerator(CGThing): needsCx = needCx(returnType, (a for (a, _) in arguments), True) if "cx" not in argsPre and needsCx: - args.prepend(CGGeneric("*cx")) + args.prepend(CGGeneric("cx")) if nativeMethodName in descriptor.inCompartmentMethods: args.append(CGGeneric("InCompartment::in_compartment(&AlreadyInCompartment::assert_for_cx(*cx))")) @@ -5649,7 +5649,7 @@ class CGInterfaceTrait(CGThing): def attribute_arguments(needCx, argument=None, inCompartment=False): if needCx: - yield "cx", "*mut JSContext" + yield "cx", "SafeJSContext" if argument: yield "value", argument_type(descriptor, argument) @@ -6720,7 +6720,7 @@ def argument_type(descriptorProvider, ty, optional=False, defaultValue=None, var def method_arguments(descriptorProvider, returnType, arguments, passJSBits=True, trailing=None, inCompartment=False): if needCx(returnType, arguments, passJSBits): - yield "cx", "*mut JSContext" + yield "cx", "SafeJSContext" for argument in arguments: ty = argument_type(descriptorProvider, argument.type, argument.optional, diff --git a/components/script/dom/bindings/iterable.rs b/components/script/dom/bindings/iterable.rs index d736d3f1b6b..5ee790cf2d3 100644 --- a/components/script/dom/bindings/iterable.rs +++ b/components/script/dom/bindings/iterable.rs @@ -76,41 +76,41 @@ impl<T: DomObject + JSTraceable + Iterable> IterableIterator<T> { /// Return the next value from the iterable object. #[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(); - rooted!(in(cx) let mut value = UndefinedValue()); - rooted!(in(cx) let mut rval = ptr::null_mut::<JSObject>()); + rooted!(in(*cx) let mut value = UndefinedValue()); + rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>()); 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 { match self.type_ { IteratorType::Keys => { unsafe { self.iterable .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 => { unsafe { self.iterable .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 => { - rooted!(in(cx) let mut key = UndefinedValue()); + rooted!(in(*cx) let mut key = UndefinedValue()); unsafe { self.iterable .get_key_at_index(index) - .to_jsval(cx, key.handle_mut()); + .to_jsval(*cx, key.handle_mut()); self.iterable .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()) }, } }; diff --git a/components/script/dom/crypto.rs b/components/script/dom/crypto.rs index 76adb3a08b1..4891c022ed5 100644 --- a/components/script/dom/crypto.rs +++ b/components/script/dom/crypto.rs @@ -9,9 +9,10 @@ use crate::dom::bindings::error::{Error, Fallible}; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::globalscope::GlobalScope; +use crate::script_runtime::JSContext; use dom_struct::dom_struct; +use js::jsapi::JSObject; use js::jsapi::Type; -use js::jsapi::{JSContext, JSObject}; use js::rust::CustomAutoRooterGuard; use js::typedarray::ArrayBufferView; use servo_rand::{Rng, ServoRng}; @@ -47,9 +48,9 @@ impl Crypto { impl CryptoMethods for Crypto { #[allow(unsafe_code)] // https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#Crypto-method-getRandomValues - unsafe fn GetRandomValues( + fn GetRandomValues( &self, - _cx: *mut JSContext, + _cx: JSContext, mut input: CustomAutoRooterGuard<ArrayBufferView>, ) -> Fallible<NonNull<JSObject>> { let array_type = input.get_array_type(); @@ -57,14 +58,14 @@ impl CryptoMethods for Crypto { if !is_integer_buffer(array_type) { return Err(Error::TypeMismatch); } else { - let mut data = input.as_mut_slice(); + let mut data = unsafe { input.as_mut_slice() }; if data.len() > 65536 { return Err(Error::QuotaExceeded); } self.rng.borrow_mut().fill_bytes(&mut data); } - Ok(NonNull::new_unchecked(*input.underlying_object())) + unsafe { Ok(NonNull::new_unchecked(*input.underlying_object())) } } } diff --git a/components/script/dom/customelementregistry.rs b/components/script/dom/customelementregistry.rs index e2355445db8..6b2f8992c0a 100644 --- a/components/script/dom/customelementregistry.rs +++ b/components/script/dom/customelementregistry.rs @@ -405,13 +405,13 @@ impl CustomElementRegistryMethods for CustomElementRegistry { /// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-get> #[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)) { - Some(definition) => { - rooted!(in(cx) let mut constructor = UndefinedValue()); + Some(definition) => unsafe { + rooted!(in(*cx) let mut constructor = UndefinedValue()); definition .constructor - .to_jsval(cx, constructor.handle_mut()); + .to_jsval(*cx, constructor.handle_mut()); constructor.get() }, None => UndefinedValue(), diff --git a/components/script/dom/customevent.rs b/components/script/dom/customevent.rs index de07a55d4d4..91035f56e03 100644 --- a/components/script/dom/customevent.rs +++ b/components/script/dom/customevent.rs @@ -13,8 +13,9 @@ use crate::dom::bindings::str::DOMString; use crate::dom::bindings::trace::RootedTraceableBox; use crate::dom::event::Event; use crate::dom::globalscope::GlobalScope; +use crate::script_runtime::JSContext; use dom_struct::dom_struct; -use js::jsapi::{Heap, JSContext}; +use js::jsapi::Heap; use js::jsval::JSVal; use js::rust::HandleValue; use servo_atoms::Atom; @@ -87,17 +88,15 @@ impl CustomEvent { } impl CustomEventMethods for CustomEvent { - #[allow(unsafe_code)] // 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() } - #[allow(unsafe_code)] // https://dom.spec.whatwg.org/#dom-customevent-initcustomevent - unsafe fn InitCustomEvent( + fn InitCustomEvent( &self, - _cx: *mut JSContext, + _cx: JSContext, type_: DOMString, can_bubble: bool, cancelable: bool, diff --git a/components/script/dom/dedicatedworkerglobalscope.rs b/components/script/dom/dedicatedworkerglobalscope.rs index dc04e848dd2..2c6042333a6 100644 --- a/components/script/dom/dedicatedworkerglobalscope.rs +++ b/components/script/dom/dedicatedworkerglobalscope.rs @@ -560,10 +560,9 @@ unsafe extern "C" fn interrupt_callback(cx: *mut JSContext) -> bool { } impl DedicatedWorkerGlobalScopeMethods for DedicatedWorkerGlobalScope { - #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-dedicatedworkerglobalscope-postmessage - unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { - let data = StructuredCloneData::write(cx, message)?; + fn PostMessage(&self, cx: SafeJSContext, message: HandleValue) -> ErrorResult { + let data = StructuredCloneData::write(*cx, message)?; let worker = self.worker.borrow().as_ref().unwrap().clone(); let pipeline_id = self.upcast::<GlobalScope>().pipeline_id(); let task = Box::new(task!(post_worker_message: move || { diff --git a/components/script/dom/dissimilaroriginwindow.rs b/components/script/dom/dissimilaroriginwindow.rs index 67a174d8508..8724516acec 100644 --- a/components/script/dom/dissimilaroriginwindow.rs +++ b/components/script/dom/dissimilaroriginwindow.rs @@ -11,10 +11,9 @@ use crate::dom::bindings::structuredclone::StructuredCloneData; use crate::dom::dissimilaroriginlocation::DissimilarOriginLocation; use crate::dom::globalscope::GlobalScope; use crate::dom::windowproxy::WindowProxy; -use crate::script_runtime::JSContext as SafeJSContext; +use crate::script_runtime::JSContext; use dom_struct::dom_struct; use ipc_channel::ipc; -use js::jsapi::JSContext; use js::jsval::{JSVal, UndefinedValue}; use js::rust::HandleValue; use msg::constellation_msg::PipelineId; @@ -69,7 +68,7 @@ impl DissimilarOriginWindow { window_proxy: Dom::from_ref(window_proxy), location: Default::default(), }); - unsafe { DissimilarOriginWindowBinding::Wrap(SafeJSContext::from_ptr(cx), win) } + unsafe { DissimilarOriginWindowBinding::Wrap(JSContext::from_ptr(cx), win) } } pub fn window_proxy(&self) -> DomRoot<WindowProxy> { @@ -134,14 +133,8 @@ impl DissimilarOriginWindowMethods for DissimilarOriginWindow { false } - #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-window-postmessage - unsafe fn PostMessage( - &self, - cx: *mut JSContext, - message: HandleValue, - origin: DOMString, - ) -> ErrorResult { + fn PostMessage(&self, cx: JSContext, message: HandleValue, origin: DOMString) -> ErrorResult { // Step 3-5. let origin = match &origin[..] { "*" => None, @@ -157,23 +150,21 @@ impl DissimilarOriginWindowMethods for DissimilarOriginWindow { // Step 1-2, 6-8. // TODO(#12717): Should implement the `transfer` argument. - let data = StructuredCloneData::write(cx, message)?; + let data = StructuredCloneData::write(*cx, message)?; // Step 9. self.post_message(origin, data); Ok(()) } - #[allow(unsafe_code)] // 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 UndefinedValue() } - #[allow(unsafe_code)] // 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 } diff --git a/components/script/dom/document.rs b/components/script/dom/document.rs index d7e77ef9243..85639964710 100644 --- a/components/script/dom/document.rs +++ b/components/script/dom/document.rs @@ -102,6 +102,7 @@ use crate::dom::wheelevent::WheelEvent; use crate::dom::window::{ReflowReason, Window}; use crate::dom::windowproxy::WindowProxy; use crate::fetch::FetchCanceller; +use crate::script_runtime::JSContext; use crate::script_runtime::{CommonScriptMsg, ScriptThreadEventCategory}; use crate::script_thread::{MainThreadScriptMsg, ScriptThread}; use crate::stylesheet_set::StylesheetSetRef; @@ -117,7 +118,7 @@ use euclid::default::Point2D; use html5ever::{LocalName, Namespace, QualName}; use hyper_serde::Serde; use ipc_channel::ipc::{self, IpcSender}; -use js::jsapi::{JSContext, JSObject, JSRuntime}; +use js::jsapi::{JSObject, JSRuntime}; use keyboard_types::{Key, KeyState, Modifiers}; use metrics::{ InteractiveFlag, InteractiveMetrics, InteractiveWindow, ProfilerMetadataFactory, @@ -4218,11 +4219,7 @@ impl DocumentMethods for Document { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-tree-accessors:dom-document-nameditem-filter - unsafe fn NamedGetter( - &self, - _cx: *mut JSContext, - name: DOMString, - ) -> Option<NonNull<JSObject>> { + fn NamedGetter(&self, _cx: JSContext, name: DOMString) -> Option<NonNull<JSObject>> { #[derive(JSTraceable, MallocSizeOf)] struct NamedElementFilter { name: Atom, @@ -4270,7 +4267,7 @@ impl DocumentMethods for Document { } let name = Atom::from(name); let root = self.upcast::<Node>(); - { + unsafe { // Step 1. let mut elements = root .traverse_preorder(ShadowIncluding::No) @@ -4291,9 +4288,11 @@ impl DocumentMethods for Document { // Step 4. let filter = NamedElementFilter { name: name }; let collection = HTMLCollection::create(self.window(), root, Box::new(filter)); - Some(NonNull::new_unchecked( - collection.reflector().get_jsobject().get(), - )) + unsafe { + Some(NonNull::new_unchecked( + collection.reflector().get_jsobject().get(), + )) + } } // https://html.spec.whatwg.org/multipage/#dom-tree-accessors:supported-property-names diff --git a/components/script/dom/dommatrixreadonly.rs b/components/script/dom/dommatrixreadonly.rs index cde3dbc4031..f8d73f628c1 100644 --- a/components/script/dom/dommatrixreadonly.rs +++ b/components/script/dom/dommatrixreadonly.rs @@ -18,10 +18,11 @@ use crate::dom::dommatrix::DOMMatrix; use crate::dom::dompoint::DOMPoint; use crate::dom::globalscope::GlobalScope; use crate::dom::window::Window; +use crate::script_runtime::JSContext; use cssparser::{Parser, ParserInput}; use dom_struct::dom_struct; use euclid::{default::Transform3D, Angle}; -use js::jsapi::{JSContext, JSObject}; +use js::jsapi::JSObject; use js::rust::CustomAutoRooterGuard; use js::typedarray::CreateWith; use js::typedarray::{Float32Array, Float64Array}; @@ -667,7 +668,7 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly { // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-tofloat32array #[allow(unsafe_code)] - unsafe fn ToFloat32Array(&self, cx: *mut JSContext) -> NonNull<JSObject> { + fn ToFloat32Array(&self, cx: JSContext) -> NonNull<JSObject> { let vec: Vec<f32> = self .matrix .borrow() @@ -675,18 +676,22 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly { .iter() .map(|&x| x as f32) .collect(); - rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); - let _ = Float32Array::create(cx, CreateWith::Slice(&vec), array.handle_mut()).unwrap(); - NonNull::new_unchecked(array.get()) + unsafe { + rooted!(in (*cx) let mut array = ptr::null_mut::<JSObject>()); + 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 #[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(); - rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); - let _ = Float64Array::create(cx, CreateWith::Slice(&arr), array.handle_mut()).unwrap(); - NonNull::new_unchecked(array.get()) + unsafe { + rooted!(in (*cx) let mut array = ptr::null_mut::<JSObject>()); + let _ = Float64Array::create(*cx, CreateWith::Slice(&arr), array.handle_mut()).unwrap(); + NonNull::new_unchecked(array.get()) + } } } diff --git a/components/script/dom/errorevent.rs b/components/script/dom/errorevent.rs index 2894482161c..c306f6cf7f9 100644 --- a/components/script/dom/errorevent.rs +++ b/components/script/dom/errorevent.rs @@ -14,8 +14,9 @@ use crate::dom::bindings::str::DOMString; use crate::dom::bindings::trace::RootedTraceableBox; use crate::dom::event::{Event, EventBubbles, EventCancelable}; use crate::dom::globalscope::GlobalScope; +use crate::script_runtime::JSContext; use dom_struct::dom_struct; -use js::jsapi::{Heap, JSContext}; +use js::jsapi::Heap; use js::jsval::JSVal; use js::rust::HandleValue; use servo_atoms::Atom; @@ -135,9 +136,8 @@ impl ErrorEventMethods for ErrorEvent { self.filename.borrow().clone() } - #[allow(unsafe_code)] // 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() } diff --git a/components/script/dom/eventtarget.rs b/components/script/dom/eventtarget.rs index 0a1d9a137ba..144f918b8d6 100644 --- a/components/script/dom/eventtarget.rs +++ b/components/script/dom/eventtarget.rs @@ -169,7 +169,7 @@ impl CompiledEventListener { CommonEventHandler::ErrorEventHandler(ref handler) => { if let Some(event) = event.downcast::<ErrorEvent>() { let cx = object.global().get_cx(); - rooted!(in(cx) let error = unsafe { event.Error(cx) }); + rooted!(in(cx) let error = unsafe { event.Error(JSContext::from_ptr(cx)) }); let return_value = handler.Call_( object, EventOrString::String(event.Message()), diff --git a/components/script/dom/extendableevent.rs b/components/script/dom/extendableevent.rs index 0cced82a384..6f1b9f322a0 100644 --- a/components/script/dom/extendableevent.rs +++ b/components/script/dom/extendableevent.rs @@ -11,8 +11,8 @@ use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::event::Event; use crate::dom::serviceworkerglobalscope::ServiceWorkerGlobalScope; +use crate::script_runtime::JSContext; use dom_struct::dom_struct; -use js::jsapi::JSContext; use js::rust::HandleValue; use servo_atoms::Atom; @@ -62,7 +62,7 @@ impl ExtendableEvent { } // 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 if !self.extensions_allowed { return Err(Error::InvalidState); diff --git a/components/script/dom/extendablemessageevent.rs b/components/script/dom/extendablemessageevent.rs index 7fd16aafec4..c2ede65745a 100644 --- a/components/script/dom/extendablemessageevent.rs +++ b/components/script/dom/extendablemessageevent.rs @@ -15,8 +15,9 @@ use crate::dom::eventtarget::EventTarget; use crate::dom::extendableevent::ExtendableEvent; use crate::dom::globalscope::GlobalScope; use crate::dom::serviceworkerglobalscope::ServiceWorkerGlobalScope; +use crate::script_runtime::JSContext; use dom_struct::dom_struct; -use js::jsapi::{Heap, JSContext}; +use js::jsapi::Heap; use js::jsval::JSVal; use js::rust::HandleValue; use servo_atoms::Atom; @@ -91,9 +92,8 @@ impl ExtendableMessageEvent { } impl ExtendableMessageEventMethods for ExtendableMessageEvent { - #[allow(unsafe_code)] // 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() } diff --git a/components/script/dom/filereader.rs b/components/script/dom/filereader.rs index 31a87c712d6..0e158dedbab 100644 --- a/components/script/dom/filereader.rs +++ b/components/script/dom/filereader.rs @@ -22,6 +22,7 @@ use crate::dom::event::{Event, EventBubbles, EventCancelable}; use crate::dom::eventtarget::EventTarget; use crate::dom::globalscope::GlobalScope; use crate::dom::progressevent::ProgressEvent; +use crate::script_runtime::JSContext as SafeJSContext; use crate::task::TaskCanceller; use crate::task_source::file_reading::{FileReadingTask, FileReadingTaskSource}; use crate::task_source::{TaskSource, TaskSourceName}; @@ -391,12 +392,14 @@ impl FileReaderMethods for FileReader { #[allow(unsafe_code)] // 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 { FileReaderResult::String(ref string) => StringOrObject::String(string.clone()), FileReaderResult::ArrayBuffer(ref arr_buffer) => { 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) }, }) diff --git a/components/script/dom/filereadersync.rs b/components/script/dom/filereadersync.rs index 82f479b0b80..1ed9c6c8007 100644 --- a/components/script/dom/filereadersync.rs +++ b/components/script/dom/filereadersync.rs @@ -13,8 +13,9 @@ use crate::dom::bindings::str::DOMString; use crate::dom::blob::Blob; use crate::dom::filereader::FileReaderSharedFunctionality; use crate::dom::globalscope::GlobalScope; +use crate::script_runtime::JSContext; use dom_struct::dom_struct; -use js::jsapi::{JSContext, JSObject}; +use js::jsapi::JSObject; use js::typedarray::{ArrayBuffer, CreateWith}; use std::ptr; use std::ptr::NonNull; @@ -87,23 +88,21 @@ impl FileReaderSyncMethods for FileReaderSync { #[allow(unsafe_code)] // https://w3c.github.io/FileAPI/#readAsArrayBufferSyncSection - unsafe fn ReadAsArrayBuffer( - &self, - cx: *mut JSContext, - blob: &Blob, - ) -> Fallible<NonNull<JSObject>> { + fn ReadAsArrayBuffer(&self, cx: JSContext, blob: &Blob) -> Fallible<NonNull<JSObject>> { // step 1 let blob_contents = FileReaderSync::get_blob_bytes(blob)?; // step 2 - rooted!(in(cx) let mut array_buffer = ptr::null_mut::<JSObject>()); - assert!(ArrayBuffer::create( - cx, - CreateWith::Slice(&blob_contents), - array_buffer.handle_mut() - ) - .is_ok()); - - Ok(NonNull::new_unchecked(array_buffer.get())) + unsafe { + rooted!(in(*cx) let mut array_buffer = ptr::null_mut::<JSObject>()); + assert!(ArrayBuffer::create( + *cx, + CreateWith::Slice(&blob_contents), + array_buffer.handle_mut() + ) + .is_ok()); + + Ok(NonNull::new_unchecked(array_buffer.get())) + } } } diff --git a/components/script/dom/gamepad.rs b/components/script/dom/gamepad.rs index fe86a3b2329..08160bfd3ad 100644 --- a/components/script/dom/gamepad.rs +++ b/components/script/dom/gamepad.rs @@ -15,8 +15,9 @@ use crate::dom::gamepadbuttonlist::GamepadButtonList; use crate::dom::gamepadevent::{GamepadEvent, GamepadEventType}; use crate::dom::globalscope::GlobalScope; use crate::dom::vrpose::VRPose; +use crate::script_runtime::JSContext; use dom_struct::dom_struct; -use js::jsapi::{Heap, JSContext, JSObject}; +use js::jsapi::{Heap, JSObject}; use js::typedarray::{CreateWith, Float64Array}; use std::cell::Cell; use std::ptr; @@ -136,8 +137,8 @@ impl GamepadMethods for Gamepad { #[allow(unsafe_code)] // https://w3c.github.io/gamepad/#dom-gamepad-axes - unsafe fn Axes(&self, _cx: *mut JSContext) -> NonNull<JSObject> { - NonNull::new_unchecked(self.axes.get()) + fn Axes(&self, _cx: JSContext) -> NonNull<JSObject> { + unsafe { NonNull::new_unchecked(self.axes.get()) } } // https://w3c.github.io/gamepad/#dom-gamepad-buttons diff --git a/components/script/dom/history.rs b/components/script/dom/history.rs index 787591af8a3..4bbcba64bad 100644 --- a/components/script/dom/history.rs +++ b/components/script/dom/history.rs @@ -18,6 +18,7 @@ use crate::dom::globalscope::GlobalScope; use crate::dom::hashchangeevent::HashChangeEvent; use crate::dom::popstateevent::PopStateEvent; use crate::dom::window::Window; +use crate::script_runtime::JSContext as SafeJSContext; use dom_struct::dom_struct; use js::jsapi::{Heap, JSContext}; use js::jsval::{JSVal, NullValue, UndefinedValue}; @@ -279,8 +280,7 @@ impl History { impl HistoryMethods for History { // https://html.spec.whatwg.org/multipage/#dom-history-state - #[allow(unsafe_code)] - unsafe fn GetState(&self, _cx: *mut JSContext) -> Fallible<JSVal> { + fn GetState(&self, _cx: SafeJSContext) -> Fallible<JSVal> { if !self.window.Document().is_fully_active() { return Err(Error::Security); } @@ -327,26 +327,24 @@ impl HistoryMethods for History { } // https://html.spec.whatwg.org/multipage/#dom-history-pushstate - #[allow(unsafe_code)] - unsafe fn PushState( + fn PushState( &self, - cx: *mut JSContext, + cx: SafeJSContext, data: HandleValue, title: DOMString, url: Option<USVString>, ) -> 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 - #[allow(unsafe_code)] - unsafe fn ReplaceState( + fn ReplaceState( &self, - cx: *mut JSContext, + cx: SafeJSContext, data: HandleValue, title: DOMString, url: Option<USVString>, ) -> ErrorResult { - self.push_or_replace_state(cx, data, title, url, PushOrReplace::Replace) + self.push_or_replace_state(*cx, data, title, url, PushOrReplace::Replace) } } diff --git a/components/script/dom/htmlcanvaselement.rs b/components/script/dom/htmlcanvaselement.rs index addef4dc666..4e9abe5f3c9 100644 --- a/components/script/dom/htmlcanvaselement.rs +++ b/components/script/dom/htmlcanvaselement.rs @@ -330,9 +330,9 @@ impl HTMLCanvasElementMethods for HTMLCanvasElement { // https://html.spec.whatwg.org/multipage/#dom-canvas-getcontext #[allow(unsafe_code)] - unsafe fn GetContext( + fn GetContext( &self, - cx: *mut JSContext, + cx: SafeJSContext, id: DOMString, options: HandleValue, ) -> Option<RenderingContext> { @@ -340,21 +340,22 @@ impl HTMLCanvasElementMethods for HTMLCanvasElement { "2d" => self .get_or_init_2d_context() .map(RenderingContext::CanvasRenderingContext2D), - "webgl" | "experimental-webgl" => self - .get_or_init_webgl_context(cx, options) - .map(RenderingContext::WebGLRenderingContext), - "webgl2" | "experimental-webgl2" => self - .get_or_init_webgl2_context(cx, options) - .map(RenderingContext::WebGL2RenderingContext), + "webgl" | "experimental-webgl" => unsafe { + self.get_or_init_webgl_context(*cx, options) + .map(RenderingContext::WebGLRenderingContext) + }, + "webgl2" | "experimental-webgl2" => unsafe { + self.get_or_init_webgl2_context(*cx, options) + .map(RenderingContext::WebGL2RenderingContext) + }, _ => None, } } // https://html.spec.whatwg.org/multipage/#dom-canvas-todataurl - #[allow(unsafe_code)] - unsafe fn ToDataURL( + fn ToDataURL( &self, - _context: *mut JSContext, + _context: SafeJSContext, _mime_type: Option<DOMString>, _quality: HandleValue, ) -> Fallible<USVString> { diff --git a/components/script/dom/imagedata.rs b/components/script/dom/imagedata.rs index 460c827ab1a..8546f73e5cf 100644 --- a/components/script/dom/imagedata.rs +++ b/components/script/dom/imagedata.rs @@ -8,10 +8,11 @@ use crate::dom::bindings::error::{Error, Fallible}; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::globalscope::GlobalScope; +use crate::script_runtime::JSContext; use dom_struct::dom_struct; use euclid::default::{Rect, Size2D}; use ipc_channel::ipc::IpcSharedMemory; -use js::jsapi::{Heap, JSContext, JSObject}; +use js::jsapi::{Heap, JSObject}; use js::rust::Runtime; use js::typedarray::{CreateWith, Uint8ClampedArray}; use std::borrow::Cow; @@ -131,7 +132,7 @@ impl ImageData { #[allow(unsafe_code)] #[allow(unused_variables)] pub unsafe fn Constructor_( - cx: *mut JSContext, + cx: JSContext, global: &GlobalScope, jsobject: *mut JSObject, width: u32, @@ -183,9 +184,8 @@ impl ImageDataMethods for ImageData { self.height } - #[allow(unsafe_code)] // 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") } } diff --git a/components/script/dom/messageevent.rs b/components/script/dom/messageevent.rs index c02df1e8e61..52c0bd1acf1 100644 --- a/components/script/dom/messageevent.rs +++ b/components/script/dom/messageevent.rs @@ -15,8 +15,9 @@ use crate::dom::event::Event; use crate::dom::eventtarget::EventTarget; use crate::dom::globalscope::GlobalScope; use crate::dom::windowproxy::WindowProxy; +use crate::script_runtime::JSContext; use dom_struct::dom_struct; -use js::jsapi::{Heap, JSContext, JSObject}; +use js::jsapi::{Heap, JSObject}; use js::jsval::JSVal; use js::rust::HandleValue; use servo_atoms::Atom; @@ -127,9 +128,8 @@ impl MessageEvent { } impl MessageEventMethods for MessageEvent { - #[allow(unsafe_code)] // 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() } @@ -139,8 +139,7 @@ impl MessageEventMethods for MessageEvent { } // https://html.spec.whatwg.org/multipage/#dom-messageevent-source - #[allow(unsafe_code)] - unsafe fn GetSource(&self, _cx: *mut JSContext) -> Option<NonNull<JSObject>> { + fn GetSource(&self, _cx: JSContext) -> Option<NonNull<JSObject>> { self.source .as_ref() .and_then(|source| NonNull::new(source.reflector().get_jsobject().get())) diff --git a/components/script/dom/offscreencanvas.rs b/components/script/dom/offscreencanvas.rs index 2087c47c91f..142379519fb 100644 --- a/components/script/dom/offscreencanvas.rs +++ b/components/script/dom/offscreencanvas.rs @@ -15,9 +15,9 @@ use crate::dom::eventtarget::EventTarget; use crate::dom::globalscope::GlobalScope; use crate::dom::htmlcanvaselement::HTMLCanvasElement; use crate::dom::offscreencanvasrenderingcontext2d::OffscreenCanvasRenderingContext2D; +use crate::script_runtime::JSContext; use dom_struct::dom_struct; use euclid::default::Size2D; -use js::jsapi::JSContext; use js::rust::HandleValue; use ref_filter_map; use std::cell::Cell; @@ -108,10 +108,9 @@ impl OffscreenCanvas { impl OffscreenCanvasMethods for OffscreenCanvas { // https://html.spec.whatwg.org/multipage/#dom-offscreencanvas-getcontext - #[allow(unsafe_code)] - unsafe fn GetContext( + fn GetContext( &self, - _cx: *mut JSContext, + _cx: JSContext, id: DOMString, _options: HandleValue, ) -> Option<OffscreenRenderingContext> { diff --git a/components/script/dom/permissions.rs b/components/script/dom/permissions.rs index 738be04d634..419115d1240 100644 --- a/components/script/dom/permissions.rs +++ b/components/script/dom/permissions.rs @@ -200,22 +200,19 @@ impl Permissions { } impl PermissionsMethods for Permissions { - #[allow(unsafe_code)] // https://w3c.github.io/permissions/#dom-permissions-query - unsafe fn Query(&self, cx: *mut JSContext, permissionDesc: *mut JSObject) -> Rc<Promise> { - self.manipulate(Operation::Query, cx, permissionDesc, None) + fn Query(&self, cx: SafeJSContext, permissionDesc: *mut JSObject) -> Rc<Promise> { + self.manipulate(Operation::Query, *cx, permissionDesc, None) } - #[allow(unsafe_code)] // https://w3c.github.io/permissions/#dom-permissions-request - unsafe fn Request(&self, cx: *mut JSContext, permissionDesc: *mut JSObject) -> Rc<Promise> { - self.manipulate(Operation::Request, cx, permissionDesc, None) + fn Request(&self, cx: SafeJSContext, permissionDesc: *mut JSObject) -> Rc<Promise> { + self.manipulate(Operation::Request, *cx, permissionDesc, None) } - #[allow(unsafe_code)] // https://w3c.github.io/permissions/#dom-permissions-revoke - unsafe fn Revoke(&self, cx: *mut JSContext, permissionDesc: *mut JSObject) -> Rc<Promise> { - self.manipulate(Operation::Revoke, cx, permissionDesc, None) + fn Revoke(&self, cx: SafeJSContext, permissionDesc: *mut JSObject) -> Rc<Promise> { + self.manipulate(Operation::Revoke, *cx, permissionDesc, None) } } diff --git a/components/script/dom/popstateevent.rs b/components/script/dom/popstateevent.rs index 35bba7dee9e..d5cb3c0ff3a 100644 --- a/components/script/dom/popstateevent.rs +++ b/components/script/dom/popstateevent.rs @@ -14,8 +14,9 @@ use crate::dom::bindings::trace::RootedTraceableBox; use crate::dom::event::Event; use crate::dom::eventtarget::EventTarget; use crate::dom::window::Window; +use crate::script_runtime::JSContext; use dom_struct::dom_struct; -use js::jsapi::{Heap, JSContext}; +use js::jsapi::Heap; use js::jsval::JSVal; use js::rust::HandleValue; use servo_atoms::Atom; @@ -81,9 +82,8 @@ impl PopStateEvent { } impl PopStateEventMethods for PopStateEvent { - #[allow(unsafe_code)] // 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() } diff --git a/components/script/dom/promiserejectionevent.rs b/components/script/dom/promiserejectionevent.rs index 4d69b63f564..4e4a148905a 100644 --- a/components/script/dom/promiserejectionevent.rs +++ b/components/script/dom/promiserejectionevent.rs @@ -14,8 +14,9 @@ use crate::dom::bindings::trace::RootedTraceableBox; use crate::dom::event::{Event, EventBubbles, EventCancelable}; use crate::dom::globalscope::GlobalScope; use crate::dom::promise::Promise; +use crate::script_runtime::JSContext; use dom_struct::dom_struct; -use js::jsapi::{Heap, JSContext}; +use js::jsapi::Heap; use js::jsval::JSVal; use js::rust::HandleValue; use servo_atoms::Atom; @@ -100,9 +101,8 @@ impl PromiseRejectionEventMethods for PromiseRejectionEvent { self.promise.clone() } - #[allow(unsafe_code)] // 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() } diff --git a/components/script/dom/rtcsessiondescription.rs b/components/script/dom/rtcsessiondescription.rs index 27ab4ca3b41..9aa46f56060 100644 --- a/components/script/dom/rtcsessiondescription.rs +++ b/components/script/dom/rtcsessiondescription.rs @@ -14,9 +14,10 @@ use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::globalscope::GlobalScope; use crate::dom::window::Window; +use crate::script_runtime::JSContext; use dom_struct::dom_struct; use js::conversions::ToJSValConvertible; -use js::jsapi::{JSContext, JSObject}; +use js::jsapi::JSObject; use js::jsval::UndefinedValue; use std::ptr::NonNull; @@ -73,13 +74,15 @@ impl RTCSessionDescriptionMethods for RTCSessionDescription { #[allow(unsafe_code)] /// 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 { type_: self.ty, sdp: self.sdp.clone(), }; - rooted!(in(cx) let mut jsval = UndefinedValue()); - init.to_jsval(cx, jsval.handle_mut()); - NonNull::new(jsval.to_object()).unwrap() + unsafe { + rooted!(in(*cx) let mut jsval = UndefinedValue()); + init.to_jsval(*cx, jsval.handle_mut()); + NonNull::new(jsval.to_object()).unwrap() + } } } diff --git a/components/script/dom/serviceworker.rs b/components/script/dom/serviceworker.rs index b0d7e4de42f..dd968c34d94 100644 --- a/components/script/dom/serviceworker.rs +++ b/components/script/dom/serviceworker.rs @@ -16,9 +16,9 @@ use crate::dom::bindings::str::USVString; use crate::dom::bindings::structuredclone::StructuredCloneData; use crate::dom::eventtarget::EventTarget; use crate::dom::globalscope::GlobalScope; +use crate::script_runtime::JSContext; use crate::task::TaskOnce; use dom_struct::dom_struct; -use js::jsapi::JSContext; use js::rust::HandleValue; use script_traits::{DOMMessage, ScriptMsg}; use servo_url::ServoUrl; @@ -90,15 +90,14 @@ impl ServiceWorkerMethods for ServiceWorker { USVString(self.script_url.borrow().clone()) } - #[allow(unsafe_code)] // 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 if let ServiceWorkerState::Redundant = self.state.get() { return Err(Error::InvalidState); } // Step 7 - let data = StructuredCloneData::write(cx, message)?; + let data = StructuredCloneData::write(*cx, message)?; let msg_vec = DOMMessage(data.move_to_arraybuffer()); let _ = self .global() diff --git a/components/script/dom/testbinding.rs b/components/script/dom/testbinding.rs index 87280aa46e2..dfa148e5c11 100644 --- a/components/script/dom/testbinding.rs +++ b/components/script/dom/testbinding.rs @@ -49,6 +49,7 @@ use crate::dom::globalscope::GlobalScope; use crate::dom::promise::Promise; use crate::dom::promisenativehandler::{Callback, PromiseNativeHandler}; use crate::dom::url::URL; +use crate::script_runtime::JSContext as SafeJSContext; use crate::timers::OneshotTimerCallback; use dom_struct::dom_struct; use js::jsapi::{Heap, JSContext, JSObject}; @@ -215,23 +216,24 @@ impl TestBindingMethods for TestBinding { } fn SetUnion9Attribute(&self, _: ByteStringOrLong) {} #[allow(unsafe_code)] - unsafe fn ArrayAttribute(&self, cx: *mut JSContext) -> NonNull<JSObject> { - rooted!(in(cx) let array = JS_NewUint8ClampedArray(cx, 16)); - NonNull::new(array.get()).expect("got a null pointer") + fn ArrayAttribute(&self, cx: SafeJSContext) -> NonNull<JSObject> { + unsafe { + rooted!(in(*cx) let array = JS_NewUint8ClampedArray(*cx, 16)); + NonNull::new(array.get()).expect("got a null pointer") + } } - #[allow(unsafe_code)] - unsafe fn AnyAttribute(&self, _: *mut JSContext) -> JSVal { + fn AnyAttribute(&self, _: SafeJSContext) -> JSVal { NullValue() } + fn SetAnyAttribute(&self, _: SafeJSContext, _: HandleValue) {} #[allow(unsafe_code)] - unsafe fn SetAnyAttribute(&self, _: *mut JSContext, _: HandleValue) {} - #[allow(unsafe_code)] - unsafe fn ObjectAttribute(&self, cx: *mut JSContext) -> NonNull<JSObject> { - rooted!(in(cx) let obj = JS_NewPlainObject(cx)); - NonNull::new(obj.get()).expect("got a null pointer") + fn ObjectAttribute(&self, cx: SafeJSContext) -> NonNull<JSObject> { + unsafe { + rooted!(in(*cx) let obj = JS_NewPlainObject(*cx)); + NonNull::new(obj.get()).expect("got a null pointer") + } } - #[allow(unsafe_code)] - unsafe fn SetObjectAttribute(&self, _: *mut JSContext, _: *mut JSObject) {} + fn SetObjectAttribute(&self, _: SafeJSContext, _: *mut JSObject) {} fn GetBooleanAttributeNullable(&self) -> Option<bool> { Some(false) @@ -329,12 +331,10 @@ impl TestBindingMethods for TestBinding { fn SetInterfaceAttributeWeak(&self, url: Option<&URL>) { self.url.set(url); } - #[allow(unsafe_code)] - unsafe fn GetObjectAttributeNullable(&self, _: *mut JSContext) -> Option<NonNull<JSObject>> { + fn GetObjectAttributeNullable(&self, _: SafeJSContext) -> Option<NonNull<JSObject>> { None } - #[allow(unsafe_code)] - unsafe fn SetObjectAttributeNullable(&self, _: *mut JSContext, _: *mut JSObject) {} + fn SetObjectAttributeNullable(&self, _: SafeJSContext, _: *mut JSObject) {} fn GetUnionAttributeNullable(&self) -> Option<HTMLElementOrLong> { Some(HTMLElementOrLong::Long(0)) } @@ -419,12 +419,10 @@ impl TestBindingMethods for TestBinding { "".to_owned(), ) } - #[allow(unsafe_code)] - unsafe fn ReceiveAny(&self, _: *mut JSContext) -> JSVal { + fn ReceiveAny(&self, _: SafeJSContext) -> JSVal { NullValue() } - #[allow(unsafe_code)] - unsafe fn ReceiveObject(&self, cx: *mut JSContext) -> NonNull<JSObject> { + fn ReceiveObject(&self, cx: SafeJSContext) -> NonNull<JSObject> { self.ObjectAttribute(cx) } fn ReceiveUnion(&self) -> HTMLElementOrLong { @@ -470,10 +468,9 @@ impl TestBindingMethods for TestBinding { "".to_owned(), )] } - #[allow(unsafe_code)] - unsafe fn ReceiveUnionIdentity( + fn ReceiveUnionIdentity( &self, - _: *mut JSContext, + _: SafeJSContext, arg: UnionTypes::StringOrObject, ) -> UnionTypes::StringOrObject { arg @@ -537,8 +534,7 @@ impl TestBindingMethods for TestBinding { "".to_owned(), )) } - #[allow(unsafe_code)] - unsafe fn ReceiveNullableObject(&self, cx: *mut JSContext) -> Option<NonNull<JSObject>> { + fn ReceiveNullableObject(&self, cx: SafeJSContext) -> Option<NonNull<JSObject>> { self.GetObjectAttributeNullable(cx) } fn ReceiveNullableUnion(&self) -> Option<HTMLElementOrLong> { @@ -666,35 +662,24 @@ impl TestBindingMethods for TestBinding { fn PassUnion7(&self, _: StringSequenceOrUnsignedLong) {} fn PassUnion8(&self, _: ByteStringSequenceOrLong) {} fn PassUnion9(&self, _: UnionTypes::TestDictionaryOrLong) {} - #[allow(unsafe_code)] - unsafe fn PassUnion10(&self, _: *mut JSContext, _: UnionTypes::StringOrObject) {} + fn PassUnion10(&self, _: SafeJSContext, _: UnionTypes::StringOrObject) {} fn PassUnion11(&self, _: UnionTypes::ArrayBufferOrArrayBufferView) {} fn PassUnionWithTypedef(&self, _: DocumentOrTestTypedef) {} fn PassUnionWithTypedef2(&self, _: LongSequenceOrTestTypedef) {} - #[allow(unsafe_code)] - unsafe fn PassAny(&self, _: *mut JSContext, _: HandleValue) {} - #[allow(unsafe_code)] - unsafe fn PassObject(&self, _: *mut JSContext, _: *mut JSObject) {} + fn PassAny(&self, _: SafeJSContext, _: HandleValue) {} + fn PassObject(&self, _: SafeJSContext, _: *mut JSObject) {} fn PassCallbackFunction(&self, _: Rc<Function>) {} fn PassCallbackInterface(&self, _: Rc<EventListener>) {} fn PassSequence(&self, _: Vec<i32>) {} - #[allow(unsafe_code)] - unsafe fn PassAnySequence(&self, _: *mut JSContext, _: CustomAutoRooterGuard<Vec<JSVal>>) {} - #[allow(unsafe_code)] - unsafe fn AnySequencePassthrough( + fn PassAnySequence(&self, _: SafeJSContext, _: CustomAutoRooterGuard<Vec<JSVal>>) {} + fn AnySequencePassthrough( &self, - _: *mut JSContext, + _: SafeJSContext, seq: CustomAutoRooterGuard<Vec<JSVal>>, ) -> Vec<JSVal> { (*seq).clone() } - #[allow(unsafe_code)] - unsafe fn PassObjectSequence( - &self, - _: *mut JSContext, - _: CustomAutoRooterGuard<Vec<*mut JSObject>>, - ) { - } + fn PassObjectSequence(&self, _: SafeJSContext, _: CustomAutoRooterGuard<Vec<*mut JSObject>>) {} fn PassStringSequence(&self, _: Vec<DOMString>) {} fn PassInterfaceSequence(&self, _: Vec<DomRoot<Blob>>) {} @@ -719,8 +704,7 @@ impl TestBindingMethods for TestBinding { fn PassNullableByteString(&self, _: Option<ByteString>) {} // fn PassNullableEnum(self, _: Option<TestEnum>) {} fn PassNullableInterface(&self, _: Option<&Blob>) {} - #[allow(unsafe_code)] - unsafe fn PassNullableObject(&self, _: *mut JSContext, _: *mut JSObject) {} + fn PassNullableObject(&self, _: SafeJSContext, _: *mut JSObject) {} fn PassNullableTypedArray(&self, _: CustomAutoRooterGuard<Option<typedarray::Int8Array>>) {} fn PassNullableUnion(&self, _: Option<HTMLElementOrLong>) {} fn PassNullableUnion2(&self, _: Option<EventOrString>) {} @@ -756,10 +740,8 @@ impl TestBindingMethods for TestBinding { fn PassOptionalUnion4(&self, _: Option<LongSequenceOrBoolean>) {} fn PassOptionalUnion5(&self, _: Option<UnsignedLongOrBoolean>) {} fn PassOptionalUnion6(&self, _: Option<ByteStringOrLong>) {} - #[allow(unsafe_code)] - unsafe fn PassOptionalAny(&self, _: *mut JSContext, _: HandleValue) {} - #[allow(unsafe_code)] - unsafe fn PassOptionalObject(&self, _: *mut JSContext, _: Option<*mut JSObject>) {} + fn PassOptionalAny(&self, _: SafeJSContext, _: HandleValue) {} + fn PassOptionalObject(&self, _: SafeJSContext, _: Option<*mut JSObject>) {} fn PassOptionalCallbackFunction(&self, _: Option<Rc<Function>>) {} fn PassOptionalCallbackInterface(&self, _: Option<Rc<EventListener>>) {} fn PassOptionalSequence(&self, _: Option<Vec<i32>>) {} @@ -782,8 +764,7 @@ impl TestBindingMethods for TestBinding { fn PassOptionalNullableByteString(&self, _: Option<Option<ByteString>>) {} // fn PassOptionalNullableEnum(self, _: Option<Option<TestEnum>>) {} fn PassOptionalNullableInterface(&self, _: Option<Option<&Blob>>) {} - #[allow(unsafe_code)] - unsafe fn PassOptionalNullableObject(&self, _: *mut JSContext, _: Option<*mut JSObject>) {} + fn PassOptionalNullableObject(&self, _: SafeJSContext, _: Option<*mut JSObject>) {} fn PassOptionalNullableUnion(&self, _: Option<Option<HTMLElementOrLong>>) {} fn PassOptionalNullableUnion2(&self, _: Option<Option<EventOrString>>) {} fn PassOptionalNullableUnion3(&self, _: Option<Option<StringOrLongSequence>>) {} @@ -827,14 +808,12 @@ impl TestBindingMethods for TestBinding { fn PassOptionalNullableByteStringWithDefault(&self, _: Option<ByteString>) {} // fn PassOptionalNullableEnumWithDefault(self, _: Option<TestEnum>) {} fn PassOptionalNullableInterfaceWithDefault(&self, _: Option<&Blob>) {} - #[allow(unsafe_code)] - unsafe fn PassOptionalNullableObjectWithDefault(&self, _: *mut JSContext, _: *mut JSObject) {} + fn PassOptionalNullableObjectWithDefault(&self, _: SafeJSContext, _: *mut JSObject) {} fn PassOptionalNullableUnionWithDefault(&self, _: Option<HTMLElementOrLong>) {} fn PassOptionalNullableUnion2WithDefault(&self, _: Option<EventOrString>) {} // fn PassOptionalNullableCallbackFunctionWithDefault(self, _: Option<Function>) {} fn PassOptionalNullableCallbackInterfaceWithDefault(&self, _: Option<Rc<EventListener>>) {} - #[allow(unsafe_code)] - unsafe fn PassOptionalAnyWithDefault(&self, _: *mut JSContext, _: HandleValue) {} + fn PassOptionalAnyWithDefault(&self, _: SafeJSContext, _: HandleValue) {} fn PassOptionalNullableBooleanWithNonNullDefault(&self, _: Option<bool>) {} fn PassOptionalNullableByteWithNonNullDefault(&self, _: Option<i8>) {} @@ -883,10 +862,8 @@ impl TestBindingMethods for TestBinding { fn PassVariadicUnion5(&self, _: Vec<StringOrUnsignedLong>) {} fn PassVariadicUnion6(&self, _: Vec<UnsignedLongOrBoolean>) {} fn PassVariadicUnion7(&self, _: Vec<ByteStringOrLong>) {} - #[allow(unsafe_code)] - unsafe fn PassVariadicAny(&self, _: *mut JSContext, _: Vec<HandleValue>) {} - #[allow(unsafe_code)] - unsafe fn PassVariadicObject(&self, _: *mut JSContext, _: Vec<*mut JSObject>) {} + fn PassVariadicAny(&self, _: SafeJSContext, _: Vec<HandleValue>) {} + fn PassVariadicObject(&self, _: SafeJSContext, _: Vec<*mut JSObject>) {} fn BooleanMozPreference(&self, pref_name: DOMString) -> bool { prefs::pref_map() .get(pref_name.as_ref()) @@ -965,32 +942,28 @@ impl TestBindingMethods for TestBinding { #[allow(unrooted_must_root)] #[allow(unsafe_code)] - unsafe fn ReturnResolvedPromise( - &self, - cx: *mut JSContext, - v: HandleValue, - ) -> Fallible<Rc<Promise>> { - Promise::new_resolved(&self.global(), cx, v) + fn ReturnResolvedPromise(&self, cx: SafeJSContext, v: HandleValue) -> Fallible<Rc<Promise>> { + unsafe { Promise::new_resolved(&self.global(), *cx, v) } } #[allow(unrooted_must_root)] #[allow(unsafe_code)] - unsafe fn ReturnRejectedPromise( - &self, - cx: *mut JSContext, - v: HandleValue, - ) -> Fallible<Rc<Promise>> { - Promise::new_rejected(&self.global(), cx, v) + fn ReturnRejectedPromise(&self, cx: SafeJSContext, v: HandleValue) -> Fallible<Rc<Promise>> { + unsafe { Promise::new_rejected(&self.global(), *cx, v) } } #[allow(unsafe_code)] - unsafe fn PromiseResolveNative(&self, cx: *mut JSContext, p: &Promise, v: HandleValue) { - p.resolve(cx, v); + fn PromiseResolveNative(&self, cx: SafeJSContext, p: &Promise, v: HandleValue) { + unsafe { + p.resolve(*cx, v); + } } #[allow(unsafe_code)] - unsafe fn PromiseRejectNative(&self, cx: *mut JSContext, p: &Promise, v: HandleValue) { - p.reject(cx, v); + fn PromiseRejectNative(&self, cx: SafeJSContext, p: &Promise, v: HandleValue) { + unsafe { + p.reject(*cx, v); + } } fn PromiseRejectWithTypeError(&self, p: &Promise, s: USVString) { diff --git a/components/script/dom/textencoder.rs b/components/script/dom/textencoder.rs index 5f1fddf5d10..fae24beaf78 100644 --- a/components/script/dom/textencoder.rs +++ b/components/script/dom/textencoder.rs @@ -9,8 +9,9 @@ use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::{DOMString, USVString}; use crate::dom::globalscope::GlobalScope; +use crate::script_runtime::JSContext; use dom_struct::dom_struct; -use js::jsapi::{JSContext, JSObject}; +use js::jsapi::JSObject; use js::typedarray::{CreateWith, Uint8Array}; use std::ptr; use std::ptr::NonNull; @@ -49,14 +50,17 @@ impl TextEncoderMethods for TextEncoder { #[allow(unsafe_code)] // 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(); - rooted!(in(cx) let mut js_object = ptr::null_mut::<JSObject>()); - assert!( - Uint8Array::create(cx, CreateWith::Slice(&encoded), js_object.handle_mut()).is_ok() - ); + unsafe { + rooted!(in(*cx) let mut js_object = ptr::null_mut::<JSObject>()); + 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()) + } } } diff --git a/components/script/dom/vreyeparameters.rs b/components/script/dom/vreyeparameters.rs index 2779989d0ae..0a8260610e1 100644 --- a/components/script/dom/vreyeparameters.rs +++ b/components/script/dom/vreyeparameters.rs @@ -9,8 +9,9 @@ use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::globalscope::GlobalScope; use crate::dom::vrfieldofview::VRFieldOfView; +use crate::script_runtime::JSContext; use dom_struct::dom_struct; -use js::jsapi::{Heap, JSContext, JSObject}; +use js::jsapi::{Heap, JSObject}; use js::typedarray::{CreateWith, Float32Array}; use std::default::Default; use std::ptr; @@ -67,8 +68,8 @@ impl VREyeParameters { impl VREyeParametersMethods for VREyeParameters { #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vreyeparameters-offset - unsafe fn Offset(&self, _cx: *mut JSContext) -> NonNull<JSObject> { - NonNull::new_unchecked(self.offset.get()) + fn Offset(&self, _cx: JSContext) -> NonNull<JSObject> { + unsafe { NonNull::new_unchecked(self.offset.get()) } } // https://w3c.github.io/webvr/#dom-vreyeparameters-fieldofview diff --git a/components/script/dom/vrframedata.rs b/components/script/dom/vrframedata.rs index 25f6af821a7..9cfcadd96a8 100644 --- a/components/script/dom/vrframedata.rs +++ b/components/script/dom/vrframedata.rs @@ -11,8 +11,9 @@ use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::globalscope::GlobalScope; use crate::dom::vrpose::VRPose; use crate::dom::window::Window; +use crate::script_runtime::JSContext; use dom_struct::dom_struct; -use js::jsapi::{Heap, JSContext, JSObject}; +use js::jsapi::{Heap, JSObject}; use js::typedarray::{CreateWith, Float32Array}; use std::cell::Cell; use std::ptr; @@ -61,13 +62,11 @@ impl VRFrameData { global, VRFrameDataBinding::Wrap, ); - let cx = global.get_cx(); - unsafe { - create_typed_array(cx, &matrix, &root.left_proj); - create_typed_array(cx, &matrix, &root.left_view); - create_typed_array(cx, &matrix, &root.right_proj); - create_typed_array(cx, &matrix, &root.right_view); - } + let cx = unsafe { JSContext::from_ptr(global.get_cx()) }; + create_typed_array(cx, &matrix, &root.left_proj); + create_typed_array(cx, &matrix, &root.left_view); + create_typed_array(cx, &matrix, &root.right_proj); + create_typed_array(cx, &matrix, &root.right_view); root } @@ -79,9 +78,11 @@ impl VRFrameData { /// FIXME(#22526) this should be in a better place #[allow(unsafe_code)] -pub unsafe fn create_typed_array(cx: *mut JSContext, src: &[f32], dst: &Heap<*mut JSObject>) { - rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); - let _ = Float32Array::create(cx, CreateWith::Slice(src), array.handle_mut()); +pub fn create_typed_array(cx: JSContext, src: &[f32], dst: &Heap<*mut JSObject>) { + rooted!(in (*cx) let mut array = ptr::null_mut::<JSObject>()); + unsafe { + let _ = Float32Array::create(*cx, CreateWith::Slice(src), array.handle_mut()); + } (*dst).set(array.get()); } @@ -89,28 +90,28 @@ impl VRFrameData { #[allow(unsafe_code)] pub fn update(&self, data: &WebVRFrameData) { unsafe { - let cx = self.global().get_cx(); - typedarray!(in(cx) let left_proj_array: Float32Array = self.left_proj.get()); + let cx = JSContext::from_ptr(self.global().get_cx()); + typedarray!(in(*cx) let left_proj_array: Float32Array = self.left_proj.get()); if let Ok(mut array) = left_proj_array { 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 { 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 { 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 { array.update(&data.right_view_matrix); } - } - self.pose.update(&data.pose); - self.timestamp.set(data.timestamp); - if self.first_timestamp.get() == 0.0 { - self.first_timestamp.set(data.timestamp); + self.pose.update(&data.pose); + self.timestamp.set(data.timestamp); + if self.first_timestamp.get() == 0.0 { + self.first_timestamp.set(data.timestamp); + } } } } @@ -123,26 +124,26 @@ impl VRFrameDataMethods for VRFrameData { #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrframedata-leftprojectionmatrix - unsafe fn LeftProjectionMatrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> { - NonNull::new_unchecked(self.left_proj.get()) + fn LeftProjectionMatrix(&self, _cx: JSContext) -> NonNull<JSObject> { + unsafe { NonNull::new_unchecked(self.left_proj.get()) } } #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrframedata-leftviewmatrix - unsafe fn LeftViewMatrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> { - NonNull::new_unchecked(self.left_view.get()) + fn LeftViewMatrix(&self, _cx: JSContext) -> NonNull<JSObject> { + unsafe { NonNull::new_unchecked(self.left_view.get()) } } #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrframedata-rightprojectionmatrix - unsafe fn RightProjectionMatrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> { - NonNull::new_unchecked(self.right_proj.get()) + fn RightProjectionMatrix(&self, _cx: JSContext) -> NonNull<JSObject> { + unsafe { NonNull::new_unchecked(self.right_proj.get()) } } #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrframedata-rightviewmatrix - unsafe fn RightViewMatrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> { - NonNull::new_unchecked(self.right_view.get()) + fn RightViewMatrix(&self, _cx: JSContext) -> NonNull<JSObject> { + unsafe { NonNull::new_unchecked(self.right_view.get()) } } // https://w3c.github.io/webvr/#dom-vrframedata-pose diff --git a/components/script/dom/vrpose.rs b/components/script/dom/vrpose.rs index 90bca0956ee..898691a9679 100644 --- a/components/script/dom/vrpose.rs +++ b/components/script/dom/vrpose.rs @@ -7,6 +7,7 @@ use crate::dom::bindings::codegen::Bindings::VRPoseBinding::VRPoseMethods; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::globalscope::GlobalScope; +use crate::script_runtime::JSContext as SafeJSContext; use dom_struct::dom_struct; use js::jsapi::{Heap, JSContext, JSObject}; use js::typedarray::{CreateWith, Float32Array}; @@ -131,39 +132,33 @@ impl VRPose { } impl VRPoseMethods for VRPose { - #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrpose-position - unsafe fn GetPosition(&self, _cx: *mut JSContext) -> Option<NonNull<JSObject>> { + fn GetPosition(&self, _cx: SafeJSContext) -> Option<NonNull<JSObject>> { heap_to_option(&self.position) } - #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrpose-linearvelocity - unsafe fn GetLinearVelocity(&self, _cx: *mut JSContext) -> Option<NonNull<JSObject>> { + fn GetLinearVelocity(&self, _cx: SafeJSContext) -> Option<NonNull<JSObject>> { heap_to_option(&self.linear_vel) } - #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrpose-linearacceleration - unsafe fn GetLinearAcceleration(&self, _cx: *mut JSContext) -> Option<NonNull<JSObject>> { + fn GetLinearAcceleration(&self, _cx: SafeJSContext) -> Option<NonNull<JSObject>> { heap_to_option(&self.linear_acc) } - #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrpose-orientation - unsafe fn GetOrientation(&self, _cx: *mut JSContext) -> Option<NonNull<JSObject>> { + fn GetOrientation(&self, _cx: SafeJSContext) -> Option<NonNull<JSObject>> { heap_to_option(&self.orientation) } - #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrpose-angularvelocity - unsafe fn GetAngularVelocity(&self, _cx: *mut JSContext) -> Option<NonNull<JSObject>> { + fn GetAngularVelocity(&self, _cx: SafeJSContext) -> Option<NonNull<JSObject>> { heap_to_option(&self.angular_vel) } - #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrpose-angularacceleration - unsafe fn GetAngularAcceleration(&self, _cx: *mut JSContext) -> Option<NonNull<JSObject>> { + fn GetAngularAcceleration(&self, _cx: SafeJSContext) -> Option<NonNull<JSObject>> { heap_to_option(&self.angular_acc) } } diff --git a/components/script/dom/vrstageparameters.rs b/components/script/dom/vrstageparameters.rs index 41184091232..0b525513f57 100644 --- a/components/script/dom/vrstageparameters.rs +++ b/components/script/dom/vrstageparameters.rs @@ -9,8 +9,9 @@ use crate::dom::bindings::num::Finite; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::globalscope::GlobalScope; +use crate::script_runtime::JSContext; use dom_struct::dom_struct; -use js::jsapi::{Heap, JSContext, JSObject}; +use js::jsapi::{Heap, JSObject}; use js::typedarray::{CreateWith, Float32Array}; use std::ptr; use std::ptr::NonNull; @@ -78,8 +79,8 @@ impl VRStageParameters { impl VRStageParametersMethods for VRStageParameters { #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrstageparameters-sittingtostandingtransform - unsafe fn SittingToStandingTransform(&self, _cx: *mut JSContext) -> NonNull<JSObject> { - NonNull::new_unchecked(self.transform.get()) + fn SittingToStandingTransform(&self, _cx: JSContext) -> NonNull<JSObject> { + unsafe { NonNull::new_unchecked(self.transform.get()) } } // https://w3c.github.io/webvr/#dom-vrstageparameters-sizex diff --git a/components/script/dom/webgl2renderingcontext.rs b/components/script/dom/webgl2renderingcontext.rs index 3b068caafca..26b81f8ad3a 100644 --- a/components/script/dom/webgl2renderingcontext.rs +++ b/components/script/dom/webgl2renderingcontext.rs @@ -29,11 +29,12 @@ use crate::dom::webglshaderprecisionformat::WebGLShaderPrecisionFormat; use crate::dom::webgltexture::WebGLTexture; use crate::dom::webgluniformlocation::WebGLUniformLocation; use crate::dom::window::Window; +use crate::script_runtime::JSContext; /// https://www.khronos.org/registry/webgl/specs/latest/2.0/webgl.idl use canvas_traits::webgl::{GLContextAttributes, WebGLVersion}; use dom_struct::dom_struct; use euclid::default::Size2D; -use js::jsapi::{JSContext, JSObject}; +use js::jsapi::JSObject; use js::jsval::JSVal; use js::rust::CustomAutoRooterGuard; use js::typedarray::ArrayBufferView; @@ -109,21 +110,19 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { self.base.DrawingBufferHeight() } - #[allow(unsafe_code)] /// 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 { - self.base.GetBufferParameter(_cx, target, parameter) + fn GetBufferParameter(&self, cx: JSContext, target: u32, parameter: u32) -> JSVal { + self.base.GetBufferParameter(cx, target, parameter) } #[allow(unsafe_code)] /// 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) } - #[allow(unsafe_code)] /// 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) } @@ -142,21 +141,15 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { self.base.GetSupportedExtensions() } - #[allow(unsafe_code)] /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.14 - unsafe fn GetExtension( - &self, - cx: *mut JSContext, - name: DOMString, - ) -> Option<NonNull<JSObject>> { + fn GetExtension(&self, cx: JSContext, name: DOMString) -> Option<NonNull<JSObject>> { self.base.GetExtension(cx, name) } - #[allow(unsafe_code)] /// https://www.khronos.org/registry/webgl/specs/latest/2.0/#3.7.4 - unsafe fn GetFramebufferAttachmentParameter( + fn GetFramebufferAttachmentParameter( &self, - cx: *mut JSContext, + cx: JSContext, target: u32, attachment: u32, pname: u32, @@ -165,14 +158,8 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { .GetFramebufferAttachmentParameter(cx, target, attachment, pname) } - #[allow(unsafe_code)] /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7 - unsafe fn GetRenderbufferParameter( - &self, - cx: *mut JSContext, - target: u32, - pname: u32, - ) -> JSVal { + fn GetRenderbufferParameter(&self, cx: JSContext, target: u32, pname: u32) -> JSVal { self.base.GetRenderbufferParameter(cx, target, pname) } @@ -505,14 +492,8 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { self.base.GetProgramInfoLog(program) } - #[allow(unsafe_code)] /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - unsafe fn GetProgramParameter( - &self, - cx: *mut JSContext, - program: &WebGLProgram, - param_id: u32, - ) -> JSVal { + fn GetProgramParameter(&self, cx: JSContext, program: &WebGLProgram, param_id: u32) -> JSVal { self.base.GetProgramParameter(cx, program, param_id) } @@ -521,14 +502,8 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { self.base.GetShaderInfoLog(shader) } - #[allow(unsafe_code)] /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - unsafe fn GetShaderParameter( - &self, - cx: *mut JSContext, - shader: &WebGLShader, - param_id: u32, - ) -> JSVal { + fn GetShaderParameter(&self, cx: JSContext, shader: &WebGLShader, param_id: u32) -> JSVal { self.base.GetShaderParameter(cx, shader, param_id) } @@ -551,9 +526,8 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { self.base.GetUniformLocation(program, name) } - #[allow(unsafe_code)] /// 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) } @@ -815,10 +789,9 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - #[allow(unsafe_code)] - unsafe fn GetUniform( + fn GetUniform( &self, - cx: *mut JSContext, + cx: JSContext, program: &WebGLProgram, location: &WebGLUniformLocation, ) -> JSVal { diff --git a/components/script/dom/webglrenderingcontext.rs b/components/script/dom/webglrenderingcontext.rs index 21927e6bf44..1240caccf7c 100644 --- a/components/script/dom/webglrenderingcontext.rs +++ b/components/script/dom/webglrenderingcontext.rs @@ -48,6 +48,7 @@ use crate::dom::webgltexture::{TexParameterValue, WebGLTexture}; use crate::dom::webgluniformlocation::WebGLUniformLocation; use crate::dom::webglvertexarrayobjectoes::WebGLVertexArrayObjectOES; use crate::dom::window::Window; +use crate::script_runtime::JSContext as SafeJSContext; #[cfg(feature = "webgl_backtrace")] use backtrace::Backtrace; use canvas_traits::webgl::WebGLError::*; @@ -1148,9 +1149,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { receiver.recv().unwrap() } - #[allow(unsafe_code)] // 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!( self, self.bound_buffer(target) @@ -1170,7 +1170,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] // 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 .extension_manager .is_get_parameter_name_enabled(parameter) @@ -1180,41 +1180,41 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } match parameter { - constants::ARRAY_BUFFER_BINDING => { - return optional_root_object_to_js_or_null!(cx, &self.bound_buffer_array.get()); + constants::ARRAY_BUFFER_BINDING => unsafe { + return optional_root_object_to_js_or_null!(*cx, &self.bound_buffer_array.get()); }, - constants::CURRENT_PROGRAM => { - return optional_root_object_to_js_or_null!(cx, &self.current_program.get()); + constants::CURRENT_PROGRAM => unsafe { + 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(); - return optional_root_object_to_js_or_null!(cx, buffer); + return optional_root_object_to_js_or_null!(*cx, buffer); }, - constants::FRAMEBUFFER_BINDING => { - return optional_root_object_to_js_or_null!(cx, &self.bound_framebuffer.get()); + constants::FRAMEBUFFER_BINDING => unsafe { + return optional_root_object_to_js_or_null!(*cx, &self.bound_framebuffer.get()); }, - constants::RENDERBUFFER_BINDING => { - return optional_root_object_to_js_or_null!(cx, &self.bound_renderbuffer.get()); + constants::RENDERBUFFER_BINDING => unsafe { + 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 .textures .active_texture_slot(constants::TEXTURE_2D) .unwrap() .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 .textures .active_texture_slot(constants::TEXTURE_CUBE_MAP) .unwrap() .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()); - 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 // we wanted to support other formats, we could ask the @@ -1227,27 +1227,27 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { constants::IMPLEMENTATION_COLOR_READ_TYPE => { 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(); - rooted!(in(cx) let mut rval = ptr::null_mut::<JSObject>()); - let _ = Uint32Array::create(cx, CreateWith::Slice(&format_ids), rval.handle_mut()) + rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>()); + let _ = Uint32Array::create(*cx, CreateWith::Slice(&format_ids), rval.handle_mut()) .unwrap(); return ObjectValue(rval.get()); }, - constants::VERSION => { - rooted!(in(cx) let mut rval = UndefinedValue()); - "WebGL 1.0".to_jsval(cx, rval.handle_mut()); + constants::VERSION => unsafe { + rooted!(in(*cx) let mut rval = UndefinedValue()); + "WebGL 1.0".to_jsval(*cx, rval.handle_mut()); return rval.get(); }, - constants::RENDERER | constants::VENDOR => { - rooted!(in(cx) let mut rval = UndefinedValue()); - "Mozilla/Servo".to_jsval(cx, rval.handle_mut()); + constants::RENDERER | constants::VENDOR => unsafe { + rooted!(in(*cx) let mut rval = UndefinedValue()); + "Mozilla/Servo".to_jsval(*cx, rval.handle_mut()); return rval.get(); }, - constants::SHADING_LANGUAGE_VERSION => { - rooted!(in(cx) let mut rval = UndefinedValue()); - "WebGL GLSL ES 1.0".to_jsval(cx, rval.handle_mut()); + constants::SHADING_LANGUAGE_VERSION => unsafe { + rooted!(in(*cx) let mut rval = UndefinedValue()); + "WebGL GLSL ES 1.0".to_jsval(*cx, rval.handle_mut()); return rval.get(); }, constants::UNPACK_FLIP_Y_WEBGL => { @@ -1314,11 +1314,11 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { self.send_command(WebGLCommand::GetParameterBool(param, sender)); BooleanValue(receiver.recv().unwrap()) }, - Parameter::Bool4(param) => { + Parameter::Bool4(param) => unsafe { let (sender, receiver) = webgl_channel().unwrap(); self.send_command(WebGLCommand::GetParameterBool4(param, sender)); - rooted!(in(cx) let mut rval = UndefinedValue()); - receiver.recv().unwrap().to_jsval(cx, rval.handle_mut()); + rooted!(in(*cx) let mut rval = UndefinedValue()); + receiver.recv().unwrap().to_jsval(*cx, rval.handle_mut()); rval.get() }, Parameter::Int(param) => { @@ -1326,24 +1326,24 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { self.send_command(WebGLCommand::GetParameterInt(param, sender)); Int32Value(receiver.recv().unwrap()) }, - Parameter::Int2(param) => { + Parameter::Int2(param) => unsafe { let (sender, receiver) = webgl_channel().unwrap(); 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( - cx, + *cx, CreateWith::Slice(&receiver.recv().unwrap()), rval.handle_mut(), ) .unwrap(); ObjectValue(rval.get()) }, - Parameter::Int4(param) => { + Parameter::Int4(param) => unsafe { let (sender, receiver) = webgl_channel().unwrap(); 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( - cx, + *cx, CreateWith::Slice(&receiver.recv().unwrap()), rval.handle_mut(), ) @@ -1355,24 +1355,24 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { self.send_command(WebGLCommand::GetParameterFloat(param, sender)); DoubleValue(receiver.recv().unwrap() as f64) }, - Parameter::Float2(param) => { + Parameter::Float2(param) => unsafe { let (sender, receiver) = webgl_channel().unwrap(); 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( - cx, + *cx, CreateWith::Slice(&receiver.recv().unwrap()), rval.handle_mut(), ) .unwrap(); ObjectValue(rval.get()) }, - Parameter::Float4(param) => { + Parameter::Float4(param) => unsafe { let (sender, receiver) = webgl_channel().unwrap(); 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( - cx, + *cx, CreateWith::Slice(&receiver.recv().unwrap()), 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 - 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!( self, 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 - unsafe fn GetExtension( - &self, - _cx: *mut JSContext, - name: DOMString, - ) -> Option<NonNull<JSObject>> { + fn GetExtension(&self, _cx: SafeJSContext, name: DOMString) -> Option<NonNull<JSObject>> { self.extension_manager .init_once(|| self.get_gl_extensions()); self.extension_manager.get_or_init_extension(&name, self) @@ -2326,9 +2320,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6 - unsafe fn GetFramebufferAttachmentParameter( + fn GetFramebufferAttachmentParameter( &self, - cx: *mut JSContext, + cx: SafeJSContext, target: u32, attachment: u32, pname: u32, @@ -2411,14 +2405,14 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { let fb = self.bound_framebuffer.get().unwrap(); if let Some(webgl_attachment) = fb.attachment(attachment) { match webgl_attachment { - WebGLFramebufferAttachmentRoot::Renderbuffer(rb) => { - rooted!(in(cx) let mut rval = NullValue()); - rb.to_jsval(cx, rval.handle_mut()); + WebGLFramebufferAttachmentRoot::Renderbuffer(rb) => unsafe { + rooted!(in(*cx) let mut rval = NullValue()); + rb.to_jsval(*cx, rval.handle_mut()); return rval.get(); }, - WebGLFramebufferAttachmentRoot::Texture(texture) => { - rooted!(in(cx) let mut rval = NullValue()); - texture.to_jsval(cx, rval.handle_mut()); + WebGLFramebufferAttachmentRoot::Texture(texture) => unsafe { + rooted!(in(*cx) let mut rval = NullValue()); + texture.to_jsval(*cx, rval.handle_mut()); return rval.get(); }, } @@ -2435,14 +2429,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { Int32Value(receiver.recv().unwrap()) } - #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7 - unsafe fn GetRenderbufferParameter( - &self, - _cx: *mut JSContext, - target: u32, - pname: u32, - ) -> JSVal { + fn GetRenderbufferParameter(&self, _cx: SafeJSContext, target: u32, pname: u32) -> JSVal { let target_matches = target == constants::RENDERBUFFER; 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 - unsafe fn GetProgramParameter( - &self, - _: *mut JSContext, - program: &WebGLProgram, - param: u32, - ) -> JSVal { + fn GetProgramParameter(&self, _: SafeJSContext, program: &WebGLProgram, param: u32) -> JSVal { handle_potential_webgl_error!(self, self.validate_ownership(program), return NullValue()); if program.is_deleted() { self.webgl_error(InvalidOperation); @@ -2541,14 +2523,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { Some(shader.info_log()) } - #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - unsafe fn GetShaderParameter( - &self, - _: *mut JSContext, - shader: &WebGLShader, - param: u32, - ) -> JSVal { + fn GetShaderParameter(&self, _: SafeJSContext, shader: &WebGLShader, param: u32) -> JSVal { handle_potential_webgl_error!(self, self.validate_ownership(shader), return NullValue()); if shader.is_deleted() { self.webgl_error(InvalidValue); @@ -2620,7 +2596,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] // 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 data = handle_potential_webgl_error!( self, @@ -2636,10 +2612,12 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { self.send_command(WebGLCommand::GetCurrentVertexAttrib(index, sender)); receiver.recv().unwrap() }; - rooted!(in(cx) let mut result = ptr::null_mut::<JSObject>()); - let _ = - Float32Array::create(cx, CreateWith::Slice(&value), result.handle_mut()).unwrap(); - return ObjectValue(result.get()); + unsafe { + rooted!(in(*cx) let mut result = ptr::null_mut::<JSObject>()); + let _ = Float32Array::create(*cx, CreateWith::Slice(&value), result.handle_mut()) + .unwrap(); + return ObjectValue(result.get()); + } } if !self @@ -2656,10 +2634,10 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { constants::VERTEX_ATTRIB_ARRAY_TYPE => Int32Value(data.type_ as i32), constants::VERTEX_ATTRIB_ARRAY_NORMALIZED => BooleanValue(data.normalized), constants::VERTEX_ATTRIB_ARRAY_STRIDE => Int32Value(data.stride as i32), - constants::VERTEX_ATTRIB_ARRAY_BUFFER_BINDING => { - rooted!(in(cx) let mut jsval = NullValue()); + constants::VERTEX_ATTRIB_ARRAY_BUFFER_BINDING => unsafe { + rooted!(in(*cx) let mut jsval = NullValue()); if let Some(buffer) = data.buffer() { - buffer.to_jsval(cx, jsval.handle_mut()); + buffer.to_jsval(*cx, jsval.handle_mut()); } jsval.get() }, @@ -3432,9 +3410,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] - unsafe fn GetUniform( + fn GetUniform( &self, - cx: *mut JSContext, + cx: SafeJSContext, program: &WebGLProgram, location: &WebGLUniformLocation, ) -> JSVal { @@ -3477,42 +3455,48 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { match location.type_() { constants::BOOL => BooleanValue(get(triple, WebGLCommand::GetUniformBool)), - constants::BOOL_VEC2 => { - rooted!(in(cx) let mut rval = NullValue()); - get(triple, WebGLCommand::GetUniformBool2).to_jsval(cx, rval.handle_mut()); + constants::BOOL_VEC2 => unsafe { + rooted!(in(*cx) let mut rval = NullValue()); + get(triple, WebGLCommand::GetUniformBool2).to_jsval(*cx, rval.handle_mut()); rval.get() }, - constants::BOOL_VEC3 => { - rooted!(in(cx) let mut rval = NullValue()); - get(triple, WebGLCommand::GetUniformBool3).to_jsval(cx, rval.handle_mut()); + constants::BOOL_VEC3 => unsafe { + rooted!(in(*cx) let mut rval = NullValue()); + get(triple, WebGLCommand::GetUniformBool3).to_jsval(*cx, rval.handle_mut()); rval.get() }, - constants::BOOL_VEC4 => { - rooted!(in(cx) let mut rval = NullValue()); - get(triple, WebGLCommand::GetUniformBool4).to_jsval(cx, rval.handle_mut()); + constants::BOOL_VEC4 => unsafe { + rooted!(in(*cx) let mut rval = NullValue()); + get(triple, WebGLCommand::GetUniformBool4).to_jsval(*cx, rval.handle_mut()); rval.get() }, constants::INT | constants::SAMPLER_2D | constants::SAMPLER_CUBE => { Int32Value(get(triple, WebGLCommand::GetUniformInt)) }, - constants::INT_VEC2 => typed::<Int32>(cx, &get(triple, WebGLCommand::GetUniformInt2)), - constants::INT_VEC3 => typed::<Int32>(cx, &get(triple, WebGLCommand::GetUniformInt3)), - constants::INT_VEC4 => typed::<Int32>(cx, &get(triple, WebGLCommand::GetUniformInt4)), + constants::INT_VEC2 => unsafe { + typed::<Int32>(*cx, &get(triple, WebGLCommand::GetUniformInt2)) + }, + 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_VEC2 => { - typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat2)) + constants::FLOAT_VEC2 => unsafe { + typed::<Float32>(*cx, &get(triple, WebGLCommand::GetUniformFloat2)) }, - constants::FLOAT_VEC3 => { - typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat3)) + constants::FLOAT_VEC3 => unsafe { + typed::<Float32>(*cx, &get(triple, WebGLCommand::GetUniformFloat3)) }, - constants::FLOAT_VEC4 | constants::FLOAT_MAT2 => { - typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat4)) + constants::FLOAT_VEC4 | constants::FLOAT_MAT2 => unsafe { + typed::<Float32>(*cx, &get(triple, WebGLCommand::GetUniformFloat4)) }, - constants::FLOAT_MAT3 => { - typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat9)) + constants::FLOAT_MAT3 => unsafe { + typed::<Float32>(*cx, &get(triple, WebGLCommand::GetUniformFloat9)) }, - constants::FLOAT_MAT4 => { - typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat16)) + constants::FLOAT_MAT4 => unsafe { + typed::<Float32>(*cx, &get(triple, WebGLCommand::GetUniformFloat16)) }, _ => panic!("wrong uniform type"), } diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 6df91312931..c97a3fd08fb 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -615,26 +615,28 @@ impl WindowMethods for Window { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-opener - unsafe fn Opener(&self, cx: *mut JSContext) -> JSVal { - self.window_proxy().opener(cx) + fn Opener(&self, cx: SafeJSContext) -> JSVal { + unsafe { self.window_proxy().opener(*cx) } } #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-opener - unsafe fn SetOpener(&self, cx: *mut JSContext, value: HandleValue) { + fn SetOpener(&self, cx: SafeJSContext, value: HandleValue) { // Step 1. if value.is_null() { return self.window_proxy().disown(); } // Step 2. let obj = self.reflector().get_jsobject(); - assert!(JS_DefineProperty( - cx, - obj, - "opener\0".as_ptr() as *const libc::c_char, - value, - JSPROP_ENUMERATE as u32 - )); + unsafe { + assert!(JS_DefineProperty( + *cx, + obj, + "opener\0".as_ptr() as *const libc::c_char, + value, + JSPROP_ENUMERATE as u32 + )); + } } // https://html.spec.whatwg.org/multipage/#dom-window-closed @@ -739,11 +741,10 @@ impl WindowMethods for Window { self.navigator.or_init(|| Navigator::new(self)) } - #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout - unsafe fn SetTimeout( + fn SetTimeout( &self, - _cx: *mut JSContext, + _cx: SafeJSContext, callback: Rc<Function>, timeout: i32, args: Vec<HandleValue>, @@ -756,11 +757,10 @@ impl WindowMethods for Window { ) } - #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout - unsafe fn SetTimeout_( + fn SetTimeout_( &self, - _cx: *mut JSContext, + _cx: SafeJSContext, callback: DOMString, timeout: i32, args: Vec<HandleValue>, @@ -779,11 +779,10 @@ impl WindowMethods for Window { .clear_timeout_or_interval(handle); } - #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval - unsafe fn SetInterval( + fn SetInterval( &self, - _cx: *mut JSContext, + _cx: SafeJSContext, callback: Rc<Function>, timeout: i32, args: Vec<HandleValue>, @@ -796,11 +795,10 @@ impl WindowMethods for Window { ) } - #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval - unsafe fn SetInterval_( + fn SetInterval_( &self, - _cx: *mut JSContext, + _cx: SafeJSContext, callback: DOMString, timeout: i32, args: Vec<HandleValue>, @@ -903,11 +901,10 @@ impl WindowMethods for Window { doc.cancel_animation_frame(ident); } - #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-window-postmessage - unsafe fn PostMessage( + fn PostMessage( &self, - cx: *mut JSContext, + cx: SafeJSContext, message: HandleValue, origin: DOMString, ) -> ErrorResult { @@ -926,7 +923,7 @@ impl WindowMethods for Window { // Step 1-2, 6-8. // TODO(#12717): Should implement the `transfer` argument. - let data = StructuredCloneData::write(cx, message)?; + let data = StructuredCloneData::write(*cx, message)?; // Step 9. self.post_message(origin, &*source.window_proxy(), data); @@ -961,8 +958,8 @@ impl WindowMethods for Window { } #[allow(unsafe_code)] - unsafe fn WebdriverCallback(&self, cx: *mut JSContext, val: HandleValue) { - let rv = jsval_to_webdriver(cx, val); + fn WebdriverCallback(&self, cx: SafeJSContext, val: HandleValue) { + let rv = unsafe { jsval_to_webdriver(*cx, val) }; let opt_chan = self.webdriver_script_chan.borrow_mut().take(); if let Some(chan) = opt_chan { chan.send(rv).unwrap(); diff --git a/components/script/dom/worker.rs b/components/script/dom/worker.rs index 46288e6947e..4b8384e3ed8 100644 --- a/components/script/dom/worker.rs +++ b/components/script/dom/worker.rs @@ -21,12 +21,13 @@ use crate::dom::eventtarget::EventTarget; use crate::dom::globalscope::GlobalScope; use crate::dom::messageevent::MessageEvent; use crate::dom::workerglobalscope::prepare_workerscope_init; +use crate::script_runtime::JSContext; use crate::task::TaskOnce; use crossbeam_channel::{unbounded, Sender}; use devtools_traits::{DevtoolsPageInfo, ScriptToDevtoolsControlMsg}; use dom_struct::dom_struct; use ipc_channel::ipc; -use js::jsapi::{JSContext, JS_RequestInterruptCallback}; +use js::jsapi::JS_RequestInterruptCallback; use js::jsval::UndefinedValue; use js::rust::HandleValue; use script_traits::WorkerScriptLoadOrigin; @@ -158,10 +159,9 @@ impl Worker { } impl WorkerMethods for Worker { - #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-worker-postmessage - unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { - let data = StructuredCloneData::write(cx, message)?; + fn PostMessage(&self, cx: JSContext, message: HandleValue) -> ErrorResult { + let data = StructuredCloneData::write(*cx, message)?; let address = Trusted::new(self); // NOTE: step 9 of https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index 04aabe6db17..bf21b8442c3 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -26,6 +26,7 @@ use crate::dom::window::{base64_atob, base64_btoa}; use crate::dom::workerlocation::WorkerLocation; use crate::dom::workernavigator::WorkerNavigator; use crate::fetch; +use crate::script_runtime::JSContext as SafeJSContext; use crate::script_runtime::{get_reports, CommonScriptMsg, Runtime, ScriptChan, ScriptPort}; use crate::task::TaskCanceller; use crate::task_source::dom_manipulation::DOMManipulationTaskSource; @@ -288,11 +289,10 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { base64_atob(atob) } - #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout - unsafe fn SetTimeout( + fn SetTimeout( &self, - _cx: *mut JSContext, + _cx: SafeJSContext, callback: Rc<Function>, timeout: i32, args: Vec<HandleValue>, @@ -305,11 +305,10 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { ) } - #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout - unsafe fn SetTimeout_( + fn SetTimeout_( &self, - _cx: *mut JSContext, + _cx: SafeJSContext, callback: DOMString, timeout: i32, args: Vec<HandleValue>, @@ -328,11 +327,10 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { .clear_timeout_or_interval(handle); } - #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval - unsafe fn SetInterval( + fn SetInterval( &self, - _cx: *mut JSContext, + _cx: SafeJSContext, callback: Rc<Function>, timeout: i32, args: Vec<HandleValue>, @@ -345,11 +343,10 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { ) } - #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval - unsafe fn SetInterval_( + fn SetInterval_( &self, - _cx: *mut JSContext, + _cx: SafeJSContext, callback: DOMString, timeout: i32, args: Vec<HandleValue>, diff --git a/components/script/dom/xmldocument.rs b/components/script/dom/xmldocument.rs index aeb088a6c77..73d7eee89c5 100644 --- a/components/script/dom/xmldocument.rs +++ b/components/script/dom/xmldocument.rs @@ -13,8 +13,8 @@ use crate::dom::document::{Document, DocumentSource, HasBrowsingContext, IsHTMLD use crate::dom::location::Location; use crate::dom::node::Node; use crate::dom::window::Window; +use crate::script_runtime::JSContext; use dom_struct::dom_struct; -use js::jsapi::JSContext; use js::jsapi::JSObject; use mime::Mime; use script_traits::DocumentActivity; @@ -106,13 +106,8 @@ impl XMLDocumentMethods for XMLDocument { self.upcast::<Document>().SupportedPropertyNames() } - #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-tree-accessors:dom-document-nameditem-filter - unsafe fn NamedGetter( - &self, - _cx: *mut JSContext, - name: DOMString, - ) -> Option<NonNull<JSObject>> { + fn NamedGetter(&self, _cx: JSContext, name: DOMString) -> Option<NonNull<JSObject>> { self.upcast::<Document>().NamedGetter(_cx, name) } } diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index 443a0711815..082973345c9 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -38,6 +38,7 @@ use crate::dom::xmlhttprequesteventtarget::XMLHttpRequestEventTarget; use crate::dom::xmlhttprequestupload::XMLHttpRequestUpload; use crate::fetch::FetchCanceller; 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::TaskSourceName; use crate::timers::{OneshotTimerCallback, OneshotTimerHandle}; @@ -877,19 +878,19 @@ impl XMLHttpRequestMethods for XMLHttpRequest { #[allow(unsafe_code)] // https://xhr.spec.whatwg.org/#the-response-attribute - unsafe fn Response(&self, cx: *mut JSContext) -> JSVal { - rooted!(in(cx) let mut rval = UndefinedValue()); + fn Response(&self, cx: SafeJSContext) -> JSVal { + rooted!(in(*cx) let mut rval = UndefinedValue()); match self.response_type.get() { - XMLHttpRequestResponseType::_empty | XMLHttpRequestResponseType::Text => { + XMLHttpRequestResponseType::_empty | XMLHttpRequestResponseType::Text => unsafe { let ready_state = self.ready_state.get(); // Step 2 if ready_state == XMLHttpRequestState::Done || ready_state == XMLHttpRequestState::Loading { - self.text_response().to_jsval(cx, rval.handle_mut()); + self.text_response().to_jsval(*cx, rval.handle_mut()); } else { // Step 1 - "".to_jsval(cx, rval.handle_mut()); + "".to_jsval(*cx, rval.handle_mut()); } }, // Step 1 @@ -897,18 +898,20 @@ impl XMLHttpRequestMethods for XMLHttpRequest { return NullValue(); }, // Step 2 - XMLHttpRequestResponseType::Document => { - self.document_response().to_jsval(cx, rval.handle_mut()); + XMLHttpRequestResponseType::Document => unsafe { + self.document_response().to_jsval(*cx, rval.handle_mut()); }, - XMLHttpRequestResponseType::Json => { - self.json_response(cx).to_jsval(cx, rval.handle_mut()); + XMLHttpRequestResponseType::Json => unsafe { + self.json_response(*cx).to_jsval(*cx, rval.handle_mut()); }, - XMLHttpRequestResponseType::Blob => { - self.blob_response().to_jsval(cx, rval.handle_mut()); + XMLHttpRequestResponseType::Blob => unsafe { + self.blob_response().to_jsval(*cx, rval.handle_mut()); }, - XMLHttpRequestResponseType::Arraybuffer => match self.arraybuffer_response(cx) { - Some(js_object) => js_object.to_jsval(cx, rval.handle_mut()), - None => return NullValue(), + XMLHttpRequestResponseType::Arraybuffer => unsafe { + match self.arraybuffer_response(*cx) { + Some(js_object) => js_object.to_jsval(*cx, rval.handle_mut()), + None => return NullValue(), + } }, } rval.get() diff --git a/components/script/dom/xrrigidtransform.rs b/components/script/dom/xrrigidtransform.rs index 887b54f688c..b9690187494 100644 --- a/components/script/dom/xrrigidtransform.rs +++ b/components/script/dom/xrrigidtransform.rs @@ -15,9 +15,10 @@ use crate::dom::globalscope::GlobalScope; use crate::dom::vrframedata::create_typed_array; use crate::dom::window::Window; use crate::dom::xrsession::ApiRigidTransform; +use crate::script_runtime::JSContext; use dom_struct::dom_struct; use euclid::{RigidTransform3D, Rotation3D, Vector3D}; -use js::jsapi::{Heap, JSContext, JSObject}; +use js::jsapi::{Heap, JSObject}; use std::ptr::NonNull; #[dom_struct] @@ -119,9 +120,9 @@ impl XRRigidTransformMethods for XRRigidTransform { } // https://immersive-web.github.io/webxr/#dom-xrrigidtransform-matrix #[allow(unsafe_code)] - unsafe fn Matrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> { + fn Matrix(&self, _cx: JSContext) -> NonNull<JSObject> { if self.matrix.get().is_null() { - let cx = self.global().get_cx(); + let cx = unsafe { JSContext::from_ptr(self.global().get_cx()) }; // According to the spec all matrices are column-major, // however euclid uses row vectors so we use .to_row_major_array() let arr = self.transform.to_transform().to_row_major_array(); diff --git a/components/script/dom/xrview.rs b/components/script/dom/xrview.rs index 807217945a6..bc51d8f38c8 100644 --- a/components/script/dom/xrview.rs +++ b/components/script/dom/xrview.rs @@ -10,8 +10,9 @@ use crate::dom::globalscope::GlobalScope; use crate::dom::vrframedata::create_typed_array; use crate::dom::xrrigidtransform::XRRigidTransform; use crate::dom::xrsession::{cast_transform, ApiViewerPose, XRSession}; +use crate::script_runtime::JSContext; use dom_struct::dom_struct; -use js::jsapi::{Heap, JSContext, JSObject}; +use js::jsapi::{Heap, JSObject}; use std::ptr::NonNull; use webxr_api::View; @@ -64,10 +65,8 @@ impl XRView { // row_major since euclid uses row vectors let proj = view.projection.to_row_major_array(); - let cx = global.get_cx(); - unsafe { - create_typed_array(cx, &proj, &ret.proj); - } + let cx = unsafe { JSContext::from_ptr(global.get_cx()) }; + create_typed_array(cx, &proj, &ret.proj); ret } @@ -82,9 +81,8 @@ impl XRViewMethods for XRView { self.eye } - #[allow(unsafe_code)] /// 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() } diff --git a/components/script/dom/xrviewerpose.rs b/components/script/dom/xrviewerpose.rs index ca47b2de390..ce3f94c1817 100644 --- a/components/script/dom/xrviewerpose.rs +++ b/components/script/dom/xrviewerpose.rs @@ -12,9 +12,10 @@ use crate::dom::xrpose::XRPose; use crate::dom::xrrigidtransform::XRRigidTransform; use crate::dom::xrsession::{cast_transform, ApiViewerPose, XRSession}; use crate::dom::xrview::XRView; +use crate::script_runtime::JSContext; use dom_struct::dom_struct; use js::conversions::ToJSValConvertible; -use js::jsapi::{Heap, JSContext}; +use js::jsapi::Heap; use js::jsval::{JSVal, UndefinedValue}; use webxr_api::Views; @@ -69,8 +70,7 @@ impl XRViewerPose { impl XRViewerPoseMethods for XRViewerPose { /// https://immersive-web.github.io/webxr/#dom-xrviewerpose-views - #[allow(unsafe_code)] - unsafe fn Views(&self, _cx: *mut JSContext) -> JSVal { + fn Views(&self, _cx: JSContext) -> JSVal { self.views.get() } } |