/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use std::cell::UnsafeCell; use std::hash::{Hash, Hasher}; use std::ops::Deref; use std::rc::Rc; use std::{fmt, mem, ptr}; use js::context::NoGC; use js::gc::{Handle, Traceable as JSTraceable}; use js::jsapi::{Heap, JSObject, JSTracer}; use js::rust::GCMethods; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use crate::assert::assert_in_script; use crate::conversions::DerivedFrom; use crate::dom::UnrootedDom; use crate::inheritance::Castable; use crate::reflector::{DomObject, MutDomObject}; use crate::trace::trace_reflector; /// A rooted value. #[cfg_attr(crown, crown::unrooted_must_root_lint::allow_unrooted_interior)] pub struct Root { /// The value to root. value: T, /// List that ensures correct dynamic root ordering root_list: *const RootCollection, } impl Root where T: StableTraceObject + 'static, { /// Create a new stack-bounded root for the provided value. /// It gives out references which cannot outlive this new `Root`. /// /// # Safety /// It must not outlive its associated `RootCollection`. pub unsafe fn new(value: T) -> Self { unsafe fn add_to_root_list(object: *const dyn JSTraceable) -> *const RootCollection { assert_in_script(); STACK_ROOTS.with(|root_list| { unsafe { root_list.root(object) }; root_list as *const _ }) } let root_list = unsafe { add_to_root_list(value.stable_trace_object()) }; Root { value, root_list } } } /// `StableTraceObject` represents values that can be rooted through a stable address that will /// not change for their whole lifetime. /// It is an unsafe trait that requires implementors to ensure certain safety guarantees. /// /// # Safety /// /// Implementors of this trait must ensure that the `trace` method correctly accounts for all /// owned and referenced objects, so that the garbage collector can accurately determine which /// objects are still in use. Failing to adhere to this contract may result in undefined behavior, /// such as use-after-free errors. pub unsafe trait StableTraceObject { /// Returns a stable trace object which address won't change for the whole /// lifetime of the value. fn stable_trace_object(&self) -> *const dyn JSTraceable; } unsafe impl StableTraceObject for Dom where T: DomObject, { fn stable_trace_object(&self) -> *const dyn JSTraceable { self.reflector() } } unsafe impl StableTraceObject for MaybeUnreflectedDom where T: DomObject, { fn stable_trace_object(&self) -> *const dyn JSTraceable { // The trace hook for MaybeUnreflectedDom can be called before the // reflector has been initialized in the contained object. Since we still // want to treat the fields of the object as reachable, we explicitly trace // the object's fields in that case. Otherwise, we only need to trace the // reflector so the object's trace hook will be invoked automatically. #[repr(transparent)] struct MaybeUnreflectedStackRoot(T); unsafe impl JSTraceable for MaybeUnreflectedStackRoot where T: DomObject, { unsafe fn trace(&self, tracer: *mut JSTracer) { if self.0.reflector().get_jsobject().is_null() { unsafe { self.0.trace(tracer) }; } else { unsafe { self.0.reflector().trace(tracer) } } } } unsafe { &*(self.ptr.as_ptr() as *const T as *const MaybeUnreflectedStackRoot) } } } impl Deref for Root where T: Deref + StableTraceObject, { type Target = ::Target; fn deref(&self) -> &Self::Target { assert_in_script(); &self.value } } impl Drop for Root where T: StableTraceObject, { fn drop(&mut self) { unsafe { (*self.root_list).unroot(self.value.stable_trace_object()); } } } impl fmt::Debug for Root { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.value.fmt(f) } } impl fmt::Debug for Dom { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) } } /// A traced reference to a DOM object /// /// This type is critical to making garbage collection work with the DOM, /// but it is very dangerous; if garbage collection happens with a `Dom` /// on the stack, the `Dom` can point to freed memory. /// /// This should only be used as a field in other DOM objects. #[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)] #[repr(transparent)] pub struct Dom { ptr: ptr::NonNull, } // Dom is similar to Rc, in that it's not always clear how to avoid double-counting. // For now, we choose not to follow any such pointers. impl MallocSizeOf for Dom { fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { 0 } } /// Compare by pointer address impl PartialEq for Dom { fn eq(&self, other: &Dom) -> bool { self.ptr.as_ptr() == other.ptr.as_ptr() } } /// Compare by pointer address impl<'a, T: DomObject> PartialEq<&'a T> for Dom { fn eq(&self, other: &&'a T) -> bool { *self == Dom::from_ref(*other) } } impl Eq for Dom {} /// Hashes the pointer address impl Hash for Dom { fn hash(&self, state: &mut H) { self.ptr.as_ptr().hash(state) } } impl Clone for Dom { #[inline] fn clone(&self) -> Self { assert_in_script(); Dom { ptr: self.ptr } } } impl Dom { /// Create a `Dom` from a `&T` pub fn from_ref(obj: &T) -> Dom { assert_in_script(); Dom { ptr: ptr::NonNull::from(obj), } } /// Return a rooted version of this DOM object ([`DomRoot`]) suitable for use on the stack. pub fn as_rooted(&self) -> DomRoot { DomRoot::from_ref(self) } /// Return an unrooted version of this DOM object ([`UnrootedDom`]) suitable for use on the /// stack which has the lifetime of the provided [`NoGC`] token. pub fn as_unrooted<'no_gc>(&self, no_gc: &'no_gc NoGC) -> UnrootedDom<'no_gc, T> { UnrootedDom::from_dom(self.clone(), no_gc) } pub fn as_ptr(&self) -> *const T { self.ptr.as_ptr() } } impl Deref for Dom { type Target = T; fn deref(&self) -> &T { assert_in_script(); // We can only have &Dom from a rooted thing, so it's safe to deref // it to &T. unsafe { &*self.ptr.as_ptr() } } } unsafe impl JSTraceable for Dom { unsafe fn trace(&self, tracer: *mut JSTracer) { let trace_info = if cfg!(debug_assertions) { std::any::type_name::() } else { "DOM object on heap" }; unsafe { trace_reflector(tracer, trace_info, (*self.ptr.as_ptr()).reflector()); } } } /// A traced reference to a DOM object that may not be reflected yet. #[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)] pub struct MaybeUnreflectedDom { ptr: ptr::NonNull, } impl MaybeUnreflectedDom where T: DomObject, { /// Create a new MaybeUnreflectedDom value from the given boxed DOM object. pub fn from_box(value: Box) -> Self { Self { ptr: Box::leak(value).into(), } } /// Create a new MaybeUnreflectedDom value from the given RCed DOM object. pub fn from_rc(value: Rc) -> Self { Self { ptr: ptr::NonNull::new(Rc::into_raw(value) as *mut T).unwrap(), } } } impl Root> where T: DomObject, { pub fn as_ptr(&self) -> *const T { self.value.ptr.as_ptr() } } impl Root> where T: MutDomObject, { /// Treat the given JS object as the reflector of this unreflected object. /// /// # Safety /// obj must point to a valid, non-null JS object. pub unsafe fn reflect_with(self, obj: *mut JSObject) -> DomRoot { let ptr = self.as_ptr(); drop(self); let root = DomRoot::from_ref(unsafe { &*ptr }); unsafe { root.init_reflector::(obj) }; root } } /// A rooted reference to a DOM object. pub type DomRoot = Root>; impl DomRoot { /// Cast a DOM object root upwards to one of the interfaces it derives from. pub fn upcast(root: DomRoot) -> DomRoot where U: Castable, T: DerivedFrom, { unsafe { mem::transmute::, DomRoot>(root) } } /// Cast a DOM object root downwards to one of the interfaces it might implement. pub fn downcast(root: DomRoot) -> Option> where U: DerivedFrom, { if root.is::() { Some(unsafe { mem::transmute::, DomRoot>(root) }) } else { None } } } impl DomRoot { /// Generate a new root from a reference pub fn from_ref(unrooted: &T) -> DomRoot { unsafe { DomRoot::new(Dom::from_ref(unrooted)) } } /// Create a traced version of this rooted object. /// /// # Safety /// /// This should never be used to create on-stack values. Instead these values should always /// end up as members of other DOM objects. pub fn as_traced(&self) -> Dom { Dom::from_ref(self) } /// Return an unrooted version of this DOM object ([`UnrootedDom`]) suitable for use on the /// stack which has the lifetime of the provided [`NoGC`] token. pub fn as_unrooted<'no_gc>(&self, no_gc: &'no_gc NoGC) -> UnrootedDom<'no_gc, T> { self.value.as_unrooted(no_gc) } } impl MallocSizeOf for DomRoot where T: DomObject + MallocSizeOf, { fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { 0 } } impl PartialEq for DomRoot where T: DomObject, { fn eq(&self, other: &Self) -> bool { self.value == other.value } } impl Eq for DomRoot {} impl Hash for DomRoot { fn hash(&self, state: &mut H) { self.value.hash(state); } } impl Clone for DomRoot where T: DomObject, { fn clone(&self) -> DomRoot { DomRoot::from_ref(self) } } unsafe impl JSTraceable for DomRoot where T: DomObject, { unsafe fn trace(&self, _: *mut JSTracer) { // Already traced. } } /// A rooting mechanism for reflectors on the stack. /// LIFO is not required. /// /// See also [*Exact Stack Rooting - Storing a GCPointer on the CStack*][cstack]. /// /// [cstack]: https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Internals/GC/Exact_Stack_Rooting pub struct RootCollection { roots: UnsafeCell>, } impl RootCollection { /// Create an empty collection of roots #[expect(clippy::new_without_default)] pub const fn new() -> RootCollection { RootCollection { roots: UnsafeCell::new(vec![]), } } /// Starts tracking a trace object. unsafe fn root(&self, object: *const dyn JSTraceable) { assert_in_script(); unsafe { (*self.roots.get()).push(object) }; } /// Stops tracking a trace object, asserting if it isn't found. unsafe fn unroot(&self, object: *const dyn JSTraceable) { assert_in_script(); let roots = unsafe { &mut *self.roots.get() }; match roots .iter() .rposition(|r| std::ptr::addr_eq(*r as *const (), object as *const ())) { Some(idx) => { // Partial inlining of `Vec::swap_remove` to avoid having to read and return the value since // we don't care about it, doing less work in our case. // SAFETY: the copy source and destination are derived from valid positions in the vector. unsafe { let len = roots.len() - 1; if len != idx { let base_ptr = roots.as_mut_ptr(); ptr::copy_nonoverlapping(base_ptr.add(len), base_ptr.add(idx), 1); } roots.set_len(len); } }, None => panic!("Can't remove a root that was never rooted!"), } } } thread_local!(pub static STACK_ROOTS: RootCollection = const { RootCollection::new() }); /// SM Callback that traces the rooted reflectors /// /// # Safety /// tracer must point to a valid, non-null JS tracer object. pub unsafe fn trace_roots(tracer: *mut JSTracer) { trace!("tracing stack roots"); STACK_ROOTS.with(|collection| { let collection = unsafe { &*collection.roots.get() }; for root in collection { unsafe { (**root).trace(tracer); } } }); } /// Get a slice of references to DOM objects. pub trait DomSlice where T: JSTraceable + DomObject, { /// Returns the slice of `T` references. fn r(&self) -> &[&T]; } impl DomSlice for [Dom] where T: JSTraceable + DomObject, { #[inline] fn r(&self) -> &[&T] { let _ = mem::transmute::, &T>; unsafe { &*(self as *const [Dom] as *const [&T]) } } } /// Returns a handle to a Heap member of a reflected DOM object. /// The provided callback acts as a projection of the rooted-ness of /// the provided DOM object; it must return a reference to a Heap /// member of the DOM object. pub fn rooted_heap_handle<'a, T: DomObject, U: GCMethods + Copy>( object: &'a T, f: impl Fn(&'a T) -> &'a Heap, ) -> Handle<'a, U> { // SAFETY: Heap::handle is safe to call when the Heap is a member // of a rooted object. Our safety invariants for DOM objects // ensure that a &T is obtained via a root of T. unsafe { Handle::from_raw(f(object).handle()) } }