Skip to main content

godot_core/obj/
base.rs

1/*
2 * Copyright (c) godot-rust; Bromeon and contributors.
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
6 */
7
8#[cfg(safeguards_balanced)] #[cfg_attr(published_docs, doc(cfg(safeguards_balanced)))]
9use std::cell::Cell;
10use std::cell::RefCell;
11use std::collections::HashMap;
12use std::collections::hash_map::Entry;
13use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
14use std::mem::ManuallyDrop;
15#[cfg(safeguards_balanced)] #[cfg_attr(published_docs, doc(cfg(safeguards_balanced)))]
16use std::rc::Rc;
17
18use crate::builtin::Callable;
19use crate::obj::{Gd, GodotClass, InstanceId, PassiveGd, bounds};
20use crate::{classes, sys};
21
22thread_local! {
23    /// Extra strong references for each instance ID, needed for [`Base::to_init_gd()`].
24    ///
25    /// At the moment, all Godot objects must be accessed from the main thread, because their deferred destruction (`Drop`) runs on the
26    /// main thread, too. This may be relaxed in the future, and a `sys::Global` could be used instead of a `thread_local!`.
27    static PENDING_STRONG_REFS: RefCell<HashMap<InstanceId, Gd<classes::RefCounted>>> = RefCell::new(HashMap::new());
28}
29
30/// Represents the initialization state of a `Base<T>` object.
31#[cfg(safeguards_balanced)] // TODO(v0.5 or v0.6): relax to strict state, once people are used to checks.
32#[derive(Debug, Copy, Clone, PartialEq, Eq)]
33enum InitState {
34    /// Object is being constructed (inside `I*::init()` or `Gd::from_init_fn()`).
35    ObjectConstructing,
36    /// Object construction is complete.
37    ObjectInitialized,
38    /// `ScriptInstance` context - always considered initialized (bypasses lifecycle checks).
39    Script,
40}
41
42#[cfg(safeguards_balanced)] #[cfg_attr(published_docs, doc(cfg(safeguards_balanced)))]
43macro_rules! base_from_obj {
44    ($obj:expr_2021, $state:expr_2021) => {
45        Base::from_obj($obj, $state)
46    };
47}
48
49#[cfg(not(safeguards_balanced))] #[cfg_attr(published_docs, doc(cfg(not(safeguards_balanced))))]
50macro_rules! base_from_obj {
51    ($obj:expr, $state:expr) => {
52        Base::from_obj($obj)
53    };
54}
55
56// ----------------------------------------------------------------------------------------------------------------------------------------------
57
58/// Restricted version of `Gd`, to hold the base instance inside a user's `GodotClass`.
59///
60/// Behaves similarly to [`Gd`][crate::obj::Gd], but is more constrained. Cannot be constructed by the user.
61pub struct Base<T: GodotClass> {
62    // Like `Gd`, it's theoretically possible that Base is destroyed while there are still other Gd pointers to the underlying object. This is
63    // safe, may however lead to unintended behavior. The base_test.rs file checks some of these scenarios.
64
65    // Internal smart pointer is never dropped. It thus acts like a weak pointer and is needed to break reference cycles between Gd<T>
66    // and the user instance owned by InstanceStorage.
67    //
68    // There is no data apart from the opaque bytes, so no memory or resources to deallocate.
69    // When triggered by Godot/GDScript, the destruction order is as follows:
70    // 1.    Most-derived Godot class (C++)
71    //      ...
72    // 2.  RefCounted (C++)
73    // 3. Object (C++) -- this triggers InstanceStorage destruction
74    // 4.   Base<T>
75    // 5.  User struct (GodotClass implementation)
76    // 6. InstanceStorage
77    //
78    // When triggered by Rust (Gd::drop on last strong ref), it's as follows:
79    // 1.   Gd<T>  -- triggers InstanceStorage destruction
80    // 2.
81    obj: ManuallyDrop<Gd<T>>,
82
83    /// Tracks the initialization state of this `Base<T>` in Debug mode.
84    ///
85    /// Rc allows to "copy-construct" the base from an existing one, while still affecting the user-instance through the original `Base<T>`.
86    #[cfg(safeguards_balanced)] #[cfg_attr(published_docs, doc(cfg(safeguards_balanced)))]
87    init_state: Rc<Cell<InitState>>,
88}
89
90impl<T: GodotClass> Base<T> {
91    /// "Copy constructor": allows to share a `Base<T>` weak pointer.
92    ///
93    /// The return value is a weak pointer, so it will not keep the instance alive.
94    ///
95    /// # Safety
96    /// `base` must be alive at the time of invocation, i.e. user `init()` (which could technically destroy it) must not have run yet.
97    /// If `base` is destroyed while the returned `Base<T>` is in use, that constitutes a logic error, not a safety issue.
98    pub(crate) unsafe fn from_base(base: &Base<T>) -> Base<T> {
99        sys::balanced_assert!(
100            base.obj.is_instance_valid(),
101            "Cannot construct Base; was object freed during initialization?"
102        );
103
104        // SAFETY:
105        let obj = unsafe { Gd::from_obj_sys_weak(base.obj.obj_sys()) };
106
107        Self {
108            obj: ManuallyDrop::new(obj),
109            #[cfg(safeguards_balanced)] #[cfg_attr(published_docs, doc(cfg(safeguards_balanced)))]
110            init_state: Rc::clone(&base.init_state),
111        }
112    }
113
114    /// Create base from existing object (used in script instances).
115    ///
116    /// The return value is a weak pointer, so it will not keep the instance alive.
117    ///
118    /// # Safety
119    /// `gd` must be alive at the time of invocation. If it is destroyed while the returned `Base<T>` is in use, that constitutes a logic
120    /// error, not a safety issue.
121    pub(crate) unsafe fn from_script_gd(gd: &Gd<T>) -> Self {
122        sys::balanced_assert!(gd.is_instance_valid());
123
124        // SAFETY: pointer is valid and remains alive while in use.
125        let obj = unsafe { Gd::from_obj_sys_weak(gd.obj_sys()) };
126
127        base_from_obj!(obj, InitState::Script)
128    }
129
130    /// Create new base from raw Godot object.
131    ///
132    /// The return value is a weak pointer, so it will not keep the instance alive.
133    ///
134    /// # Safety
135    /// `base_ptr` must point to a valid, live object at the time of invocation. If it is destroyed while the returned `Base<T>` is in use,
136    /// that constitutes a logic error, not a safety issue.
137    pub(crate) unsafe fn from_sys(base_ptr: sys::GDExtensionObjectPtr) -> Self {
138        sys::balanced_assert!(!base_ptr.is_null(), "instance base is null pointer");
139
140        // Initialize only as weak pointer (don't increment reference count).
141        // SAFETY: pointer is valid and remains alive while in use.
142        let obj = unsafe { Gd::from_obj_sys_weak(base_ptr) };
143
144        // This obj does not contribute to the strong count, otherwise we create a reference cycle:
145        // 1. RefCounted (dropped in GDScript)
146        // 2. holds user T (via extension instance and storage)
147        // 3. holds Base<T> RefCounted (last ref, dropped in T destructor, but T is never destroyed because this ref keeps storage alive)
148        // Note that if late-init never happened on self, we have the same behavior (still a raw pointer instead of weak Gd)
149        base_from_obj!(obj, InitState::ObjectConstructing)
150    }
151
152    #[cfg(safeguards_balanced)] #[cfg_attr(published_docs, doc(cfg(safeguards_balanced)))]
153    fn from_obj(obj: Gd<T>, init_state: InitState) -> Self {
154        Self {
155            obj: ManuallyDrop::new(obj),
156            init_state: Rc::new(Cell::new(init_state)),
157        }
158    }
159
160    #[cfg(not(safeguards_balanced))] #[cfg_attr(published_docs, doc(cfg(not(safeguards_balanced))))]
161    fn from_obj(obj: Gd<T>) -> Self {
162        Self {
163            obj: ManuallyDrop::new(obj),
164        }
165    }
166
167    /// Returns a [`Gd`] referencing the base object, for exclusive use during object initialization and `NOTIFICATION_POSTINITIALIZE`.
168    ///
169    /// Can be used during an initialization function [`I*::init()`][crate::classes::IObject::init] or [`Gd::from_init_fn()`], or [`POSTINITIALIZE`][crate::classes::notify::ObjectNotification::POSTINITIALIZE].
170    ///
171    /// The base pointer is only pointing to a base object; you cannot yet downcast it to the object being constructed.
172    /// The instance ID is the same as the one the in-construction object will have.
173    ///
174    /// # Lifecycle for ref-counted classes
175    /// If `T: Inherits<RefCounted>`, then the ref-counted object is not yet fully-initialized at the time of the `init` function and [`POSTINITIALIZE`][crate::classes::notify::ObjectNotification::POSTINITIALIZE] running.
176    /// Accessing the base object without further measures would be dangerous. Here, godot-rust employs a workaround: the `Base` object (which
177    /// holds a weak pointer to the actual instance) is temporarily upgraded to a strong pointer, preventing use-after-free.
178    ///
179    /// This additional reference is automatically dropped at an implementation-defined point in time (which may change, and technically delay
180    /// destruction of your object as soon as you use `Base::to_init_gd()`). Right now, this refcount-decrement is deferred to the next frame.
181    ///
182    /// For now, ref-counted bases can only use `to_init_gd()` on the main thread.
183    ///
184    /// # Panics (Debug)
185    /// If called outside an initialization function, or for ref-counted objects on a non-main thread.
186    pub fn to_init_gd(&self) -> Gd<T> {
187        sys::balanced_assert!(
188            self.is_initializing(),
189            "Base::to_init_gd() can only be called during object initialization, inside I*::init() or Gd::from_init_fn()"
190        );
191
192        // For manually-managed objects, regular clone is fine.
193        // Only static type matters, because this happens immediately after initialization, so T is both static and dynamic type.
194        if !<T::Memory as bounds::Memory>::IS_REF_COUNTED {
195            return Gd::clone(&self.obj);
196        }
197
198        sys::balanced_assert!(
199            sys::is_main_thread(),
200            "Base::to_init_gd() can only be called on the main thread for ref-counted objects (for now)"
201        );
202
203        // First time handing out a Gd<T>, we need to take measures to temporarily upgrade the Base's weak pointer to a strong one.
204        // During the initialization phase (derived object being constructed), increment refcount by 1.
205        let instance_id = self.obj.instance_id();
206        PENDING_STRONG_REFS.with(|refs| {
207            let mut pending_refs = refs.borrow_mut();
208            if let Entry::Vacant(e) = pending_refs.entry(instance_id) {
209                let strong_ref: Gd<T> = unsafe { Gd::from_obj_sys(self.obj.obj_sys()) };
210
211                // We know that T: Inherits<RefCounted> due to check above, but don't it as a static bound for Gd::upcast().
212                // Thus fall back to low-level FFI cast on RawGd.
213                let strong_ref_raw = strong_ref.raw;
214                let raw = strong_ref_raw
215                    .ffi_cast::<classes::RefCounted>()
216                    .expect("Base must be RefCounted")
217                    .into_dest(strong_ref_raw);
218
219                e.insert(Gd { raw });
220            }
221        });
222
223        let name = format!("Base<{}> deferred unref", T::class_id());
224        let callable = Callable::from_once_fn(name, move |_args| {
225            Self::drop_strong_ref(instance_id);
226        });
227
228        // Use Callable::call_deferred() instead of Gd::apply_deferred(). The latter implicitly borrows &mut self,
229        // causing a "destroyed while bind was active" panic.
230        callable.call_deferred(&[]);
231
232        (*self.obj).clone()
233    }
234
235    /// Drops any extra strong references, possibly causing object destruction.
236    fn drop_strong_ref(instance_id: InstanceId) {
237        PENDING_STRONG_REFS.with(|refs| {
238            let mut pending_refs = refs.borrow_mut();
239            let strong_ref = pending_refs.remove(&instance_id);
240            sys::strict_assert!(
241                strong_ref.is_some(),
242                "Base unexpectedly had its strong ref rug-pulled"
243            );
244
245            // Editor creates instances of given class for various purposes (getting class docs, default values...)
246            // and frees them instantly before our callable can be executed.
247            // Perform "weak" drop instead of "strong" one iff our instance is no longer valid.
248            if !instance_id.lookup_validity() {
249                strong_ref.unwrap().drop_weak();
250            }
251
252            // Triggers RawGd::drop() -> dec-ref -> possibly object destruction.
253        });
254    }
255
256    /// Finalizes the initialization of this `Base<T>` and returns whether
257    pub(crate) fn mark_initialized(&mut self) {
258        #[cfg(safeguards_balanced)]
259        {
260            assert_eq!(
261                self.init_state.get(),
262                InitState::ObjectConstructing,
263                "Base<T> is already initialized, or holds a script instance"
264            );
265
266            self.init_state.set(InitState::ObjectInitialized);
267        }
268
269        // May return whether there is a "surplus" strong ref in the future, as self.extra_strong_ref.borrow().is_some().
270    }
271
272    /// Returns a [`Gd`] referencing the base object, for use in script contexts only.
273    #[doc(hidden)]
274    pub fn __script_gd(&self) -> Gd<T> {
275        // Used internally by `SiMut::base()` and `SiMut::base_mut()` for script re-entrancy.
276        // Could maybe add debug validation to ensure script context in the future.
277        (*self.obj).clone()
278    }
279
280    // Currently only used in outbound virtual calls (for scripts); search for: base_field(self).obj_sys().
281    #[doc(hidden)]
282    pub fn obj_sys(&self) -> sys::GDExtensionObjectPtr {
283        self.obj.obj_sys()
284    }
285
286    // Internal use only, do not make public.
287    #[cfg(feature = "debug-log")] #[cfg_attr(published_docs, doc(cfg(feature = "debug-log")))]
288    pub(crate) fn debug_instance_id(&self) -> crate::obj::InstanceId {
289        self.obj.instance_id()
290    }
291
292    /// Returns a passive reference to the base object, for use in script contexts only.
293    pub(crate) fn to_script_passive(&self) -> PassiveGd<T> {
294        #[cfg(safeguards_balanced)] #[cfg_attr(published_docs, doc(cfg(safeguards_balanced)))]
295        assert_eq!(
296            self.init_state.get(),
297            InitState::Script,
298            "to_script_passive() can only be called on script-context Base objects"
299        );
300
301        // SAFETY: the object remains valid for script contexts as per the assertion above.
302        unsafe { PassiveGd::from_strong_ref(&self.obj) }
303    }
304
305    /// Returns `true` if this `Base<T>` is currently in the initializing state.
306    #[cfg(safeguards_balanced)] #[cfg_attr(published_docs, doc(cfg(safeguards_balanced)))]
307    fn is_initializing(&self) -> bool {
308        self.init_state.get() == InitState::ObjectConstructing
309    }
310
311    /// Returns a [`Gd`] referencing the base object, assuming the derived object is fully constructed.
312    #[doc(hidden)]
313    pub fn __constructed_gd(&self) -> Gd<T> {
314        sys::balanced_assert!(
315            !self.is_initializing(),
316            "WithBaseField::to_gd(), base(), base_mut() can only be called on fully-constructed objects, after I*::init() or Gd::from_init_fn()"
317        );
318
319        (*self.obj).clone()
320    }
321
322    /// Returns a [`PassiveGd`] referencing the base object, assuming the derived object is fully constructed.
323    ///
324    /// Unlike [`Self::__constructed_gd()`], this does not increment the reference count for ref-counted `T`s.
325    /// The returned weak reference is safe to use only as long as the associated instance remains alive.
326    ///
327    /// # Safety
328    /// Caller must ensure that the underlying object remains valid for the entire lifetime of the returned `PassiveGd`.
329    pub(crate) unsafe fn constructed_passive(&self) -> PassiveGd<T> {
330        sys::balanced_assert!(
331            !self.is_initializing(),
332            "WithBaseField::base(), base_mut() can only be called on fully-constructed objects, after I*::init() or Gd::from_init_fn()"
333        );
334
335        // SAFETY: object pointer is valid and remains valid as long as self is alive (per safety precondition of this fn).
336        unsafe { PassiveGd::from_obj_sys(self.obj.obj_sys()) }
337    }
338}
339
340impl<T: GodotClass> Debug for Base<T> {
341    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
342        classes::debug_string(&self.obj, f, "Base")
343    }
344}
345
346impl<T: GodotClass> Display for Base<T> {
347    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
348        classes::display_string(&self.obj, f)
349    }
350}