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