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