Skip to main content

script_bindings/
callback.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//! Base classes to work with IDL callbacks.
6
7use std::default::Default;
8use std::ffi::CStr;
9use std::rc::Rc;
10
11use js::jsapi::{AddRawValueRoot, Heap, IsCallable, JSObject, RemoveRawValueRoot};
12use js::jsval::{JSVal, NullValue, ObjectValue, UndefinedValue};
13use js::rust::wrappers2::{EnterRealm, JS_GetProperty, JS_WrapObject, LeaveRealm};
14use js::rust::{HandleObject, MutableHandleValue, Runtime};
15
16use crate::codegen::GenericBindings::WindowBinding::Window_Binding::WindowMethods;
17use crate::error::{Error, Fallible};
18use crate::inheritance::Castable;
19use crate::interfaces::{DocumentHelpers, DomHelpers, GlobalScopeHelpers};
20use crate::realms::{InRealm, enter_auto_realm};
21use crate::reflector::DomObject;
22use crate::root::Dom;
23use crate::script_runtime::{CanGc, JSContext};
24use crate::settings_stack::{run_a_callback, run_a_script};
25use crate::{DomTypes, cformat};
26
27pub trait ThisReflector {
28    fn jsobject(&self) -> *mut JSObject;
29}
30
31impl<T: DomObject> ThisReflector for T {
32    fn jsobject(&self) -> *mut JSObject {
33        self.reflector().get_jsobject().get()
34    }
35}
36
37impl ThisReflector for HandleObject<'_> {
38    fn jsobject(&self) -> *mut JSObject {
39        self.get()
40    }
41}
42
43/// The exception handling used for a call.
44#[derive(Clone, Copy, PartialEq)]
45pub enum ExceptionHandling {
46    /// Report any exception and don't throw it to the caller code.
47    Report,
48    /// Throw any exception to the caller code.
49    Rethrow,
50}
51
52/// A common base class for representing IDL callback function and
53/// callback interface types.
54#[derive(JSTraceable, MallocSizeOf)]
55#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
56pub struct CallbackObject<D: DomTypes> {
57    /// The underlying `JSObject`.
58    #[ignore_malloc_size_of = "measured by mozjs"]
59    callback: Heap<*mut JSObject>,
60    #[ignore_malloc_size_of = "measured by mozjs"]
61    permanent_js_root: Heap<JSVal>,
62
63    /// The ["callback context"], that is, the global to use as incumbent
64    /// global when calling the callback.
65    ///
66    /// Looking at the WebIDL standard, it appears as though there would always
67    /// be a value here, but [sometimes] callback functions are created by
68    /// hand-waving without defining the value of the callback context, and
69    /// without any JavaScript code on the stack to grab an incumbent global
70    /// from.
71    ///
72    /// ["callback context"]: https://heycam.github.io/webidl/#dfn-callback-context
73    /// [sometimes]: https://github.com/whatwg/html/issues/2248
74    incumbent: Option<Dom<D::GlobalScope>>,
75}
76
77impl<D: DomTypes> CallbackObject<D> {
78    // These are used by the bindings and do not need `default()` functions.
79    #[allow(clippy::new_without_default)]
80    fn new() -> Self {
81        Self {
82            callback: Heap::default(),
83            permanent_js_root: Heap::default(),
84            incumbent: D::GlobalScope::incumbent().map(|i| Dom::from_ref(&*i)),
85        }
86    }
87
88    pub fn get(&self) -> *mut JSObject {
89        self.callback.get()
90    }
91
92    #[expect(unsafe_code)]
93    unsafe fn init(&mut self, cx: JSContext, callback: *mut JSObject) {
94        self.callback.set(callback);
95        self.permanent_js_root.set(ObjectValue(callback));
96        unsafe {
97            assert!(AddRawValueRoot(
98                *cx,
99                self.permanent_js_root.get_unsafe(),
100                c"CallbackObject::root".as_ptr()
101            ));
102        }
103    }
104}
105
106impl<D: DomTypes> Drop for CallbackObject<D> {
107    #[expect(unsafe_code)]
108    fn drop(&mut self) {
109        unsafe {
110            if let Some(cx) = Runtime::get() {
111                RemoveRawValueRoot(cx.as_ptr(), self.permanent_js_root.get_unsafe());
112            }
113        }
114    }
115}
116
117impl<D: DomTypes> PartialEq for CallbackObject<D> {
118    fn eq(&self, other: &CallbackObject<D>) -> bool {
119        self.callback.get() == other.callback.get()
120    }
121}
122
123/// A trait to be implemented by concrete IDL callback function and
124/// callback interface types.
125pub trait CallbackContainer<D: DomTypes> {
126    /// Create a new CallbackContainer object for the given `JSObject`.
127    ///
128    /// # Safety
129    /// `callback` must point to a valid, non-null JSObject.
130    unsafe fn new(cx: JSContext, callback: *mut JSObject) -> Rc<Self>;
131    /// Returns the underlying `CallbackObject`.
132    fn callback_holder(&self) -> &CallbackObject<D>;
133    /// Returns the underlying `JSObject`.
134    fn callback(&self) -> *mut JSObject {
135        self.callback_holder().get()
136    }
137    /// Returns the ["callback context"], that is, the global to use as
138    /// incumbent global when calling the callback.
139    ///
140    /// ["callback context"]: https://heycam.github.io/webidl/#dfn-callback-context
141    fn incumbent(&self) -> Option<&D::GlobalScope> {
142        self.callback_holder().incumbent.as_deref()
143    }
144}
145
146/// A common base class for representing IDL callback function types.
147#[derive(JSTraceable, MallocSizeOf, PartialEq)]
148#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
149pub struct CallbackFunction<D: DomTypes> {
150    object: CallbackObject<D>,
151}
152
153impl<D: DomTypes> CallbackFunction<D> {
154    /// Create a new `CallbackFunction` for this object.
155    // These are used by the bindings and do not need `default()` functions.
156    #[expect(clippy::new_without_default)]
157    pub fn new() -> Self {
158        Self {
159            object: CallbackObject::new(),
160        }
161    }
162
163    /// Returns the underlying `CallbackObject`.
164    pub fn callback_holder(&self) -> &CallbackObject<D> {
165        &self.object
166    }
167
168    /// Initialize the callback function with a value.
169    /// Should be called once this object is done moving.
170    ///
171    /// # Safety
172    /// `callback` must point to a valid, non-null JSObject.
173    pub unsafe fn init(&mut self, cx: JSContext, callback: *mut JSObject) {
174        unsafe { self.object.init(cx, callback) };
175    }
176}
177
178/// A common base class for representing IDL callback interface types.
179#[derive(JSTraceable, MallocSizeOf, PartialEq)]
180#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
181pub struct CallbackInterface<D: DomTypes> {
182    object: CallbackObject<D>,
183}
184
185impl<D: DomTypes> CallbackInterface<D> {
186    /// Create a new CallbackInterface object for the given `JSObject`.
187    // These are used by the bindings and do not need `default()` functions.
188    #[expect(clippy::new_without_default)]
189    pub fn new() -> Self {
190        Self {
191            object: CallbackObject::new(),
192        }
193    }
194
195    /// Returns the underlying `CallbackObject`.
196    pub fn callback_holder(&self) -> &CallbackObject<D> {
197        &self.object
198    }
199
200    /// Initialize the callback function with a value.
201    /// Should be called once this object is done moving.
202    ///
203    /// # Safety
204    /// `callback` must point to a valid, non-null JSObject.
205    pub unsafe fn init(&mut self, cx: JSContext, callback: *mut JSObject) {
206        unsafe { self.object.init(cx, callback) };
207    }
208
209    /// Returns the property with the given `name`, if it is a callable object,
210    /// or an error otherwise.
211    pub fn get_callable_property(
212        &self,
213        cx: &mut js::context::JSContext,
214        name: &CStr,
215    ) -> Fallible<JSVal> {
216        rooted!(&in(cx) let mut callable = UndefinedValue());
217        rooted!(&in(cx) let obj = self.callback_holder().get());
218        unsafe {
219            if !JS_GetProperty(cx, obj.handle(), name.as_ptr(), callable.handle_mut()) {
220                return Err(Error::JSFailed);
221            }
222
223            if !callable.is_object() || !IsCallable(callable.to_object()) {
224                return Err(Error::Type(cformat!(
225                    "The value of the {} property is not callable",
226                    name.to_string_lossy()
227                )));
228            }
229        }
230        Ok(callable.get())
231    }
232}
233
234/// Wraps the reflector for `p` into the realm of `cx`.
235pub(crate) fn wrap_call_this_value<T: ThisReflector>(
236    cx: &mut js::context::JSContext,
237    p: &T,
238    mut rval: MutableHandleValue,
239) -> bool {
240    rooted!(&in(cx) let mut obj = p.jsobject());
241
242    if obj.is_null() {
243        rval.set(NullValue());
244        return true;
245    }
246
247    unsafe {
248        if !JS_WrapObject(cx, obj.handle_mut()) {
249            return false;
250        }
251    }
252
253    rval.set(ObjectValue(*obj));
254    true
255}
256
257/// A function wrapper that performs whatever setup we need to safely make a call.
258///
259/// <https://webidl.spec.whatwg.org/#es-invoking-callback-functions>
260pub fn call_setup<D: DomTypes, T: CallbackContainer<D>, R>(
261    cx: &mut js::context::JSContext,
262    callback: &T,
263    handling: ExceptionHandling,
264    f: impl FnOnce(&mut js::context::JSContext) -> R,
265) -> R {
266    // The global for reporting exceptions. This is the global object of the
267    // (possibly wrapped) callback object.
268    let global = unsafe { D::GlobalScope::from_object(callback.callback()) };
269    if let Some(window) = global.downcast::<D::Window>() {
270        window.Document().ensure_safe_to_run_script_or_layout();
271    }
272
273    let global = &global;
274
275    // Step 8: Prepare to run script with relevant settings.
276    run_a_script::<D, R>(global, move || {
277        let actual_callback = || {
278            let old_realm = unsafe { EnterRealm(cx, callback.callback()) };
279            let result = f(cx);
280            unsafe {
281                LeaveRealm(cx, old_realm);
282            }
283            if handling == ExceptionHandling::Report {
284                let mut realm = enter_auto_realm::<D>(cx, &**global);
285                let cx = &mut realm.current_realm();
286
287                let in_realm_proof = cx.into();
288                let in_realm = InRealm::Already(&in_realm_proof);
289
290                <D as DomHelpers<D>>::report_pending_exception(
291                    cx.into(),
292                    in_realm,
293                    CanGc::from_cx(cx),
294                );
295            }
296            result
297        };
298        if let Some(incumbent_global) = callback.incumbent() {
299            // Step 9: Prepare to run a callback with stored settings.
300            run_a_callback::<D, R>(incumbent_global, actual_callback)
301        } else {
302            actual_callback()
303        }
304    }) // Step 14.2: Clean up after running script with relevant settings.
305}