Fix crash when enumerating properties of global object (#36491)

These changes make our implementation of the enumeration hook for
globals [match
Gecko's](https://searchfox.org/mozilla-central/rev/1f65969e57c757146e3e548614b49d3a4168eeb8/dom/base/nsGlobalWindowInner.cpp#3297),
fixing an assertion failure that occurred in the previous
implementation.

Our enumeration hook is supposed to fill a vector with names of
properties on the global object without modifying the global in any way;
instead we were defining all of the missing webidl interfaces. We now do
much less work and crash less.

Testing: New crashtest based on manual testcase.
Fixes: #34686

---------

Signed-off-by: Josh Matthews <josh@joshmatthews.net>
This commit is contained in:
Josh Matthews 2025-04-16 23:32:53 -04:00 committed by GitHub
parent a1b9949f75
commit 30390f8c5e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 98 additions and 34 deletions

View file

@ -43,13 +43,21 @@ fn main() {
let json: Value = serde_json::from_reader(File::open(json).unwrap()).unwrap();
let mut map = phf_codegen::Map::new();
for (key, value) in json.as_object().unwrap() {
map.entry(Bytes(key), value.as_str().unwrap());
let parts = value.as_array().unwrap();
map.entry(
Bytes(key),
&format!(
"Interface {{ define: {}, enabled: {} }}",
parts[0].as_str().unwrap(),
parts[1].as_str().unwrap()
),
);
}
let phf = PathBuf::from(env::var_os("OUT_DIR").unwrap()).join("InterfaceObjectMapPhf.rs");
let mut phf = File::create(phf).unwrap();
writeln!(
&mut phf,
"pub(crate) static MAP: phf::Map<&'static [u8], fn(JSContext, HandleObject)> = {};",
"pub(crate) static MAP: phf::Map<&'static [u8], Interface> = {};",
map.build(),
)
.unwrap();

View file

@ -2972,7 +2972,8 @@ class CGConstructorEnabled(CGAbstractMethod):
'ConstructorEnabled', 'bool',
[Argument("SafeJSContext", "aCx"),
Argument("HandleObject", "aObj")],
templateArgs=['D: DomTypes'])
templateArgs=['D: DomTypes'],
pub=True)
def definition_body(self):
conditions = []
@ -8531,8 +8532,7 @@ class GlobalGenRoots():
def InterfaceObjectMap(config):
mods = [
"crate::dom::bindings::codegen",
"crate::script_runtime::JSContext",
"js::rust::HandleObject",
"script_bindings::interfaces::Interface",
]
imports = CGList([CGGeneric(f"use {mod};") for mod in mods], "\n")
@ -8555,9 +8555,13 @@ class GlobalGenRoots():
for ctor in d.interface.legacyFactoryFunctions:
pairs.append((ctor.identifier.name, binding_mod, binding_ns))
pairs.sort(key=operator.itemgetter(0))
def bindingPath(pair):
return f'codegen::Bindings::{pair[1]}::{pair[2]}'
mappings = [
CGGeneric(f'"{pair[0]}": "codegen::Bindings::{pair[1]}'
f'::{pair[2]}::DefineDOMInterface::<crate::DomTypeHolder>"')
CGGeneric(f'"{pair[0]}": ["{bindingPath(pair)}::DefineDOMInterface::<crate::DomTypeHolder>", '
f'"{bindingPath(pair)}::ConstructorEnabled::<crate::DomTypeHolder>"]')
for pair in pairs
]
return CGWrapper(

View file

@ -23,6 +23,17 @@ use crate::script_runtime::{CanGc, JSContext};
use crate::settings_stack::StackEntry;
use crate::utils::ProtoOrIfaceArray;
/// Operations that can be invoked for a WebIDL interface against
/// a global object.
///
/// <https://github.com/mozilla/gecko-dev/blob/3fd619f47/dom/bindings/WebIDLGlobalNameHash.h#L24>
pub struct Interface {
/// Define the JS object for this interface on the given global.
pub define: fn(JSContext, HandleObject),
/// Returns true if this interface's conditions are met for the given global.
pub enabled: fn(JSContext, HandleObject) -> bool,
}
/// Operations that must be invoked from the generated bindings.
pub trait DomHelpers<D: DomTypes> {
fn throw_dom_exception(cx: JSContext, global: &D::GlobalScope, result: Error, can_gc: CanGc);
@ -42,7 +53,7 @@ pub trait DomHelpers<D: DomTypes> {
fn is_platform_object_same_origin(cx: JSContext, obj: RawHandleObject) -> bool;
fn interface_map() -> &'static phf::Map<&'static [u8], for<'a> fn(JSContext, HandleObject)>;
fn interface_map() -> &'static phf::Map<&'static [u8], Interface>;
fn push_new_element_queue();
fn pop_current_element_queue(can_gc: CanGc);

View file

@ -10,19 +10,19 @@ use std::slice;
use js::conversions::ToJSValConvertible;
use js::gc::Handle;
use js::glue::{
CallJitGetterOp, CallJitMethodOp, CallJitSetterOp, JS_GetReservedSlot,
AppendToIdVector, CallJitGetterOp, CallJitMethodOp, CallJitSetterOp, JS_GetReservedSlot,
RUST_FUNCTION_VALUE_TO_JITINFO,
};
use js::jsapi::{
AtomToLinearString, CallArgs, ExceptionStackBehavior, GetLinearStringCharAt,
GetLinearStringLength, GetNonCCWObjectGlobal, HandleId as RawHandleId,
HandleObject as RawHandleObject, Heap, JS_ClearPendingException,
JS_DeprecatedStringHasLatin1Chars, JS_EnumerateStandardClasses,
JS_GetLatin1StringCharsAndLength, JS_IsExceptionPending, JS_IsGlobalObject,
JS_ResolveStandardClass, JSAtom, JSContext, JSJitInfo, JSObject, JSTracer,
MutableHandleIdVector as RawMutableHandleIdVector, MutableHandleValue as RawMutableHandleValue,
ObjectOpResult, StringIsArrayIndex,
HandleObject as RawHandleObject, Heap, JS_AtomizeStringN, JS_ClearPendingException,
JS_DeprecatedStringHasLatin1Chars, JS_GetLatin1StringCharsAndLength, JS_IsExceptionPending,
JS_IsGlobalObject, JS_NewEnumerateStandardClasses, JS_ResolveStandardClass, JSAtom, JSContext,
JSJitInfo, JSObject, JSTracer, MutableHandleIdVector as RawMutableHandleIdVector,
MutableHandleValue as RawMutableHandleValue, ObjectOpResult, StringIsArrayIndex,
};
use js::jsid::StringId;
use js::jsval::{JSVal, UndefinedValue};
use js::rust::wrappers::{
CallOriginalPromiseReject, JS_DeletePropertyById, JS_ForwardGetPropertyTo,
@ -576,18 +576,36 @@ impl AsCCharPtrPtr for [u8] {
}
/// Enumerate lazy properties of a global object.
/// Modeled after <https://github.com/mozilla/gecko-dev/blob/3fd619f47/dom/bindings/BindingUtils.cpp#L2814>
/// and <https://github.com/mozilla/gecko-dev/blob/3fd619f47/dom/base/nsGlobalWindowInner.cpp#3297>
pub(crate) unsafe extern "C" fn enumerate_global<D: DomTypes>(
cx: *mut JSContext,
obj: RawHandleObject,
_props: RawMutableHandleIdVector,
_enumerable_only: bool,
props: RawMutableHandleIdVector,
enumerable_only: bool,
) -> bool {
assert!(JS_IsGlobalObject(obj.get()));
if !JS_EnumerateStandardClasses(cx, obj) {
if !JS_NewEnumerateStandardClasses(cx, obj, props, enumerable_only) {
return false;
}
for init_fun in <D as DomHelpers<D>>::interface_map().values() {
init_fun(SafeJSContext::from_ptr(cx), Handle::from_raw(obj));
if enumerable_only {
// All WebIDL interface names are defined as non-enumerable, so there's
// no point in checking them if we're only returning enumerable names.
return true;
}
let cx = SafeJSContext::from_ptr(cx);
let obj = Handle::from_raw(obj);
for (name, interface) in <D as DomHelpers<D>>::interface_map() {
if !(interface.enabled)(cx, obj) {
continue;
}
let s = JS_AtomizeStringN(*cx, name.as_c_char_ptr(), name.len());
rooted!(in(*cx) let id = StringId(s));
if s.is_null() || !AppendToIdVector(props, id.handle().into()) {
return false;
}
}
true
}
@ -621,8 +639,8 @@ pub(crate) unsafe extern "C" fn resolve_global<D: DomTypes>(
assert!(!ptr.is_null());
let bytes = slice::from_raw_parts(ptr, length);
if let Some(init_fun) = <D as DomHelpers<D>>::interface_map().get(bytes) {
init_fun(SafeJSContext::from_ptr(cx), Handle::from_raw(obj));
if let Some(interface) = <D as DomHelpers<D>>::interface_map().get(bytes) {
(interface.define)(SafeJSContext::from_ptr(cx), Handle::from_raw(obj));
*rval = true;
} else {
*rval = false;