Skip to main content

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