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;
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, 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_ForwardGetPropertyTo, JS_FreezeObject,
30    JS_GetPendingException, JS_GetProperty, JS_GetPrototype, JS_HasOwnProperty, JS_HasProperty,
31    JS_HasPropertyById, JS_IsExceptionPending, JS_SetPendingException, JS_SetProperty,
32};
33use js::rust::{
34    HandleId, HandleObject, HandleValue, MutableHandleValue, Runtime, 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::js::{JS_DefineProperty, PropertyFlags};
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    if let Ok(search) = DOMString::from_js_string(cx, v) {
221        let result = pairs
222            .iter()
223            .find(|(key, _)| search == *key)
224            .map(|(_, ev)| ev);
225        Ok((result, search))
226    } else {
227        Err(())
228    }
229}
230
231/// Get the property with name `property` from `object`.
232/// Returns `Err(())` on JSAPI failure (there is a pending exception), and
233/// `Ok(false)` if there was no property with the given name.
234pub(crate) fn get_dictionary_property(
235    cx: &mut JSContext,
236    object: HandleObject,
237    property: &CStr,
238    rval: MutableHandleValue,
239) -> Result<bool, ()> {
240    if object.get().is_null() {
241        return Ok(false);
242    }
243
244    let mut found = false;
245    if unsafe { !JS_HasProperty(cx, object, property.as_ptr(), &mut found) } {
246        return Err(());
247    }
248
249    if !found {
250        return Ok(false);
251    }
252
253    if unsafe { !JS_GetProperty(cx, object, property.as_ptr(), rval) } {
254        return Err(());
255    }
256
257    Ok(true)
258}
259
260/// Set the property with name `property` from `object`.
261/// Returns `Err(())` on JSAPI failure, or null object,
262/// and Ok(()) otherwise
263#[expect(clippy::result_unit_err)]
264pub fn set_dictionary_property(
265    cx: &mut JSContext,
266    object: HandleObject,
267    property: &CStr,
268    value: HandleValue,
269) -> Result<(), ()> {
270    if object.get().is_null() {
271        return Err(());
272    }
273
274    if unsafe { !JS_SetProperty(cx, object, property.as_ptr(), value) } {
275        return Err(());
276    }
277
278    Ok(())
279}
280
281/// Define an own enumerable data property with name `property` on `object`.
282/// Returns `Err(())` on JSAPI failure, or null object,
283/// and Ok(()) otherwise.
284#[expect(clippy::result_unit_err)]
285pub fn define_dictionary_property(
286    cx: &mut JSContext,
287    object: HandleObject,
288    property: &CStr,
289    value: HandleValue,
290) -> Result<(), ()> {
291    if object.get().is_null() {
292        return Err(());
293    }
294
295    if !JS_DefineProperty(
296        cx,
297        object,
298        property,
299        value,
300        PropertyFlags::ENUMERABLE | PropertyFlags::WRITABLE | PropertyFlags::CONFIGURABLE,
301    ) {
302        return Err(());
303    }
304
305    Ok(())
306}
307
308/// Checks whether `object` has an own property named `property`.
309/// Returns `Err(())` on JSAPI failure (there is a pending exception),
310/// and `Ok(false)` for null objects or when the property is not own.
311#[expect(clippy::result_unit_err)]
312pub fn has_own_property(
313    cx: &mut JSContext,
314    object: HandleObject,
315    property: &CStr,
316) -> Result<bool, ()> {
317    if object.get().is_null() {
318        return Ok(false);
319    }
320
321    let mut found = false;
322    if unsafe { !JS_HasOwnProperty(cx, object, property.as_ptr(), &mut found) } {
323        return Err(());
324    }
325
326    Ok(found)
327}
328
329/// Computes whether `proxy` has a property `id` on its prototype and stores
330/// the result in `found`.
331///
332/// Returns a boolean indicating whether the check succeeded.
333/// If `false` is returned then the value of `found` is unspecified.
334pub fn has_property_on_prototype(
335    cx: &mut JSContext,
336    proxy: HandleObject,
337    id: HandleId,
338    found: &mut bool,
339) -> bool {
340    rooted!(&in(cx) let mut proto = ptr::null_mut::<JSObject>());
341    if unsafe { !JS_GetPrototype(cx, proxy, proto.handle_mut()) } {
342        return false;
343    }
344    assert!(!proto.is_null());
345    unsafe { JS_HasPropertyById(cx, proto.handle(), id, found) }
346}
347
348pub trait CallPolicy {
349    const INFO: CallPolicyInfo;
350}
351pub mod call_policies {
352    use super::*;
353    pub struct Normal;
354    pub struct TargetClassMaybeCrossOrigin;
355    pub struct LenientThis;
356    pub struct LenientThisTargetClassMaybeCrossOrigin;
357    pub struct CrossOriginCallable;
358    impl CallPolicy for Normal {
359        const INFO: CallPolicyInfo = CallPolicyInfo {
360            lenient_this: false,
361            needs_security_check_on_interface_match: false,
362        };
363    }
364    impl CallPolicy for TargetClassMaybeCrossOrigin {
365        const INFO: CallPolicyInfo = CallPolicyInfo {
366            lenient_this: false,
367            needs_security_check_on_interface_match: true,
368        };
369    }
370    impl CallPolicy for LenientThis {
371        const INFO: CallPolicyInfo = CallPolicyInfo {
372            lenient_this: true,
373            needs_security_check_on_interface_match: false,
374        };
375    }
376    impl CallPolicy for LenientThisTargetClassMaybeCrossOrigin {
377        const INFO: CallPolicyInfo = CallPolicyInfo {
378            lenient_this: true,
379            needs_security_check_on_interface_match: true,
380        };
381    }
382    impl CallPolicy for CrossOriginCallable {
383        const INFO: CallPolicyInfo = CallPolicyInfo {
384            lenient_this: false,
385            needs_security_check_on_interface_match: false,
386        };
387    }
388}
389/// Controls various details of an IDL operation, such as whether a
390/// `[`[`LegacyLenientThis`][1]`]` attribute is specified and preconditions that
391/// affect the outcome of the "[perform a security check][2]" steps.
392///
393/// [1]: https://heycam.github.io/webidl/#LegacyLenientThis
394/// [2]: https://html.spec.whatwg.org/multipage/#integration-with-idl
395#[derive(Clone, Copy, Eq, PartialEq)]
396pub struct CallPolicyInfo {
397    /// Specifies whether a `[LegacyLenientThis]` attribute is specified on the
398    /// interface member this operation is associated with.
399    pub lenient_this: bool,
400    /// Indicates whether a [security check][1] is required if the target object
401    /// implements this operation's interface.
402    ///
403    /// Regardless of this value, performing a security check is always
404    /// necessary if the target object doesn't implement this operation's
405    /// interface.
406    ///
407    /// This field is `false` iff any of the following are true:
408    ///
409    ///  - The operation is not implemented by any cross-origin objects (i.e.,
410    ///    any `Window` or `Location` objects).
411    ///
412    ///  - The operation is defined as cross origin (i.e., it's included in
413    ///    [`CrossOriginProperties`][2]`(obj)`, given `obj` implementing the
414    ///    operation's interface).
415    ///
416    /// [1]: https://html.spec.whatwg.org/multipage/#integration-with-idl
417    /// [2]: https://html.spec.whatwg.org/multipage/#crossoriginproperties-(-o-)
418    pub needs_security_check_on_interface_match: bool,
419}
420
421unsafe fn generic_call<D: DomTypes, const EXCEPTION_TO_REJECTION: bool>(
422    cx: &mut JSContext,
423    argc: libc::c_uint,
424    vp: *mut JSVal,
425    CallPolicyInfo {
426        lenient_this,
427        needs_security_check_on_interface_match,
428    }: CallPolicyInfo,
429    call: unsafe fn(
430        *const JSJitInfo,
431        &mut JSContext,
432        HandleObject,
433        *mut libc::c_void,
434        u32,
435        *mut JSVal,
436    ) -> bool,
437) -> bool {
438    let args = unsafe { CallArgs::from_vp(vp, argc) };
439
440    let info = unsafe { RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx.raw_cx_no_gc(), vp)) };
441    let proto_id = unsafe { (*info).__bindgen_anon_2.protoID };
442
443    // <https://heycam.github.io/webidl/#es-operations>
444    //
445    // > To create an operation function, given an operation `op`, a namespace
446    // > or interface `target`, and a Realm `realm`:
447    // >
448    // > 2. Let `steps` be the following series of steps, [...]
449    // >
450    // > 2.1.2.1. Let `esValue` be the `this` value, if it is not `null` or
451    // >          `undefined`, or `realm`’s global object otherwise. [...]
452    // >
453    // > 2.1.2.2. If `esValue` is a platform object, then perform a security
454    // >          check, passing `esValue`, `id`, and "method".
455    // >
456    // > 2.1.2.3. If `esValue` does not implement the interface `target`, throw
457    // >          a `TypeError`. [...]
458    //
459    // <https://html.spec.whatwg.org/multipage/#integration-with-idl>
460    //
461    // > When perform a security check is invoked, with a `platformObject`,
462    // > `identifier`, and `type`, run these steps:
463    // >
464    // > 1. If `platformObject` is not a `Window` or `Location` object, then
465    // >    return.
466    // >
467    // > 2. For each `e` of `! CrossOriginProperties(platformObject)`:
468    // >
469    // > 2.1. If `SameValue(e.[[Property]], identifier)` is true, then:
470    // >
471    // > 2.1.1. If type is "method" and `e` has neither `[[NeedsGet]]` nor
472    // >        `[[NeedsSet]]`, then return. [... ditto for other types]
473    // >
474    // > 3. If `! IsPlatformObjectSameOrigin(platformObject)` is false, then
475    // >    throw a "SecurityError" `DOMException`.
476    //
477    // According to the above steps, the outcome of an IDL operation is
478    // determined be the following boolean variables:
479    //
480    //  - `this_same_origin`: The current principals object subsumes that of
481    //    `thisobj`
482    //  - `this_class_cross_origin`: `thisobj`'s class provides a cross-origin
483    //    member
484    //  - `cross_origin_operation`: The tuple `(operation_name, operation_type)`
485    //    (e.g., `("focus", "method")`) is a member of
486    //    `CrossOriginProperties(thisobj)`
487    //  - `this_implements_operation`: `thisobj`'s class implements the
488    //    current operation.
489    //
490    // The Karnaugh-esque map of the expected outcome is shown below:
491    //
492    //                            this_same_origin
493    //                                ,-------,
494    //                            ,---+---+---+---,
495    //                            | T | T | o | o |
496    //                          ,-+---+---+---+---+
497    //                          | | S | T | o | S |
498    //  this_class_cross_origin | +---+---+---+---+-,
499    //                          | | T | T | o | o | |
500    //                          '-+---+---+---+---+ | cross_origin_operation
501    //                            | T | T |   |   | |
502    //                            '---+---+---+---+-'
503    //                                    '-------'
504    //                            this_implements_operation
505    //
506    //       T: TypeError (generated by WebIDL opration function step 2.1.2.3)
507    //       S: SecurityError (generated by HTML security check step 3)
508    //       o: OK
509    //   blank: don't-care (impossible cases)
510    //
511    // Under some circumstances, we can rule out some cases from this map.
512    // E.g., if the operation is known to be not implemented by any cross-origin
513    // objects, `this_implements_operation → ¬this_class_cross_origin`, so in
514    // this case, we don't have to perform the security check at all if
515    // `thisobj`'s class implements the expected interface. `CallPolicyInfo::
516    // needs_security_check_on_interface_match` indicates whether this applies.
517
518    let thisobj = args.thisv();
519    if !thisobj.get().is_null_or_undefined() && !thisobj.get().is_object() {
520        // `thisobj` is not a platform object, so the security check is not
521        // invoked in this case
522        throw_invalid_this(cx, proto_id);
523        return if EXCEPTION_TO_REJECTION {
524            exception_to_promise(cx, args.rval())
525        } else {
526            false
527        };
528    }
529
530    rooted!(&in(cx) let obj = if thisobj.get().is_object() {
531        thisobj.get().to_object()
532    } else {
533        unsafe { GetNonCCWObjectGlobal(JS_CALLEE(cx.raw_cx_no_gc(), vp).to_object_or_null()) }
534    });
535    let depth = unsafe { (*info).__bindgen_anon_3.depth as usize };
536    let proto_check = PrototypeCheck::Depth { depth, proto_id };
537    let this = match unsafe { private_from_proto_check(cx, obj.get(), proto_check) } {
538        Ok(val) => val,
539        Err(()) => {
540            // [this_implements_operation == false]
541            //
542            // For now, We don't check the conditions for `SecurityError` in
543            // this case, following WebKit's behavior.
544            //
545            // FIXME: Implement a different browser or the specification's
546            //        behavior? (They all differ subtly.) Some behavior is more
547            //        challenging to implement - for example, implementing the
548            //        specification's behavior requires `generic_call`'s code to
549            //        have access to the current IDL operation's name and type
550            //        and the target object's `CrossOriginProperties`.
551            if lenient_this {
552                unsafe {
553                    debug_assert!(!JS_IsExceptionPending(cx));
554                    *vp = UndefinedValue();
555                }
556                return true;
557            } else {
558                throw_invalid_this(cx, proto_id);
559                return if EXCEPTION_TO_REJECTION {
560                    exception_to_promise(cx, args.rval())
561                } else {
562                    false
563                };
564            }
565        },
566    };
567
568    // [this_implements_operation == true]
569
570    if needs_security_check_on_interface_match {
571        let mut realm = js::realm::CurrentRealm::assert(cx);
572        // [cross_origin_operation == false]
573        if is_cross_origin_object::<D>(&mut realm, obj.handle()) &&
574            !is_platform_object_same_origin(&realm, obj.handle())
575        {
576            // [this_class_cross_origin == true && this_same_origin == false]
577            // Throw a `SecurityError` `DOMException`.
578            // FIXME: `Handle<jsid>` could have a default constructor
579            //        like `Handle<Value>::null`
580            rooted!(&in(*realm) let mut void_jsid: jsid);
581            let result = report_cross_origin_denial::<D>(&mut realm, void_jsid.handle(), "call");
582            return if EXCEPTION_TO_REJECTION {
583                exception_to_promise(cx, args.rval())
584            } else {
585                result
586            };
587        }
588    } else {
589        // [(cross_origin_operation == true && this_class_cross_origin == true)
590        //  || cross_origin_operation == false && this_class_cross_origin == false]
591    }
592
593    unsafe { call(info, cx, obj.handle(), this as *mut libc::c_void, argc, vp) }
594}
595
596/// Generic method of IDL interface.
597///
598/// # Safety
599/// `cx` must point to a valid, non-null JSContext.
600/// `vp` must point to a VALID, non-null JSVal.
601pub(crate) unsafe extern "C" fn generic_method<
602    D: DomTypes,
603    Policy: CallPolicy,
604    const EXCEPTION_TO_REJECTION: bool,
605>(
606    cx: *mut RawJSContext,
607    argc: libc::c_uint,
608    vp: *mut JSVal,
609) -> bool {
610    unsafe {
611        // SAFETY: it is safe to construct a JSContext from engine hook.
612        let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
613        let cx = &mut cx;
614
615        generic_call::<D, EXCEPTION_TO_REJECTION>(cx, argc, vp, Policy::INFO, CallJitMethodOp)
616    }
617}
618
619/// Generic getter of IDL interface.
620///
621/// # Safety
622/// `cx` must point to a valid, non-null JSContext.
623/// `vp` must point to a VALID, non-null JSVal.
624pub(crate) unsafe extern "C" fn generic_getter<
625    D: DomTypes,
626    Policy: CallPolicy,
627    const EXCEPTION_TO_REJECTION: bool,
628>(
629    cx: *mut RawJSContext,
630    argc: libc::c_uint,
631    vp: *mut JSVal,
632) -> bool {
633    unsafe {
634        // SAFETY: it is safe to construct a JSContext from engine hook.
635        let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
636        let cx = &mut cx;
637
638        generic_call::<D, EXCEPTION_TO_REJECTION>(cx, argc, vp, Policy::INFO, CallJitGetterOp)
639    }
640}
641
642unsafe fn call_setter(
643    info: *const JSJitInfo,
644    cx: &mut JSContext,
645    handle: HandleObject,
646    this: *mut libc::c_void,
647    argc: u32,
648    vp: *mut JSVal,
649) -> bool {
650    unsafe {
651        if !CallJitSetterOp(info, cx, handle, this, argc, vp) {
652            return false;
653        }
654        *vp = UndefinedValue();
655    }
656    true
657}
658
659/// Generic setter of IDL interface.
660///
661/// # Safety
662/// `cx` must point to a valid, non-null JSContext.
663/// `vp` must point to a VALID, non-null JSVal.
664pub(crate) unsafe extern "C" fn generic_setter<D: DomTypes, Policy: CallPolicy>(
665    cx: *mut RawJSContext,
666    argc: libc::c_uint,
667    vp: *mut JSVal,
668) -> bool {
669    unsafe {
670        // SAFETY: it is safe to construct a JSContext from engine hook.
671        let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
672        let cx = &mut cx;
673
674        generic_call::<D, false>(cx, argc, vp, Policy::INFO, call_setter)
675    }
676}
677
678/// <https://searchfox.org/mozilla-central/rev/7279a1df13a819be254fd4649e07c4ff93e4bd45/dom/bindings/BindingUtils.cpp#3300>
679/// # Safety
680///
681/// `cx` must point to a valid, non-null JSContext.
682/// `vp` must point to a VALID, non-null JSVal.
683pub(crate) unsafe extern "C" fn generic_static_promise_method(
684    cx: *mut RawJSContext,
685    argc: libc::c_uint,
686    vp: *mut JSVal,
687) -> bool {
688    unsafe {
689        // SAFETY: it is safe to construct a JSContext from engine hook.
690        let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
691        let cx = &mut cx;
692
693        let args = CallArgs::from_vp(vp, argc);
694
695        let info = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx.raw_cx(), vp));
696        assert!(!info.is_null());
697        // TODO: we need safe wrappers for this in mozjs!
698        // assert_eq!((*info)._bitfield_1, JSJitInfo_OpType::StaticMethod as u8)
699        let static_fn = (*info).__bindgen_anon_1.staticMethod.unwrap();
700        if static_fn(cx.raw_cx(), argc, vp) {
701            return true;
702        }
703        exception_to_promise(cx, args.rval())
704    }
705}
706
707/// Coverts exception to promise rejection
708///
709/// <https://searchfox.org/mozilla-central/rev/b220e40ff2ee3d10ce68e07d8a8a577d5558e2a2/dom/bindings/BindingUtils.cpp#3315>
710pub(crate) fn exception_to_promise(cx: &mut JSContext, rval: RawMutableHandleValue) -> bool {
711    unsafe {
712        rooted!(&in(cx) let mut exception = UndefinedValue());
713        if !JS_GetPendingException(cx, exception.handle_mut()) {
714            return false;
715        }
716        JS_ClearPendingException(cx);
717        if let Some(promise) = NonNull::new(CallOriginalPromiseReject(cx, exception.handle())) {
718            promise.to_jsval(cx, MutableHandleValue::from_raw(rval));
719            true
720        } else {
721            // We just give up. Put the exception back.
722            JS_SetPendingException(cx, exception.handle(), ExceptionStackBehavior::Capture);
723            false
724        }
725    }
726}
727
728/// Trace the resources held by reserved slots of a global object
729///
730/// # Safety
731/// `tracer` must point to a valid, non-null JSTracer.
732/// `obj` must point to a valid, non-null JSObject.
733pub(crate) unsafe fn trace_global(tracer: *mut JSTracer, obj: *mut JSObject) {
734    unsafe {
735        let array = get_proto_or_iface_array(obj);
736        for proto in (*array).iter() {
737            if !proto.is_null() {
738                trace_object(
739                    tracer,
740                    "prototype",
741                    &*(proto as *const *mut JSObject as *const Heap<*mut JSObject>),
742                );
743            }
744        }
745    }
746}
747
748/// Enumerate lazy properties of a global object.
749/// Modeled after <https://github.com/mozilla/gecko-dev/blob/3fd619f47/dom/bindings/BindingUtils.cpp#L2814>
750pub(crate) unsafe extern "C" fn enumerate_global(
751    cx: *mut RawJSContext,
752    obj: RawHandleObject,
753    props: RawMutableHandleIdVector,
754    enumerable_only: bool,
755) -> bool {
756    unsafe {
757        assert!(JS_IsGlobalObject(obj.get()));
758        JS_NewEnumerateStandardClasses(cx, obj, props, enumerable_only)
759    }
760}
761
762/// Enumerate lazy properties of a global object that is a Window.
763/// <https://github.com/mozilla/gecko-dev/blob/3fd619f47/dom/base/nsGlobalWindowInner.cpp#3297>
764pub(crate) unsafe extern "C" fn enumerate_window<D: DomTypes>(
765    cx: *mut RawJSContext,
766    obj: RawHandleObject,
767    props: RawMutableHandleIdVector,
768    enumerable_only: bool,
769) -> bool {
770    unsafe {
771        let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
772        if !enumerate_global(cx.raw_cx(), obj, props, enumerable_only) {
773            return false;
774        }
775
776        if enumerable_only {
777            // All WebIDL interface names are defined as non-enumerable, so there's
778            // no point in checking them if we're only returning enumerable names.
779            return true;
780        }
781
782        let obj = Handle::from_raw(obj);
783        for (name, interface) in <D as DomHelpers<D>>::interface_map() {
784            if !(interface.enabled)(&mut cx, obj) {
785                continue;
786            }
787            let s = JS_AtomizeStringN(&cx, name.as_ptr() as *const c_char, name.len());
788            rooted!(&in(cx) let id = StringId(s));
789            if s.is_null() || !AppendToIdVector(props, id.handle()) {
790                return false;
791            }
792        }
793    }
794    true
795}
796
797/// Returns true if the resolve hook for this global may resolve the provided id.
798/// <https://searchfox.org/mozilla-central/rev/f3c8c63a097b61bb1f01e13629b9514e09395947/dom/bindings/BindingUtils.cpp#2809>
799/// <https://searchfox.org/mozilla-central/rev/f3c8c63a097b61bb1f01e13629b9514e09395947/js/public/Class.h#283-291>
800pub(crate) unsafe extern "C" fn may_resolve_global(
801    names: *const JSAtomState,
802    id: PropertyKey,
803    maybe_obj: *mut JSObject,
804) -> bool {
805    unsafe { JS_MayResolveStandardClass(names, id, maybe_obj) }
806}
807
808/// Returns true if the resolve hook for this window may resolve the provided id.
809/// <https://searchfox.org/mozilla-central/rev/f3c8c63a097b61bb1f01e13629b9514e09395947/dom/base/nsGlobalWindowInner.cpp#3275>
810/// <https://searchfox.org/mozilla-central/rev/f3c8c63a097b61bb1f01e13629b9514e09395947/js/public/Class.h#283-291>
811pub(crate) unsafe extern "C" fn may_resolve_window<D: DomTypes>(
812    names: *const JSAtomState,
813    id: PropertyKey,
814    maybe_obj: *mut JSObject,
815) -> bool {
816    if unsafe { may_resolve_global(names, id, maybe_obj) } {
817        return true;
818    }
819
820    let cx = Runtime::get()
821        .expect("There must be a JSContext active")
822        .as_ptr();
823    let Ok(bytes) = (unsafe { latin1_bytes_from_id(cx, id) }) else {
824        return false;
825    };
826
827    <D as DomHelpers<D>>::interface_map().contains_key(bytes)
828}
829
830/// Resolve a lazy global property, for interface objects and named constructors.
831pub(crate) unsafe extern "C" fn resolve_global(
832    cx: *mut RawJSContext,
833    obj: RawHandleObject,
834    id: RawHandleId,
835    rval: *mut bool,
836) -> bool {
837    unsafe {
838        assert!(JS_IsGlobalObject(obj.get()));
839        JS_ResolveStandardClass(cx, obj, id, rval)
840    }
841}
842
843/// Resolve a lazy global property for a Window global.
844pub(crate) unsafe extern "C" fn resolve_window<D: DomTypes>(
845    cx: *mut RawJSContext,
846    obj: RawHandleObject,
847    id: RawHandleId,
848    rval: *mut bool,
849) -> bool {
850    unsafe {
851        let mut cx = JSContext::from_ptr(NonNull::new(cx).unwrap());
852        if !resolve_global(cx.raw_cx(), obj, id, rval) {
853            return false;
854        }
855
856        if *rval {
857            return true;
858        }
859        let Ok(bytes) = latin1_bytes_from_id(cx.raw_cx(), *id) else {
860            *rval = false;
861            return true;
862        };
863
864        if let Some(interface) = <D as DomHelpers<D>>::interface_map().get(bytes) {
865            (interface.define)(&mut cx, Handle::from_raw(obj));
866            *rval = true;
867        } else {
868            *rval = false;
869        }
870    }
871    true
872}
873
874/// Returns a slice of bytes corresponding to the bytes in the provided string id.
875/// Returns an error if the id is not a string, or the string contains non-latin1 characters.
876/// # Safety
877/// The slice is only valid as long as the original id is not garbage collected.
878unsafe fn latin1_bytes_from_id(cx: *mut RawJSContext, id: jsid) -> Result<&'static [u8], ()> {
879    if !id.is_string() {
880        return Err(());
881    }
882
883    let string = id.to_string();
884    if !unsafe { JS_DeprecatedStringHasLatin1Chars(string) } {
885        return Err(());
886    }
887    let mut length = 0;
888    let ptr = unsafe { JS_GetLatin1StringCharsAndLength(cx, ptr::null(), string, &mut length) };
889    assert!(!ptr.is_null());
890    Ok(unsafe { slice::from_raw_parts(ptr, length) })
891}
892
893/// Returns a JSVal representing the frozen JavaScript array
894pub fn to_frozen_array<T: ToJSValConvertible>(
895    cx: &mut JSContext,
896    convertibles: &[T],
897    mut rval: MutableHandleValue,
898) {
899    convertibles.to_jsval(cx, rval.reborrow());
900
901    rooted!(&in(cx) let obj = rval.to_object());
902    unsafe { JS_FreezeObject(cx, obj.handle()) };
903}