xref: /qemu/rust/qemu-api/src/qom.rs (revision 0fcccf3ff04a54d597bffcb7a42668c52a7dcec0)
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_dynamic_cast, object_get_class, object_get_typename, object_ref, object_unref,
70         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 /// This trait provides safe casting operations for QOM objects to raw pointers,
267 /// to be used for example for FFI. The trait can be applied to any kind of
268 /// reference or smart pointers, and enforces correctness through the [`IsA`]
269 /// trait.
270 pub trait ObjectDeref: Deref
271 where
272     Self::Target: ObjectType,
273 {
274     /// Convert to a const Rust pointer, to be used for example for FFI.
275     /// The target pointer type must be the type of `self` or a superclass
276     fn as_ptr<U: ObjectType>(&self) -> *const U
277     where
278         Self::Target: IsA<U>,
279     {
280         let ptr: *const Self::Target = self.deref();
281         ptr.cast::<U>()
282     }
283 
284     /// Convert to a mutable Rust pointer, to be used for example for FFI.
285     /// The target pointer type must be the type of `self` or a superclass.
286     /// Used to implement interior mutability for objects.
287     ///
288     /// # Safety
289     ///
290     /// This method is safe because only the actual dereference of the pointer
291     /// has to be unsafe.  Bindings to C APIs will use it a lot, but care has
292     /// to be taken because it overrides the const-ness of `&self`.
293     fn as_mut_ptr<U: ObjectType>(&self) -> *mut U
294     where
295         Self::Target: IsA<U>,
296     {
297         #[allow(clippy::as_ptr_cast_mut)]
298         {
299             self.as_ptr::<U>() as *mut _
300         }
301     }
302 }
303 
304 /// Trait that adds extra functionality for `&T` where `T` is a QOM
305 /// object type.  Allows conversion to/from C objects in generic code.
306 pub trait ObjectCast: ObjectDeref + Copy
307 where
308     Self::Target: ObjectType,
309 {
310     /// Safely convert from a derived type to one of its parent types.
311     ///
312     /// This is always safe; the [`IsA`] trait provides static verification
313     /// trait that `Self` dereferences to `U` or a child of `U`.
314     fn upcast<'a, U: ObjectType>(self) -> &'a U
315     where
316         Self::Target: IsA<U>,
317         Self: 'a,
318     {
319         // SAFETY: soundness is declared via IsA<U>, which is an unsafe trait
320         unsafe { self.unsafe_cast::<U>() }
321     }
322 
323     /// Attempt to convert to a derived type.
324     ///
325     /// Returns `None` if the object is not actually of type `U`. This is
326     /// verified at runtime by checking the object's type information.
327     fn downcast<'a, U: IsA<Self::Target>>(self) -> Option<&'a U>
328     where
329         Self: 'a,
330     {
331         self.dynamic_cast::<U>()
332     }
333 
334     /// Attempt to convert between any two types in the QOM hierarchy.
335     ///
336     /// Returns `None` if the object is not actually of type `U`. This is
337     /// verified at runtime by checking the object's type information.
338     fn dynamic_cast<'a, U: ObjectType>(self) -> Option<&'a U>
339     where
340         Self: 'a,
341     {
342         unsafe {
343             // SAFETY: upcasting to Object is always valid, and the
344             // return type is either NULL or the argument itself
345             let result: *const U =
346                 object_dynamic_cast(self.as_object_mut_ptr(), U::TYPE_NAME.as_ptr()).cast();
347 
348             result.as_ref()
349         }
350     }
351 
352     /// Convert to any QOM type without verification.
353     ///
354     /// # Safety
355     ///
356     /// What safety? You need to know yourself that the cast is correct; only
357     /// use when performance is paramount.  It is still better than a raw
358     /// pointer `cast()`, which does not even check that you remain in the
359     /// realm of QOM `ObjectType`s.
360     ///
361     /// `unsafe_cast::<Object>()` is always safe.
362     unsafe fn unsafe_cast<'a, U: ObjectType>(self) -> &'a U
363     where
364         Self: 'a,
365     {
366         unsafe { &*(self.as_ptr::<Self::Target>().cast::<U>()) }
367     }
368 }
369 
370 impl<T: ObjectType> ObjectDeref for &T {}
371 impl<T: ObjectType> ObjectCast for &T {}
372 
373 /// Trait for mutable type casting operations in the QOM hierarchy.
374 ///
375 /// This trait provides the mutable counterparts to [`ObjectCast`]'s conversion
376 /// functions. Unlike `ObjectCast`, this trait returns `Result` for fallible
377 /// conversions to preserve the original smart pointer if the cast fails. This
378 /// is necessary because mutable references cannot be copied, so a failed cast
379 /// must return ownership of the original reference. For example:
380 ///
381 /// ```ignore
382 /// let mut dev = get_device();
383 /// // If this fails, we need the original `dev` back to try something else
384 /// match dev.dynamic_cast_mut::<FooDevice>() {
385 ///    Ok(foodev) => /* use foodev */,
386 ///    Err(dev) => /* still have ownership of dev */
387 /// }
388 /// ```
389 pub trait ObjectCastMut: Sized + ObjectDeref + DerefMut
390 where
391     Self::Target: ObjectType,
392 {
393     /// Safely convert from a derived type to one of its parent types.
394     ///
395     /// This is always safe; the [`IsA`] trait provides static verification
396     /// that `Self` dereferences to `U` or a child of `U`.
397     fn upcast_mut<'a, U: ObjectType>(self) -> &'a mut U
398     where
399         Self::Target: IsA<U>,
400         Self: 'a,
401     {
402         // SAFETY: soundness is declared via IsA<U>, which is an unsafe trait
403         unsafe { self.unsafe_cast_mut::<U>() }
404     }
405 
406     /// Attempt to convert to a derived type.
407     ///
408     /// Returns `Ok(..)` if the object is of type `U`, or `Err(self)` if the
409     /// object if the conversion failed. This is verified at runtime by
410     /// checking the object's type information.
411     fn downcast_mut<'a, U: IsA<Self::Target>>(self) -> Result<&'a mut U, Self>
412     where
413         Self: 'a,
414     {
415         self.dynamic_cast_mut::<U>()
416     }
417 
418     /// Attempt to convert between any two types in the QOM hierarchy.
419     ///
420     /// Returns `Ok(..)` if the object is of type `U`, or `Err(self)` if the
421     /// object if the conversion failed. This is verified at runtime by
422     /// checking the object's type information.
423     fn dynamic_cast_mut<'a, U: ObjectType>(self) -> Result<&'a mut U, Self>
424     where
425         Self: 'a,
426     {
427         unsafe {
428             // SAFETY: upcasting to Object is always valid, and the
429             // return type is either NULL or the argument itself
430             let result: *mut U =
431                 object_dynamic_cast(self.as_object_mut_ptr(), U::TYPE_NAME.as_ptr()).cast();
432 
433             result.as_mut().ok_or(self)
434         }
435     }
436 
437     /// Convert to any QOM type without verification.
438     ///
439     /// # Safety
440     ///
441     /// What safety? You need to know yourself that the cast is correct; only
442     /// use when performance is paramount.  It is still better than a raw
443     /// pointer `cast()`, which does not even check that you remain in the
444     /// realm of QOM `ObjectType`s.
445     ///
446     /// `unsafe_cast::<Object>()` is always safe.
447     unsafe fn unsafe_cast_mut<'a, U: ObjectType>(self) -> &'a mut U
448     where
449         Self: 'a,
450     {
451         unsafe { &mut *self.as_mut_ptr::<Self::Target>().cast::<U>() }
452     }
453 }
454 
455 impl<T: ObjectType> ObjectDeref for &mut T {}
456 impl<T: ObjectType> ObjectCastMut for &mut T {}
457 
458 /// Trait a type must implement to be registered with QEMU.
459 pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> {
460     /// The parent of the type.  This should match the first field of the
461     /// struct that implements `ObjectImpl`, minus the `ParentField<_>` wrapper.
462     type ParentType: ObjectType;
463 
464     /// Whether the object can be instantiated
465     const ABSTRACT: bool = false;
466 
467     /// Function that is called to initialize an object.  The parent class will
468     /// have already been initialized so the type is only responsible for
469     /// initializing its own members.
470     ///
471     /// FIXME: The argument is not really a valid reference. `&mut
472     /// MaybeUninit<Self>` would be a better description.
473     const INSTANCE_INIT: Option<unsafe fn(&mut Self)> = None;
474 
475     /// Function that is called to finish initialization of an object, once
476     /// `INSTANCE_INIT` functions have been called.
477     const INSTANCE_POST_INIT: Option<fn(&Self)> = None;
478 
479     /// Called on descendent classes after all parent class initialization
480     /// has occurred, but before the class itself is initialized.  This
481     /// is only useful if a class is not a leaf, and can be used to undo
482     /// the effects of copying the contents of the parent's class struct
483     /// to the descendants.
484     const CLASS_BASE_INIT: Option<
485         unsafe extern "C" fn(klass: *mut ObjectClass, data: *mut c_void),
486     > = None;
487 
488     const TYPE_INFO: TypeInfo = TypeInfo {
489         name: Self::TYPE_NAME.as_ptr(),
490         parent: Self::ParentType::TYPE_NAME.as_ptr(),
491         instance_size: core::mem::size_of::<Self>(),
492         instance_align: core::mem::align_of::<Self>(),
493         instance_init: match Self::INSTANCE_INIT {
494             None => None,
495             Some(_) => Some(rust_instance_init::<Self>),
496         },
497         instance_post_init: match Self::INSTANCE_POST_INIT {
498             None => None,
499             Some(_) => Some(rust_instance_post_init::<Self>),
500         },
501         instance_finalize: Some(drop_object::<Self>),
502         abstract_: Self::ABSTRACT,
503         class_size: core::mem::size_of::<Self::Class>(),
504         class_init: Some(rust_class_init::<Self>),
505         class_base_init: Self::CLASS_BASE_INIT,
506         class_data: core::ptr::null_mut(),
507         interfaces: core::ptr::null_mut(),
508     };
509 
510     // methods on ObjectClass
511     const UNPARENT: Option<fn(&Self)> = None;
512 }
513 
514 /// Internal trait used to automatically fill in a class struct.
515 ///
516 /// Each QOM class that has virtual methods describes them in a
517 /// _class struct_.  Class structs include a parent field corresponding
518 /// to the vtable of the parent class, all the way up to [`ObjectClass`].
519 /// Each QOM type has one such class struct; this trait takes care of
520 /// initializing the `T` part of the class struct, for the type that
521 /// implements the trait.
522 ///
523 /// Each struct will implement this trait with `T` equal to each
524 /// superclass.  For example, a device should implement at least
525 /// `ClassInitImpl<`[`DeviceClass`](crate::qdev::DeviceClass)`>` and
526 /// `ClassInitImpl<`[`ObjectClass`]`>`.  Such implementations are made
527 /// in one of two ways.
528 ///
529 /// For most superclasses, `ClassInitImpl` is provided by the `qemu-api`
530 /// crate itself.  The Rust implementation of methods will come from a
531 /// trait like [`ObjectImpl`] or [`DeviceImpl`](crate::qdev::DeviceImpl),
532 /// and `ClassInitImpl` is provided by blanket implementations that
533 /// operate on all implementors of the `*Impl`* trait.  For example:
534 ///
535 /// ```ignore
536 /// impl<T> ClassInitImpl<DeviceClass> for T
537 /// where
538 ///     T: ClassInitImpl<ObjectClass> + DeviceImpl,
539 /// ```
540 ///
541 /// The bound on `ClassInitImpl<ObjectClass>` is needed so that,
542 /// after initializing the `DeviceClass` part of the class struct,
543 /// the parent [`ObjectClass`] is initialized as well.
544 ///
545 /// The other case is when manual implementation of the trait is needed.
546 /// This covers the following cases:
547 ///
548 /// * if a class implements a QOM interface, the Rust code _has_ to define its
549 ///   own class struct `FooClass` and implement `ClassInitImpl<FooClass>`.
550 ///   `ClassInitImpl<FooClass>`'s `class_init` method will then forward to
551 ///   multiple other `class_init`s, for the interfaces as well as the
552 ///   superclass. (Note that there is no Rust example yet for using interfaces).
553 ///
554 /// * for classes implemented outside the ``qemu-api`` crate, it's not possible
555 ///   to add blanket implementations like the above one, due to orphan rules. In
556 ///   that case, the easiest solution is to implement
557 ///   `ClassInitImpl<YourSuperclass>` for each subclass and not have a
558 ///   `YourSuperclassImpl` trait at all.
559 ///
560 /// ```ignore
561 /// impl ClassInitImpl<YourSuperclass> for YourSubclass {
562 ///     fn class_init(klass: &mut YourSuperclass) {
563 ///         klass.some_method = Some(Self::some_method);
564 ///         <Self as ClassInitImpl<SysBusDeviceClass>>::class_init(&mut klass.parent_class);
565 ///     }
566 /// }
567 /// ```
568 ///
569 ///   While this method incurs a small amount of code duplication,
570 ///   it is generally limited to the recursive call on the last line.
571 ///   This is because classes defined in Rust do not need the same
572 ///   glue code that is needed when the classes are defined in C code.
573 ///   You may consider using a macro if you have many subclasses.
574 pub trait ClassInitImpl<T> {
575     /// Initialize `klass` to point to the virtual method implementations
576     /// for `Self`.  On entry, the virtual method pointers are set to
577     /// the default values coming from the parent classes; the function
578     /// can change them to override virtual methods of a parent class.
579     ///
580     /// The virtual method implementations usually come from another
581     /// trait, for example [`DeviceImpl`](crate::qdev::DeviceImpl)
582     /// when `T` is [`DeviceClass`](crate::qdev::DeviceClass).
583     ///
584     /// On entry, `klass`'s parent class is initialized, while the other fields
585     /// are all zero; it is therefore assumed that all fields in `T` can be
586     /// zeroed, otherwise it would not be possible to provide the class as a
587     /// `&mut T`.  TODO: add a bound of [`Zeroable`](crate::zeroable::Zeroable)
588     /// to T; this is more easily done once Zeroable does not require a manual
589     /// implementation (Rust 1.75.0).
590     fn class_init(klass: &mut T);
591 }
592 
593 /// # Safety
594 ///
595 /// We expect the FFI user of this function to pass a valid pointer that
596 /// can be downcasted to type `T`. We also expect the device is
597 /// readable/writeable from one thread at any time.
598 unsafe extern "C" fn rust_unparent_fn<T: ObjectImpl>(dev: *mut Object) {
599     let state = NonNull::new(dev).unwrap().cast::<T>();
600     T::UNPARENT.unwrap()(unsafe { state.as_ref() });
601 }
602 
603 impl<T> ClassInitImpl<ObjectClass> for T
604 where
605     T: ObjectImpl,
606 {
607     fn class_init(oc: &mut ObjectClass) {
608         if <T as ObjectImpl>::UNPARENT.is_some() {
609             oc.unparent = Some(rust_unparent_fn::<T>);
610         }
611     }
612 }
613 
614 unsafe impl ObjectType for Object {
615     type Class = ObjectClass;
616     const TYPE_NAME: &'static CStr =
617         unsafe { CStr::from_bytes_with_nul_unchecked(bindings::TYPE_OBJECT) };
618 }
619 
620 /// A reference-counted pointer to a QOM object.
621 ///
622 /// `Owned<T>` wraps `T` with automatic reference counting.  It increases the
623 /// reference count when created via [`Owned::from`] or cloned, and decreases
624 /// it when dropped.  This ensures that the reference count remains elevated
625 /// as long as any `Owned<T>` references to it exist.
626 ///
627 /// `Owned<T>` can be used for two reasons:
628 /// * because the lifetime of the QOM object is unknown and someone else could
629 ///   take a reference (similar to `Arc<T>`, for example): in this case, the
630 ///   object can escape and outlive the Rust struct that contains the `Owned<T>`
631 ///   field;
632 ///
633 /// * to ensure that the object stays alive until after `Drop::drop` is called
634 ///   on the Rust struct: in this case, the object will always die together with
635 ///   the Rust struct that contains the `Owned<T>` field.
636 ///
637 /// Child properties are an example of the second case: in C, an object that
638 /// is created with `object_initialize_child` will die *before*
639 /// `instance_finalize` is called, whereas Rust expects the struct to have valid
640 /// contents when `Drop::drop` is called.  Therefore Rust structs that have
641 /// child properties need to keep a reference to the child object.  Right now
642 /// this can be done with `Owned<T>`; in the future one might have a separate
643 /// `Child<'parent, T>` smart pointer that keeps a reference to a `T`, like
644 /// `Owned`, but does not allow cloning.
645 ///
646 /// Note that dropping an `Owned<T>` requires the big QEMU lock to be taken.
647 #[repr(transparent)]
648 #[derive(PartialEq, Eq, Hash, PartialOrd, Ord)]
649 pub struct Owned<T: ObjectType>(NonNull<T>);
650 
651 // The following rationale for safety is taken from Linux's kernel::sync::Arc.
652 
653 // SAFETY: It is safe to send `Owned<T>` to another thread when the underlying
654 // `T` is `Sync` because it effectively means sharing `&T` (which is safe
655 // because `T` is `Sync`); additionally, it needs `T` to be `Send` because any
656 // thread that has an `Owned<T>` may ultimately access `T` using a
657 // mutable reference when the reference count reaches zero and `T` is dropped.
658 unsafe impl<T: ObjectType + Send + Sync> Send for Owned<T> {}
659 
660 // SAFETY: It is safe to send `&Owned<T>` to another thread when the underlying
661 // `T` is `Sync` because it effectively means sharing `&T` (which is safe
662 // because `T` is `Sync`); additionally, it needs `T` to be `Send` because any
663 // thread that has a `&Owned<T>` may clone it and get an `Owned<T>` on that
664 // thread, so the thread may ultimately access `T` using a mutable reference
665 // when the reference count reaches zero and `T` is dropped.
666 unsafe impl<T: ObjectType + Sync + Send> Sync for Owned<T> {}
667 
668 impl<T: ObjectType> Owned<T> {
669     /// Convert a raw C pointer into an owned reference to the QOM
670     /// object it points to.  The object's reference count will be
671     /// decreased when the `Owned` is dropped.
672     ///
673     /// # Panics
674     ///
675     /// Panics if `ptr` is NULL.
676     ///
677     /// # Safety
678     ///
679     /// The caller must indeed own a reference to the QOM object.
680     /// The object must not be embedded in another unless the outer
681     /// object is guaranteed to have a longer lifetime.
682     ///
683     /// A raw pointer obtained via [`Owned::into_raw()`] can always be passed
684     /// back to `from_raw()` (assuming the original `Owned` was valid!),
685     /// since the owned reference remains there between the calls to
686     /// `into_raw()` and `from_raw()`.
687     pub unsafe fn from_raw(ptr: *const T) -> Self {
688         // SAFETY NOTE: while NonNull requires a mutable pointer, only
689         // Deref is implemented so the pointer passed to from_raw
690         // remains const
691         Owned(NonNull::new(ptr as *mut T).unwrap())
692     }
693 
694     /// Obtain a raw C pointer from a reference.  `src` is consumed
695     /// and the reference is leaked.
696     #[allow(clippy::missing_const_for_fn)]
697     pub fn into_raw(src: Owned<T>) -> *mut T {
698         let src = ManuallyDrop::new(src);
699         src.0.as_ptr()
700     }
701 
702     /// Increase the reference count of a QOM object and return
703     /// a new owned reference to it.
704     ///
705     /// # Safety
706     ///
707     /// The object must not be embedded in another, unless the outer
708     /// object is guaranteed to have a longer lifetime.
709     pub unsafe fn from(obj: &T) -> Self {
710         unsafe {
711             object_ref(obj.as_object_mut_ptr().cast::<c_void>());
712 
713             // SAFETY NOTE: while NonNull requires a mutable pointer, only
714             // Deref is implemented so the reference passed to from_raw
715             // remains shared
716             Owned(NonNull::new_unchecked(obj.as_mut_ptr()))
717         }
718     }
719 }
720 
721 impl<T: ObjectType> Clone for Owned<T> {
722     fn clone(&self) -> Self {
723         // SAFETY: creation method is unsafe; whoever calls it has
724         // responsibility that the pointer is valid, and remains valid
725         // throughout the lifetime of the `Owned<T>` and its clones.
726         unsafe { Owned::from(self.deref()) }
727     }
728 }
729 
730 impl<T: ObjectType> Deref for Owned<T> {
731     type Target = T;
732 
733     fn deref(&self) -> &Self::Target {
734         // SAFETY: creation method is unsafe; whoever calls it has
735         // responsibility that the pointer is valid, and remains valid
736         // throughout the lifetime of the `Owned<T>` and its clones.
737         // With that guarantee, reference counting ensures that
738         // the object remains alive.
739         unsafe { &*self.0.as_ptr() }
740     }
741 }
742 impl<T: ObjectType> ObjectDeref for Owned<T> {}
743 
744 impl<T: ObjectType> Drop for Owned<T> {
745     fn drop(&mut self) {
746         assert!(bql_locked());
747         // SAFETY: creation method is unsafe, and whoever calls it has
748         // responsibility that the pointer is valid, and remains valid
749         // throughout the lifetime of the `Owned<T>` and its clones.
750         unsafe {
751             object_unref(self.as_object_mut_ptr().cast::<c_void>());
752         }
753     }
754 }
755 
756 impl<T: IsA<Object>> fmt::Debug for Owned<T> {
757     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
758         self.deref().debug_fmt(f)
759     }
760 }
761 
762 /// Trait for methods exposed by the Object class.  The methods can be
763 /// called on all objects that have the trait `IsA<Object>`.
764 ///
765 /// The trait should only be used through the blanket implementation,
766 /// which guarantees safety via `IsA`
767 pub trait ObjectMethods: ObjectDeref
768 where
769     Self::Target: IsA<Object>,
770 {
771     /// Return the name of the type of `self`
772     fn typename(&self) -> std::borrow::Cow<'_, str> {
773         let obj = self.upcast::<Object>();
774         // SAFETY: safety of this is the requirement for implementing IsA
775         // The result of the C API has static lifetime
776         unsafe {
777             let p = object_get_typename(obj.as_mut_ptr());
778             CStr::from_ptr(p).to_string_lossy()
779         }
780     }
781 
782     fn get_class(&self) -> &'static <Self::Target as ObjectType>::Class {
783         let obj = self.upcast::<Object>();
784 
785         // SAFETY: all objects can call object_get_class; the actual class
786         // type is guaranteed by the implementation of `ObjectType` and
787         // `ObjectImpl`.
788         let klass: &'static <Self::Target as ObjectType>::Class =
789             unsafe { &*object_get_class(obj.as_mut_ptr()).cast() };
790 
791         klass
792     }
793 
794     /// Convenience function for implementing the Debug trait
795     fn debug_fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
796         f.debug_tuple(&self.typename())
797             .field(&(self as *const Self))
798             .finish()
799     }
800 }
801 
802 impl<R: ObjectDeref> ObjectMethods for R where R::Target: IsA<Object> {}
803