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