Skip to content

Commit

Permalink
Convert CGTraitInterface to use safe JSContext instead of raw JSContext
Browse files Browse the repository at this point in the history
  • Loading branch information
marmeladema committed Jul 24, 2019
1 parent 808fa65 commit 2c5d0a6
Show file tree
Hide file tree
Showing 43 changed files with 444 additions and 529 deletions.
21 changes: 10 additions & 11 deletions components/script/dom/audiobuffer.rs
Expand Up @@ -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};
Expand Down Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions components/script/dom/bindings/codegen/CodegenRust.py
Expand Up @@ -3332,7 +3332,7 @@ def __init__(self, errorResult, arguments, argsPre, returnType,
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))"))

Expand Down Expand Up @@ -5649,7 +5649,7 @@ def __init__(self, descriptor):

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)
Expand Down Expand Up @@ -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,
Expand Down
24 changes: 12 additions & 12 deletions components/script/dom/bindings/iterable.rs
Expand Up @@ -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())
},
}
};
Expand Down
11 changes: 6 additions & 5 deletions components/script/dom/crypto.rs
Expand Up @@ -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};
Expand Down Expand Up @@ -47,24 +48,24 @@ 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();

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

Expand Down
8 changes: 4 additions & 4 deletions components/script/dom/customelementregistry.rs
Expand Up @@ -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(),
Expand Down
11 changes: 5 additions & 6 deletions components/script/dom/customevent.rs
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down
5 changes: 2 additions & 3 deletions components/script/dom/dedicatedworkerglobalscope.rs
Expand Up @@ -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 || {
Expand Down
21 changes: 6 additions & 15 deletions components/script/dom/dissimilaroriginwindow.rs
Expand Up @@ -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;
Expand Down Expand Up @@ -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> {
Expand Down Expand Up @@ -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,
Expand All @@ -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
}

Expand Down
19 changes: 9 additions & 10 deletions components/script/dom/document.rs
Expand Up @@ -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;
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down
23 changes: 14 additions & 9 deletions components/script/dom/dommatrixreadonly.rs
Expand Up @@ -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};
Expand Down Expand Up @@ -667,26 +668,30 @@ 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()
.to_row_major_array()
.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())
}
}
}

Expand Down

0 comments on commit 2c5d0a6

Please sign in to comment.