xref: /qemu/rust/qemu-api/src/qom.rs (revision 70ce076fa6dff60585c229a4b641b13e64bf03cf)
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     mem::ManuallyDrop,
60     ops::{Deref, DerefMut},
61     os::raw::c_void,
62     ptr::NonNull,
63 };
64 
65 pub use bindings::{Object, ObjectClass};
66 
67 use crate::{
68     bindings::{
69         self, object_class_dynamic_cast, object_dynamic_cast, object_get_class,
70         object_get_typename, object_new, object_ref, object_unref, TypeInfo,
71     },
72     cell::bql_locked,
73 };
74 
75 /// Marker trait: `Self` can be statically upcasted to `P` (i.e. `P` is a direct
76 /// or indirect parent of `Self`).
77 ///
78 /// # Safety
79 ///
80 /// The struct `Self` must be `#[repr(C)]` and must begin, directly or
81 /// indirectly, with a field of type `P`.  This ensures that invalid casts,
82 /// which rely on `IsA<>` for static checking, are rejected at compile time.
83 pub unsafe trait IsA<P: ObjectType>: ObjectType {}
84 
85 // SAFETY: it is always safe to cast to your own type
86 unsafe impl<T: ObjectType> IsA<T> for T {}
87 
88 /// Macro to mark superclasses of QOM classes.  This enables type-safe
89 /// up- and downcasting.
90 ///
91 /// # Safety
92 ///
93 /// This macro is a thin wrapper around the [`IsA`] trait and performs
94 /// no checking whatsoever of what is declared.  It is the caller's
95 /// responsibility to have $struct begin, directly or indirectly, with
96 /// a field of type `$parent`.
97 #[macro_export]
98 macro_rules! qom_isa {
99     ($struct:ty : $($parent:ty),* ) => {
100         $(
101             // SAFETY: it is the caller responsibility to have $parent as the
102             // first field
103             unsafe impl $crate::qom::IsA<$parent> for $struct {}
104 
105             impl AsRef<$parent> for $struct {
106                 fn as_ref(&self) -> &$parent {
107                     // SAFETY: follows the same rules as for IsA<U>, which is
108                     // declared above.
109                     let ptr: *const Self = self;
110                     unsafe { &*ptr.cast::<$parent>() }
111                 }
112             }
113         )*
114     };
115 }
116 
117 /// This is the same as [`ManuallyDrop<T>`](std::mem::ManuallyDrop), though
118 /// it hides the standard methods of `ManuallyDrop`.
119 ///
120 /// The first field of an `ObjectType` must be of type `ParentField<T>`.
121 /// (Technically, this is only necessary if there is at least one Rust
122 /// superclass in the hierarchy).  This is to ensure that the parent field is
123 /// dropped after the subclass; this drop order is enforced by the C
124 /// `object_deinit` function.
125 ///
126 /// # Examples
127 ///
128 /// ```ignore
129 /// #[repr(C)]
130 /// #[derive(qemu_api_macros::Object)]
131 /// pub struct MyDevice {
132 ///     parent: ParentField<DeviceState>,
133 ///     ...
134 /// }
135 /// ```
136 #[derive(Debug)]
137 #[repr(transparent)]
138 pub struct ParentField<T: ObjectType>(std::mem::ManuallyDrop<T>);
139 
140 impl<T: ObjectType> Deref for ParentField<T> {
141     type Target = T;
142 
143     #[inline(always)]
144     fn deref(&self) -> &Self::Target {
145         &self.0
146     }
147 }
148 
149 impl<T: ObjectType> DerefMut for ParentField<T> {
150     #[inline(always)]
151     fn deref_mut(&mut self) -> &mut Self::Target {
152         &mut self.0
153     }
154 }
155 
156 impl<T: fmt::Display + ObjectType> fmt::Display for ParentField<T> {
157     #[inline(always)]
158     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
159         self.0.fmt(f)
160     }
161 }
162 
163 unsafe extern "C" fn rust_instance_init<T: ObjectImpl>(obj: *mut Object) {
164     let mut state = NonNull::new(obj).unwrap().cast::<T>();
165     // SAFETY: obj is an instance of T, since rust_instance_init<T>
166     // is called from QOM core as the instance_init function
167     // for class T
168     unsafe {
169         T::INSTANCE_INIT.unwrap()(state.as_mut());
170     }
171 }
172 
173 unsafe extern "C" fn rust_instance_post_init<T: ObjectImpl>(obj: *mut Object) {
174     let state = NonNull::new(obj).unwrap().cast::<T>();
175     // SAFETY: obj is an instance of T, since rust_instance_post_init<T>
176     // is called from QOM core as the instance_post_init function
177     // for class T
178     T::INSTANCE_POST_INIT.unwrap()(unsafe { state.as_ref() });
179 }
180 
181 unsafe extern "C" fn rust_class_init<T: ObjectType + ClassInitImpl<T::Class>>(
182     klass: *mut ObjectClass,
183     _data: *mut c_void,
184 ) {
185     let mut klass = NonNull::new(klass)
186         .unwrap()
187         .cast::<<T as ObjectType>::Class>();
188     // SAFETY: klass is a T::Class, since rust_class_init<T>
189     // is called from QOM core as the class_init function
190     // for class T
191     T::class_init(unsafe { klass.as_mut() })
192 }
193 
194 unsafe extern "C" fn drop_object<T: ObjectImpl>(obj: *mut Object) {
195     // SAFETY: obj is an instance of T, since drop_object<T> is called
196     // from the QOM core function object_deinit() as the instance_finalize
197     // function for class T.  Note that while object_deinit() will drop the
198     // superclass field separately after this function returns, `T` must
199     // implement the unsafe trait ObjectType; the safety rules for the
200     // trait mandate that the parent field is manually dropped.
201     unsafe { std::ptr::drop_in_place(obj.cast::<T>()) }
202 }
203 
204 /// Trait exposed by all structs corresponding to QOM objects.
205 ///
206 /// # Safety
207 ///
208 /// For classes declared in C:
209 ///
210 /// - `Class` and `TYPE` must match the data in the `TypeInfo`;
211 ///
212 /// - the first field of the struct must be of the instance type corresponding
213 ///   to the superclass, as declared in the `TypeInfo`
214 ///
215 /// - likewise, the first field of the `Class` struct must be of the class type
216 ///   corresponding to the superclass
217 ///
218 /// For classes declared in Rust and implementing [`ObjectImpl`]:
219 ///
220 /// - the struct must be `#[repr(C)]`;
221 ///
222 /// - the first field of the struct must be of type
223 ///   [`ParentField<T>`](ParentField), where `T` is the parent type
224 ///   [`ObjectImpl::ParentType`]
225 ///
226 /// - the first field of the `Class` must be of the class struct corresponding
227 ///   to the superclass, which is `ObjectImpl::ParentType::Class`. `ParentField`
228 ///   is not needed here.
229 ///
230 /// In both cases, having a separate class type is not necessary if the subclass
231 /// does not add any field.
232 pub unsafe trait ObjectType: Sized {
233     /// The QOM class object corresponding to this struct.  This is used
234     /// to automatically generate a `class_init` method.
235     type Class;
236 
237     /// The name of the type, which can be passed to `object_new()` to
238     /// generate an instance of this type.
239     const TYPE_NAME: &'static CStr;
240 
241     /// Return the receiver as an Object.  This is always safe, even
242     /// if this type represents an interface.
243     fn as_object(&self) -> &Object {
244         unsafe { &*self.as_object_ptr() }
245     }
246 
247     /// Return the receiver as a const raw pointer to Object.
248     /// This is preferrable to `as_object_mut_ptr()` if a C
249     /// function only needs a `const Object *`.
250     fn as_object_ptr(&self) -> *const Object {
251         self.as_ptr().cast()
252     }
253 
254     /// Return the receiver as a mutable raw pointer to Object.
255     ///
256     /// # Safety
257     ///
258     /// This cast is always safe, but because the result is mutable
259     /// and the incoming reference is not, this should only be used
260     /// for calls to C functions, and only if needed.
261     unsafe fn as_object_mut_ptr(&self) -> *mut Object {
262         self.as_object_ptr() as *mut _
263     }
264 }
265 
266 /// Trait exposed by all structs corresponding to QOM interfaces.
267 /// Unlike `ObjectType`, it is implemented on the class type (which provides
268 /// the vtable for the interfaces).
269 ///
270 /// # Safety
271 ///
272 /// `TYPE` must match the contents of the `TypeInfo` as found in the C code;
273 /// right now, interfaces can only be declared in C.
274 pub unsafe trait InterfaceType: Sized {
275     /// The name of the type, which can be passed to
276     /// `object_class_dynamic_cast()` to obtain the pointer to the vtable
277     /// for this interface.
278     const TYPE_NAME: &'static CStr;
279 
280     /// Initialize the vtable for the interface; the generic argument `T` is the
281     /// type being initialized, while the generic argument `U` is the type that
282     /// lists the interface in its `TypeInfo`.
283     ///
284     /// # Panics
285     ///
286     /// Panic if the incoming argument if `T` does not implement the interface.
287     fn interface_init<
288         T: ObjectType + ClassInitImpl<Self> + ClassInitImpl<U::Class>,
289         U: ObjectType,
290     >(
291         klass: &mut U::Class,
292     ) {
293         unsafe {
294             // SAFETY: upcasting to ObjectClass is always valid, and the
295             // return type is either NULL or the argument itself
296             let result: *mut Self = object_class_dynamic_cast(
297                 (klass as *mut U::Class).cast(),
298                 Self::TYPE_NAME.as_ptr(),
299             )
300             .cast();
301 
302             <T as ClassInitImpl<Self>>::class_init(result.as_mut().unwrap())
303         }
304     }
305 }
306 
307 /// This trait provides safe casting operations for QOM objects to raw pointers,
308 /// to be used for example for FFI. The trait can be applied to any kind of
309 /// reference or smart pointers, and enforces correctness through the [`IsA`]
310 /// trait.
311 pub trait ObjectDeref: Deref
312 where
313     Self::Target: ObjectType,
314 {
315     /// Convert to a const Rust pointer, to be used for example for FFI.
316     /// The target pointer type must be the type of `self` or a superclass
317     fn as_ptr<U: ObjectType>(&self) -> *const U
318     where
319         Self::Target: IsA<U>,
320     {
321         let ptr: *const Self::Target = self.deref();
322         ptr.cast::<U>()
323     }
324 
325     /// Convert to a mutable Rust pointer, to be used for example for FFI.
326     /// The target pointer type must be the type of `self` or a superclass.
327     /// Used to implement interior mutability for objects.
328     ///
329     /// # Safety
330     ///
331     /// This method is safe because only the actual dereference of the pointer
332     /// has to be unsafe.  Bindings to C APIs will use it a lot, but care has
333     /// to be taken because it overrides the const-ness of `&self`.
334     fn as_mut_ptr<U: ObjectType>(&self) -> *mut U
335     where
336         Self::Target: IsA<U>,
337     {
338         #[allow(clippy::as_ptr_cast_mut)]
339         {
340             self.as_ptr::<U>() as *mut _
341         }
342     }
343 }
344 
345 /// Trait that adds extra functionality for `&T` where `T` is a QOM
346 /// object type.  Allows conversion to/from C objects in generic code.
347 pub trait ObjectCast: ObjectDeref + Copy
348 where
349     Self::Target: ObjectType,
350 {
351     /// Safely convert from a derived type to one of its parent types.
352     ///
353     /// This is always safe; the [`IsA`] trait provides static verification
354     /// trait that `Self` dereferences to `U` or a child of `U`.
355     fn upcast<'a, U: ObjectType>(self) -> &'a U
356     where
357         Self::Target: IsA<U>,
358         Self: 'a,
359     {
360         // SAFETY: soundness is declared via IsA<U>, which is an unsafe trait
361         unsafe { self.unsafe_cast::<U>() }
362     }
363 
364     /// Attempt to convert to a derived type.
365     ///
366     /// Returns `None` if the object is not actually of type `U`. This is
367     /// verified at runtime by checking the object's type information.
368     fn downcast<'a, U: IsA<Self::Target>>(self) -> Option<&'a U>
369     where
370         Self: 'a,
371     {
372         self.dynamic_cast::<U>()
373     }
374 
375     /// Attempt to convert between any two types in the QOM hierarchy.
376     ///
377     /// Returns `None` if the object is not actually of type `U`. This is
378     /// verified at runtime by checking the object's type information.
379     fn dynamic_cast<'a, U: ObjectType>(self) -> Option<&'a U>
380     where
381         Self: 'a,
382     {
383         unsafe {
384             // SAFETY: upcasting to Object is always valid, and the
385             // return type is either NULL or the argument itself
386             let result: *const U =
387                 object_dynamic_cast(self.as_object_mut_ptr(), U::TYPE_NAME.as_ptr()).cast();
388 
389             result.as_ref()
390         }
391     }
392 
393     /// Convert to any QOM type without verification.
394     ///
395     /// # Safety
396     ///
397     /// What safety? You need to know yourself that the cast is correct; only
398     /// use when performance is paramount.  It is still better than a raw
399     /// pointer `cast()`, which does not even check that you remain in the
400     /// realm of QOM `ObjectType`s.
401     ///
402     /// `unsafe_cast::<Object>()` is always safe.
403     unsafe fn unsafe_cast<'a, U: ObjectType>(self) -> &'a U
404     where
405         Self: 'a,
406     {
407         unsafe { &*(self.as_ptr::<Self::Target>().cast::<U>()) }
408     }
409 }
410 
411 impl<T: ObjectType> ObjectDeref for &T {}
412 impl<T: ObjectType> ObjectCast for &T {}
413 
414 /// Trait for mutable type casting operations in the QOM hierarchy.
415 ///
416 /// This trait provides the mutable counterparts to [`ObjectCast`]'s conversion
417 /// functions. Unlike `ObjectCast`, this trait returns `Result` for fallible
418 /// conversions to preserve the original smart pointer if the cast fails. This
419 /// is necessary because mutable references cannot be copied, so a failed cast
420 /// must return ownership of the original reference. For example:
421 ///
422 /// ```ignore
423 /// let mut dev = get_device();
424 /// // If this fails, we need the original `dev` back to try something else
425 /// match dev.dynamic_cast_mut::<FooDevice>() {
426 ///    Ok(foodev) => /* use foodev */,
427 ///    Err(dev) => /* still have ownership of dev */
428 /// }
429 /// ```
430 pub trait ObjectCastMut: Sized + ObjectDeref + DerefMut
431 where
432     Self::Target: ObjectType,
433 {
434     /// Safely convert from a derived type to one of its parent types.
435     ///
436     /// This is always safe; the [`IsA`] trait provides static verification
437     /// that `Self` dereferences to `U` or a child of `U`.
438     fn upcast_mut<'a, U: ObjectType>(self) -> &'a mut U
439     where
440         Self::Target: IsA<U>,
441         Self: 'a,
442     {
443         // SAFETY: soundness is declared via IsA<U>, which is an unsafe trait
444         unsafe { self.unsafe_cast_mut::<U>() }
445     }
446 
447     /// Attempt to convert to a derived type.
448     ///
449     /// Returns `Ok(..)` if the object is of type `U`, or `Err(self)` if the
450     /// object if the conversion failed. This is verified at runtime by
451     /// checking the object's type information.
452     fn downcast_mut<'a, U: IsA<Self::Target>>(self) -> Result<&'a mut U, Self>
453     where
454         Self: 'a,
455     {
456         self.dynamic_cast_mut::<U>()
457     }
458 
459     /// Attempt to convert between any two types in the QOM hierarchy.
460     ///
461     /// Returns `Ok(..)` if the object is of type `U`, or `Err(self)` if the
462     /// object if the conversion failed. This is verified at runtime by
463     /// checking the object's type information.
464     fn dynamic_cast_mut<'a, U: ObjectType>(self) -> Result<&'a mut U, Self>
465     where
466         Self: 'a,
467     {
468         unsafe {
469             // SAFETY: upcasting to Object is always valid, and the
470             // return type is either NULL or the argument itself
471             let result: *mut U =
472                 object_dynamic_cast(self.as_object_mut_ptr(), U::TYPE_NAME.as_ptr()).cast();
473 
474             result.as_mut().ok_or(self)
475         }
476     }
477 
478     /// Convert to any QOM type without verification.
479     ///
480     /// # Safety
481     ///
482     /// What safety? You need to know yourself that the cast is correct; only
483     /// use when performance is paramount.  It is still better than a raw
484     /// pointer `cast()`, which does not even check that you remain in the
485     /// realm of QOM `ObjectType`s.
486     ///
487     /// `unsafe_cast::<Object>()` is always safe.
488     unsafe fn unsafe_cast_mut<'a, U: ObjectType>(self) -> &'a mut U
489     where
490         Self: 'a,
491     {
492         unsafe { &mut *self.as_mut_ptr::<Self::Target>().cast::<U>() }
493     }
494 }
495 
496 impl<T: ObjectType> ObjectDeref for &mut T {}
497 impl<T: ObjectType> ObjectCastMut for &mut T {}
498 
499 /// Trait a type must implement to be registered with QEMU.
500 pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> {
501     /// The parent of the type.  This should match the first field of the
502     /// struct that implements `ObjectImpl`, minus the `ParentField<_>` wrapper.
503     type ParentType: ObjectType;
504 
505     /// Whether the object can be instantiated
506     const ABSTRACT: bool = false;
507 
508     /// Function that is called to initialize an object.  The parent class will
509     /// have already been initialized so the type is only responsible for
510     /// initializing its own members.
511     ///
512     /// FIXME: The argument is not really a valid reference. `&mut
513     /// MaybeUninit<Self>` would be a better description.
514     const INSTANCE_INIT: Option<unsafe fn(&mut Self)> = None;
515 
516     /// Function that is called to finish initialization of an object, once
517     /// `INSTANCE_INIT` functions have been called.
518     const INSTANCE_POST_INIT: Option<fn(&Self)> = None;
519 
520     /// Called on descendent classes after all parent class initialization
521     /// has occurred, but before the class itself is initialized.  This
522     /// is only useful if a class is not a leaf, and can be used to undo
523     /// the effects of copying the contents of the parent's class struct
524     /// to the descendants.
525     const CLASS_BASE_INIT: Option<
526         unsafe extern "C" fn(klass: *mut ObjectClass, data: *mut c_void),
527     > = None;
528 
529     const TYPE_INFO: TypeInfo = TypeInfo {
530         name: Self::TYPE_NAME.as_ptr(),
531         parent: Self::ParentType::TYPE_NAME.as_ptr(),
532         instance_size: core::mem::size_of::<Self>(),
533         instance_align: core::mem::align_of::<Self>(),
534         instance_init: match Self::INSTANCE_INIT {
535             None => None,
536             Some(_) => Some(rust_instance_init::<Self>),
537         },
538         instance_post_init: match Self::INSTANCE_POST_INIT {
539             None => None,
540             Some(_) => Some(rust_instance_post_init::<Self>),
541         },
542         instance_finalize: Some(drop_object::<Self>),
543         abstract_: Self::ABSTRACT,
544         class_size: core::mem::size_of::<Self::Class>(),
545         class_init: Some(rust_class_init::<Self>),
546         class_base_init: Self::CLASS_BASE_INIT,
547         class_data: core::ptr::null_mut(),
548         interfaces: core::ptr::null_mut(),
549     };
550 
551     // methods on ObjectClass
552     const UNPARENT: Option<fn(&Self)> = None;
553 }
554 
555 /// Internal trait used to automatically fill in a class struct.
556 ///
557 /// Each QOM class that has virtual methods describes them in a
558 /// _class struct_.  Class structs include a parent field corresponding
559 /// to the vtable of the parent class, all the way up to [`ObjectClass`].
560 /// Each QOM type has one such class struct; this trait takes care of
561 /// initializing the `T` part of the class struct, for the type that
562 /// implements the trait.
563 ///
564 /// Each struct will implement this trait with `T` equal to each
565 /// superclass.  For example, a device should implement at least
566 /// `ClassInitImpl<`[`DeviceClass`](crate::qdev::DeviceClass)`>` and
567 /// `ClassInitImpl<`[`ObjectClass`]`>`.  Such implementations are made
568 /// in one of two ways.
569 ///
570 /// For most superclasses, `ClassInitImpl` is provided by the `qemu-api`
571 /// crate itself.  The Rust implementation of methods will come from a
572 /// trait like [`ObjectImpl`] or [`DeviceImpl`](crate::qdev::DeviceImpl),
573 /// and `ClassInitImpl` is provided by blanket implementations that
574 /// operate on all implementors of the `*Impl`* trait.  For example:
575 ///
576 /// ```ignore
577 /// impl<T> ClassInitImpl<DeviceClass> for T
578 /// where
579 ///     T: ClassInitImpl<ObjectClass> + DeviceImpl,
580 /// ```
581 ///
582 /// The bound on `ClassInitImpl<ObjectClass>` is needed so that,
583 /// after initializing the `DeviceClass` part of the class struct,
584 /// the parent [`ObjectClass`] is initialized as well.
585 ///
586 /// The other case is when manual implementation of the trait is needed.
587 /// This covers the following cases:
588 ///
589 /// * if a class implements a QOM interface, the Rust code _has_ to define its
590 ///   own class struct `FooClass` and implement `ClassInitImpl<FooClass>`.
591 ///   `ClassInitImpl<FooClass>`'s `class_init` method will then forward to
592 ///   multiple other `class_init`s, for the interfaces as well as the
593 ///   superclass. (Note that there is no Rust example yet for using interfaces).
594 ///
595 /// * for classes implemented outside the ``qemu-api`` crate, it's not possible
596 ///   to add blanket implementations like the above one, due to orphan rules. In
597 ///   that case, the easiest solution is to implement
598 ///   `ClassInitImpl<YourSuperclass>` for each subclass and not have a
599 ///   `YourSuperclassImpl` trait at all.
600 ///
601 /// ```ignore
602 /// impl ClassInitImpl<YourSuperclass> for YourSubclass {
603 ///     fn class_init(klass: &mut YourSuperclass) {
604 ///         klass.some_method = Some(Self::some_method);
605 ///         <Self as ClassInitImpl<SysBusDeviceClass>>::class_init(&mut klass.parent_class);
606 ///     }
607 /// }
608 /// ```
609 ///
610 ///   While this method incurs a small amount of code duplication,
611 ///   it is generally limited to the recursive call on the last line.
612 ///   This is because classes defined in Rust do not need the same
613 ///   glue code that is needed when the classes are defined in C code.
614 ///   You may consider using a macro if you have many subclasses.
615 pub trait ClassInitImpl<T> {
616     /// Initialize `klass` to point to the virtual method implementations
617     /// for `Self`.  On entry, the virtual method pointers are set to
618     /// the default values coming from the parent classes; the function
619     /// can change them to override virtual methods of a parent class.
620     ///
621     /// The virtual method implementations usually come from another
622     /// trait, for example [`DeviceImpl`](crate::qdev::DeviceImpl)
623     /// when `T` is [`DeviceClass`](crate::qdev::DeviceClass).
624     ///
625     /// On entry, `klass`'s parent class is initialized, while the other fields
626     /// are all zero; it is therefore assumed that all fields in `T` can be
627     /// zeroed, otherwise it would not be possible to provide the class as a
628     /// `&mut T`.  TODO: add a bound of [`Zeroable`](crate::zeroable::Zeroable)
629     /// to T; this is more easily done once Zeroable does not require a manual
630     /// implementation (Rust 1.75.0).
631     fn class_init(klass: &mut T);
632 }
633 
634 /// # Safety
635 ///
636 /// We expect the FFI user of this function to pass a valid pointer that
637 /// can be downcasted to type `T`. We also expect the device is
638 /// readable/writeable from one thread at any time.
639 unsafe extern "C" fn rust_unparent_fn<T: ObjectImpl>(dev: *mut Object) {
640     let state = NonNull::new(dev).unwrap().cast::<T>();
641     T::UNPARENT.unwrap()(unsafe { state.as_ref() });
642 }
643 
644 impl<T> ClassInitImpl<ObjectClass> for T
645 where
646     T: ObjectImpl,
647 {
648     fn class_init(oc: &mut ObjectClass) {
649         if <T as ObjectImpl>::UNPARENT.is_some() {
650             oc.unparent = Some(rust_unparent_fn::<T>);
651         }
652     }
653 }
654 
655 unsafe impl ObjectType for Object {
656     type Class = ObjectClass;
657     const TYPE_NAME: &'static CStr =
658         unsafe { CStr::from_bytes_with_nul_unchecked(bindings::TYPE_OBJECT) };
659 }
660 
661 /// A reference-counted pointer to a QOM object.
662 ///
663 /// `Owned<T>` wraps `T` with automatic reference counting.  It increases the
664 /// reference count when created via [`Owned::from`] or cloned, and decreases
665 /// it when dropped.  This ensures that the reference count remains elevated
666 /// as long as any `Owned<T>` references to it exist.
667 ///
668 /// `Owned<T>` can be used for two reasons:
669 /// * because the lifetime of the QOM object is unknown and someone else could
670 ///   take a reference (similar to `Arc<T>`, for example): in this case, the
671 ///   object can escape and outlive the Rust struct that contains the `Owned<T>`
672 ///   field;
673 ///
674 /// * to ensure that the object stays alive until after `Drop::drop` is called
675 ///   on the Rust struct: in this case, the object will always die together with
676 ///   the Rust struct that contains the `Owned<T>` field.
677 ///
678 /// Child properties are an example of the second case: in C, an object that
679 /// is created with `object_initialize_child` will die *before*
680 /// `instance_finalize` is called, whereas Rust expects the struct to have valid
681 /// contents when `Drop::drop` is called.  Therefore Rust structs that have
682 /// child properties need to keep a reference to the child object.  Right now
683 /// this can be done with `Owned<T>`; in the future one might have a separate
684 /// `Child<'parent, T>` smart pointer that keeps a reference to a `T`, like
685 /// `Owned`, but does not allow cloning.
686 ///
687 /// Note that dropping an `Owned<T>` requires the big QEMU lock to be taken.
688 #[repr(transparent)]
689 #[derive(PartialEq, Eq, Hash, PartialOrd, Ord)]
690 pub struct Owned<T: ObjectType>(NonNull<T>);
691 
692 // The following rationale for safety is taken from Linux's kernel::sync::Arc.
693 
694 // SAFETY: It is safe to send `Owned<T>` to another thread when the underlying
695 // `T` is `Sync` because it effectively means sharing `&T` (which is safe
696 // because `T` is `Sync`); additionally, it needs `T` to be `Send` because any
697 // thread that has an `Owned<T>` may ultimately access `T` using a
698 // mutable reference when the reference count reaches zero and `T` is dropped.
699 unsafe impl<T: ObjectType + Send + Sync> Send for Owned<T> {}
700 
701 // SAFETY: It is safe to send `&Owned<T>` to another thread when the underlying
702 // `T` is `Sync` because it effectively means sharing `&T` (which is safe
703 // because `T` is `Sync`); additionally, it needs `T` to be `Send` because any
704 // thread that has a `&Owned<T>` may clone it and get an `Owned<T>` on that
705 // thread, so the thread may ultimately access `T` using a mutable reference
706 // when the reference count reaches zero and `T` is dropped.
707 unsafe impl<T: ObjectType + Sync + Send> Sync for Owned<T> {}
708 
709 impl<T: ObjectType> Owned<T> {
710     /// Convert a raw C pointer into an owned reference to the QOM
711     /// object it points to.  The object's reference count will be
712     /// decreased when the `Owned` is dropped.
713     ///
714     /// # Panics
715     ///
716     /// Panics if `ptr` is NULL.
717     ///
718     /// # Safety
719     ///
720     /// The caller must indeed own a reference to the QOM object.
721     /// The object must not be embedded in another unless the outer
722     /// object is guaranteed to have a longer lifetime.
723     ///
724     /// A raw pointer obtained via [`Owned::into_raw()`] can always be passed
725     /// back to `from_raw()` (assuming the original `Owned` was valid!),
726     /// since the owned reference remains there between the calls to
727     /// `into_raw()` and `from_raw()`.
728     pub unsafe fn from_raw(ptr: *const T) -> Self {
729         // SAFETY NOTE: while NonNull requires a mutable pointer, only
730         // Deref is implemented so the pointer passed to from_raw
731         // remains const
732         Owned(NonNull::new(ptr as *mut T).unwrap())
733     }
734 
735     /// Obtain a raw C pointer from a reference.  `src` is consumed
736     /// and the reference is leaked.
737     #[allow(clippy::missing_const_for_fn)]
738     pub fn into_raw(src: Owned<T>) -> *mut T {
739         let src = ManuallyDrop::new(src);
740         src.0.as_ptr()
741     }
742 
743     /// Increase the reference count of a QOM object and return
744     /// a new owned reference to it.
745     ///
746     /// # Safety
747     ///
748     /// The object must not be embedded in another, unless the outer
749     /// object is guaranteed to have a longer lifetime.
750     pub unsafe fn from(obj: &T) -> Self {
751         unsafe {
752             object_ref(obj.as_object_mut_ptr().cast::<c_void>());
753 
754             // SAFETY NOTE: while NonNull requires a mutable pointer, only
755             // Deref is implemented so the reference passed to from_raw
756             // remains shared
757             Owned(NonNull::new_unchecked(obj.as_mut_ptr()))
758         }
759     }
760 }
761 
762 impl<T: ObjectType> Clone for Owned<T> {
763     fn clone(&self) -> Self {
764         // SAFETY: creation method is unsafe; whoever calls it has
765         // responsibility that the pointer is valid, and remains valid
766         // throughout the lifetime of the `Owned<T>` and its clones.
767         unsafe { Owned::from(self.deref()) }
768     }
769 }
770 
771 impl<T: ObjectType> Deref for Owned<T> {
772     type Target = T;
773 
774     fn deref(&self) -> &Self::Target {
775         // SAFETY: creation method is unsafe; whoever calls it has
776         // responsibility that the pointer is valid, and remains valid
777         // throughout the lifetime of the `Owned<T>` and its clones.
778         // With that guarantee, reference counting ensures that
779         // the object remains alive.
780         unsafe { &*self.0.as_ptr() }
781     }
782 }
783 impl<T: ObjectType> ObjectDeref for Owned<T> {}
784 
785 impl<T: ObjectType> Drop for Owned<T> {
786     fn drop(&mut self) {
787         assert!(bql_locked());
788         // SAFETY: creation method is unsafe, and whoever calls it has
789         // responsibility that the pointer is valid, and remains valid
790         // throughout the lifetime of the `Owned<T>` and its clones.
791         unsafe {
792             object_unref(self.as_object_mut_ptr().cast::<c_void>());
793         }
794     }
795 }
796 
797 impl<T: IsA<Object>> fmt::Debug for Owned<T> {
798     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
799         self.deref().debug_fmt(f)
800     }
801 }
802 
803 /// Trait for class methods exposed by the Object class.  The methods can be
804 /// called on all objects that have the trait `IsA<Object>`.
805 ///
806 /// The trait should only be used through the blanket implementation,
807 /// which guarantees safety via `IsA`
808 pub trait ObjectClassMethods: IsA<Object> {
809     /// Return a new reference counted instance of this class
810     fn new() -> Owned<Self> {
811         assert!(bql_locked());
812         // SAFETY: the object created by object_new is allocated on
813         // the heap and has a reference count of 1
814         unsafe {
815             let obj = &*object_new(Self::TYPE_NAME.as_ptr());
816             Owned::from_raw(obj.unsafe_cast::<Self>())
817         }
818     }
819 }
820 
821 /// Trait for methods exposed by the Object class.  The methods can be
822 /// called on all objects that have the trait `IsA<Object>`.
823 ///
824 /// The trait should only be used through the blanket implementation,
825 /// which guarantees safety via `IsA`
826 pub trait ObjectMethods: ObjectDeref
827 where
828     Self::Target: IsA<Object>,
829 {
830     /// Return the name of the type of `self`
831     fn typename(&self) -> std::borrow::Cow<'_, str> {
832         let obj = self.upcast::<Object>();
833         // SAFETY: safety of this is the requirement for implementing IsA
834         // The result of the C API has static lifetime
835         unsafe {
836             let p = object_get_typename(obj.as_mut_ptr());
837             CStr::from_ptr(p).to_string_lossy()
838         }
839     }
840 
841     fn get_class(&self) -> &'static <Self::Target as ObjectType>::Class {
842         let obj = self.upcast::<Object>();
843 
844         // SAFETY: all objects can call object_get_class; the actual class
845         // type is guaranteed by the implementation of `ObjectType` and
846         // `ObjectImpl`.
847         let klass: &'static <Self::Target as ObjectType>::Class =
848             unsafe { &*object_get_class(obj.as_mut_ptr()).cast() };
849 
850         klass
851     }
852 
853     /// Convenience function for implementing the Debug trait
854     fn debug_fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
855         f.debug_tuple(&self.typename())
856             .field(&(self as *const Self))
857             .finish()
858     }
859 }
860 
861 impl<T> ObjectClassMethods for T where T: IsA<Object> {}
862 impl<R: ObjectDeref> ObjectMethods for R where R::Target: IsA<Object> {}
863