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

View file

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

View file

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

View file

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

View file

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

View file

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