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