script_bindings/
utils.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::ffi::CString;
6use std::os::raw::{c_char, c_void};
7use std::ptr::{self, NonNull};
8use std::slice;
9
10use js::conversions::{ToJSValConvertible, jsstr_to_string};
11use js::gc::Handle;
12use js::glue::{
13    AppendToIdVector, CallJitGetterOp, CallJitMethodOp, CallJitSetterOp, JS_GetReservedSlot,
14    RUST_FUNCTION_VALUE_TO_JITINFO,
15};
16use js::jsapi::{
17    AtomToLinearString, CallArgs, ExceptionStackBehavior, GetLinearStringCharAt,
18    GetLinearStringLength, GetNonCCWObjectGlobal, HandleId as RawHandleId,
19    HandleObject as RawHandleObject, Heap, JS_AtomizeStringN, JS_ClearPendingException,
20    JS_DeprecatedStringHasLatin1Chars, JS_GetLatin1StringCharsAndLength, JS_IsExceptionPending,
21    JS_IsGlobalObject, JS_MayResolveStandardClass, JS_NewEnumerateStandardClasses,
22    JS_ResolveStandardClass, JSAtom, JSAtomState, JSContext, JSJitInfo, JSObject, JSTracer,
23    MutableHandleIdVector as RawMutableHandleIdVector, MutableHandleValue as RawMutableHandleValue,
24    ObjectOpResult, PropertyKey, StringIsArrayIndex, jsid,
25};
26use js::jsid::StringId;
27use js::jsval::{JSVal, UndefinedValue};
28use js::rust::wrappers::{
29    CallOriginalPromiseReject, JS_DeletePropertyById, JS_ForwardGetPropertyTo,
30    JS_GetPendingException, JS_GetProperty, JS_GetPrototype, JS_HasProperty, JS_HasPropertyById,
31    JS_SetPendingException, JS_SetProperty,
32};
33use js::rust::{
34    HandleId, HandleObject, HandleValue, MutableHandleValue, Runtime, ToString, get_object_class,
35};
36use js::{JS_CALLEE, rooted};
37use malloc_size_of::MallocSizeOfOps;
38
39use crate::DomTypes;
40use crate::codegen::Globals::Globals;
41use crate::codegen::InheritTypes::TopTypeId;
42use crate::codegen::PrototypeList::{self, MAX_PROTO_CHAIN_LENGTH, PROTO_OR_IFACE_LENGTH};
43use crate::conversions::{PrototypeCheck, private_from_proto_check};
44use crate::error::throw_invalid_this;
45use crate::interfaces::DomHelpers;
46use crate::script_runtime::{CanGc, JSContext as SafeJSContext};
47use crate::str::DOMString;
48use crate::trace::trace_object;
49
50/// The struct that holds inheritance information for DOM object reflectors.
51#[derive(Clone, Copy)]
52pub struct DOMClass {
53    /// A list of interfaces that this object implements, in order of decreasing
54    /// derivedness.
55    pub interface_chain: [PrototypeList::ID; MAX_PROTO_CHAIN_LENGTH],
56
57    /// The last valid index of `interface_chain`.
58    pub depth: u8,
59
60    /// The type ID of that interface.
61    pub type_id: TopTypeId,
62
63    /// The MallocSizeOf function wrapper for that interface.
64    pub malloc_size_of: unsafe fn(ops: &mut MallocSizeOfOps, *const c_void) -> usize,
65
66    /// The `Globals` flag for this global interface, if any.
67    pub global: Globals,
68}
69unsafe impl Sync for DOMClass {}
70
71/// The JSClass used for DOM object reflectors.
72#[derive(Copy)]
73#[repr(C)]
74pub struct DOMJSClass {
75    /// The actual JSClass.
76    pub base: js::jsapi::JSClass,
77    /// Associated data for DOM object reflectors.
78    pub dom_class: DOMClass,
79}
80impl Clone for DOMJSClass {
81    fn clone(&self) -> DOMJSClass {
82        *self
83    }
84}
85unsafe impl Sync for DOMJSClass {}
86
87/// The index of the slot where the object holder of that interface's
88/// unforgeable members are defined.
89pub(crate) const DOM_PROTO_UNFORGEABLE_HOLDER_SLOT: u32 = 0;
90
91/// The index of the slot that contains a reference to the ProtoOrIfaceArray.
92// All DOM globals must have a slot at DOM_PROTOTYPE_SLOT.
93pub(crate) const DOM_PROTOTYPE_SLOT: u32 = js::JSCLASS_GLOBAL_SLOT_COUNT;
94
95/// The flag set on the `JSClass`es for DOM global objects.
96// NOTE: This is baked into the Ion JIT as 0 in codegen for LGetDOMProperty and
97// LSetDOMProperty. Those constants need to be changed accordingly if this value
98// changes.
99pub(crate) const JSCLASS_DOM_GLOBAL: u32 = js::JSCLASS_USERBIT1;
100
101/// Returns the ProtoOrIfaceArray for the given global object.
102/// Fails if `global` is not a DOM global object.
103///
104/// # Safety
105/// `global` must point to a valid, non-null JS object.
106pub(crate) unsafe fn get_proto_or_iface_array(global: *mut JSObject) -> *mut ProtoOrIfaceArray {
107    assert_ne!(((*get_object_class(global)).flags & JSCLASS_DOM_GLOBAL), 0);
108    let mut slot = UndefinedValue();
109    JS_GetReservedSlot(global, DOM_PROTOTYPE_SLOT, &mut slot);
110    slot.to_private() as *mut ProtoOrIfaceArray
111}
112
113/// An array of *mut JSObject of size PROTO_OR_IFACE_LENGTH.
114pub type ProtoOrIfaceArray = [*mut JSObject; PROTO_OR_IFACE_LENGTH];
115
116/// Gets the property `id` on  `proxy`'s prototype. If it exists, `*found` is
117/// set to true and `*vp` to the value, otherwise `*found` is set to false.
118///
119/// Returns false on JSAPI failure.
120///
121/// # Safety
122/// `cx` must point to a valid, non-null JSContext.
123/// `found` must point to a valid, non-null bool.
124pub(crate) unsafe fn get_property_on_prototype(
125    cx: *mut JSContext,
126    proxy: HandleObject,
127    receiver: HandleValue,
128    id: HandleId,
129    found: *mut bool,
130    vp: MutableHandleValue,
131) -> bool {
132    rooted!(in(cx) let mut proto = ptr::null_mut::<JSObject>());
133    if !JS_GetPrototype(cx, proxy, proto.handle_mut()) || proto.is_null() {
134        *found = false;
135        return true;
136    }
137    let mut has_property = false;
138    if !JS_HasPropertyById(cx, proto.handle(), id, &mut has_property) {
139        return false;
140    }
141    *found = has_property;
142    if !has_property {
143        return true;
144    }
145
146    JS_ForwardGetPropertyTo(cx, proto.handle(), id, receiver, vp)
147}
148
149/// Get an array index from the given `jsid`. Returns `None` if the given
150/// `jsid` is not an integer.
151pub fn get_array_index_from_id(id: HandleId) -> Option<u32> {
152    let raw_id = *id;
153    if raw_id.is_int() {
154        return Some(raw_id.to_int() as u32);
155    }
156
157    if raw_id.is_void() || !raw_id.is_string() {
158        return None;
159    }
160
161    unsafe {
162        let atom = raw_id.to_string() as *mut JSAtom;
163        let s = AtomToLinearString(atom);
164        if GetLinearStringLength(s) == 0 {
165            return None;
166        }
167
168        let chars = [GetLinearStringCharAt(s, 0)];
169        let first_char = char::decode_utf16(chars.iter().cloned())
170            .next()
171            .map_or('\0', |r| r.unwrap_or('\0'));
172        if first_char.is_ascii_lowercase() {
173            return None;
174        }
175
176        let mut i = 0;
177        if StringIsArrayIndex(s, &mut i) {
178            Some(i)
179        } else {
180            None
181        }
182    }
183
184    /*let s = jsstr_to_string(cx, RUST_JSID_TO_STRING(raw_id));
185    if s.len() == 0 {
186        return None;
187    }
188
189    let first = s.chars().next().unwrap();
190    if first.is_ascii_lowercase() {
191        return None;
192    }
193
194    let mut i: u32 = 0;
195    let is_array = if s.is_ascii() {
196        let chars = s.as_bytes();
197        StringIsArrayIndex1(chars.as_ptr() as *const _, chars.len() as u32, &mut i)
198    } else {
199        let chars = s.encode_utf16().collect::<Vec<u16>>();
200        let slice = chars.as_slice();
201        StringIsArrayIndex2(slice.as_ptr(), chars.len() as u32, &mut i)
202    };
203
204    if is_array {
205        Some(i)
206    } else {
207        None
208    }*/
209}
210
211/// Find the enum equivelent of a string given by `v` in `pairs`.
212/// Returns `Err(())` on JSAPI failure (there is a pending exception), and
213/// `Ok((None, value))` if there was no matching string.
214///
215/// # Safety
216/// `cx` must point to a valid, non-null JSContext.
217#[allow(clippy::result_unit_err)]
218pub(crate) unsafe fn find_enum_value<'a, T>(
219    cx: *mut JSContext,
220    v: HandleValue,
221    pairs: &'a [(&'static str, T)],
222) -> Result<(Option<&'a T>, DOMString), ()> {
223    match ptr::NonNull::new(ToString(cx, v)) {
224        Some(jsstr) => {
225            let search = DOMString::from_string(jsstr_to_string(cx, jsstr));
226            Ok((
227                pairs
228                    .iter()
229                    .find(|&&(key, _)| search == *key)
230                    .map(|(_, ev)| ev),
231                search,
232            ))
233        },
234        None => Err(()),
235    }
236}
237
238/// Get the property with name `property` from `object`.
239/// Returns `Err(())` on JSAPI failure (there is a pending exception), and
240/// `Ok(false)` if there was no property with the given name.
241///
242/// # Safety
243/// `cx` must point to a valid, non-null JSContext.
244#[allow(clippy::result_unit_err)]
245pub unsafe fn get_dictionary_property(
246    cx: *mut JSContext,
247    object: HandleObject,
248    property: &str,
249    rval: MutableHandleValue,
250    _can_gc: CanGc,
251) -> Result<bool, ()> {
252    unsafe fn has_property(
253        cx: *mut JSContext,
254        object: HandleObject,
255        property: &CString,
256        found: &mut bool,
257    ) -> bool {
258        JS_HasProperty(cx, object, property.as_ptr(), found)
259    }
260    unsafe fn get_property(
261        cx: *mut JSContext,
262        object: HandleObject,
263        property: &CString,
264        value: MutableHandleValue,
265    ) -> bool {
266        JS_GetProperty(cx, object, property.as_ptr(), value)
267    }
268
269    let property = CString::new(property).unwrap();
270    if object.get().is_null() {
271        return Ok(false);
272    }
273
274    let mut found = false;
275    if !has_property(cx, object, &property, &mut found) {
276        return Err(());
277    }
278
279    if !found {
280        return Ok(false);
281    }
282
283    if !get_property(cx, object, &property, rval) {
284        return Err(());
285    }
286
287    Ok(true)
288}
289
290/// Set the property with name `property` from `object`.
291/// Returns `Err(())` on JSAPI failure, or null object,
292/// and Ok(()) otherwise
293#[allow(clippy::result_unit_err)]
294pub fn set_dictionary_property(
295    cx: SafeJSContext,
296    object: HandleObject,
297    property: &str,
298    value: HandleValue,
299) -> Result<(), ()> {
300    if object.get().is_null() {
301        return Err(());
302    }
303
304    let property = CString::new(property).unwrap();
305    unsafe {
306        if !JS_SetProperty(*cx, object, property.as_ptr(), value) {
307            return Err(());
308        }
309    }
310
311    Ok(())
312}
313
314/// Computes whether `proxy` has a property `id` on its prototype and stores
315/// the result in `found`.
316///
317/// Returns a boolean indicating whether the check succeeded.
318/// If `false` is returned then the value of `found` is unspecified.
319///
320/// # Safety
321/// `cx` must point to a valid, non-null JSContext.
322pub unsafe fn has_property_on_prototype(
323    cx: *mut JSContext,
324    proxy: HandleObject,
325    id: HandleId,
326    found: &mut bool,
327) -> bool {
328    rooted!(in(cx) let mut proto = ptr::null_mut::<JSObject>());
329    if !JS_GetPrototype(cx, proxy, proto.handle_mut()) {
330        return false;
331    }
332    assert!(!proto.is_null());
333    JS_HasPropertyById(cx, proto.handle(), id, found)
334}
335
336/// Deletes the property `id` from `object`.
337///
338/// # Safety
339/// `cx` must point to a valid, non-null JSContext.
340pub(crate) unsafe fn delete_property_by_id(
341    cx: *mut JSContext,
342    object: HandleObject,
343    id: HandleId,
344    bp: *mut ObjectOpResult,
345) -> bool {
346    JS_DeletePropertyById(cx, object, id, bp)
347}
348
349unsafe fn generic_call<const EXCEPTION_TO_REJECTION: bool>(
350    cx: *mut JSContext,
351    argc: libc::c_uint,
352    vp: *mut JSVal,
353    is_lenient: bool,
354    call: unsafe extern "C" fn(
355        *const JSJitInfo,
356        *mut JSContext,
357        RawHandleObject,
358        *mut libc::c_void,
359        u32,
360        *mut JSVal,
361    ) -> bool,
362    can_gc: CanGc,
363) -> bool {
364    let args = CallArgs::from_vp(vp, argc);
365
366    let info = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx, vp));
367    let proto_id = (*info).__bindgen_anon_2.protoID;
368    let cx = SafeJSContext::from_ptr(cx);
369
370    let thisobj = args.thisv();
371    if !thisobj.get().is_null_or_undefined() && !thisobj.get().is_object() {
372        throw_invalid_this(cx, proto_id);
373        return if EXCEPTION_TO_REJECTION {
374            exception_to_promise(*cx, args.rval(), can_gc)
375        } else {
376            false
377        };
378    }
379
380    rooted!(in(*cx) let obj = if thisobj.get().is_object() {
381        thisobj.get().to_object()
382    } else {
383        GetNonCCWObjectGlobal(JS_CALLEE(*cx, vp).to_object_or_null())
384    });
385    let depth = (*info).__bindgen_anon_3.depth as usize;
386    let proto_check = PrototypeCheck::Depth { depth, proto_id };
387    let this = match private_from_proto_check(obj.get(), *cx, proto_check) {
388        Ok(val) => val,
389        Err(()) => {
390            if is_lenient {
391                debug_assert!(!JS_IsExceptionPending(*cx));
392                *vp = UndefinedValue();
393                return true;
394            } else {
395                throw_invalid_this(cx, proto_id);
396                return if EXCEPTION_TO_REJECTION {
397                    exception_to_promise(*cx, args.rval(), can_gc)
398                } else {
399                    false
400                };
401            }
402        },
403    };
404    call(
405        info,
406        *cx,
407        obj.handle().into(),
408        this as *mut libc::c_void,
409        argc,
410        vp,
411    )
412}
413
414/// Generic method of IDL interface.
415///
416/// # Safety
417/// `cx` must point to a valid, non-null JSContext.
418/// `vp` must point to a VALID, non-null JSVal.
419pub(crate) unsafe extern "C" fn generic_method<const EXCEPTION_TO_REJECTION: bool>(
420    cx: *mut JSContext,
421    argc: libc::c_uint,
422    vp: *mut JSVal,
423) -> bool {
424    generic_call::<EXCEPTION_TO_REJECTION>(cx, argc, vp, false, CallJitMethodOp, CanGc::note())
425}
426
427/// Generic getter of IDL interface.
428///
429/// # Safety
430/// `cx` must point to a valid, non-null JSContext.
431/// `vp` must point to a VALID, non-null JSVal.
432pub(crate) unsafe extern "C" fn generic_getter<const EXCEPTION_TO_REJECTION: bool>(
433    cx: *mut JSContext,
434    argc: libc::c_uint,
435    vp: *mut JSVal,
436) -> bool {
437    generic_call::<EXCEPTION_TO_REJECTION>(cx, argc, vp, false, CallJitGetterOp, CanGc::note())
438}
439
440/// Generic lenient getter of IDL interface.
441///
442/// # Safety
443/// `cx` must point to a valid, non-null JSContext.
444/// `vp` must point to a VALID, non-null JSVal.
445pub(crate) unsafe extern "C" fn generic_lenient_getter<const EXCEPTION_TO_REJECTION: bool>(
446    cx: *mut JSContext,
447    argc: libc::c_uint,
448    vp: *mut JSVal,
449) -> bool {
450    generic_call::<EXCEPTION_TO_REJECTION>(cx, argc, vp, true, CallJitGetterOp, CanGc::note())
451}
452
453unsafe extern "C" fn call_setter(
454    info: *const JSJitInfo,
455    cx: *mut JSContext,
456    handle: RawHandleObject,
457    this: *mut libc::c_void,
458    argc: u32,
459    vp: *mut JSVal,
460) -> bool {
461    if !CallJitSetterOp(info, cx, handle, this, argc, vp) {
462        return false;
463    }
464    *vp = UndefinedValue();
465    true
466}
467
468/// Generic setter of IDL interface.
469///
470/// # Safety
471/// `cx` must point to a valid, non-null JSContext.
472/// `vp` must point to a VALID, non-null JSVal.
473pub(crate) unsafe extern "C" fn generic_setter(
474    cx: *mut JSContext,
475    argc: libc::c_uint,
476    vp: *mut JSVal,
477) -> bool {
478    generic_call::<false>(cx, argc, vp, false, call_setter, CanGc::note())
479}
480
481/// Generic lenient setter of IDL interface.
482///
483/// # Safety
484/// `cx` must point to a valid, non-null JSContext.
485/// `vp` must point to a VALID, non-null JSVal.
486pub(crate) unsafe extern "C" fn generic_lenient_setter(
487    cx: *mut JSContext,
488    argc: libc::c_uint,
489    vp: *mut JSVal,
490) -> bool {
491    generic_call::<false>(cx, argc, vp, true, call_setter, CanGc::note())
492}
493
494/// <https://searchfox.org/mozilla-central/rev/7279a1df13a819be254fd4649e07c4ff93e4bd45/dom/bindings/BindingUtils.cpp#3300>
495/// # Safety
496///
497/// `cx` must point to a valid, non-null JSContext.
498/// `vp` must point to a VALID, non-null JSVal.
499pub(crate) unsafe extern "C" fn generic_static_promise_method(
500    cx: *mut JSContext,
501    argc: libc::c_uint,
502    vp: *mut JSVal,
503) -> bool {
504    let args = CallArgs::from_vp(vp, argc);
505
506    let info = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx, vp));
507    assert!(!info.is_null());
508    // TODO: we need safe wrappers for this in mozjs!
509    // assert_eq!((*info)._bitfield_1, JSJitInfo_OpType::StaticMethod as u8)
510    let static_fn = (*info).__bindgen_anon_1.staticMethod.unwrap();
511    if static_fn(cx, argc, vp) {
512        return true;
513    }
514    exception_to_promise(cx, args.rval(), CanGc::note())
515}
516
517/// Coverts exception to promise rejection
518///
519/// <https://searchfox.org/mozilla-central/rev/b220e40ff2ee3d10ce68e07d8a8a577d5558e2a2/dom/bindings/BindingUtils.cpp#3315>
520///
521/// # Safety
522/// `cx` must point to a valid, non-null JSContext.
523pub(crate) unsafe fn exception_to_promise(
524    cx: *mut JSContext,
525    rval: RawMutableHandleValue,
526    _can_gc: CanGc,
527) -> bool {
528    rooted!(in(cx) let mut exception = UndefinedValue());
529    if !JS_GetPendingException(cx, exception.handle_mut()) {
530        return false;
531    }
532    JS_ClearPendingException(cx);
533    if let Some(promise) = NonNull::new(CallOriginalPromiseReject(cx, exception.handle())) {
534        promise.to_jsval(cx, MutableHandleValue::from_raw(rval));
535        true
536    } else {
537        // We just give up.  Put the exception back.
538        JS_SetPendingException(cx, exception.handle(), ExceptionStackBehavior::Capture);
539        false
540    }
541}
542
543/// Trace the resources held by reserved slots of a global object
544///
545/// # Safety
546/// `tracer` must point to a valid, non-null JSTracer.
547/// `obj` must point to a valid, non-null JSObject.
548pub(crate) unsafe fn trace_global(tracer: *mut JSTracer, obj: *mut JSObject) {
549    let array = get_proto_or_iface_array(obj);
550    for proto in (*array).iter() {
551        if !proto.is_null() {
552            trace_object(
553                tracer,
554                "prototype",
555                &*(proto as *const *mut JSObject as *const Heap<*mut JSObject>),
556            );
557        }
558    }
559}
560
561// Generic method for returning libc::c_void from caller
562pub trait AsVoidPtr {
563    fn as_void_ptr(&self) -> *const libc::c_void;
564}
565impl<T> AsVoidPtr for T {
566    fn as_void_ptr(&self) -> *const libc::c_void {
567        self as *const T as *const libc::c_void
568    }
569}
570
571// Generic method for returning c_char from caller
572pub(crate) trait AsCCharPtrPtr {
573    fn as_c_char_ptr(&self) -> *const c_char;
574}
575
576impl AsCCharPtrPtr for [u8] {
577    fn as_c_char_ptr(&self) -> *const c_char {
578        self as *const [u8] as *const c_char
579    }
580}
581
582/// Enumerate lazy properties of a global object.
583/// Modeled after <https://github.com/mozilla/gecko-dev/blob/3fd619f47/dom/bindings/BindingUtils.cpp#L2814>
584pub(crate) unsafe extern "C" fn enumerate_global(
585    cx: *mut JSContext,
586    obj: RawHandleObject,
587    props: RawMutableHandleIdVector,
588    enumerable_only: bool,
589) -> bool {
590    assert!(JS_IsGlobalObject(obj.get()));
591    JS_NewEnumerateStandardClasses(cx, obj, props, enumerable_only)
592}
593
594/// Enumerate lazy properties of a global object that is a Window.
595/// <https://github.com/mozilla/gecko-dev/blob/3fd619f47/dom/base/nsGlobalWindowInner.cpp#3297>
596pub(crate) unsafe extern "C" fn enumerate_window<D: DomTypes>(
597    cx: *mut JSContext,
598    obj: RawHandleObject,
599    props: RawMutableHandleIdVector,
600    enumerable_only: bool,
601) -> bool {
602    if !enumerate_global(cx, obj, props, enumerable_only) {
603        return false;
604    }
605
606    if enumerable_only {
607        // All WebIDL interface names are defined as non-enumerable, so there's
608        // no point in checking them if we're only returning enumerable names.
609        return true;
610    }
611
612    let cx = SafeJSContext::from_ptr(cx);
613    let obj = Handle::from_raw(obj);
614    for (name, interface) in <D as DomHelpers<D>>::interface_map() {
615        if !(interface.enabled)(cx, obj) {
616            continue;
617        }
618        let s = JS_AtomizeStringN(*cx, name.as_c_char_ptr(), name.len());
619        rooted!(in(*cx) let id = StringId(s));
620        if s.is_null() || !AppendToIdVector(props, id.handle().into()) {
621            return false;
622        }
623    }
624    true
625}
626
627/// Returns true if the resolve hook for this global may resolve the provided id.
628/// <https://searchfox.org/mozilla-central/rev/f3c8c63a097b61bb1f01e13629b9514e09395947/dom/bindings/BindingUtils.cpp#2809>
629/// <https://searchfox.org/mozilla-central/rev/f3c8c63a097b61bb1f01e13629b9514e09395947/js/public/Class.h#283-291>
630pub(crate) unsafe extern "C" fn may_resolve_global(
631    names: *const JSAtomState,
632    id: PropertyKey,
633    maybe_obj: *mut JSObject,
634) -> bool {
635    JS_MayResolveStandardClass(names, id, maybe_obj)
636}
637
638/// Returns true if the resolve hook for this window may resolve the provided id.
639/// <https://searchfox.org/mozilla-central/rev/f3c8c63a097b61bb1f01e13629b9514e09395947/dom/base/nsGlobalWindowInner.cpp#3275>
640/// <https://searchfox.org/mozilla-central/rev/f3c8c63a097b61bb1f01e13629b9514e09395947/js/public/Class.h#283-291>
641pub(crate) unsafe extern "C" fn may_resolve_window<D: DomTypes>(
642    names: *const JSAtomState,
643    id: PropertyKey,
644    maybe_obj: *mut JSObject,
645) -> bool {
646    if may_resolve_global(names, id, maybe_obj) {
647        return true;
648    }
649
650    let cx = Runtime::get()
651        .expect("There must be a JSContext active")
652        .as_ptr();
653    let Ok(bytes) = latin1_bytes_from_id(cx, id) else {
654        return false;
655    };
656
657    <D as DomHelpers<D>>::interface_map().contains_key(bytes)
658}
659
660/// Resolve a lazy global property, for interface objects and named constructors.
661pub(crate) unsafe extern "C" fn resolve_global(
662    cx: *mut JSContext,
663    obj: RawHandleObject,
664    id: RawHandleId,
665    rval: *mut bool,
666) -> bool {
667    assert!(JS_IsGlobalObject(obj.get()));
668    JS_ResolveStandardClass(cx, obj, id, rval)
669}
670
671/// Resolve a lazy global property for a Window global.
672pub(crate) unsafe extern "C" fn resolve_window<D: DomTypes>(
673    cx: *mut JSContext,
674    obj: RawHandleObject,
675    id: RawHandleId,
676    rval: *mut bool,
677) -> bool {
678    if !resolve_global(cx, obj, id, rval) {
679        return false;
680    }
681
682    if *rval {
683        return true;
684    }
685    let Ok(bytes) = latin1_bytes_from_id(cx, *id) else {
686        *rval = false;
687        return true;
688    };
689
690    if let Some(interface) = <D as DomHelpers<D>>::interface_map().get(bytes) {
691        (interface.define)(SafeJSContext::from_ptr(cx), Handle::from_raw(obj));
692        *rval = true;
693    } else {
694        *rval = false;
695    }
696    true
697}
698
699/// Returns a slice of bytes corresponding to the bytes in the provided string id.
700/// Returns an error if the id is not a string, or the string contains non-latin1 characters.
701/// # Safety
702/// The slice is only valid as long as the original id is not garbage collected.
703unsafe fn latin1_bytes_from_id(cx: *mut JSContext, id: jsid) -> Result<&'static [u8], ()> {
704    if !id.is_string() {
705        return Err(());
706    }
707
708    let string = id.to_string();
709    if !JS_DeprecatedStringHasLatin1Chars(string) {
710        return Err(());
711    }
712    let mut length = 0;
713    let ptr = JS_GetLatin1StringCharsAndLength(cx, ptr::null(), string, &mut length);
714    assert!(!ptr.is_null());
715    Ok(slice::from_raw_parts(ptr, length))
716}