Skip to main content

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
5#![cfg_attr(crown, allow(crown::jscontext_first_arg))]
6
7use std::ffi::CStr;
8use std::os::raw::{c_char, c_void};
9use std::ptr::{self, NonNull};
10use std::slice;
11
12use js::context::{JSContext, RawJSContext};
13use js::conversions::{ToJSValConvertible, jsstr_to_string};
14use js::gc::Handle;
15use js::glue::{JS_GetReservedSlot, RUST_FUNCTION_VALUE_TO_JITINFO};
16use js::jsapi::{
17    AtomToLinearString, CallArgs, ExceptionStackBehavior, GetLinearStringCharAt,
18    GetLinearStringLength, GetNonCCWObjectGlobal, HandleId as RawHandleId,
19    HandleObject as RawHandleObject, Heap, JS_DeprecatedStringHasLatin1Chars,
20    JS_GetLatin1StringCharsAndLength, JS_IsGlobalObject, JS_MayResolveStandardClass,
21    JS_NewEnumerateStandardClasses, JS_ResolveStandardClass, JSAtom, JSAtomState, JSJitInfo,
22    JSObject, JSPROP_ENUMERATE, JSTracer, MutableHandleIdVector as RawMutableHandleIdVector,
23    MutableHandleValue as RawMutableHandleValue, PropertyKey, StringIsArrayIndex, jsid,
24};
25use js::jsid::StringId;
26use js::jsval::{JSVal, UndefinedValue};
27use js::rust::wrappers2::{
28    AppendToIdVector, CallJitGetterOp, CallJitMethodOp, CallJitSetterOp, CallOriginalPromiseReject,
29    JS_AtomizeStringN, JS_ClearPendingException, JS_DefineProperty, JS_ForwardGetPropertyTo,
30    JS_FreezeObject, JS_GetPendingException, JS_GetProperty, JS_GetPrototype, JS_HasOwnProperty,
31    JS_HasProperty, JS_HasPropertyById, JS_IsExceptionPending, JS_SetPendingException,
32    JS_SetProperty,
33};
34use js::rust::{
35    HandleId, HandleObject, HandleValue, MutableHandleValue, Runtime, ToString, get_object_class,
36};
37use js::{JS_CALLEE, rooted};
38use malloc_size_of::MallocSizeOfOps;
39
40use crate::DomTypes;
41use crate::codegen::Globals::Globals;
42use crate::codegen::InheritTypes::TopTypeId;
43use crate::codegen::PrototypeList::{self, MAX_PROTO_CHAIN_LENGTH, PROTO_OR_IFACE_LENGTH};
44use crate::conversions::{PrototypeCheck, private_from_proto_check};
45use crate::error::throw_invalid_this;
46use crate::interfaces::DomHelpers;
47use crate::proxyhandler::{
48    is_cross_origin_object, is_platform_object_same_origin, report_cross_origin_denial,
49};
50use crate::str::DOMString;
51use crate::trace::trace_object;
52
53/// The struct that holds inheritance information for DOM object reflectors.
54#[derive(Clone, Copy)]
55pub struct DOMClass {
56    /// A list of interfaces that this object implements, in order of decreasing
57    /// derivedness.
58    pub interface_chain: [PrototypeList::ID; MAX_PROTO_CHAIN_LENGTH],
59
60    /// The last valid index of `interface_chain`.
61    pub depth: u8,
62
63    /// The type ID of that interface.
64    pub type_id: TopTypeId,
65
66    /// The MallocSizeOf function wrapper for that interface.
67    pub malloc_size_of: unsafe fn(ops: &mut MallocSizeOfOps, *const c_void) -> usize,
68
69    /// The `Globals` flag for this global interface, if any.
70    pub global: Globals,
71}
72unsafe impl Sync for DOMClass {}
73
74/// The JSClass used for DOM object reflectors.
75#[derive(Copy)]
76#[repr(C)]
77pub struct DOMJSClass {
78    /// The actual JSClass.
79    pub base: js::jsapi::JSClass,
80    /// Associated data for DOM object reflectors.
81    pub dom_class: DOMClass,
82}
83impl Clone for DOMJSClass {
84    fn clone(&self) -> DOMJSClass {
85        *self
86    }
87}
88unsafe impl Sync for DOMJSClass {}
89
90/// The index of the slot where the object holder of that interface's
91/// unforgeable members are defined.
92pub(crate) const DOM_PROTO_UNFORGEABLE_HOLDER_SLOT: u32 = 0;
93
94/// The index of the slot that contains a reference to the ProtoOrIfaceArray.
95// All DOM globals must have a slot at DOM_PROTOTYPE_SLOT.
96pub(crate) const DOM_PROTOTYPE_SLOT: u32 = js::JSCLASS_GLOBAL_SLOT_COUNT;
97
98/// The flag set on the `JSClass`es for DOM global objects.
99// NOTE: This is baked into the Ion JIT as 0 in codegen for LGetDOMProperty and
100// LSetDOMProperty. Those constants need to be changed accordingly if this value
101// changes.
102pub(crate) const JSCLASS_DOM_GLOBAL: u32 = js::JSCLASS_USERBIT1;
103
104/// Returns the ProtoOrIfaceArray for the given global object.
105/// Fails if `global` is not a DOM global object.
106///
107/// # Safety
108/// `global` must point to a valid, non-null JS object.
109pub(crate) unsafe fn get_proto_or_iface_array(global: *mut JSObject) -> *mut ProtoOrIfaceArray {
110    unsafe {
111        assert_ne!(((*get_object_class(global)).flags & JSCLASS_DOM_GLOBAL), 0);
112        let mut slot = UndefinedValue();
113        JS_GetReservedSlot(global, DOM_PROTOTYPE_SLOT, &mut slot);
114        slot.to_private() as *mut ProtoOrIfaceArray
115    }
116}
117
118/// An array of *mut JSObject of size PROTO_OR_IFACE_LENGTH.
119pub type ProtoOrIfaceArray = [*mut JSObject; PROTO_OR_IFACE_LENGTH];
120
121/// Gets the property `id` on  `proxy`'s prototype. If it exists, `*found` is
122/// set to true and `*vp` to the value, otherwise `*found` is set to false.
123///
124/// Returns false on JSAPI failure.
125pub(crate) fn get_property_on_prototype(
126    cx: &mut JSContext,
127    proxy: HandleObject,
128    receiver: HandleValue,
129    id: HandleId,
130    found: &mut bool,
131    vp: MutableHandleValue,
132) -> bool {
133    rooted!(&in(cx) let mut proto = ptr::null_mut::<JSObject>());
134    if unsafe { !JS_GetPrototype(cx, proxy, proto.handle_mut()) || proto.is_null() } {
135        *found = false;
136        return true;
137    }
138    let mut has_property = false;
139    if unsafe { !JS_HasPropertyById(cx, proto.handle(), id, &mut has_property) } {
140        return false;
141    }
142    *found = has_property;
143    if !has_property {
144        return true;
145    }
146
147    unsafe { JS_ForwardGetPropertyTo(cx, proto.handle(), id, receiver, vp) }
148}
149
150/// Get an array index from the given `jsid`. Returns `None` if the given
151/// `jsid` is not an integer.
152pub fn get_array_index_from_id(id: HandleId) -> Option<u32> {
153    let raw_id = *id;
154    if raw_id.is_int() {
155        return Some(raw_id.to_int() as u32);
156    }
157
158    if raw_id.is_void() || !raw_id.is_string() {
159        return None;
160    }
161
162    unsafe {
163        let atom = raw_id.to_string() as *mut JSAtom;
164        let s = AtomToLinearString(atom);
165        if GetLinearStringLength(s) == 0 {
166            return None;
167        }
168
169        let chars = [GetLinearStringCharAt(s, 0)];
170        let first_char = char::decode_utf16(chars.iter().cloned())
171            .next()
172            .map_or('\0', |r| r.unwrap_or('\0'));
173        if first_char.is_ascii_lowercase() {
174            return None;
175        }
176
177        let mut i = 0;
178        if StringIsArrayIndex(s, &mut i) {
179            Some(i)
180        } else {
181            None
182        }
183    }
184
185    /*let s = jsstr_to_string(cx, RUST_JSID_TO_STRING(raw_id));
186    if s.len() == 0 {
187        return None;
188    }
189
190    let first = s.chars().next().unwrap();
191    if first.is_ascii_lowercase() {
192        return None;
193    }
194
195    let mut i: u32 = 0;
196    let is_array = if s.is_ascii() {
197        let chars = s.as_bytes();
198        StringIsArrayIndex1(chars.as_ptr() as *const _, chars.len() as u32, &mut i)
199    } else {
200        let chars = s.encode_utf16().collect::<Vec<u16>>();
201        let slice = chars.as_slice();
202        StringIsArrayIndex2(slice.as_ptr(), chars.len() as u32, &mut i)
203    };
204
205    if is_array {
206        Some(i)
207    } else {
208        None
209    }*/
210}
211
212/// Find the enum equivelent of a string given by `v` in `pairs`.
213/// Returns `Err(())` on JSAPI failure (there is a pending exception), and
214/// `Ok((None, value))` if there was no matching string.
215pub(crate) fn find_enum_value<'a, T>(
216    cx: &mut JSContext,
217    v: HandleValue,
218    pairs: &'a [(&'static str, T)],
219) -> Result<(Option<&'a T>, DOMString), ()> {
220    match NonNull::new(unsafe { ToString(cx, v) }) {
221        Some(jsstr) => {
222            let search = unsafe { jsstr_to_string(cx, jsstr) }.into();
223            Ok((
224                pairs
225                    .iter()
226                    .find(|&&(key, _)| search == key)
227                    .map(|(_, ev)| ev),
228                search,
229            ))
230        },
231        None => Err(()),
232    }
233}
234
235/// Get the property with name `property` from `object`.
236/// Returns `Err(())` on JSAPI failure (there is a pending exception), and
237/// `Ok(false)` if there was no property with the given name.
238pub(crate) fn get_dictionary_property(
239    cx: &mut JSContext,
240    object: HandleObject,
241    property: &CStr,
242    rval: MutableHandleValue,
243) -> Result<bool, ()> {
244    if object.get().is_null() {
245        return Ok(false);
246    }
247
248    let mut found = false;
249    if unsafe { !JS_HasProperty(cx, object, property.as_ptr(), &mut found) } {
250        return Err(());
251    }
252
253    if !found {
254        return Ok(false);
255    }
256
257    if unsafe { !JS_GetProperty(cx, object, property.as_ptr(), rval) } {
258        return Err(());
259    }
260
261    Ok(true)
262}
263
264/// Set the property with name `property` from `object`.
265/// Returns `Err(())` on JSAPI failure, or null object,
266/// and Ok(()) otherwise
267#[expect(clippy::result_unit_err)]
268pub fn set_dictionary_property(
269    cx: &mut JSContext,
270    object: HandleObject,
271    property: &CStr,
272    value: HandleValue,
273) -> Result<(), ()> {
274    if object.get().is_null() {
275        return Err(());
276    }
277
278    if unsafe { !JS_SetProperty(cx, object, property.as_ptr(), value) } {
279        return Err(());
280    }
281
282    Ok(())
283}
284
285/// Define an own enumerable data property with name `property` on `object`.
286/// Returns `Err(())` on JSAPI failure, or null object,
287/// and Ok(()) otherwise.
288#[expect(clippy::result_unit_err)]
289pub fn define_dictionary_property(
290    cx: &mut JSContext,
291    object: HandleObject,
292    property: &CStr,
293    value: HandleValue,
294) -> Result<(), ()> {
295    if object.get().is_null() {
296        return Err(());
297    }
298
299    if unsafe {
300        !JS_DefineProperty(
301            cx,
302            object,
303            property.as_ptr(),
304            value,
305            JSPROP_ENUMERATE as u32,
306        )
307    } {
308        return Err(());
309    }
310
311    Ok(())
312}
313
314/// Checks whether `object` has an own property named `property`.
315/// Returns `Err(())` on JSAPI failure (there is a pending exception),
316/// and `Ok(false)` for null objects or when the property is not own.
317#[expect(clippy::result_unit_err)]
318pub fn has_own_property(
319    cx: &mut JSContext,
320    object: HandleObject,
321    property: &CStr,
322) -> Result<bool, ()> {
323    if object.get().is_null() {
324        return Ok(false);
325    }
326
327    let mut found = false;
328    if unsafe { !JS_HasOwnProperty(cx, object, property.as_ptr(), &mut found) } {
329        return Err(());
330    }
331
332    Ok(found)
333}
334
335/// Computes whether `proxy` has a property `id` on its prototype and stores
336/// the result in `found`.
337///
338/// Returns a boolean indicating whether the check succeeded.
339/// If `false` is returned then the value of `found` is unspecified.
340pub fn has_property_on_prototype(
341    cx: &mut JSContext,
342    proxy: HandleObject,
343    id: HandleId,
344    found: &mut bool,
345) -> bool {
346    rooted!(&in(cx) let mut proto = ptr::null_mut::<JSObject>());
347    if unsafe { !JS_GetPrototype(cx, proxy, proto.handle_mut()) } {
348        return false;
349    }
350    assert!(!proto.is_null());
351    unsafe { JS_HasPropertyById(cx, proto.handle(), id, found) }
352}
353
354pub trait CallPolicy {
355    const INFO: CallPolicyInfo;
356}
357pub mod call_policies {
358    use super::*;
359    pub struct Normal;
360    pub struct TargetClassMaybeCrossOrigin;
361    pub struct LenientThis;
362    pub struct LenientThisTargetClassMaybeCrossOrigin;
363    pub struct CrossOriginCallable;
364    impl CallPolicy for Normal {
365        const INFO: CallPolicyInfo = CallPolicyInfo {
366            lenient_this: false,
367            needs_security_check_on_interface_match: false,
368        };
369    }
370    impl CallPolicy for TargetClassMaybeCrossOrigin {
371        const INFO: CallPolicyInfo = CallPolicyInfo {
372            lenient_this: false,
373            needs_security_check_on_interface_match: true,
374        };
375    }
376    impl CallPolicy for LenientThis {
377        const INFO: CallPolicyInfo = CallPolicyInfo {
378            lenient_this: true,
379            needs_security_check_on_interface_match: false,
380        };
381    }
382    impl CallPolicy for LenientThisTargetClassMaybeCrossOrigin {
383        const INFO: CallPolicyInfo = CallPolicyInfo {
384            lenient_this: true,
385            needs_security_check_on_interface_match: true,
386        };
387    }
388    impl CallPolicy for CrossOriginCallable {
389        const INFO: CallPolicyInfo = CallPolicyInfo {
390            lenient_this: false,
391            needs_security_check_on_interface_match: false,
392        };
393    }
394}
395/// Controls various details of an IDL operation, such as whether a
396/// `[`[`LegacyLenientThis`][1]`]` attribute is specified and preconditions that
397/// affect the outcome of the "[perform a security check][2]" steps.
398///
399/// [1]: https://heycam.github.io/webidl/#LegacyLenientThis
400/// [2]: https://html.spec.whatwg.org/multipage/#integration-with-idl
401#[derive(Clone, Copy, Eq, PartialEq)]
402pub struct CallPolicyInfo {
403    /// Specifies whether a `[LegacyLenientThis]` attribute is specified on the
404    /// interface member this operation is associated with.
405    pub lenient_this: bool,
406    /// Indicates whether a [security check][1] is required if the target object
407    /// implements this operation's interface.
408    ///
409    /// Regardless of this value, performing a security check is always
410    /// necessary if the target object doesn't implement this operation's
411    /// interface.
412    ///
413    /// This field is `false` iff any of the following are true:
414    ///
415    ///  - The operation is not implemented by any cross-origin objects (i.e.,
416    ///    any `Window` or `Location` objects).
417    ///
418    ///  - The operation is defined as cross origin (i.e., it's included in
419    ///    [`CrossOriginProperties`][2]`(obj)`, given `obj` implementing the
420    ///    operation's interface).
421    ///
422    /// [1]: https://html.spec.whatwg.org/multipage/#integration-with-idl
423    /// [2]: https://html.spec.whatwg.org/multipage/#crossoriginproperties-(-o-)
424    pub needs_security_check_on_interface_match: bool,
425}
426
427unsafe fn generic_call<D: DomTypes, const EXCEPTION_TO_REJECTION: bool>(
428    cx: &mut JSContext,
429    argc: libc::c_uint,
430    vp: *mut JSVal,
431    CallPolicyInfo {
432        lenient_this,
433        needs_security_check_on_interface_match,
434    }: CallPolicyInfo,
435    call: unsafe fn(
436        *const JSJitInfo,
437        &mut JSContext,
438        HandleObject,
439        *mut libc::c_void,
440        u32,
441        *mut JSVal,
442    ) -> bool,
443) -> bool {
444    let args = unsafe { CallArgs::from_vp(vp, argc) };
445
446    let info = unsafe { RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx.raw_cx_no_gc(), vp)) };
447    let proto_id = unsafe { (*info).__bindgen_anon_2.protoID };
448
449    // <https://heycam.github.io/webidl/#es-operations>
450    //
451    // > To create an operation function, given an operation `op`, a namespace
452    // > or interface `target`, and a Realm `realm`:
453    // >
454    // > 2. Let `steps` be the following series of steps, [...]
455    // >
456    // > 2.1.2.1. Let `esValue` be the `this` value, if it is not `null` or
457    // >          `undefined`, or `realm`’s global object otherwise. [...]
458    // >
459    // > 2.1.2.2. If `esValue` is a platform object, then perform a security
460    // >          check, passing `esValue`, `id`, and "method".
461    // >
462    // > 2.1.2.3. If `esValue` does not implement the interface `target`, throw
463    // >          a `TypeError`. [...]
464    //
465    // <https://html.spec.whatwg.org/multipage/#integration-with-idl>
466    //
467    // > When perform a security check is invoked, with a `platformObject`,
468    // > `identifier`, and `type`, run these steps:
469    // >
470    // > 1. If `platformObject` is not a `Window` or `Location` object, then
471    // >    return.
472    // >
473    // > 2. For each `e` of `! CrossOriginProperties(platformObject)`:
474    // >
475    // > 2.1. If `SameValue(e.[[Property]], identifier)` is true, then:
476    // >
477    // > 2.1.1. If type is "method" and `e` has neither `[[NeedsGet]]` nor
478    // >        `[[NeedsSet]]`, then return. [... ditto for other types]
479    // >
480    // > 3. If `! IsPlatformObjectSameOrigin(platformObject)` is false, then
481    // >    throw a "SecurityError" `DOMException`.
482    //
483    // According to the above steps, the outcome of an IDL operation is
484    // determined be the following boolean variables:
485    //
486    //  - `this_same_origin`: The current principals object subsumes that of
487    //    `thisobj`
488    //  - `this_class_cross_origin`: `thisobj`'s class provides a cross-origin
489    //    member
490    //  - `cross_origin_operation`: The tuple `(operation_name, operation_type)`
491    //    (e.g., `("focus", "method")`) is a member of
492    //    `CrossOriginProperties(thisobj)`
493    //  - `this_implements_operation`: `thisobj`'s class implements the
494    //    current operation.
495    //
496    // The Karnaugh-esque map of the expected outcome is shown below:
497    //
498    //                            this_same_origin
499    //                                ,-------,
500    //                            ,---+---+---+---,
501    //                            | T | T | o | o |
502    //                          ,-+---+---+---+---+
503    //                          | | S | T | o | S |
504    //  this_class_cross_origin | +---+---+---+---+-,
505    //                          | | T | T | o | o | |
506    //                          '-+---+---+---+---+ | cross_origin_operation
507    //                            | T | T |   |   | |
508    //                            '---+---+---+---+-'
509    //                                    '-------'
510    //                            this_implements_operation
511    //
512    //       T: TypeError (generated by WebIDL opration function step 2.1.2.3)
513    //       S: SecurityError (generated by HTML security check step 3)
514    //       o: OK
515    //   blank: don't-care (impossible cases)
516    //
517    // Under some circumstances, we can rule out some cases from this map.
518    // E.g., if the operation is known to be not implemented by any cross-origin
519    // objects, `this_implements_operation → ¬this_class_cross_origin`, so in
520    // this case, we don't have to perform the security check at all if
521    // `thisobj`'s class implements the expected interface. `CallPolicyInfo::
522    // needs_security_check_on_interface_match` indicates whether this applies.
523
524    let thisobj = args.thisv();
525    if !thisobj.get().is_null_or_undefined() && !thisobj.get().is_object() {
526        // `thisobj` is not a platform object, so the security check is not
527        // invoked in this case
528        throw_invalid_this(cx, proto_id);
529        return if EXCEPTION_TO_REJECTION {
530            exception_to_promise(cx, args.rval())
531        } else {
532            false
533        };
534    }
535
536    rooted!(&in(cx) let obj = if thisobj.get().is_object() {
537        thisobj.get().to_object()
538    } else {
539        unsafe { GetNonCCWObjectGlobal(JS_CALLEE(cx.raw_cx_no_gc(), vp).to_object_or_null()) }
540    });
541    let depth = unsafe { (*info).__bindgen_anon_3.depth as usize };
542    let proto_check = PrototypeCheck::Depth { depth, proto_id };
543    let this = match unsafe { private_from_proto_check(cx, obj.get(), proto_check) } {
544        Ok(val) => val,
545        Err(()) => {
546            // [this_implements_operation == false]
547            //
548            // For now, We don't check the conditions for `SecurityError` in
549            // this case, following WebKit's behavior.
550            //
551            // FIXME: Implement a different browser or the specification's
552            //        behavior? (They all differ subtly.) Some behavior is more
553            //        challenging to implement - for example, implementing the
554            //        specification's behavior requires `generic_call`'s code to
555            //        have access to the current IDL operation's name and type
556            //        and the target object's `CrossOriginProperties`.
557            if lenient_this {
558                unsafe {
559                    debug_assert!(!JS_IsExceptionPending(cx));
560                    *vp = UndefinedValue();
561                }
562                return true;
563            } else {
564                throw_invalid_this(cx, proto_id);
565                return if EXCEPTION_TO_REJECTION {
566                    exception_to_promise(cx, args.rval())
567                } else {
568                    false
569                };
570            }
571        },
572    };
573
574    // [this_implements_operation == true]
575
576    if needs_security_check_on_interface_match {
577        let mut realm = js::realm::CurrentRealm::assert(cx);
578        // [cross_origin_operation == false]
579        if is_cross_origin_object::<D>(&mut realm, obj.handle()) &&
580            !is_platform_object_same_origin(&realm, obj.handle())
581        {
582            // [this_class_cross_origin == true && this_same_origin == false]
583            // Throw a `SecurityError` `DOMException`.
584            // FIXME: `Handle<jsid>` could have a default constructor
585            //        like `Handle<Value>::null`
586            rooted!(&in(*realm) let mut void_jsid: jsid);
587            let result = report_cross_origin_denial::<D>(&mut realm, void_jsid.handle(), "call");
588            return if EXCEPTION_TO_REJECTION {
589                exception_to_promise(cx, args.rval())
590            } else {
591                result
592            };
593        }
594    } else {
595        // [(cross_origin_operation == true && this_class_cross_origin == true)
596        //  || cross_origin_operation == false && this_class_cross_origin == false]
597    }
598
599    unsafe { call(info, cx, obj.handle(), this as *mut libc::c_void, argc, vp) }
600}
601
602/// Generic method of IDL interface.
603///
604/// # Safety
605/// `cx` must point to a valid, non-null JSContext.
606/// `vp` must point to a VALID, non-null JSVal.
607pub(crate) unsafe extern "C" fn generic_method<
608    D: DomTypes,
609    Policy: CallPolicy,
610    const EXCEPTION_TO_REJECTION: bool,
611>(
612    cx: *mut RawJSContext,
613    argc: libc::c_uint,
614    vp: *mut JSVal,
615) -> bool {
616    unsafe {
617        // SAFETY: it is safe to construct a JSContext from engine hook.
618        let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
619        let cx = &mut cx;
620
621        generic_call::<D, EXCEPTION_TO_REJECTION>(cx, argc, vp, Policy::INFO, CallJitMethodOp)
622    }
623}
624
625/// Generic getter of IDL interface.
626///
627/// # Safety
628/// `cx` must point to a valid, non-null JSContext.
629/// `vp` must point to a VALID, non-null JSVal.
630pub(crate) unsafe extern "C" fn generic_getter<
631    D: DomTypes,
632    Policy: CallPolicy,
633    const EXCEPTION_TO_REJECTION: bool,
634>(
635    cx: *mut RawJSContext,
636    argc: libc::c_uint,
637    vp: *mut JSVal,
638) -> bool {
639    unsafe {
640        // SAFETY: it is safe to construct a JSContext from engine hook.
641        let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
642        let cx = &mut cx;
643
644        generic_call::<D, EXCEPTION_TO_REJECTION>(cx, argc, vp, Policy::INFO, CallJitGetterOp)
645    }
646}
647
648unsafe fn call_setter(
649    info: *const JSJitInfo,
650    cx: &mut JSContext,
651    handle: HandleObject,
652    this: *mut libc::c_void,
653    argc: u32,
654    vp: *mut JSVal,
655) -> bool {
656    unsafe {
657        if !CallJitSetterOp(info, cx, handle, this, argc, vp) {
658            return false;
659        }
660        *vp = UndefinedValue();
661    }
662    true
663}
664
665/// Generic setter of IDL interface.
666///
667/// # Safety
668/// `cx` must point to a valid, non-null JSContext.
669/// `vp` must point to a VALID, non-null JSVal.
670pub(crate) unsafe extern "C" fn generic_setter<D: DomTypes, Policy: CallPolicy>(
671    cx: *mut RawJSContext,
672    argc: libc::c_uint,
673    vp: *mut JSVal,
674) -> bool {
675    unsafe {
676        // SAFETY: it is safe to construct a JSContext from engine hook.
677        let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
678        let cx = &mut cx;
679
680        generic_call::<D, false>(cx, argc, vp, Policy::INFO, call_setter)
681    }
682}
683
684/// <https://searchfox.org/mozilla-central/rev/7279a1df13a819be254fd4649e07c4ff93e4bd45/dom/bindings/BindingUtils.cpp#3300>
685/// # Safety
686///
687/// `cx` must point to a valid, non-null JSContext.
688/// `vp` must point to a VALID, non-null JSVal.
689pub(crate) unsafe extern "C" fn generic_static_promise_method(
690    cx: *mut RawJSContext,
691    argc: libc::c_uint,
692    vp: *mut JSVal,
693) -> bool {
694    unsafe {
695        // SAFETY: it is safe to construct a JSContext from engine hook.
696        let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
697        let cx = &mut cx;
698
699        let args = CallArgs::from_vp(vp, argc);
700
701        let info = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx.raw_cx(), vp));
702        assert!(!info.is_null());
703        // TODO: we need safe wrappers for this in mozjs!
704        // assert_eq!((*info)._bitfield_1, JSJitInfo_OpType::StaticMethod as u8)
705        let static_fn = (*info).__bindgen_anon_1.staticMethod.unwrap();
706        if static_fn(cx.raw_cx(), argc, vp) {
707            return true;
708        }
709        exception_to_promise(cx, args.rval())
710    }
711}
712
713/// Coverts exception to promise rejection
714///
715/// <https://searchfox.org/mozilla-central/rev/b220e40ff2ee3d10ce68e07d8a8a577d5558e2a2/dom/bindings/BindingUtils.cpp#3315>
716pub(crate) fn exception_to_promise(cx: &mut JSContext, rval: RawMutableHandleValue) -> bool {
717    unsafe {
718        rooted!(&in(cx) let mut exception = UndefinedValue());
719        if !JS_GetPendingException(cx, exception.handle_mut()) {
720            return false;
721        }
722        JS_ClearPendingException(cx);
723        if let Some(promise) = NonNull::new(CallOriginalPromiseReject(cx, exception.handle())) {
724            promise.to_jsval(cx, MutableHandleValue::from_raw(rval));
725            true
726        } else {
727            // We just give up. Put the exception back.
728            JS_SetPendingException(cx, exception.handle(), ExceptionStackBehavior::Capture);
729            false
730        }
731    }
732}
733
734/// Trace the resources held by reserved slots of a global object
735///
736/// # Safety
737/// `tracer` must point to a valid, non-null JSTracer.
738/// `obj` must point to a valid, non-null JSObject.
739pub(crate) unsafe fn trace_global(tracer: *mut JSTracer, obj: *mut JSObject) {
740    unsafe {
741        let array = get_proto_or_iface_array(obj);
742        for proto in (*array).iter() {
743            if !proto.is_null() {
744                trace_object(
745                    tracer,
746                    "prototype",
747                    &*(proto as *const *mut JSObject as *const Heap<*mut JSObject>),
748                );
749            }
750        }
751    }
752}
753
754/// Enumerate lazy properties of a global object.
755/// Modeled after <https://github.com/mozilla/gecko-dev/blob/3fd619f47/dom/bindings/BindingUtils.cpp#L2814>
756pub(crate) unsafe extern "C" fn enumerate_global(
757    cx: *mut RawJSContext,
758    obj: RawHandleObject,
759    props: RawMutableHandleIdVector,
760    enumerable_only: bool,
761) -> bool {
762    unsafe {
763        assert!(JS_IsGlobalObject(obj.get()));
764        JS_NewEnumerateStandardClasses(cx, obj, props, enumerable_only)
765    }
766}
767
768/// Enumerate lazy properties of a global object that is a Window.
769/// <https://github.com/mozilla/gecko-dev/blob/3fd619f47/dom/base/nsGlobalWindowInner.cpp#3297>
770pub(crate) unsafe extern "C" fn enumerate_window<D: DomTypes>(
771    cx: *mut RawJSContext,
772    obj: RawHandleObject,
773    props: RawMutableHandleIdVector,
774    enumerable_only: bool,
775) -> bool {
776    unsafe {
777        let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
778        if !enumerate_global(cx.raw_cx(), obj, props, enumerable_only) {
779            return false;
780        }
781
782        if enumerable_only {
783            // All WebIDL interface names are defined as non-enumerable, so there's
784            // no point in checking them if we're only returning enumerable names.
785            return true;
786        }
787
788        let obj = Handle::from_raw(obj);
789        for (name, interface) in <D as DomHelpers<D>>::interface_map() {
790            if !(interface.enabled)(&mut cx, obj) {
791                continue;
792            }
793            let s = JS_AtomizeStringN(&cx, name.as_ptr() as *const c_char, name.len());
794            rooted!(&in(cx) let id = StringId(s));
795            if s.is_null() || !AppendToIdVector(props, id.handle()) {
796                return false;
797            }
798        }
799    }
800    true
801}
802
803/// Returns true if the resolve hook for this global may resolve the provided id.
804/// <https://searchfox.org/mozilla-central/rev/f3c8c63a097b61bb1f01e13629b9514e09395947/dom/bindings/BindingUtils.cpp#2809>
805/// <https://searchfox.org/mozilla-central/rev/f3c8c63a097b61bb1f01e13629b9514e09395947/js/public/Class.h#283-291>
806pub(crate) unsafe extern "C" fn may_resolve_global(
807    names: *const JSAtomState,
808    id: PropertyKey,
809    maybe_obj: *mut JSObject,
810) -> bool {
811    unsafe { JS_MayResolveStandardClass(names, id, maybe_obj) }
812}
813
814/// Returns true if the resolve hook for this window may resolve the provided id.
815/// <https://searchfox.org/mozilla-central/rev/f3c8c63a097b61bb1f01e13629b9514e09395947/dom/base/nsGlobalWindowInner.cpp#3275>
816/// <https://searchfox.org/mozilla-central/rev/f3c8c63a097b61bb1f01e13629b9514e09395947/js/public/Class.h#283-291>
817pub(crate) unsafe extern "C" fn may_resolve_window<D: DomTypes>(
818    names: *const JSAtomState,
819    id: PropertyKey,
820    maybe_obj: *mut JSObject,
821) -> bool {
822    if unsafe { may_resolve_global(names, id, maybe_obj) } {
823        return true;
824    }
825
826    let cx = Runtime::get()
827        .expect("There must be a JSContext active")
828        .as_ptr();
829    let Ok(bytes) = (unsafe { latin1_bytes_from_id(cx, id) }) else {
830        return false;
831    };
832
833    <D as DomHelpers<D>>::interface_map().contains_key(bytes)
834}
835
836/// Resolve a lazy global property, for interface objects and named constructors.
837pub(crate) unsafe extern "C" fn resolve_global(
838    cx: *mut RawJSContext,
839    obj: RawHandleObject,
840    id: RawHandleId,
841    rval: *mut bool,
842) -> bool {
843    unsafe {
844        assert!(JS_IsGlobalObject(obj.get()));
845        JS_ResolveStandardClass(cx, obj, id, rval)
846    }
847}
848
849/// Resolve a lazy global property for a Window global.
850pub(crate) unsafe extern "C" fn resolve_window<D: DomTypes>(
851    cx: *mut RawJSContext,
852    obj: RawHandleObject,
853    id: RawHandleId,
854    rval: *mut bool,
855) -> bool {
856    unsafe {
857        let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
858        if !resolve_global(cx.raw_cx(), obj, id, rval) {
859            return false;
860        }
861
862        if *rval {
863            return true;
864        }
865        let Ok(bytes) = latin1_bytes_from_id(cx.raw_cx(), *id) else {
866            *rval = false;
867            return true;
868        };
869
870        if let Some(interface) = <D as DomHelpers<D>>::interface_map().get(bytes) {
871            (interface.define)(&mut cx, Handle::from_raw(obj));
872            *rval = true;
873        } else {
874            *rval = false;
875        }
876    }
877    true
878}
879
880/// Returns a slice of bytes corresponding to the bytes in the provided string id.
881/// Returns an error if the id is not a string, or the string contains non-latin1 characters.
882/// # Safety
883/// The slice is only valid as long as the original id is not garbage collected.
884unsafe fn latin1_bytes_from_id(cx: *mut RawJSContext, id: jsid) -> Result<&'static [u8], ()> {
885    if !id.is_string() {
886        return Err(());
887    }
888
889    let string = id.to_string();
890    if !unsafe { JS_DeprecatedStringHasLatin1Chars(string) } {
891        return Err(());
892    }
893    let mut length = 0;
894    let ptr = unsafe { JS_GetLatin1StringCharsAndLength(cx, ptr::null(), string, &mut length) };
895    assert!(!ptr.is_null());
896    Ok(unsafe { slice::from_raw_parts(ptr, length) })
897}
898
899/// Returns a JSVal representing the frozen JavaScript array
900pub fn to_frozen_array<T: ToJSValConvertible>(
901    cx: &mut JSContext,
902    convertibles: &[T],
903    mut rval: MutableHandleValue,
904) {
905    convertibles.to_jsval(cx, rval.reborrow());
906
907    rooted!(&in(cx) let obj = rval.to_object());
908    unsafe { JS_FreezeObject(cx, obj.handle()) };
909}