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