Skip to main content

script_bindings/
reflector.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#![cfg_attr(crown, allow(crown::jscontext_first_arg))]
6
7use std::cell::Cell;
8use std::rc::Rc;
9
10use js::context::JSContext;
11use js::jsapi::{AddAssociatedMemory, Heap, JSObject, MemoryUse, RemoveAssociatedMemory};
12use js::rust::HandleObject;
13use malloc_size_of_derive::MallocSizeOf;
14
15use crate::codegen::PrototypeList;
16use crate::conversions::DerivedFrom;
17use crate::interfaces::GlobalScopeHelpers;
18use crate::iterable::{Iterable, IterableIterator};
19use crate::realms::enter_auto_realm;
20use crate::root::{Dom, DomRoot, Root};
21use crate::{DomTypes, JSTraceable};
22
23pub trait AssociatedMemorySize: Default {
24    fn size(&self) -> usize;
25}
26
27impl AssociatedMemorySize for () {
28    fn size(&self) -> usize {
29        0
30    }
31}
32
33#[derive(Default, MallocSizeOf)]
34pub struct AssociatedMemory(Cell<usize>);
35
36impl AssociatedMemorySize for AssociatedMemory {
37    fn size(&self) -> usize {
38        self.0.get()
39    }
40}
41
42/// A struct to store a reference to the reflector of a DOM object.
43#[derive(MallocSizeOf)]
44#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
45// If you're renaming or moving this field, update the path in plugins::reflector as well
46pub struct Reflector<T = ()> {
47    #[ignore_malloc_size_of = "defined and measured in rust-mozjs"]
48    object: Heap<*mut JSObject>,
49    /// Associated memory size (of rust side). Used for memory reporting to SM.
50    size: T,
51    /// Cached prototype ID for fast type checks.
52    proto_id: u16,
53}
54
55unsafe impl<T> js::gc::Traceable for Reflector<T> {
56    unsafe fn trace(&self, tracer: *mut js::jsapi::JSTracer) {
57        unsafe {
58            self.object.trace(tracer);
59        }
60    }
61}
62
63impl<T> PartialEq for Reflector<T> {
64    fn eq(&self, other: &Reflector<T>) -> bool {
65        self.object.get() == other.object.get()
66    }
67}
68
69impl<T> Reflector<T> {
70    /// Get the reflector.
71    #[inline]
72    pub fn get_jsobject(&self) -> HandleObject<'_> {
73        // We're rooted, so it's safe to hand out a handle to object in Heap
74        unsafe { HandleObject::from_raw(self.object.handle()) }
75    }
76
77    /// Get the cached prototype ID.
78    #[inline]
79    pub fn proto_id(&self) -> u16 {
80        self.proto_id
81    }
82
83    /// Initialize the reflector. (May be called only once.)
84    ///
85    /// # Safety
86    ///
87    /// The provided [`JSObject`] pointer must point to a valid [`JSObject`].
88    unsafe fn set_jsobject(&self, object: *mut JSObject) {
89        assert!(self.object.get().is_null());
90        assert!(!object.is_null());
91        self.object.set(object);
92    }
93
94    /// Return a pointer to the memory location at which the JS reflector
95    /// object is stored. Used to root the reflector, as
96    /// required by the JSAPI rooting APIs.
97    pub fn rootable(&self) -> &Heap<*mut JSObject> {
98        &self.object
99    }
100}
101
102impl<T: AssociatedMemorySize> Reflector<T> {
103    /// Create an uninitialized `Reflector`.
104    // These are used by the bindings and do not need `default()` functions.
105    #[expect(clippy::new_without_default)]
106    pub fn new() -> Reflector<T> {
107        Reflector {
108            object: Heap::default(),
109            proto_id: u16::MAX,
110            size: T::default(),
111        }
112    }
113
114    pub fn rust_size<D>(&self, _: &D) -> usize {
115        size_of::<D>() + size_of::<Box<D>>() + self.size.size()
116    }
117
118    /// This function should be called from finalize of the DOM objects
119    pub fn drop_memory<D>(&self, d: &D) {
120        unsafe {
121            RemoveAssociatedMemory(self.object.get(), self.rust_size(d), MemoryUse::DOMBinding);
122        }
123    }
124}
125
126impl Reflector<AssociatedMemory> {
127    /// Update the associated memory size.
128    pub fn update_memory_size<D>(&self, d: &D, new_size: usize) {
129        if self.size.size() == new_size {
130            return;
131        }
132        unsafe {
133            RemoveAssociatedMemory(self.object.get(), self.rust_size(d), MemoryUse::DOMBinding);
134            self.size.0.set(new_size);
135            AddAssociatedMemory(self.object.get(), self.rust_size(d), MemoryUse::DOMBinding);
136        }
137    }
138}
139
140pub trait HasPrototype {
141    const PROTOTYPE_ID: PrototypeList::ID;
142}
143
144pub trait PrototypeInitializer {
145    fn set_proto_id(&mut self, id: PrototypeList::ID);
146}
147
148impl<T: AssociatedMemorySize> PrototypeInitializer for Reflector<T> {
149    #[inline]
150    fn set_proto_id(&mut self, id: PrototypeList::ID) {
151        self.proto_id = id as u16;
152    }
153}
154
155/// A trait to provide access to the `Reflector` for a DOM object.
156pub trait DomObject: js::gc::Traceable + 'static {
157    type ReflectorType: AssociatedMemorySize;
158    /// Returns the receiver's reflector.
159    fn reflector(&self) -> &Reflector<Self::ReflectorType>;
160}
161
162impl DomObject for Reflector<()> {
163    type ReflectorType = ();
164
165    fn reflector(&self) -> &Reflector<Self::ReflectorType> {
166        self
167    }
168}
169
170impl DomObject for Reflector<AssociatedMemory> {
171    type ReflectorType = AssociatedMemory;
172
173    fn reflector(&self) -> &Reflector<Self::ReflectorType> {
174        self
175    }
176}
177
178/// A trait to initialize the `Reflector` for a DOM object.
179pub trait MutDomObject: DomObject {
180    /// Initializes the Reflector
181    ///
182    /// # Safety
183    ///
184    /// The provided [`JSObject`] pointer must point to a valid [`JSObject`].
185    /// The provided [`JSObject`] pointer must not be allocated in the nursery.
186    unsafe fn init_reflector<D>(&self, obj: *mut JSObject);
187
188    /// Initializes the Reflector without recording any associated memory usage.
189    ///
190    /// # Safety
191    ///
192    /// The provided [`JSObject`] pointer must point to a valid [`JSObject`].
193    unsafe fn init_reflector_without_associated_memory(&self, obj: *mut JSObject);
194}
195
196impl MutDomObject for Reflector<()> {
197    unsafe fn init_reflector<D>(&self, obj: *mut JSObject) {
198        unsafe {
199            js::jsapi::AddAssociatedMemory(
200                obj,
201                size_of::<D>() + size_of::<Box<D>>(),
202                MemoryUse::DOMBinding,
203            );
204            self.init_reflector_without_associated_memory(obj);
205        }
206    }
207
208    unsafe fn init_reflector_without_associated_memory(&self, obj: *mut JSObject) {
209        unsafe {
210            self.set_jsobject(obj);
211        }
212    }
213}
214
215impl MutDomObject for Reflector<AssociatedMemory> {
216    unsafe fn init_reflector<D>(&self, obj: *mut JSObject) {
217        unsafe {
218            js::jsapi::AddAssociatedMemory(
219                obj,
220                size_of::<D>() + size_of::<Box<D>>(),
221                MemoryUse::DOMBinding,
222            );
223            self.init_reflector_without_associated_memory(obj);
224        }
225    }
226
227    unsafe fn init_reflector_without_associated_memory(&self, obj: *mut JSObject) {
228        unsafe {
229            self.set_jsobject(obj);
230        }
231    }
232}
233
234pub trait DomGlobalGeneric<D: DomTypes>: DomObject {
235    /// Returns the [`GlobalScope`] of the realm that the [`DomObject`] was created in.  If this
236    /// object is a `Node`, this will be different from it's owning `Document` if adopted by. For
237    /// `Node`s it's almost always better to use `NodeTraits::owning_global`.
238    fn global_from_reflector(&self) -> DomRoot<D::GlobalScope>
239    where
240        Self: Sized,
241    {
242        // SAFETY: We only use this `cx` to enter a realm. That does not
243        // incur a GC and hence is safe to perform. We do not want to
244        // pass a `cx` as parameter to this function, as this used in
245        // loads of places. At the same time, it also isn't necessary in
246        // nearly all cases to enter realm, since we are already in the
247        // correct realm.
248        //
249        // However, there are cases where it is difficult to ensure that
250        // we are in the correct realm. Hence we always enter a realm here
251        // even if that is unnecessary at times.
252        let cx = unsafe { JSContext::get_from_thread() };
253        let cx = &mut cx.expect("JS runtime has shut down");
254        let _realm = enter_auto_realm::<D>(cx, self);
255        D::GlobalScope::from_reflector(self)
256    }
257}
258
259impl<D: DomTypes, T: DomObject> DomGlobalGeneric<D> for T {}
260
261/// A trait to provide a function pointer to wrap function for DOM objects.
262pub trait DomObjectWrap<D: DomTypes>: Sized + DomObject + DomGlobalGeneric<D> {
263    /// Function pointer to the general wrap function type
264    #[expect(clippy::type_complexity)]
265    const WRAP: unsafe fn(
266        &mut JSContext,
267        &D::GlobalScope,
268        Option<HandleObject>,
269        Box<Self>,
270    ) -> Root<Dom<Self>>;
271}
272
273/// A trait to provide a function pointer to wrap function for DOM objects.
274pub trait WeakReferenceableDomObjectWrap<D: DomTypes>:
275    Sized + DomObject + DomGlobalGeneric<D>
276{
277    /// Function pointer to the general wrap function type
278    #[expect(clippy::type_complexity)]
279    const WRAP: unsafe fn(
280        &mut JSContext,
281        &D::GlobalScope,
282        Option<HandleObject>,
283        Rc<Self>,
284    ) -> Root<Dom<Self>>;
285}
286
287/// A trait to provide a function pointer to wrap function for
288/// DOM iterator interfaces.
289pub trait DomObjectIteratorWrap<D: DomTypes>: DomObjectWrap<D> + JSTraceable + Iterable {
290    /// Function pointer to the wrap function for `IterableIterator<T>`
291    #[expect(clippy::type_complexity)]
292    const ITER_WRAP: unsafe fn(
293        &mut JSContext,
294        &D::GlobalScope,
295        Option<HandleObject>,
296        Box<IterableIterator<D, Self>>,
297    ) -> Root<Dom<IterableIterator<D, Self>>>;
298}
299
300/// Create the reflector for a new DOM object and yield ownership to the
301/// reflector.
302pub fn reflect_dom_object<D, T, U>(cx: &mut JSContext, obj: Box<T>, global: &U) -> DomRoot<T>
303where
304    D: DomTypes,
305    T: DomObject + DomObjectWrap<D>,
306    U: DerivedFrom<D::GlobalScope>,
307{
308    let global_scope = global.upcast();
309    unsafe { T::WRAP(cx, global_scope, None, obj) }
310}
311
312pub fn reflect_dom_object_with_proto<D, T, U>(
313    cx: &mut JSContext,
314    obj: Box<T>,
315    global: &U,
316    proto: Option<HandleObject>,
317) -> DomRoot<T>
318where
319    D: DomTypes,
320    T: DomObject + DomObjectWrap<D>,
321    U: DerivedFrom<D::GlobalScope>,
322{
323    let global_scope = global.upcast();
324    unsafe { T::WRAP(cx, global_scope, proto, obj) }
325}
326
327/// Create the reflector for a new DOM object and yield ownership to the
328/// reflector.
329pub fn reflect_weak_referenceable_dom_object<D, T, U>(
330    cx: &mut JSContext,
331    obj: Rc<T>,
332    global: &U,
333) -> DomRoot<T>
334where
335    D: DomTypes,
336    T: DomObject + WeakReferenceableDomObjectWrap<D>,
337    U: DerivedFrom<D::GlobalScope>,
338{
339    let global_scope = global.upcast();
340    unsafe { T::WRAP(cx, global_scope, None, obj) }
341}
342
343pub fn reflect_weak_referenceable_dom_object_with_proto<D, T, U>(
344    cx: &mut JSContext,
345    obj: Rc<T>,
346    global: &U,
347    proto: Option<HandleObject>,
348) -> DomRoot<T>
349where
350    D: DomTypes,
351    T: DomObject + WeakReferenceableDomObjectWrap<D>,
352    U: DerivedFrom<D::GlobalScope>,
353{
354    let global_scope = global.upcast();
355    unsafe { T::WRAP(cx, global_scope, proto, obj) }
356}
357
358type WrapFn<D, AbstractType> = unsafe fn(
359    &mut JSContext,
360    &<D as DomTypes>::GlobalScope,
361    Option<HandleObject>,
362    Box<AbstractType>,
363) -> DomRoot<AbstractType>;
364
365/// Create the reflector for a new DOM object and yield ownership to the
366/// reflector.
367pub fn reflect_dom_object_with_proto_and_wrap<D, AbstractType, GlobalType>(
368    cx: &mut JSContext,
369    obj: Box<AbstractType>,
370    global: &GlobalType,
371    proto: Option<HandleObject>,
372    wrap: WrapFn<D, AbstractType>,
373) -> DomRoot<AbstractType>
374where
375    D: DomTypes,
376    AbstractType: DomObject,
377    GlobalType: DerivedFrom<D::GlobalScope>,
378    Box<AbstractType>: From<Box<AbstractType>>,
379    DomRoot<AbstractType>: From<DomRoot<AbstractType>>,
380{
381    let global_scope = global.upcast();
382    unsafe { wrap(cx, global_scope, proto, obj) }
383}
384
385/// Create the reflector for a new DOM object and yield ownership to the
386/// reflector.
387pub fn reflect_dom_object_with_wrap<D, AbstractType, GlobalType>(
388    cx: &mut JSContext,
389    obj: Box<AbstractType>,
390    global: &GlobalType,
391    wrap: WrapFn<D, AbstractType>,
392) -> DomRoot<AbstractType>
393where
394    D: DomTypes,
395    AbstractType: DomObject,
396    GlobalType: DerivedFrom<D::GlobalScope>,
397    Box<AbstractType>: From<Box<AbstractType>>,
398    DomRoot<AbstractType>: From<DomRoot<AbstractType>>,
399{
400    let global_scope = global.upcast();
401    unsafe { wrap(cx, global_scope, None, obj) }
402}
403
404type WrapFnRc<D, AbstractType> = unsafe fn(
405    &mut JSContext,
406    &<D as DomTypes>::GlobalScope,
407    Option<HandleObject>,
408    Rc<AbstractType>,
409) -> DomRoot<AbstractType>;
410
411/// Create the reflector for a new DOM object and yield ownership to the
412/// reflector.
413pub fn reflect_weak_referenceable_dom_object_with_wrap<D, AbstractType, GlobalType>(
414    cx: &mut JSContext,
415    obj: Rc<AbstractType>,
416    global: &GlobalType,
417    wrap: WrapFnRc<D, AbstractType>,
418) -> DomRoot<AbstractType>
419where
420    D: DomTypes,
421    AbstractType: DomObject,
422    GlobalType: DerivedFrom<D::GlobalScope>,
423    Rc<AbstractType>: From<Rc<AbstractType>>,
424    DomRoot<AbstractType>: From<DomRoot<AbstractType>>,
425{
426    let global_scope = global.upcast();
427    unsafe { wrap(cx, global_scope, None, obj) }
428}