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