script/dom/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//! Various utilities to glue JavaScript and the DOM implementation together.
6
7use std::cell::RefCell;
8use std::thread::LocalKey;
9
10use js::conversions::ToJSValConvertible;
11use js::glue::{IsWrapper, JSPrincipalsCallbacks, UnwrapObjectDynamic, UnwrapObjectStatic};
12use js::jsapi::{
13    CallArgs, DOMCallbacks, HandleObject as RawHandleObject, JS_FreezeObject, JSContext, JSObject,
14};
15use js::realm::CurrentRealm;
16use js::rust::{HandleObject, MutableHandleValue, get_object_class, is_dom_class};
17use script_bindings::conversions::SafeToJSValConvertible;
18use script_bindings::interfaces::{DomHelpers, Interface};
19use script_bindings::settings_stack::StackEntry;
20
21use crate::DomTypes;
22use crate::dom::bindings::codegen::{InterfaceObjectMap, PrototypeList};
23use crate::dom::bindings::constructor::call_html_constructor;
24use crate::dom::bindings::conversions::DerivedFrom;
25use crate::dom::bindings::error::{Error, report_pending_exception, throw_dom_exception};
26use crate::dom::bindings::principals::PRINCIPALS_CALLBACKS;
27use crate::dom::bindings::proxyhandler::is_platform_object_same_origin;
28use crate::dom::bindings::reflector::{DomObject, DomObjectWrap, reflect_dom_object};
29use crate::dom::bindings::root::DomRoot;
30use crate::dom::bindings::settings_stack;
31use crate::dom::globalscope::GlobalScope;
32use crate::dom::windowproxy::WindowProxyHandler;
33use crate::realms::InRealm;
34use crate::script_runtime::{CanGc, JSContext as SafeJSContext};
35use crate::script_thread::ScriptThread;
36
37#[derive(JSTraceable, MallocSizeOf)]
38/// Static data associated with a global object.
39pub(crate) struct GlobalStaticData {
40    #[ignore_malloc_size_of = "WindowProxyHandler does not properly implement it anyway"]
41    /// The WindowProxy proxy handler for this global.
42    pub(crate) windowproxy_handler: &'static WindowProxyHandler,
43}
44
45impl GlobalStaticData {
46    /// Creates a new GlobalStaticData.
47    pub(crate) fn new() -> GlobalStaticData {
48        GlobalStaticData {
49            windowproxy_handler: WindowProxyHandler::proxy_handler(),
50        }
51    }
52}
53
54pub(crate) use script_bindings::utils::*;
55
56/// Returns a JSVal representing the frozen JavaScript array
57pub(crate) fn to_frozen_array<T: ToJSValConvertible>(
58    convertibles: &[T],
59    cx: SafeJSContext,
60    mut rval: MutableHandleValue,
61    can_gc: CanGc,
62) {
63    convertibles.safe_to_jsval(cx, rval.reborrow(), can_gc);
64
65    rooted!(in(*cx) let obj = rval.to_object());
66    unsafe { JS_FreezeObject(*cx, RawHandleObject::from(obj.handle())) };
67}
68
69/// Returns wether `obj` is a platform object using dynamic unwrap
70/// <https://heycam.github.io/webidl/#dfn-platform-object>
71#[expect(dead_code)]
72pub(crate) fn is_platform_object_dynamic(obj: *mut JSObject, cx: *mut JSContext) -> bool {
73    is_platform_object(obj, &|o| unsafe {
74        UnwrapObjectDynamic(o, cx, /* stopAtWindowProxy = */ false)
75    })
76}
77
78/// Returns wether `obj` is a platform object using static unwrap
79/// <https://heycam.github.io/webidl/#dfn-platform-object>
80pub(crate) fn is_platform_object_static(obj: *mut JSObject) -> bool {
81    is_platform_object(obj, &|o| unsafe { UnwrapObjectStatic(o) })
82}
83
84fn is_platform_object(
85    obj: *mut JSObject,
86    unwrap_obj: &dyn Fn(*mut JSObject) -> *mut JSObject,
87) -> bool {
88    unsafe {
89        // Fast-path the common case
90        let mut clasp = get_object_class(obj);
91        if is_dom_class(&*clasp) {
92            return true;
93        }
94        // Now for simplicity check for security wrappers before anything else
95        if IsWrapper(obj) {
96            let unwrapped_obj = unwrap_obj(obj);
97            if unwrapped_obj.is_null() {
98                return false;
99            }
100            clasp = get_object_class(obj);
101        }
102        // TODO also check if JS_IsArrayBufferObject
103        is_dom_class(&*clasp)
104    }
105}
106
107unsafe extern "C" fn instance_class_has_proto_at_depth(
108    clasp: *const js::jsapi::JSClass,
109    proto_id: u32,
110    depth: u32,
111) -> bool {
112    let domclass: *const DOMJSClass = clasp as *const _;
113    let domclass = unsafe { &*domclass };
114    domclass.dom_class.interface_chain[depth as usize] as u32 == proto_id
115}
116
117/// <https://searchfox.org/mozilla-central/rev/c18faaae88b30182e487fa3341bc7d923e22f23a/xpcom/base/CycleCollectedJSRuntime.cpp#792>
118unsafe extern "C" fn instance_class_is_error(clasp: *const js::jsapi::JSClass) -> bool {
119    if !is_dom_class(unsafe { &*clasp }) {
120        return false;
121    }
122    let domclass: *const DOMJSClass = clasp as *const _;
123    let domclass = unsafe { &*domclass };
124    let root_interface = domclass.dom_class.interface_chain[0] as u32;
125    // TODO: support checking bare Exception prototype as well.
126    root_interface == PrototypeList::ID::DOMException as u32
127}
128
129pub(crate) const DOM_CALLBACKS: DOMCallbacks = DOMCallbacks {
130    instanceClassMatchesProto: Some(instance_class_has_proto_at_depth),
131    instanceClassIsError: Some(instance_class_is_error),
132};
133
134/// Eagerly define all relevant WebIDL interface constructors on the
135/// provided global object.
136pub(crate) fn define_all_exposed_interfaces(cx: &mut CurrentRealm, global: &GlobalScope) {
137    for (_, interface) in &InterfaceObjectMap::MAP {
138        (interface.define)(cx, global.reflector().get_jsobject());
139    }
140}
141
142impl DomHelpers<crate::DomTypeHolder> for crate::DomTypeHolder {
143    fn throw_dom_exception(
144        cx: SafeJSContext,
145        global: &<crate::DomTypeHolder as DomTypes>::GlobalScope,
146        result: Error,
147        can_gc: CanGc,
148    ) {
149        throw_dom_exception(cx, global, result, can_gc)
150    }
151
152    fn call_html_constructor<
153        T: DerivedFrom<<crate::DomTypeHolder as DomTypes>::Element> + DomObject,
154    >(
155        cx: &mut js::context::JSContext,
156        args: &CallArgs,
157        global: &<crate::DomTypeHolder as DomTypes>::GlobalScope,
158        proto_id: PrototypeList::ID,
159        creator: unsafe fn(SafeJSContext, HandleObject, *mut ProtoOrIfaceArray),
160    ) -> bool {
161        call_html_constructor::<T>(cx, args, global, proto_id, creator)
162    }
163
164    fn settings_stack() -> &'static LocalKey<RefCell<Vec<StackEntry<crate::DomTypeHolder>>>> {
165        &settings_stack::STACK
166    }
167
168    fn principals_callbacks() -> &'static JSPrincipalsCallbacks {
169        &PRINCIPALS_CALLBACKS
170    }
171
172    fn is_platform_object_same_origin(cx: &CurrentRealm, obj: RawHandleObject) -> bool {
173        unsafe { is_platform_object_same_origin(cx, obj) }
174    }
175
176    fn interface_map() -> &'static phf::Map<&'static [u8], Interface> {
177        &InterfaceObjectMap::MAP
178    }
179
180    fn push_new_element_queue() {
181        ScriptThread::custom_element_reaction_stack().push_new_element_queue()
182    }
183    fn pop_current_element_queue(can_gc: CanGc) {
184        ScriptThread::custom_element_reaction_stack().pop_current_element_queue(can_gc)
185    }
186
187    fn reflect_dom_object<T, U>(obj: Box<T>, global: &U, can_gc: CanGc) -> DomRoot<T>
188    where
189        T: DomObject + DomObjectWrap<crate::DomTypeHolder>,
190        U: DerivedFrom<GlobalScope>,
191    {
192        reflect_dom_object(obj, global, can_gc)
193    }
194
195    fn report_pending_exception(
196        cx: SafeJSContext,
197        dispatch_event: bool,
198        realm: InRealm,
199        can_gc: CanGc,
200    ) {
201        report_pending_exception(cx, dispatch_event, realm, can_gc)
202    }
203}