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