script: Make get_property_jsval a safe function (#39137)

Accept the safe `JSContext` wraper to this function so that it can be
safe. Some callers also become safe as well.

Testing: This does not change behavior and is thus covered by existing
tests.
Fixes: #39129.

Signed-off-by: Martin Robinson <mrobinson@igalia.com>
This commit is contained in:
Martin Robinson 2025-09-04 16:11:15 -07:00 committed by GitHub
parent 589a750cac
commit e5fbb31452
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 59 additions and 75 deletions

View file

@ -37,11 +37,12 @@ use std::ffi;
pub(crate) use js::conversions::{
ConversionBehavior, ConversionResult, FromJSValConvertible, ToJSValConvertible,
};
use js::jsapi::{JS_IsExceptionPending, JSContext, JSObject};
use js::jsapi::{JS_IsExceptionPending, JSContext as RawJSContext, JSObject};
use js::jsval::UndefinedValue;
use js::rust::wrappers::{JS_GetProperty, JS_HasProperty};
use js::rust::{HandleObject, MutableHandleValue};
pub(crate) use script_bindings::conversions::{is_dom_proxy, *};
use script_bindings::script_runtime::JSContext;
use crate::dom::bindings::error::{Error, Fallible};
use crate::dom::bindings::reflector::DomObject;
@ -63,7 +64,7 @@ where
/// Get a `DomRoot<T>` for a DOM object accessible from a `HandleObject`.
pub(crate) fn root_from_handleobject<T>(
obj: HandleObject,
cx: *mut JSContext,
cx: *mut RawJSContext,
) -> Result<DomRoot<T>, ()>
where
T: DomObject + IDLInterface,
@ -72,36 +73,38 @@ where
}
/// Get a property from a JS object.
pub(crate) unsafe fn get_property_jsval(
cx: *mut JSContext,
pub(crate) fn get_property_jsval(
cx: JSContext,
object: HandleObject,
name: &str,
mut rval: MutableHandleValue,
) -> Fallible<()> {
rval.set(UndefinedValue());
let cname = match ffi::CString::new(name) {
Ok(cname) => cname,
Err(_) => return Ok(()),
let Ok(cname) = ffi::CString::new(name) else {
return Ok(());
};
let mut found = false;
unsafe {
if JS_HasProperty(cx, object, cname.as_ptr(), &mut found) && found {
JS_GetProperty(cx, object, cname.as_ptr(), rval);
if JS_IsExceptionPending(cx) {
if !JS_HasProperty(*cx, object, cname.as_ptr(), &mut found) || !found {
if JS_IsExceptionPending(*cx) {
return Err(Error::JSFailed);
}
Ok(())
} else if JS_IsExceptionPending(cx) {
Err(Error::JSFailed)
} else {
Ok(())
return Ok(());
}
JS_GetProperty(*cx, object, cname.as_ptr(), rval);
if JS_IsExceptionPending(*cx) {
return Err(Error::JSFailed);
}
Ok(())
}
}
/// Get a property from a JS object, and convert it to a Rust value.
pub(crate) unsafe fn get_property<T>(
cx: *mut JSContext,
pub(crate) fn get_property<T>(
cx: JSContext,
object: HandleObject,
name: &str,
option: T::Config,
@ -110,14 +113,14 @@ where
T: FromJSValConvertible,
{
debug!("Getting property {}.", name);
rooted!(in(cx) let mut result = UndefinedValue());
unsafe { get_property_jsval(cx, object, name, result.handle_mut())? };
rooted!(in(*cx) let mut result = UndefinedValue());
get_property_jsval(cx, object, name, result.handle_mut())?;
if result.is_undefined() {
debug!("No property {}.", name);
return Ok(None);
}
debug!("Converting property {}.", name);
let value = unsafe { T::from_jsval(cx, result.handle(), option) };
let value = unsafe { T::from_jsval(*cx, result.handle(), option) };
match value {
Ok(ConversionResult::Success(value)) => Ok(Some(value)),
Ok(ConversionResult::Failure(_)) => Ok(None),

View file

@ -513,20 +513,17 @@ impl PaintWorkletGlobalScopeMethods<crate::DomTypeHolder> for PaintWorkletGlobal
// Step 4-6.
let mut property_names: Vec<String> =
unsafe { get_property(*cx, paint_obj.handle(), "inputProperties", ()) }?
.unwrap_or_default();
get_property(cx, paint_obj.handle(), "inputProperties", ())?.unwrap_or_default();
let properties = property_names.drain(..).map(Atom::from).collect();
// Step 7-9.
let input_arguments: Vec<String> =
unsafe { get_property(*cx, paint_obj.handle(), "inputArguments", ()) }?
.unwrap_or_default();
get_property(cx, paint_obj.handle(), "inputArguments", ())?.unwrap_or_default();
// TODO: Steps 10-11.
// Steps 12-13.
let alpha: bool =
unsafe { get_property(*cx, paint_obj.handle(), "alpha", ()) }?.unwrap_or(true);
let alpha: bool = get_property(cx, paint_obj.handle(), "alpha", ())?.unwrap_or(true);
// Step 14
if unsafe { !IsConstructor(paint_obj.get()) } {
@ -535,9 +532,7 @@ impl PaintWorkletGlobalScopeMethods<crate::DomTypeHolder> for PaintWorkletGlobal
// Steps 15-16
rooted!(in(*cx) let mut prototype = UndefinedValue());
unsafe {
get_property_jsval(*cx, paint_obj.handle(), "prototype", prototype.handle_mut())?;
}
get_property_jsval(cx, paint_obj.handle(), "prototype", prototype.handle_mut())?;
if !prototype.is_object() {
return Err(Error::Type(String::from("Prototype is not an object.")));
}
@ -545,14 +540,7 @@ impl PaintWorkletGlobalScopeMethods<crate::DomTypeHolder> for PaintWorkletGlobal
// Steps 17-18
rooted!(in(*cx) let mut paint_function = UndefinedValue());
unsafe {
get_property_jsval(
*cx,
prototype.handle(),
"paint",
paint_function.handle_mut(),
)?;
}
get_property_jsval(cx, prototype.handle(), "paint", paint_function.handle_mut())?;
if !paint_function.is_object() || unsafe { !IsCallable(paint_function.to_object()) } {
return Err(Error::Type(String::from("Paint function is not callable.")));
}

View file

@ -457,7 +457,13 @@ unsafe fn jsval_to_webdriver_inner(
Err(WebDriverJSError::JSError)
}
} else {
clone_an_object(cx, global_scope, val, seen, object.handle())
clone_an_object(
SafeJSContext::from_ptr(cx),
global_scope,
val,
seen,
object.handle(),
)
}
} else {
Err(WebDriverJSError::UnknownType)
@ -467,7 +473,7 @@ unsafe fn jsval_to_webdriver_inner(
#[allow(unsafe_code)]
/// <https://w3c.github.io/webdriver/#dfn-clone-an-object>
unsafe fn clone_an_object(
cx: *mut JSContext,
cx: SafeJSContext,
global_scope: &GlobalScope,
val: HandleValue,
seen: &mut HashSet<HashableJSVal>,
@ -482,49 +488,38 @@ unsafe fn clone_an_object(
seen.insert(hashable.clone());
let return_val = if unsafe {
is_array_like::<crate::DomTypeHolder>(cx, val) || is_arguments_object(cx, val)
is_array_like::<crate::DomTypeHolder>(*cx, val) || is_arguments_object(*cx, val)
} {
let mut result: Vec<JSValue> = Vec::new();
let get_property_result = unsafe {
get_property::<u32>(cx, object_handle, "length", ConversionBehavior::Default)
};
let get_property_result =
get_property::<u32>(cx, object_handle, "length", ConversionBehavior::Default);
let length = match get_property_result {
Ok(length) => match length {
Some(length) => length,
_ => return Err(WebDriverJSError::UnknownType),
},
Err(error) => {
throw_dom_exception(
unsafe { SafeJSContext::from_ptr(cx) },
global_scope,
error,
CanGc::note(),
);
throw_dom_exception(cx, global_scope, error, CanGc::note());
return Err(WebDriverJSError::JSError);
},
};
// Step 4. For each enumerable property in value, run the following substeps:
for i in 0..length {
rooted!(in(cx) let mut item = UndefinedValue());
rooted!(in(*cx) let mut item = UndefinedValue());
let get_property_result =
unsafe { get_property_jsval(cx, object_handle, &i.to_string(), item.handle_mut()) };
get_property_jsval(cx, object_handle, &i.to_string(), item.handle_mut());
match get_property_result {
Ok(_) => {
let conversion_result =
unsafe { jsval_to_webdriver_inner(cx, global_scope, item.handle(), seen) };
unsafe { jsval_to_webdriver_inner(*cx, global_scope, item.handle(), seen) };
match conversion_result {
Ok(converted_item) => result.push(converted_item),
err @ Err(_) => return err,
}
},
Err(error) => {
throw_dom_exception(
unsafe { SafeJSContext::from_ptr(cx) },
global_scope,
error,
CanGc::note(),
);
throw_dom_exception(cx, global_scope, error, CanGc::note());
return Err(WebDriverJSError::JSError);
},
}
@ -533,10 +528,10 @@ unsafe fn clone_an_object(
} else {
let mut result = HashMap::new();
let mut ids = unsafe { IdVector::new(cx) };
let mut ids = unsafe { IdVector::new(*cx) };
let succeeded = unsafe {
GetPropertyKeys(
cx,
*cx,
object_handle.into(),
jsapi::JSITER_OWNONLY,
ids.handle_mut(),
@ -546,13 +541,13 @@ unsafe fn clone_an_object(
return Err(WebDriverJSError::JSError);
}
for id in ids.iter() {
rooted!(in(cx) let id = *id);
rooted!(in(cx) let mut desc = PropertyDescriptor::default());
rooted!(in(*cx) let id = *id);
rooted!(in(*cx) let mut desc = PropertyDescriptor::default());
let mut is_none = false;
let succeeded = unsafe {
JS_GetOwnPropertyDescriptorById(
cx,
*cx,
object_handle.into(),
id.handle().into(),
desc.handle_mut().into(),
@ -563,10 +558,10 @@ unsafe fn clone_an_object(
return Err(WebDriverJSError::JSError);
}
rooted!(in(cx) let mut property = UndefinedValue());
rooted!(in(*cx) let mut property = UndefinedValue());
let succeeded = unsafe {
JS_GetPropertyById(
cx,
*cx,
object_handle.into(),
id.handle().into(),
property.handle_mut().into(),
@ -577,13 +572,13 @@ unsafe fn clone_an_object(
}
if !property.is_undefined() {
let name = unsafe { jsid_to_string(cx, id.handle()) };
let name = unsafe { jsid_to_string(*cx, id.handle()) };
let Some(name) = name else {
return Err(WebDriverJSError::JSError);
};
if let Ok(value) =
unsafe { jsval_to_webdriver_inner(cx, global_scope, property.handle(), seen) }
unsafe { jsval_to_webdriver_inner(*cx, global_scope, property.handle(), seen) }
{
result.insert(name.into(), value);
} else {
@ -1705,14 +1700,12 @@ pub(crate) fn handle_get_property(
let cx = document.window().get_cx();
rooted!(in(*cx) let mut property = UndefinedValue());
match unsafe {
get_property_jsval(
*cx,
element.reflector().get_jsobject(),
&name,
property.handle_mut(),
)
} {
match get_property_jsval(
cx,
element.reflector().get_jsobject(),
&name,
property.handle_mut(),
) {
Ok(_) => {
match jsval_to_webdriver(
cx,