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::CStr;
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: &CStr,
249    rval: MutableHandleValue,
250    _can_gc: CanGc,
251) -> Result<bool, ()> {
252    unsafe fn has_property(
253        cx: *mut JSContext,
254        object: HandleObject,
255        property: &CStr,
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: &CStr,
264        value: MutableHandleValue,
265    ) -> bool {
266        JS_GetProperty(cx, object, property.as_ptr(), value)
267    }
268
269    if object.get().is_null() {
270        return Ok(false);
271    }
272
273    let mut found = false;
274    if !has_property(cx, object, property, &mut found) {
275        return Err(());
276    }
277
278    if !found {
279        return Ok(false);
280    }
281
282    if !get_property(cx, object, property, rval) {
283        return Err(());
284    }
285
286    Ok(true)
287}
288
289/// Set the property with name `property` from `object`.
290/// Returns `Err(())` on JSAPI failure, or null object,
291/// and Ok(()) otherwise
292#[allow(clippy::result_unit_err)]
293pub fn set_dictionary_property(
294    cx: SafeJSContext,
295    object: HandleObject,
296    property: &CStr,
297    value: HandleValue,
298) -> Result<(), ()> {
299    if object.get().is_null() {
300        return Err(());
301    }
302
303    unsafe {
304        if !JS_SetProperty(*cx, object, property.as_ptr(), value) {
305            return Err(());
306        }
307    }
308
309    Ok(())
310}
311
312/// Computes whether `proxy` has a property `id` on its prototype and stores
313/// the result in `found`.
314///
315/// Returns a boolean indicating whether the check succeeded.
316/// If `false` is returned then the value of `found` is unspecified.
317///
318/// # Safety
319/// `cx` must point to a valid, non-null JSContext.
320pub unsafe fn has_property_on_prototype(
321    cx: *mut JSContext,
322    proxy: HandleObject,
323    id: HandleId,
324    found: &mut bool,
325) -> bool {
326    rooted!(in(cx) let mut proto = ptr::null_mut::<JSObject>());
327    if !JS_GetPrototype(cx, proxy, proto.handle_mut()) {
328        return false;
329    }
330    assert!(!proto.is_null());
331    JS_HasPropertyById(cx, proto.handle(), id, found)
332}
333
334/// Deletes the property `id` from `object`.
335///
336/// # Safety
337/// `cx` must point to a valid, non-null JSContext.
338pub(crate) unsafe fn delete_property_by_id(
339    cx: *mut JSContext,
340    object: HandleObject,
341    id: HandleId,
342    bp: *mut ObjectOpResult,
343) -> bool {
344    JS_DeletePropertyById(cx, object, id, bp)
345}
346
347unsafe fn generic_call<const EXCEPTION_TO_REJECTION: bool>(
348    cx: *mut JSContext,
349    argc: libc::c_uint,
350    vp: *mut JSVal,
351    is_lenient: bool,
352    call: unsafe extern "C" fn(
353        *const JSJitInfo,
354        *mut JSContext,
355        RawHandleObject,
356        *mut libc::c_void,
357        u32,
358        *mut JSVal,
359    ) -> bool,
360    can_gc: CanGc,
361) -> bool {
362    let args = CallArgs::from_vp(vp, argc);
363
364    let info = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx, vp));
365    let proto_id = (*info).__bindgen_anon_2.protoID;
366    let cx = SafeJSContext::from_ptr(cx);
367
368    let thisobj = args.thisv();
369    if !thisobj.get().is_null_or_undefined() && !thisobj.get().is_object() {
370        throw_invalid_this(cx, proto_id);
371        return if EXCEPTION_TO_REJECTION {
372            exception_to_promise(*cx, args.rval(), can_gc)
373        } else {
374            false
375        };
376    }
377
378    rooted!(in(*cx) let obj = if thisobj.get().is_object() {
379        thisobj.get().to_object()
380    } else {
381        GetNonCCWObjectGlobal(JS_CALLEE(*cx, vp).to_object_or_null())
382    });
383    let depth = (*info).__bindgen_anon_3.depth as usize;
384    let proto_check = PrototypeCheck::Depth { depth, proto_id };
385    let this = match private_from_proto_check(obj.get(), *cx, proto_check) {
386        Ok(val) => val,
387        Err(()) => {
388            if is_lenient {
389                debug_assert!(!JS_IsExceptionPending(*cx));
390                *vp = UndefinedValue();
391                return true;
392            } else {
393                throw_invalid_this(cx, proto_id);
394                return if EXCEPTION_TO_REJECTION {
395                    exception_to_promise(*cx, args.rval(), can_gc)
396                } else {
397                    false
398                };
399            }
400        },
401    };
402    call(
403        info,
404        *cx,
405        obj.handle().into(),
406        this as *mut libc::c_void,
407        argc,
408        vp,
409    )
410}
411
412/// Generic method of IDL interface.
413///
414/// # Safety
415/// `cx` must point to a valid, non-null JSContext.
416/// `vp` must point to a VALID, non-null JSVal.
417pub(crate) unsafe extern "C" fn generic_method<const EXCEPTION_TO_REJECTION: bool>(
418    cx: *mut JSContext,
419    argc: libc::c_uint,
420    vp: *mut JSVal,
421) -> bool {
422    generic_call::<EXCEPTION_TO_REJECTION>(cx, argc, vp, false, CallJitMethodOp, CanGc::note())
423}
424
425/// Generic getter of IDL interface.
426///
427/// # Safety
428/// `cx` must point to a valid, non-null JSContext.
429/// `vp` must point to a VALID, non-null JSVal.
430pub(crate) unsafe extern "C" fn generic_getter<const EXCEPTION_TO_REJECTION: bool>(
431    cx: *mut JSContext,
432    argc: libc::c_uint,
433    vp: *mut JSVal,
434) -> bool {
435    generic_call::<EXCEPTION_TO_REJECTION>(cx, argc, vp, false, CallJitGetterOp, CanGc::note())
436}
437
438/// Generic lenient getter of IDL interface.
439///
440/// # Safety
441/// `cx` must point to a valid, non-null JSContext.
442/// `vp` must point to a VALID, non-null JSVal.
443pub(crate) unsafe extern "C" fn generic_lenient_getter<const EXCEPTION_TO_REJECTION: bool>(
444    cx: *mut JSContext,
445    argc: libc::c_uint,
446    vp: *mut JSVal,
447) -> bool {
448    generic_call::<EXCEPTION_TO_REJECTION>(cx, argc, vp, true, CallJitGetterOp, CanGc::note())
449}
450
451unsafe extern "C" fn call_setter(
452    info: *const JSJitInfo,
453    cx: *mut JSContext,
454    handle: RawHandleObject,
455    this: *mut libc::c_void,
456    argc: u32,
457    vp: *mut JSVal,
458) -> bool {
459    if !CallJitSetterOp(info, cx, handle, this, argc, vp) {
460        return false;
461    }
462    *vp = UndefinedValue();
463    true
464}
465
466/// Generic setter of IDL interface.
467///
468/// # Safety
469/// `cx` must point to a valid, non-null JSContext.
470/// `vp` must point to a VALID, non-null JSVal.
471pub(crate) unsafe extern "C" fn generic_setter(
472    cx: *mut JSContext,
473    argc: libc::c_uint,
474    vp: *mut JSVal,
475) -> bool {
476    generic_call::<false>(cx, argc, vp, false, call_setter, CanGc::note())
477}
478
479/// Generic lenient setter of IDL interface.
480///
481/// # Safety
482/// `cx` must point to a valid, non-null JSContext.
483/// `vp` must point to a VALID, non-null JSVal.
484pub(crate) unsafe extern "C" fn generic_lenient_setter(
485    cx: *mut JSContext,
486    argc: libc::c_uint,
487    vp: *mut JSVal,
488) -> bool {
489    generic_call::<false>(cx, argc, vp, true, call_setter, CanGc::note())
490}
491
492/// <https://searchfox.org/mozilla-central/rev/7279a1df13a819be254fd4649e07c4ff93e4bd45/dom/bindings/BindingUtils.cpp#3300>
493/// # Safety
494///
495/// `cx` must point to a valid, non-null JSContext.
496/// `vp` must point to a VALID, non-null JSVal.
497pub(crate) unsafe extern "C" fn generic_static_promise_method(
498    cx: *mut JSContext,
499    argc: libc::c_uint,
500    vp: *mut JSVal,
501) -> bool {
502    let args = CallArgs::from_vp(vp, argc);
503
504    let info = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx, vp));
505    assert!(!info.is_null());
506    // TODO: we need safe wrappers for this in mozjs!
507    // assert_eq!((*info)._bitfield_1, JSJitInfo_OpType::StaticMethod as u8)
508    let static_fn = (*info).__bindgen_anon_1.staticMethod.unwrap();
509    if static_fn(cx, argc, vp) {
510        return true;
511    }
512    exception_to_promise(cx, args.rval(), CanGc::note())
513}
514
515/// Coverts exception to promise rejection
516///
517/// <https://searchfox.org/mozilla-central/rev/b220e40ff2ee3d10ce68e07d8a8a577d5558e2a2/dom/bindings/BindingUtils.cpp#3315>
518///
519/// # Safety
520/// `cx` must point to a valid, non-null JSContext.
521pub(crate) unsafe fn exception_to_promise(
522    cx: *mut JSContext,
523    rval: RawMutableHandleValue,
524    _can_gc: CanGc,
525) -> bool {
526    rooted!(in(cx) let mut exception = UndefinedValue());
527    if !JS_GetPendingException(cx, exception.handle_mut()) {
528        return false;
529    }
530    JS_ClearPendingException(cx);
531    if let Some(promise) = NonNull::new(CallOriginalPromiseReject(cx, exception.handle())) {
532        promise.to_jsval(cx, MutableHandleValue::from_raw(rval));
533        true
534    } else {
535        // We just give up.  Put the exception back.
536        JS_SetPendingException(cx, exception.handle(), ExceptionStackBehavior::Capture);
537        false
538    }
539}
540
541/// Trace the resources held by reserved slots of a global object
542///
543/// # Safety
544/// `tracer` must point to a valid, non-null JSTracer.
545/// `obj` must point to a valid, non-null JSObject.
546pub(crate) unsafe fn trace_global(tracer: *mut JSTracer, obj: *mut JSObject) {
547    let array = get_proto_or_iface_array(obj);
548    for proto in (*array).iter() {
549        if !proto.is_null() {
550            trace_object(
551                tracer,
552                "prototype",
553                &*(proto as *const *mut JSObject as *const Heap<*mut JSObject>),
554            );
555        }
556    }
557}
558
559/// Enumerate lazy properties of a global object.
560/// Modeled after <https://github.com/mozilla/gecko-dev/blob/3fd619f47/dom/bindings/BindingUtils.cpp#L2814>
561pub(crate) unsafe extern "C" fn enumerate_global(
562    cx: *mut JSContext,
563    obj: RawHandleObject,
564    props: RawMutableHandleIdVector,
565    enumerable_only: bool,
566) -> bool {
567    assert!(JS_IsGlobalObject(obj.get()));
568    JS_NewEnumerateStandardClasses(cx, obj, props, enumerable_only)
569}
570
571/// Enumerate lazy properties of a global object that is a Window.
572/// <https://github.com/mozilla/gecko-dev/blob/3fd619f47/dom/base/nsGlobalWindowInner.cpp#3297>
573pub(crate) unsafe extern "C" fn enumerate_window<D: DomTypes>(
574    cx: *mut JSContext,
575    obj: RawHandleObject,
576    props: RawMutableHandleIdVector,
577    enumerable_only: bool,
578) -> bool {
579    let mut cx = js::context::JSContext::from_ptr(NonNull::new(cx).unwrap());
580    if !enumerate_global(cx.raw_cx(), obj, props, enumerable_only) {
581        return false;
582    }
583
584    if enumerable_only {
585        // All WebIDL interface names are defined as non-enumerable, so there's
586        // no point in checking them if we're only returning enumerable names.
587        return true;
588    }
589
590    let obj = Handle::from_raw(obj);
591    for (name, interface) in <D as DomHelpers<D>>::interface_map() {
592        if !(interface.enabled)(&mut cx, obj) {
593            continue;
594        }
595        let s = JS_AtomizeStringN(cx.raw_cx(), name.as_ptr() as *const c_char, name.len());
596        rooted!(&in(cx) let id = StringId(s));
597        if s.is_null() || !AppendToIdVector(props, id.handle().into()) {
598            return false;
599        }
600    }
601    true
602}
603
604/// Returns true if the resolve hook for this global may resolve the provided id.
605/// <https://searchfox.org/mozilla-central/rev/f3c8c63a097b61bb1f01e13629b9514e09395947/dom/bindings/BindingUtils.cpp#2809>
606/// <https://searchfox.org/mozilla-central/rev/f3c8c63a097b61bb1f01e13629b9514e09395947/js/public/Class.h#283-291>
607pub(crate) unsafe extern "C" fn may_resolve_global(
608    names: *const JSAtomState,
609    id: PropertyKey,
610    maybe_obj: *mut JSObject,
611) -> bool {
612    JS_MayResolveStandardClass(names, id, maybe_obj)
613}
614
615/// Returns true if the resolve hook for this window may resolve the provided id.
616/// <https://searchfox.org/mozilla-central/rev/f3c8c63a097b61bb1f01e13629b9514e09395947/dom/base/nsGlobalWindowInner.cpp#3275>
617/// <https://searchfox.org/mozilla-central/rev/f3c8c63a097b61bb1f01e13629b9514e09395947/js/public/Class.h#283-291>
618pub(crate) unsafe extern "C" fn may_resolve_window<D: DomTypes>(
619    names: *const JSAtomState,
620    id: PropertyKey,
621    maybe_obj: *mut JSObject,
622) -> bool {
623    if may_resolve_global(names, id, maybe_obj) {
624        return true;
625    }
626
627    let cx = Runtime::get()
628        .expect("There must be a JSContext active")
629        .as_ptr();
630    let Ok(bytes) = latin1_bytes_from_id(cx, id) else {
631        return false;
632    };
633
634    <D as DomHelpers<D>>::interface_map().contains_key(bytes)
635}
636
637/// Resolve a lazy global property, for interface objects and named constructors.
638pub(crate) unsafe extern "C" fn resolve_global(
639    cx: *mut JSContext,
640    obj: RawHandleObject,
641    id: RawHandleId,
642    rval: *mut bool,
643) -> bool {
644    assert!(JS_IsGlobalObject(obj.get()));
645    JS_ResolveStandardClass(cx, obj, id, rval)
646}
647
648/// Resolve a lazy global property for a Window global.
649pub(crate) unsafe extern "C" fn resolve_window<D: DomTypes>(
650    cx: *mut JSContext,
651    obj: RawHandleObject,
652    id: RawHandleId,
653    rval: *mut bool,
654) -> bool {
655    let mut cx = js::context::JSContext::from_ptr(NonNull::new(cx).unwrap());
656    if !resolve_global(cx.raw_cx(), obj, id, rval) {
657        return false;
658    }
659
660    if *rval {
661        return true;
662    }
663    let Ok(bytes) = latin1_bytes_from_id(cx.raw_cx(), *id) else {
664        *rval = false;
665        return true;
666    };
667
668    if let Some(interface) = <D as DomHelpers<D>>::interface_map().get(bytes) {
669        (interface.define)(&mut cx, Handle::from_raw(obj));
670        *rval = true;
671    } else {
672        *rval = false;
673    }
674    true
675}
676
677/// Returns a slice of bytes corresponding to the bytes in the provided string id.
678/// Returns an error if the id is not a string, or the string contains non-latin1 characters.
679/// # Safety
680/// The slice is only valid as long as the original id is not garbage collected.
681unsafe fn latin1_bytes_from_id(cx: *mut JSContext, id: jsid) -> Result<&'static [u8], ()> {
682    if !id.is_string() {
683        return Err(());
684    }
685
686    let string = id.to_string();
687    if !JS_DeprecatedStringHasLatin1Chars(string) {
688        return Err(());
689    }
690    let mut length = 0;
691    let ptr = JS_GetLatin1StringCharsAndLength(cx, ptr::null(), string, &mut length);
692    assert!(!ptr.is_null());
693    Ok(slice::from_raw_parts(ptr, length))
694}