script_bindings/permanent_root.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::ffi::CStr;
6
7use js::context::JSContext;
8use js::jsapi::{Heap, JSObject, RemoveRawValueRoot};
9use js::jsval::{JSVal, ObjectValue};
10use js::rust::Runtime;
11use js::rust::wrappers2::AddRawValueRoot;
12
13/// A manual GC root that will exist until this PermanentRoot is dropped.
14#[derive(JSTraceable)] // TODO: remove this once this is no longer part of Promise and callback objects.
15#[derive(Default, MallocSizeOf)]
16#[cfg_attr(crown, crown::unrooted_must_root_lint::allow_unrooted_interior)]
17/// Maintains a GC root for the contained value until this object is dropped.
18///
19/// # Safety
20/// The root (and the contained value) is only valid as long as this value
21/// is never moved after it is initialized. It should only be used inside
22/// of a container like Box or Rc and never extracted from it.
23pub struct PermanentRoot(#[ignore_malloc_size_of = "mozjs value"] Heap<JSVal>);
24
25impl PermanentRoot {
26 /// Add a GC root for the provided JS object.
27 ///
28 /// # Safety
29 /// - This method must only be called on a `PermanentRoot` that will not
30 /// move for the remainder of its lifetime (e.g. inside of Box, Rc, etc.)
31 /// - This must only be called once per instance of `PermanentRoot`
32 #[expect(unsafe_code)]
33 pub unsafe fn init(&self, cx: &JSContext, object: *mut JSObject, name: &'static CStr) {
34 self.0.set(ObjectValue(object));
35 unsafe {
36 assert!(AddRawValueRoot(cx, self.0.get_unsafe(), name.as_ptr(),));
37 }
38 }
39}
40
41impl Drop for PermanentRoot {
42 #[expect(unsafe_code)]
43 fn drop(&mut self) {
44 let js_root = self.0.get();
45 if js_root.is_undefined() {
46 return;
47 }
48 let object = js_root.to_object();
49 assert!(!object.is_null());
50 if let Some(cx) = Runtime::get() {
51 unsafe {
52 RemoveRawValueRoot(cx.as_ptr(), self.0.get_unsafe());
53 }
54 }
55 }
56}