Skip to main content

script_bindings/
finalize.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//! Generic finalizer implementations for DOM binding implementations.
6
7use std::any::type_name;
8use std::ptr;
9use std::rc::Rc;
10
11use js::jsapi::JSObject;
12use js::rust::GCMethods;
13
14use crate::DomObject;
15use crate::codegen::PrototypeList::PROTO_OR_IFACE_LENGTH;
16use crate::utils::{ProtoOrIfaceArray, get_proto_or_iface_array};
17use crate::weakref::WeakReferenceable;
18
19/// Drop the resources held by reserved slots of a global object
20unsafe fn do_finalize_global(obj: *mut JSObject) {
21    unsafe {
22        let protolist = get_proto_or_iface_array(obj);
23        let list = (*protolist).as_mut_ptr();
24        for idx in 0..PROTO_OR_IFACE_LENGTH as isize {
25            let entry = list.offset(idx);
26            let value = *entry;
27            <*mut JSObject>::post_barrier(entry, value, ptr::null_mut());
28        }
29        let _: Box<ProtoOrIfaceArray> = Box::from_raw(protolist);
30    }
31}
32
33/// # Safety
34/// `this` must point to a valid, non-null instance of T.
35pub(crate) unsafe fn finalize_common<T: DomObject>(this: *const T) {
36    if !this.is_null() {
37        // The pointer can be null if the object is the unforgeable holder of that interface.
38        let this = unsafe { Box::from_raw(this as *mut T) };
39        this.reflector().drop_memory(&*this);
40    }
41    debug!("{} finalize: {:p}", type_name::<T>(), this);
42}
43
44/// # Safety
45/// `obj` must point to a valid, non-null JS object.
46/// `this` must point to a valid, non-null instance of T.
47pub(crate) unsafe fn finalize_global<T: DomObject>(obj: *mut JSObject, this: *const T) {
48    unsafe {
49        do_finalize_global(obj);
50        finalize_common::<T>(this);
51    }
52}
53
54/// # Safety
55/// `this` must point to a Rced valid, non-null instance of T.
56pub(crate) unsafe fn finalize_weak_referenceable<T: WeakReferenceable>(this: *const T) {
57    if !this.is_null() {
58        // The pointer can be null if the object is the unforgeable holder of that interface.
59        let this = unsafe { Rc::from_raw(this) };
60        this.reflector().drop_memory(&*this);
61    }
62    debug!("{} finalize: {:p}", type_name::<T>(), this);
63}