script: Use the new C string literal in the DOM bindings (#32741)

* simple conversion to cstrings using as_ptr()

Signed-off-by: Bum Kim <bumcrystlbum@gmail.com>

* replaced byte strings with c strings using new helper functions

Signed-off-by: Bum Kim <bumcrystlbum@gmail.com>

* changed &[u8] type parameters to &CStr

Signed-off-by: Bum Kim <bumcrystlbum@gmail.com>

---------

Signed-off-by: Bum Kim <bumcrystlbum@gmail.com>
This commit is contained in:
Bumsoo Kim 2024-07-11 00:18:54 -04:00 committed by GitHub
parent 3e163bfcdb
commit c6cb7ee981
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 60 additions and 63 deletions

View file

@ -1862,7 +1862,7 @@ class MethodDefiner(PropertyDefiner):
if flags != "0":
flags = f"({flags}) as u16"
if "selfHostedName" in m:
selfHostedName = '%s as *const u8 as *const libc::c_char' % str_to_const_array(m["selfHostedName"])
selfHostedName = str_to_cstr_ptr(m["selfHostedName"])
assert not m.get("methodInfo", True)
accessor = "None"
jitinfo = "ptr::null()"
@ -1883,8 +1883,8 @@ class MethodDefiner(PropertyDefiner):
assert not self.crossorigin
name = 'JSPropertySpec_Name { symbol_: SymbolCode::%s as usize + 1 }' % m["name"][2:]
else:
name = ('JSPropertySpec_Name { string_: %s as *const u8 as *const libc::c_char }'
% str_to_const_array(m["name"]))
name = ('JSPropertySpec_Name { string_: %s }'
% str_to_cstr_ptr(m["name"]))
return (name, accessor, jitinfo, m["length"], flags, selfHostedName)
specTemplate = (
@ -2013,12 +2013,12 @@ class AttrDefiner(PropertyDefiner):
def specData(attr):
if attr["name"] == "@@toStringTag":
return (attr["name"][2:], attr["flags"], attr["kind"],
str_to_const_array(self.descriptor.interface.getClassName()))
str_to_cstr_ptr(self.descriptor.interface.getClassName()))
flags = attr["flags"]
if self.unforgeable:
flags += " | JSPROP_PERMANENT"
return (str_to_const_array(attr["attr"].identifier.name), flags, attr["kind"], getter(attr),
return (str_to_cstr_ptr(attr["attr"].identifier.name), flags, attr["kind"], getter(attr),
setter(attr))
def template(m):
@ -2031,14 +2031,14 @@ class AttrDefiner(PropertyDefiner):
value: JSPropertySpec_ValueWrapper {
type_: JSPropertySpec_ValueWrapper_Type::String,
__bindgen_anon_1: JSPropertySpec_ValueWrapper__bindgen_ty_1 {
string: %s as *const u8 as *const libc::c_char,
string: %s,
}
}
}
}
"""
return """ JSPropertySpec {
name: JSPropertySpec_Name { string_: %s as *const u8 as *const libc::c_char },
name: JSPropertySpec_Name { string_: %s },
attributes_: (%s),
kind_: (%s),
u: JSPropertySpec_AccessorsOrValue {
@ -2084,7 +2084,7 @@ class ConstDefiner(PropertyDefiner):
return ""
def specData(const):
return (str_to_const_array(const.identifier.name),
return (str_to_cstr(const.identifier.name),
convertConstIDLValueToJSVal(const.value))
return self.generateGuardedArray(
@ -2379,7 +2379,7 @@ class CGDOMJSClass(CGThing):
"enumerateHook": "None",
"finalizeHook": FINALIZE_HOOK_NAME,
"flags": "JSCLASS_FOREGROUND_FINALIZE",
"name": str_to_const_array(self.descriptor.interface.identifier.name),
"name": str_to_cstr_ptr(self.descriptor.interface.identifier.name),
"resolveHook": "None",
"slots": "1",
"traceHook": TRACE_HOOK_NAME,
@ -2409,7 +2409,7 @@ static CLASS_OPS: JSClassOps = JSClassOps {
static Class: DOMJSClass = DOMJSClass {
base: JSClass {
name: %(name)s as *const u8 as *const libc::c_char,
name: %(name)s,
flags: JSCLASS_IS_DOMJSCLASS | %(flags)s |
(((%(slots)s) & JSCLASS_RESERVED_SLOTS_MASK) << JSCLASS_RESERVED_SLOTS_SHIFT)
/* JSCLASS_HAS_RESERVED_SLOTS(%(slots)s) */,
@ -2466,8 +2466,12 @@ impl %(selfName)s {
""" % args
def str_to_const_array(s):
return "b\"%s\\0\"" % s
def str_to_cstr(s):
return "c\"%s\"" % s
def str_to_cstr_ptr(s):
return "c\"%s\".as_ptr()" % s
class CGPrototypeJSClass(CGThing):
@ -2476,13 +2480,13 @@ class CGPrototypeJSClass(CGThing):
self.descriptor = descriptor
def define(self):
name = str_to_const_array(self.descriptor.interface.identifier.name + "Prototype")
name = str_to_cstr_ptr(self.descriptor.interface.identifier.name + "Prototype")
slotCount = 0
if self.descriptor.hasLegacyUnforgeableMembers:
slotCount += 1
return """\
static PrototypeClass: JSClass = JSClass {
name: %(name)s as *const u8 as *const libc::c_char,
name: %(name)s,
flags:
// JSCLASS_HAS_RESERVED_SLOTS(%(slotCount)s)
(%(slotCount)s ) << JSCLASS_RESERVED_SLOTS_SHIFT,
@ -2511,7 +2515,7 @@ class CGInterfaceObjectJSClass(CGThing):
static NAMESPACE_OBJECT_CLASS: NamespaceObjectClass = unsafe {
NamespaceObjectClass::new(%s)
};
""" % str_to_const_array(classString)
""" % str_to_cstr(classString)
if self.descriptor.interface.ctor():
constructorBehavior = "InterfaceConstructorBehavior::call(%s)" % CONSTRUCT_HOOK_NAME
else:
@ -3245,13 +3249,13 @@ let global = incumbent_global.reflector().get_jsobject();\n"""
return false;
}
if !JS_DefineProperty(cx, result.handle(),
${nameAsArray} as *const u8 as *const libc::c_char,
${nameAsArray},
temp.handle(), JSPROP_ENUMERATE as u32) {
return false;
}
}
""",
name=name, nameAsArray=str_to_const_array(name), conditions=ret_conditions)
name=name, nameAsArray=str_to_cstr_ptr(name), conditions=ret_conditions)
ret += 'true\n'
return CGGeneric(ret)
@ -3292,7 +3296,7 @@ rooted!(in(*cx) let proto = {proto});
assert!(!proto.is_null());
rooted!(in(*cx) let mut namespace = ptr::null_mut::<JSObject>());
create_namespace_object(cx, global, proto.handle(), &NAMESPACE_OBJECT_CLASS,
{methods}, {constants}, {str_to_const_array(name)}, namespace.handle_mut());
{methods}, {constants}, {str_to_cstr(name)}, namespace.handle_mut());
assert!(!namespace.is_null());
assert!((*cache)[PrototypeList::Constructor::{id} as usize].is_null());
(*cache)[PrototypeList::Constructor::{id} as usize] = namespace.get();
@ -3311,7 +3315,7 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null());
<*mut JSObject>::post_barrier((*cache).as_mut_ptr().offset(PrototypeList::Constructor::%(id)s as isize),
ptr::null_mut(),
interface.get());
""" % {"id": name, "name": str_to_const_array(name)})
""" % {"id": name, "name": str_to_cstr(name)})
parentName = self.descriptor.getParentName()
if not parentName:
@ -3382,7 +3386,7 @@ assert!((*cache)[PrototypeList::ID::%(id)s as usize].is_null());
""" % proto_properties))
if self.descriptor.interface.hasInterfaceObject():
properties["name"] = str_to_const_array(name)
properties["name"] = str_to_cstr(name)
if self.descriptor.interface.ctor():
properties["length"] = methodLength(self.descriptor.interface.ctor())
else:
@ -3463,7 +3467,7 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null());
${prop} as *const u8 as *const _,
aliasedVal.handle_mut()));
""",
prop=str_to_const_array(m.identifier.name)))
prop=str_to_cstr_ptr(m.identifier.name)))
] + [defineAlias(alias) for alias in sorted(m.aliases)])
defineAliases = CGList([
@ -3477,11 +3481,11 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null());
constructors = self.descriptor.interface.legacyFactoryFunctions
if constructors:
decl = "let named_constructors: [(ConstructorClassHook, &[u8], u32); %d]" % len(constructors)
decl = "let named_constructors: [(ConstructorClassHook, &std::ffi::CStr, u32); %d]" % len(constructors)
specs = []
for constructor in constructors:
hook = CONSTRUCT_HOOK_NAME + "_" + constructor.identifier.name
name = str_to_const_array(constructor.identifier.name)
name = str_to_cstr(constructor.identifier.name)
length = methodLength(constructor)
specs.append(CGGeneric("(%s as ConstructorClassHook, %s, %d)" % (hook, name, length)))
values = CGIndenter(CGList(specs, "\n"), 4)
@ -4225,7 +4229,7 @@ class CGSpecializedForwardingSetter(CGSpecializedSetter):
return CGGeneric("""\
let cx = SafeJSContext::from_ptr(cx);
rooted!(in(*cx) let mut v = UndefinedValue());
if !JS_GetProperty(*cx, HandleObject::from_raw(obj), %s as *const u8 as *const libc::c_char, v.handle_mut()) {
if !JS_GetProperty(*cx, HandleObject::from_raw(obj), %s, v.handle_mut()) {
return false;
}
if !v.is_object() {
@ -4233,8 +4237,8 @@ if !v.is_object() {
return false;
}
rooted!(in(*cx) let target_obj = v.to_object());
JS_SetProperty(*cx, target_obj.handle(), %s as *const u8 as *const libc::c_char, HandleValue::from_raw(args.get(0)))
""" % (str_to_const_array(attrName), attrName, str_to_const_array(forwardToAttrName)))
JS_SetProperty(*cx, target_obj.handle(), %s, HandleValue::from_raw(args.get(0)))
""" % (str_to_cstr_ptr(attrName), attrName, str_to_cstr_ptr(forwardToAttrName)))
class CGSpecializedReplaceableSetter(CGSpecializedSetter):
@ -4246,11 +4250,11 @@ class CGSpecializedReplaceableSetter(CGSpecializedSetter):
def definition_body(self):
assert self.attr.readonly
name = str_to_const_array(self.attr.identifier.name)
name = str_to_cstr_ptr(self.attr.identifier.name)
# JS_DefineProperty can only deal with ASCII.
assert all(ord(c) < 128 for c in name)
return CGGeneric("""\
JS_DefineProperty(cx, HandleObject::from_raw(obj), %s as *const u8 as *const libc::c_char,
JS_DefineProperty(cx, HandleObject::from_raw(obj), %s,
HandleValue::from_raw(args.get(0)), JSPROP_ENUMERATE as u32)""" % name)
@ -6055,7 +6059,7 @@ class CGDOMJSProxyHandler_className(CGAbstractExternMethod):
self.descriptor = descriptor
def getBody(self):
return '%s as *const u8 as *const libc::c_char' % str_to_const_array(self.descriptor.name)
return str_to_cstr_ptr(self.descriptor.name)
def definition_body(self):
return CGGeneric(self.getBody())
@ -6456,8 +6460,8 @@ class CGDescriptor(CGThing):
if unscopableNames:
haveUnscopables = True
cgThings.append(
CGList([CGGeneric("const unscopable_names: &[&[u8]] = &["),
CGIndenter(CGList([CGGeneric(str_to_const_array(name)) for
CGList([CGGeneric("const unscopable_names: &[&std::ffi::CStr] = &["),
CGIndenter(CGList([CGGeneric(str_to_cstr(name)) for
name in unscopableNames], ",\n")),
CGGeneric("];\n")], "\n"))
if descriptor.concrete or descriptor.hasDescendants():
@ -6475,8 +6479,8 @@ class CGDescriptor(CGThing):
haveLegacyWindowAliases = len(legacyWindowAliases) != 0
if haveLegacyWindowAliases:
cgThings.append(
CGList([CGGeneric("const legacy_window_aliases: &[&[u8]] = &["),
CGIndenter(CGList([CGGeneric(str_to_const_array(name)) for
CGList([CGGeneric("const legacy_window_aliases: &[&std::ffi::CStr] = &["),
CGIndenter(CGList([CGGeneric(str_to_cstr(name)) for
name in legacyWindowAliases], ",\n")),
CGGeneric("];\n")], "\n"))

View file

@ -4,6 +4,8 @@
//! WebIDL constants.
use std::ffi::CStr;
use js::jsapi::{JSPROP_ENUMERATE, JSPROP_PERMANENT, JSPROP_READONLY};
use js::jsval::{BooleanValue, DoubleValue, Int32Value, JSVal, NullValue, UInt32Value};
use js::rust::wrappers::JS_DefineProperty;
@ -15,7 +17,7 @@ use crate::script_runtime::JSContext;
#[derive(Clone)]
pub struct ConstantSpec {
/// name of the constant.
pub name: &'static [u8],
pub name: &'static CStr,
/// value of the constant.
pub value: ConstantVal,
}
@ -58,7 +60,7 @@ pub fn define_constants(cx: JSContext, obj: HandleObject, constants: &[ConstantS
assert!(JS_DefineProperty(
*cx,
obj,
spec.name.as_ptr() as *const libc::c_char,
spec.name.as_ptr(),
value.handle(),
(JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT) as u32
));

View file

@ -5,6 +5,7 @@
//! Machinery to initialise interface prototype objects and interface objects.
use std::convert::TryFrom;
use std::ffi::CStr;
use std::ptr;
use js::error::throw_type_error;
@ -215,7 +216,7 @@ pub fn create_callback_interface_object(
cx: SafeJSContext,
global: HandleObject,
constants: &[Guard<&[ConstantSpec]>],
name: &[u8],
name: &CStr,
mut rval: MutableHandleObject,
) {
assert!(!constants.is_empty());
@ -238,7 +239,7 @@ pub fn create_interface_prototype_object(
regular_methods: &[Guard<&'static [JSFunctionSpec]>],
regular_properties: &[Guard<&'static [JSPropertySpec]>],
constants: &[Guard<&[ConstantSpec]>],
unscopable_names: &[&[u8]],
unscopable_names: &[&CStr],
rval: MutableHandleObject,
) {
create_object(
@ -284,9 +285,9 @@ pub fn create_noncallback_interface_object(
static_properties: &[Guard<&'static [JSPropertySpec]>],
constants: &[Guard<&[ConstantSpec]>],
interface_prototype_object: HandleObject,
name: &[u8],
name: &CStr,
length: u32,
legacy_window_alias_names: &[&[u8]],
legacy_window_alias_names: &[&CStr],
rval: MutableHandleObject,
) {
create_object(
@ -321,22 +322,14 @@ pub fn create_noncallback_interface_object(
pub fn create_named_constructors(
cx: SafeJSContext,
global: HandleObject,
named_constructors: &[(ConstructorClassHook, &[u8], u32)],
named_constructors: &[(ConstructorClassHook, &CStr, u32)],
interface_prototype_object: HandleObject,
) {
rooted!(in(*cx) let mut constructor = ptr::null_mut::<JSObject>());
for &(native, name, arity) in named_constructors {
assert_eq!(*name.last().unwrap(), b'\0');
unsafe {
let fun = JS_NewFunction(
*cx,
Some(native),
arity,
JSFUN_CONSTRUCTOR,
name.as_ptr() as *const libc::c_char,
);
let fun = JS_NewFunction(*cx, Some(native), arity, JSFUN_CONSTRUCTOR, name.as_ptr());
assert!(!fun.is_null());
constructor.set(JS_GetFunctionObject(fun));
assert!(!constructor.is_null());
@ -436,15 +429,14 @@ pub fn is_exposed_in(object: HandleObject, globals: Globals) -> bool {
pub fn define_on_global_object(
cx: SafeJSContext,
global: HandleObject,
name: &[u8],
name: &CStr,
obj: HandleObject,
) {
assert_eq!(*name.last().unwrap(), b'\0');
unsafe {
assert!(JS_DefineProperty3(
*cx,
global,
name.as_ptr() as *const libc::c_char,
name.as_ptr(),
obj,
JSPROP_RESOLVING
));
@ -477,18 +469,17 @@ unsafe extern "C" fn fun_to_string_hook(
ret
}
fn create_unscopable_object(cx: SafeJSContext, names: &[&[u8]], mut rval: MutableHandleObject) {
fn create_unscopable_object(cx: SafeJSContext, names: &[&CStr], mut rval: MutableHandleObject) {
assert!(!names.is_empty());
assert!(rval.is_null());
unsafe {
rval.set(JS_NewPlainObject(*cx));
assert!(!rval.is_null());
for &name in names {
assert_eq!(*name.last().unwrap(), b'\0');
assert!(JS_DefineProperty(
*cx,
rval.handle(),
name.as_ptr() as *const libc::c_char,
name.as_ptr(),
HandleValue::from_raw(TrueHandleValue),
JSPROP_READONLY as u32,
));
@ -496,10 +487,9 @@ fn create_unscopable_object(cx: SafeJSContext, names: &[&[u8]], mut rval: Mutabl
}
}
fn define_name(cx: SafeJSContext, obj: HandleObject, name: &[u8]) {
assert_eq!(*name.last().unwrap(), b'\0');
fn define_name(cx: SafeJSContext, obj: HandleObject, name: &CStr) {
unsafe {
rooted!(in(*cx) let name = JS_AtomizeAndPinString(*cx, name.as_ptr() as *const libc::c_char));
rooted!(in(*cx) let name = JS_AtomizeAndPinString(*cx, name.as_ptr()));
assert!(!name.is_null());
assert!(JS_DefineProperty4(
*cx,

View file

@ -4,6 +4,7 @@
//! Machinery to initialise namespace objects.
use std::ffi::CStr;
use std::ptr;
use js::jsapi::{JSClass, JSFunctionSpec};
@ -22,9 +23,9 @@ unsafe impl Sync for NamespaceObjectClass {}
impl NamespaceObjectClass {
/// Create a new `NamespaceObjectClass` structure.
pub const unsafe fn new(name: &'static [u8]) -> Self {
pub const unsafe fn new(name: &'static CStr) -> Self {
NamespaceObjectClass(JSClass {
name: name as *const _ as *const libc::c_char,
name: name.as_ptr(),
flags: 0,
cOps: 0 as *mut _,
spec: ptr::null(),
@ -43,7 +44,7 @@ pub fn create_namespace_object(
class: &'static NamespaceObjectClass,
methods: &[Guard<&'static [JSFunctionSpec]>],
constants: &[Guard<&'static [ConstantSpec]>],
name: &[u8],
name: &CStr,
rval: MutableHandleObject,
) {
create_object(cx, global, proto, &class.0, methods, &[], constants, rval);

View file

@ -732,7 +732,7 @@ impl WindowMethods for Window {
assert!(JS_DefineProperty(
*cx,
obj,
"opener\0".as_ptr() as *const libc::c_char,
c"opener".as_ptr(),
value,
JSPROP_ENUMERATE as u32
));

View file

@ -1469,7 +1469,7 @@ unsafe extern "C" fn HostPopulateImportMeta(
JS_DefineProperty4(
cx,
meta_object,
"url\0".as_ptr() as *const _,
c"url".as_ptr(),
url_string.handle().into_handle(),
JSPROP_ENUMERATE.into(),
)