xref: /qemu/rust/qemu-api/src/qom.rs (revision 45c3d6cfbbe1336176a719a9487289ecd951fb99)
1 // Copyright 2024, Linaro Limited
2 // Author(s): Manos Pitsidianakis <manos.pitsidianakis@linaro.org>
3 // SPDX-License-Identifier: GPL-2.0-or-later
4 
5 //! Bindings to access QOM functionality from Rust.
6 //!
7 //! The QEMU Object Model (QOM) provides inheritance and dynamic typing for QEMU
8 //! devices. This module makes QOM's features available in Rust through three
9 //! main mechanisms:
10 //!
11 //! * Automatic creation and registration of `TypeInfo` for classes that are
12 //!   written in Rust, as well as mapping between Rust traits and QOM vtables.
13 //!
14 //! * Type-safe casting between parent and child classes, through the [`IsA`]
15 //!   trait and methods such as [`upcast`](ObjectCast::upcast) and
16 //!   [`downcast`](ObjectCast::downcast).
17 //!
18 //! * Automatic delegation of parent class methods to child classes. When a
19 //!   trait uses [`IsA`] as a bound, its contents become available to all child
20 //!   classes through blanket implementations. This works both for class methods
21 //!   and for instance methods accessed through references or smart pointers.
22 //!
23 //! # Structure of a class
24 //!
25 //! A leaf class only needs a struct holding instance state. The struct must
26 //! implement the [`ObjectType`] and [`IsA`] traits, as well as any `*Impl`
27 //! traits that exist for its superclasses.
28 //!
29 //! If a class has subclasses, it will also provide a struct for instance data,
30 //! with the same characteristics as for concrete classes, but it also needs
31 //! additional components to support virtual methods:
32 //!
33 //! * a struct for class data, for example `DeviceClass`. This corresponds to
34 //!   the C "class struct" and holds the vtable that is used by instances of the
35 //!   class and its subclasses. It must start with its parent's class struct.
36 //!
37 //! * a trait for virtual method implementations, for example `DeviceImpl`.
38 //!   Child classes implement this trait to provide their own behavior for
39 //!   virtual methods. The trait's methods take `&self` to access instance data.
40 //!
41 //! * an implementation of [`ClassInitImpl`], for example
42 //!   `ClassInitImpl<DeviceClass>`. This fills the vtable in the class struct;
43 //!   the source for this is the `*Impl` trait; the associated consts and
44 //!   functions if needed are wrapped to map C types into Rust types.
45 //!
46 //! * a trait for instance methods, for example `DeviceMethods`. This trait is
47 //!   automatically implemented for any reference or smart pointer to a device
48 //!   instance.  It calls into the vtable provides access across all subclasses
49 //!   to methods defined for the class.
50 //!
51 //! * optionally, a trait for class methods, for example `DeviceClassMethods`.
52 //!   This provides access to class-wide functionality that doesn't depend on
53 //!   instance data. Like instance methods, these are automatically inherited by
54 //!   child classes.
55 
56 use std::{
57     ffi::CStr,
58     fmt,
59     ops::{Deref, DerefMut},
60     os::raw::c_void,
61 };
62 
63 pub use bindings::{Object, ObjectClass};
64 
65 use crate::bindings::{self, object_dynamic_cast, object_get_class, object_get_typename, TypeInfo};
66 
67 /// Marker trait: `Self` can be statically upcasted to `P` (i.e. `P` is a direct
68 /// or indirect parent of `Self`).
69 ///
70 /// # Safety
71 ///
72 /// The struct `Self` must be `#[repr(C)]` and must begin, directly or
73 /// indirectly, with a field of type `P`.  This ensures that invalid casts,
74 /// which rely on `IsA<>` for static checking, are rejected at compile time.
75 pub unsafe trait IsA<P: ObjectType>: ObjectType {}
76 
77 // SAFETY: it is always safe to cast to your own type
78 unsafe impl<T: ObjectType> IsA<T> for T {}
79 
80 /// Macro to mark superclasses of QOM classes.  This enables type-safe
81 /// up- and downcasting.
82 ///
83 /// # Safety
84 ///
85 /// This macro is a thin wrapper around the [`IsA`] trait and performs
86 /// no checking whatsoever of what is declared.  It is the caller's
87 /// responsibility to have $struct begin, directly or indirectly, with
88 /// a field of type `$parent`.
89 #[macro_export]
90 macro_rules! qom_isa {
91     ($struct:ty : $($parent:ty),* ) => {
92         $(
93             // SAFETY: it is the caller responsibility to have $parent as the
94             // first field
95             unsafe impl $crate::qom::IsA<$parent> for $struct {}
96 
97             impl AsRef<$parent> for $struct {
98                 fn as_ref(&self) -> &$parent {
99                     // SAFETY: follows the same rules as for IsA<U>, which is
100                     // declared above.
101                     let ptr: *const Self = self;
102                     unsafe { &*ptr.cast::<$parent>() }
103                 }
104             }
105         )*
106     };
107 }
108 
109 /// This is the same as [`ManuallyDrop<T>`](std::mem::ManuallyDrop), though
110 /// it hides the standard methods of `ManuallyDrop`.
111 ///
112 /// The first field of an `ObjectType` must be of type `ParentField<T>`.
113 /// (Technically, this is only necessary if there is at least one Rust
114 /// superclass in the hierarchy).  This is to ensure that the parent field is
115 /// dropped after the subclass; this drop order is enforced by the C
116 /// `object_deinit` function.
117 ///
118 /// # Examples
119 ///
120 /// ```ignore
121 /// #[repr(C)]
122 /// #[derive(qemu_api_macros::Object)]
123 /// pub struct MyDevice {
124 ///     parent: ParentField<DeviceState>,
125 ///     ...
126 /// }
127 /// ```
128 #[derive(Debug)]
129 #[repr(transparent)]
130 pub struct ParentField<T: ObjectType>(std::mem::ManuallyDrop<T>);
131 
132 impl<T: ObjectType> Deref for ParentField<T> {
133     type Target = T;
134 
135     #[inline(always)]
136     fn deref(&self) -> &Self::Target {
137         &self.0
138     }
139 }
140 
141 impl<T: ObjectType> DerefMut for ParentField<T> {
142     #[inline(always)]
143     fn deref_mut(&mut self) -> &mut Self::Target {
144         &mut self.0
145     }
146 }
147 
148 impl<T: fmt::Display + ObjectType> fmt::Display for ParentField<T> {
149     #[inline(always)]
150     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
151         self.0.fmt(f)
152     }
153 }
154 
155 unsafe extern "C" fn rust_instance_init<T: ObjectImpl>(obj: *mut Object) {
156     // SAFETY: obj is an instance of T, since rust_instance_init<T>
157     // is called from QOM core as the instance_init function
158     // for class T
159     unsafe { T::INSTANCE_INIT.unwrap()(&mut *obj.cast::<T>()) }
160 }
161 
162 unsafe extern "C" fn rust_instance_post_init<T: ObjectImpl>(obj: *mut Object) {
163     // SAFETY: obj is an instance of T, since rust_instance_post_init<T>
164     // is called from QOM core as the instance_post_init function
165     // for class T
166     T::INSTANCE_POST_INIT.unwrap()(unsafe { &*obj.cast::<T>() })
167 }
168 
169 unsafe extern "C" fn rust_class_init<T: ObjectType + ClassInitImpl<T::Class>>(
170     klass: *mut ObjectClass,
171     _data: *mut c_void,
172 ) {
173     // SAFETY: klass is a T::Class, since rust_class_init<T>
174     // is called from QOM core as the class_init function
175     // for class T
176     T::class_init(unsafe { &mut *klass.cast::<T::Class>() })
177 }
178 
179 unsafe extern "C" fn drop_object<T: ObjectImpl>(obj: *mut Object) {
180     // SAFETY: obj is an instance of T, since drop_object<T> is called
181     // from the QOM core function object_deinit() as the instance_finalize
182     // function for class T.  Note that while object_deinit() will drop the
183     // superclass field separately after this function returns, `T` must
184     // implement the unsafe trait ObjectType; the safety rules for the
185     // trait mandate that the parent field is manually dropped.
186     unsafe { std::ptr::drop_in_place(obj.cast::<T>()) }
187 }
188 
189 /// Trait exposed by all structs corresponding to QOM objects.
190 ///
191 /// # Safety
192 ///
193 /// For classes declared in C:
194 ///
195 /// - `Class` and `TYPE` must match the data in the `TypeInfo`;
196 ///
197 /// - the first field of the struct must be of the instance type corresponding
198 ///   to the superclass, as declared in the `TypeInfo`
199 ///
200 /// - likewise, the first field of the `Class` struct must be of the class type
201 ///   corresponding to the superclass
202 ///
203 /// For classes declared in Rust and implementing [`ObjectImpl`]:
204 ///
205 /// - the struct must be `#[repr(C)]`;
206 ///
207 /// - the first field of the struct must be of type
208 ///   [`ParentField<T>`](ParentField), where `T` is the parent type
209 ///   [`ObjectImpl::ParentType`]
210 ///
211 /// - the first field of the `Class` must be of the class struct corresponding
212 ///   to the superclass, which is `ObjectImpl::ParentType::Class`. `ParentField`
213 ///   is not needed here.
214 ///
215 /// In both cases, having a separate class type is not necessary if the subclass
216 /// does not add any field.
217 pub unsafe trait ObjectType: Sized {
218     /// The QOM class object corresponding to this struct.  This is used
219     /// to automatically generate a `class_init` method.
220     type Class;
221 
222     /// The name of the type, which can be passed to `object_new()` to
223     /// generate an instance of this type.
224     const TYPE_NAME: &'static CStr;
225 
226     /// Return the receiver as an Object.  This is always safe, even
227     /// if this type represents an interface.
228     fn as_object(&self) -> &Object {
229         unsafe { &*self.as_object_ptr() }
230     }
231 
232     /// Return the receiver as a const raw pointer to Object.
233     /// This is preferrable to `as_object_mut_ptr()` if a C
234     /// function only needs a `const Object *`.
235     fn as_object_ptr(&self) -> *const Object {
236         self.as_ptr().cast()
237     }
238 
239     /// Return the receiver as a mutable raw pointer to Object.
240     ///
241     /// # Safety
242     ///
243     /// This cast is always safe, but because the result is mutable
244     /// and the incoming reference is not, this should only be used
245     /// for calls to C functions, and only if needed.
246     unsafe fn as_object_mut_ptr(&self) -> *mut Object {
247         self.as_object_ptr() as *mut _
248     }
249 }
250 
251 /// This trait provides safe casting operations for QOM objects to raw pointers,
252 /// to be used for example for FFI. The trait can be applied to any kind of
253 /// reference or smart pointers, and enforces correctness through the [`IsA`]
254 /// trait.
255 pub trait ObjectDeref: Deref
256 where
257     Self::Target: ObjectType,
258 {
259     /// Convert to a const Rust pointer, to be used for example for FFI.
260     /// The target pointer type must be the type of `self` or a superclass
261     fn as_ptr<U: ObjectType>(&self) -> *const U
262     where
263         Self::Target: IsA<U>,
264     {
265         let ptr: *const Self::Target = self.deref();
266         ptr.cast::<U>()
267     }
268 
269     /// Convert to a mutable Rust pointer, to be used for example for FFI.
270     /// The target pointer type must be the type of `self` or a superclass.
271     /// Used to implement interior mutability for objects.
272     ///
273     /// # Safety
274     ///
275     /// This method is unsafe because it overrides const-ness of `&self`.
276     /// Bindings to C APIs will use it a lot, but otherwise it should not
277     /// be necessary.
278     unsafe fn as_mut_ptr<U: ObjectType>(&self) -> *mut U
279     where
280         Self::Target: IsA<U>,
281     {
282         #[allow(clippy::as_ptr_cast_mut)]
283         {
284             self.as_ptr::<U>() as *mut _
285         }
286     }
287 }
288 
289 /// Trait that adds extra functionality for `&T` where `T` is a QOM
290 /// object type.  Allows conversion to/from C objects in generic code.
291 pub trait ObjectCast: ObjectDeref + Copy
292 where
293     Self::Target: ObjectType,
294 {
295     /// Safely convert from a derived type to one of its parent types.
296     ///
297     /// This is always safe; the [`IsA`] trait provides static verification
298     /// trait that `Self` dereferences to `U` or a child of `U`.
299     fn upcast<'a, U: ObjectType>(self) -> &'a U
300     where
301         Self::Target: IsA<U>,
302         Self: 'a,
303     {
304         // SAFETY: soundness is declared via IsA<U>, which is an unsafe trait
305         unsafe { self.unsafe_cast::<U>() }
306     }
307 
308     /// Attempt to convert to a derived type.
309     ///
310     /// Returns `None` if the object is not actually of type `U`. This is
311     /// verified at runtime by checking the object's type information.
312     fn downcast<'a, U: IsA<Self::Target>>(self) -> Option<&'a U>
313     where
314         Self: 'a,
315     {
316         self.dynamic_cast::<U>()
317     }
318 
319     /// Attempt to convert between any two types in the QOM hierarchy.
320     ///
321     /// Returns `None` if the object is not actually of type `U`. This is
322     /// verified at runtime by checking the object's type information.
323     fn dynamic_cast<'a, U: ObjectType>(self) -> Option<&'a U>
324     where
325         Self: 'a,
326     {
327         unsafe {
328             // SAFETY: upcasting to Object is always valid, and the
329             // return type is either NULL or the argument itself
330             let result: *const U =
331                 object_dynamic_cast(self.as_object_mut_ptr(), U::TYPE_NAME.as_ptr()).cast();
332 
333             result.as_ref()
334         }
335     }
336 
337     /// Convert to any QOM type without verification.
338     ///
339     /// # Safety
340     ///
341     /// What safety? You need to know yourself that the cast is correct; only
342     /// use when performance is paramount.  It is still better than a raw
343     /// pointer `cast()`, which does not even check that you remain in the
344     /// realm of QOM `ObjectType`s.
345     ///
346     /// `unsafe_cast::<Object>()` is always safe.
347     unsafe fn unsafe_cast<'a, U: ObjectType>(self) -> &'a U
348     where
349         Self: 'a,
350     {
351         unsafe { &*(self.as_ptr::<Self::Target>().cast::<U>()) }
352     }
353 }
354 
355 impl<T: ObjectType> ObjectDeref for &T {}
356 impl<T: ObjectType> ObjectCast for &T {}
357 
358 /// Trait for mutable type casting operations in the QOM hierarchy.
359 ///
360 /// This trait provides the mutable counterparts to [`ObjectCast`]'s conversion
361 /// functions. Unlike `ObjectCast`, this trait returns `Result` for fallible
362 /// conversions to preserve the original smart pointer if the cast fails. This
363 /// is necessary because mutable references cannot be copied, so a failed cast
364 /// must return ownership of the original reference. For example:
365 ///
366 /// ```ignore
367 /// let mut dev = get_device();
368 /// // If this fails, we need the original `dev` back to try something else
369 /// match dev.dynamic_cast_mut::<FooDevice>() {
370 ///    Ok(foodev) => /* use foodev */,
371 ///    Err(dev) => /* still have ownership of dev */
372 /// }
373 /// ```
374 pub trait ObjectCastMut: Sized + ObjectDeref + DerefMut
375 where
376     Self::Target: ObjectType,
377 {
378     /// Safely convert from a derived type to one of its parent types.
379     ///
380     /// This is always safe; the [`IsA`] trait provides static verification
381     /// that `Self` dereferences to `U` or a child of `U`.
382     fn upcast_mut<'a, U: ObjectType>(self) -> &'a mut U
383     where
384         Self::Target: IsA<U>,
385         Self: 'a,
386     {
387         // SAFETY: soundness is declared via IsA<U>, which is an unsafe trait
388         unsafe { self.unsafe_cast_mut::<U>() }
389     }
390 
391     /// Attempt to convert to a derived type.
392     ///
393     /// Returns `Ok(..)` if the object is of type `U`, or `Err(self)` if the
394     /// object if the conversion failed. This is verified at runtime by
395     /// checking the object's type information.
396     fn downcast_mut<'a, U: IsA<Self::Target>>(self) -> Result<&'a mut U, Self>
397     where
398         Self: 'a,
399     {
400         self.dynamic_cast_mut::<U>()
401     }
402 
403     /// Attempt to convert between any two types in the QOM hierarchy.
404     ///
405     /// Returns `Ok(..)` if the object is of type `U`, or `Err(self)` if the
406     /// object if the conversion failed. This is verified at runtime by
407     /// checking the object's type information.
408     fn dynamic_cast_mut<'a, U: ObjectType>(self) -> Result<&'a mut U, Self>
409     where
410         Self: 'a,
411     {
412         unsafe {
413             // SAFETY: upcasting to Object is always valid, and the
414             // return type is either NULL or the argument itself
415             let result: *mut U =
416                 object_dynamic_cast(self.as_object_mut_ptr(), U::TYPE_NAME.as_ptr()).cast();
417 
418             result.as_mut().ok_or(self)
419         }
420     }
421 
422     /// Convert to any QOM type without verification.
423     ///
424     /// # Safety
425     ///
426     /// What safety? You need to know yourself that the cast is correct; only
427     /// use when performance is paramount.  It is still better than a raw
428     /// pointer `cast()`, which does not even check that you remain in the
429     /// realm of QOM `ObjectType`s.
430     ///
431     /// `unsafe_cast::<Object>()` is always safe.
432     unsafe fn unsafe_cast_mut<'a, U: ObjectType>(self) -> &'a mut U
433     where
434         Self: 'a,
435     {
436         unsafe { &mut *self.as_mut_ptr::<Self::Target>().cast::<U>() }
437     }
438 }
439 
440 impl<T: ObjectType> ObjectDeref for &mut T {}
441 impl<T: ObjectType> ObjectCastMut for &mut T {}
442 
443 /// Trait a type must implement to be registered with QEMU.
444 pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> {
445     /// The parent of the type.  This should match the first field of the
446     /// struct that implements `ObjectImpl`, minus the `ParentField<_>` wrapper.
447     type ParentType: ObjectType;
448 
449     /// Whether the object can be instantiated
450     const ABSTRACT: bool = false;
451 
452     /// Function that is called to initialize an object.  The parent class will
453     /// have already been initialized so the type is only responsible for
454     /// initializing its own members.
455     ///
456     /// FIXME: The argument is not really a valid reference. `&mut
457     /// MaybeUninit<Self>` would be a better description.
458     const INSTANCE_INIT: Option<unsafe fn(&mut Self)> = None;
459 
460     /// Function that is called to finish initialization of an object, once
461     /// `INSTANCE_INIT` functions have been called.
462     const INSTANCE_POST_INIT: Option<fn(&Self)> = None;
463 
464     /// Called on descendent classes after all parent class initialization
465     /// has occurred, but before the class itself is initialized.  This
466     /// is only useful if a class is not a leaf, and can be used to undo
467     /// the effects of copying the contents of the parent's class struct
468     /// to the descendants.
469     const CLASS_BASE_INIT: Option<
470         unsafe extern "C" fn(klass: *mut ObjectClass, data: *mut c_void),
471     > = None;
472 
473     const TYPE_INFO: TypeInfo = TypeInfo {
474         name: Self::TYPE_NAME.as_ptr(),
475         parent: Self::ParentType::TYPE_NAME.as_ptr(),
476         instance_size: core::mem::size_of::<Self>(),
477         instance_align: core::mem::align_of::<Self>(),
478         instance_init: match Self::INSTANCE_INIT {
479             None => None,
480             Some(_) => Some(rust_instance_init::<Self>),
481         },
482         instance_post_init: match Self::INSTANCE_POST_INIT {
483             None => None,
484             Some(_) => Some(rust_instance_post_init::<Self>),
485         },
486         instance_finalize: Some(drop_object::<Self>),
487         abstract_: Self::ABSTRACT,
488         class_size: core::mem::size_of::<Self::Class>(),
489         class_init: Some(rust_class_init::<Self>),
490         class_base_init: Self::CLASS_BASE_INIT,
491         class_data: core::ptr::null_mut(),
492         interfaces: core::ptr::null_mut(),
493     };
494 
495     // methods on ObjectClass
496     const UNPARENT: Option<fn(&Self)> = None;
497 }
498 
499 /// Internal trait used to automatically fill in a class struct.
500 ///
501 /// Each QOM class that has virtual methods describes them in a
502 /// _class struct_.  Class structs include a parent field corresponding
503 /// to the vtable of the parent class, all the way up to [`ObjectClass`].
504 /// Each QOM type has one such class struct; this trait takes care of
505 /// initializing the `T` part of the class struct, for the type that
506 /// implements the trait.
507 ///
508 /// Each struct will implement this trait with `T` equal to each
509 /// superclass.  For example, a device should implement at least
510 /// `ClassInitImpl<`[`DeviceClass`](crate::qdev::DeviceClass)`>` and
511 /// `ClassInitImpl<`[`ObjectClass`]`>`.  Such implementations are made
512 /// in one of two ways.
513 ///
514 /// For most superclasses, `ClassInitImpl` is provided by the `qemu-api`
515 /// crate itself.  The Rust implementation of methods will come from a
516 /// trait like [`ObjectImpl`] or [`DeviceImpl`](crate::qdev::DeviceImpl),
517 /// and `ClassInitImpl` is provided by blanket implementations that
518 /// operate on all implementors of the `*Impl`* trait.  For example:
519 ///
520 /// ```ignore
521 /// impl<T> ClassInitImpl<DeviceClass> for T
522 /// where
523 ///     T: ClassInitImpl<ObjectClass> + DeviceImpl,
524 /// ```
525 ///
526 /// The bound on `ClassInitImpl<ObjectClass>` is needed so that,
527 /// after initializing the `DeviceClass` part of the class struct,
528 /// the parent [`ObjectClass`] is initialized as well.
529 ///
530 /// The other case is when manual implementation of the trait is needed.
531 /// This covers the following cases:
532 ///
533 /// * if a class implements a QOM interface, the Rust code _has_ to define its
534 ///   own class struct `FooClass` and implement `ClassInitImpl<FooClass>`.
535 ///   `ClassInitImpl<FooClass>`'s `class_init` method will then forward to
536 ///   multiple other `class_init`s, for the interfaces as well as the
537 ///   superclass. (Note that there is no Rust example yet for using interfaces).
538 ///
539 /// * for classes implemented outside the ``qemu-api`` crate, it's not possible
540 ///   to add blanket implementations like the above one, due to orphan rules. In
541 ///   that case, the easiest solution is to implement
542 ///   `ClassInitImpl<YourSuperclass>` for each subclass and not have a
543 ///   `YourSuperclassImpl` trait at all.
544 ///
545 /// ```ignore
546 /// impl ClassInitImpl<YourSuperclass> for YourSubclass {
547 ///     fn class_init(klass: &mut YourSuperclass) {
548 ///         klass.some_method = Some(Self::some_method);
549 ///         <Self as ClassInitImpl<SysBusDeviceClass>>::class_init(&mut klass.parent_class);
550 ///     }
551 /// }
552 /// ```
553 ///
554 ///   While this method incurs a small amount of code duplication,
555 ///   it is generally limited to the recursive call on the last line.
556 ///   This is because classes defined in Rust do not need the same
557 ///   glue code that is needed when the classes are defined in C code.
558 ///   You may consider using a macro if you have many subclasses.
559 pub trait ClassInitImpl<T> {
560     /// Initialize `klass` to point to the virtual method implementations
561     /// for `Self`.  On entry, the virtual method pointers are set to
562     /// the default values coming from the parent classes; the function
563     /// can change them to override virtual methods of a parent class.
564     ///
565     /// The virtual method implementations usually come from another
566     /// trait, for example [`DeviceImpl`](crate::qdev::DeviceImpl)
567     /// when `T` is [`DeviceClass`](crate::qdev::DeviceClass).
568     ///
569     /// On entry, `klass`'s parent class is initialized, while the other fields
570     /// are all zero; it is therefore assumed that all fields in `T` can be
571     /// zeroed, otherwise it would not be possible to provide the class as a
572     /// `&mut T`.  TODO: add a bound of [`Zeroable`](crate::zeroable::Zeroable)
573     /// to T; this is more easily done once Zeroable does not require a manual
574     /// implementation (Rust 1.75.0).
575     fn class_init(klass: &mut T);
576 }
577 
578 /// # Safety
579 ///
580 /// We expect the FFI user of this function to pass a valid pointer that
581 /// can be downcasted to type `T`. We also expect the device is
582 /// readable/writeable from one thread at any time.
583 unsafe extern "C" fn rust_unparent_fn<T: ObjectImpl>(dev: *mut Object) {
584     unsafe {
585         assert!(!dev.is_null());
586         let state = core::ptr::NonNull::new_unchecked(dev.cast::<T>());
587         T::UNPARENT.unwrap()(state.as_ref());
588     }
589 }
590 
591 impl<T> ClassInitImpl<ObjectClass> for T
592 where
593     T: ObjectImpl,
594 {
595     fn class_init(oc: &mut ObjectClass) {
596         if <T as ObjectImpl>::UNPARENT.is_some() {
597             oc.unparent = Some(rust_unparent_fn::<T>);
598         }
599     }
600 }
601 
602 unsafe impl ObjectType for Object {
603     type Class = ObjectClass;
604     const TYPE_NAME: &'static CStr =
605         unsafe { CStr::from_bytes_with_nul_unchecked(bindings::TYPE_OBJECT) };
606 }
607 
608 /// Trait for methods exposed by the Object class.  The methods can be
609 /// called on all objects that have the trait `IsA<Object>`.
610 ///
611 /// The trait should only be used through the blanket implementation,
612 /// which guarantees safety via `IsA`
613 pub trait ObjectMethods: ObjectDeref
614 where
615     Self::Target: IsA<Object>,
616 {
617     /// Return the name of the type of `self`
618     fn typename(&self) -> std::borrow::Cow<'_, str> {
619         let obj = self.upcast::<Object>();
620         // SAFETY: safety of this is the requirement for implementing IsA
621         // The result of the C API has static lifetime
622         unsafe {
623             let p = object_get_typename(obj.as_mut_ptr());
624             CStr::from_ptr(p).to_string_lossy()
625         }
626     }
627 
628     fn get_class(&self) -> &'static <Self::Target as ObjectType>::Class {
629         let obj = self.upcast::<Object>();
630 
631         // SAFETY: all objects can call object_get_class; the actual class
632         // type is guaranteed by the implementation of `ObjectType` and
633         // `ObjectImpl`.
634         let klass: &'static <Self::Target as ObjectType>::Class =
635             unsafe { &*object_get_class(obj.as_mut_ptr()).cast() };
636 
637         klass
638     }
639 }
640 
641 impl<R: ObjectDeref> ObjectMethods for R where R::Target: IsA<Object> {}
642