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
5use std::cell::Cell;
6
7use js::jsapi::{AddAssociatedMemory, Heap, JSObject, MemoryUse, RemoveAssociatedMemory};
8use js::rust::HandleObject;
9use malloc_size_of_derive::MallocSizeOf;
10
11use crate::interfaces::GlobalScopeHelpers;
12use crate::iterable::{Iterable, IterableIterator};
13use crate::realms::InRealm;
14use crate::root::{Dom, DomRoot, Root};
15use crate::script_runtime::{CanGc, JSContext};
16use crate::{DomTypes, JSTraceable};
17
18pub trait AssociatedMemorySize: Default {
19    fn size(&self) -> usize;
20}
21
22impl AssociatedMemorySize for () {
23    fn size(&self) -> usize {
24        0
25    }
26}
27
28#[derive(Default, MallocSizeOf)]
29pub struct AssociatedMemory(Cell<usize>);
30
31impl AssociatedMemorySize for AssociatedMemory {
32    fn size(&self) -> usize {
33        self.0.get()
34    }
35}
36
37/// A struct to store a reference to the reflector of a DOM object.
38#[derive(MallocSizeOf)]
39#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
40// If you're renaming or moving this field, update the path in plugins::reflector as well
41pub struct Reflector<T = ()> {
42    #[ignore_malloc_size_of = "defined and measured in rust-mozjs"]
43    object: Heap<*mut JSObject>,
44    /// Associated memory size (of rust side). Used for memory reporting to SM.
45    size: T,
46}
47
48unsafe impl<T> js::gc::Traceable for Reflector<T> {
49    unsafe fn trace(&self, _: *mut js::jsapi::JSTracer) {}
50}
51
52impl<T> PartialEq for Reflector<T> {
53    fn eq(&self, other: &Reflector<T>) -> bool {
54        self.object.get() == other.object.get()
55    }
56}
57
58impl<T> Reflector<T> {
59    /// Get the reflector.
60    #[inline]
61    pub fn get_jsobject(&self) -> HandleObject<'_> {
62        // We're rooted, so it's safe to hand out a handle to object in Heap
63        unsafe { HandleObject::from_raw(self.object.handle()) }
64    }
65
66    /// Initialize the reflector. (May be called only once.)
67    ///
68    /// # Safety
69    ///
70    /// The provided [`JSObject`] pointer must point to a valid [`JSObject`].
71    unsafe fn set_jsobject(&self, object: *mut JSObject) {
72        assert!(self.object.get().is_null());
73        assert!(!object.is_null());
74        self.object.set(object);
75    }
76
77    /// Return a pointer to the memory location at which the JS reflector
78    /// object is stored. Used to root the reflector, as
79    /// required by the JSAPI rooting APIs.
80    pub fn rootable(&self) -> &Heap<*mut JSObject> {
81        &self.object
82    }
83}
84
85impl<T: AssociatedMemorySize> Reflector<T> {
86    /// Create an uninitialized `Reflector`.
87    // These are used by the bindings and do not need `default()` functions.
88    #[expect(clippy::new_without_default)]
89    pub fn new() -> Reflector<T> {
90        Reflector {
91            object: Heap::default(),
92            size: T::default(),
93        }
94    }
95
96    pub fn rust_size<D>(&self, _: &D) -> usize {
97        size_of::<D>() + size_of::<Box<D>>() + self.size.size()
98    }
99
100    /// This function should be called from Drop of the DOM objects
101    pub fn drop_memory<D>(&self, d: &D) {
102        unsafe {
103            RemoveAssociatedMemory(self.object.get(), self.rust_size(d), MemoryUse::DOMBinding);
104        }
105    }
106}
107
108impl Reflector<AssociatedMemory> {
109    /// Update the associated memory size.
110    pub fn update_memory_size<D>(&self, d: &D, new_size: usize) {
111        if self.size.size() == new_size {
112            return;
113        }
114        unsafe {
115            RemoveAssociatedMemory(self.object.get(), self.rust_size(d), MemoryUse::DOMBinding);
116            self.size.0.set(new_size);
117            AddAssociatedMemory(self.object.get(), self.rust_size(d), MemoryUse::DOMBinding);
118        }
119    }
120}
121
122/// A trait to provide access to the `Reflector` for a DOM object.
123pub trait DomObject: js::gc::Traceable + 'static {
124    /// Returns the receiver's reflector.
125    fn reflector(&self) -> &Reflector;
126}
127
128impl DomObject for Reflector<()> {
129    fn reflector(&self) -> &Reflector<()> {
130        self
131    }
132}
133
134impl DomObject for Reflector<AssociatedMemory> {
135    fn reflector(&self) -> &Reflector<()> {
136        // SAFETY: This is safe because we are only shortening the size of struct.
137        unsafe { std::mem::transmute(self) }
138    }
139}
140
141/// A trait to initialize the `Reflector` for a DOM object.
142pub trait MutDomObject: DomObject {
143    /// Initializes the Reflector
144    ///
145    /// # Safety
146    ///
147    /// The provided [`JSObject`] pointer must point to a valid [`JSObject`].
148    unsafe fn init_reflector<D>(&self, obj: *mut JSObject);
149}
150
151impl MutDomObject for Reflector<()> {
152    unsafe fn init_reflector<D>(&self, obj: *mut JSObject) {
153        unsafe {
154            js::jsapi::AddAssociatedMemory(
155                obj,
156                size_of::<D>() + size_of::<Box<D>>(),
157                MemoryUse::DOMBinding,
158            );
159            self.set_jsobject(obj);
160        }
161    }
162}
163
164impl MutDomObject for Reflector<AssociatedMemory> {
165    unsafe fn init_reflector<D>(&self, obj: *mut JSObject) {
166        unsafe {
167            js::jsapi::AddAssociatedMemory(
168                obj,
169                size_of::<D>() + size_of::<Box<D>>(),
170                MemoryUse::DOMBinding,
171            );
172            self.set_jsobject(obj);
173        }
174    }
175}
176
177pub trait DomGlobalGeneric<D: DomTypes>: DomObject {
178    /// Returns the [`GlobalScope`] of the realm that the [`DomObject`] was created in.  If this
179    /// object is a `Node`, this will be different from it's owning `Document` if adopted by. For
180    /// `Node`s it's almost always better to use `NodeTraits::owning_global`.
181    fn global_(&self, realm: InRealm) -> DomRoot<D::GlobalScope>
182    where
183        Self: Sized,
184    {
185        D::GlobalScope::from_reflector(self, realm)
186    }
187}
188
189impl<D: DomTypes, T: DomObject> DomGlobalGeneric<D> for T {}
190
191/// A trait to provide a function pointer to wrap function for DOM objects.
192pub trait DomObjectWrap<D: DomTypes>: Sized + DomObject + DomGlobalGeneric<D> {
193    /// Function pointer to the general wrap function type
194    #[expect(clippy::type_complexity)]
195    const WRAP: unsafe fn(
196        JSContext,
197        &D::GlobalScope,
198        Option<HandleObject>,
199        Box<Self>,
200        CanGc,
201    ) -> Root<Dom<Self>>;
202}
203
204/// A trait to provide a function pointer to wrap function for
205/// DOM iterator interfaces.
206pub trait DomObjectIteratorWrap<D: DomTypes>: DomObjectWrap<D> + JSTraceable + Iterable {
207    /// Function pointer to the wrap function for `IterableIterator<T>`
208    #[expect(clippy::type_complexity)]
209    const ITER_WRAP: unsafe fn(
210        JSContext,
211        &D::GlobalScope,
212        Option<HandleObject>,
213        Box<IterableIterator<D, Self>>,
214        CanGc,
215    ) -> Root<Dom<IterableIterator<D, Self>>>;
216}