xref: /openbmc/qemu/rust/qemu-api/src/qom.rs (revision 4aed0296b307b6e2e3b7d38ee6c5204cf2dfe1ca)
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 //! This module provides automatic creation and registration of `TypeInfo`
8 //! for classes that are written in Rust, and mapping between Rust traits
9 //! and QOM vtables.
10 //!
11 //! # Structure of a class
12 //!
13 //! A leaf class only needs a struct holding instance state. The struct must
14 //! implement the [`ObjectType`] trait, as well as any `*Impl` traits that exist
15 //! for its superclasses.
16 //!
17 //! If a class has subclasses, it will also provide a struct for instance data,
18 //! with the same characteristics as for concrete classes, but it also needs
19 //! additional components to support virtual methods:
20 //!
21 //! * a struct for class data, for example `DeviceClass`. This corresponds to
22 //!   the C "class struct" and holds the vtable that is used by instances of the
23 //!   class and its subclasses. It must start with its parent's class struct.
24 //!
25 //! * a trait for virtual method implementations, for example `DeviceImpl`.
26 //!   Child classes implement this trait to provide their own behavior for
27 //!   virtual methods. The trait's methods take `&self` to access instance data.
28 //!
29 //! * an implementation of [`ClassInitImpl`], for example
30 //!   `ClassInitImpl<DeviceClass>`. This fills the vtable in the class struct;
31 //!   the source for this is the `*Impl` trait; the associated consts and
32 //!   functions if needed are wrapped to map C types into Rust types.
33 
34 use std::{ffi::CStr, os::raw::c_void};
35 
36 use crate::bindings::{self, Object, ObjectClass, TypeInfo};
37 
38 unsafe extern "C" fn rust_instance_init<T: ObjectImpl>(obj: *mut Object) {
39     // SAFETY: obj is an instance of T, since rust_instance_init<T>
40     // is called from QOM core as the instance_init function
41     // for class T
42     unsafe { T::INSTANCE_INIT.unwrap()(&mut *obj.cast::<T>()) }
43 }
44 
45 unsafe extern "C" fn rust_instance_post_init<T: ObjectImpl>(obj: *mut Object) {
46     // SAFETY: obj is an instance of T, since rust_instance_post_init<T>
47     // is called from QOM core as the instance_post_init function
48     // for class T
49     //
50     // FIXME: it's not really guaranteed that there are no backpointers to
51     // obj; it's quite possible that they have been created by instance_init().
52     // The receiver should be &self, not &mut self.
53     T::INSTANCE_POST_INIT.unwrap()(unsafe { &mut *obj.cast::<T>() })
54 }
55 
56 unsafe extern "C" fn rust_class_init<T: ObjectType + ClassInitImpl<T::Class>>(
57     klass: *mut ObjectClass,
58     _data: *mut c_void,
59 ) {
60     // SAFETY: klass is a T::Class, since rust_class_init<T>
61     // is called from QOM core as the class_init function
62     // for class T
63     T::class_init(unsafe { &mut *klass.cast::<T::Class>() })
64 }
65 
66 /// Trait exposed by all structs corresponding to QOM objects.
67 ///
68 /// # Safety
69 ///
70 /// For classes declared in C:
71 ///
72 /// - `Class` and `TYPE` must match the data in the `TypeInfo`;
73 ///
74 /// - the first field of the struct must be of the instance type corresponding
75 ///   to the superclass, as declared in the `TypeInfo`
76 ///
77 /// - likewise, the first field of the `Class` struct must be of the class type
78 ///   corresponding to the superclass
79 ///
80 /// For classes declared in Rust and implementing [`ObjectImpl`]:
81 ///
82 /// - the struct must be `#[repr(C)]`;
83 ///
84 /// - the first field of the struct must be of the instance struct corresponding
85 ///   to the superclass, which is `ObjectImpl::ParentType`
86 ///
87 /// - likewise, the first field of the `Class` must be of the class struct
88 ///   corresponding to the superclass, which is `ObjectImpl::ParentType::Class`.
89 pub unsafe trait ObjectType: Sized {
90     /// The QOM class object corresponding to this struct.  This is used
91     /// to automatically generate a `class_init` method.
92     type Class;
93 
94     /// The name of the type, which can be passed to `object_new()` to
95     /// generate an instance of this type.
96     const TYPE_NAME: &'static CStr;
97 }
98 
99 /// Trait a type must implement to be registered with QEMU.
100 pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> {
101     /// The parent of the type.  This should match the first field of
102     /// the struct that implements `ObjectImpl`:
103     type ParentType: ObjectType;
104 
105     /// Whether the object can be instantiated
106     const ABSTRACT: bool = false;
107     const INSTANCE_FINALIZE: Option<unsafe extern "C" fn(obj: *mut Object)> = None;
108 
109     /// Function that is called to initialize an object.  The parent class will
110     /// have already been initialized so the type is only responsible for
111     /// initializing its own members.
112     ///
113     /// FIXME: The argument is not really a valid reference. `&mut
114     /// MaybeUninit<Self>` would be a better description.
115     const INSTANCE_INIT: Option<unsafe fn(&mut Self)> = None;
116 
117     /// Function that is called to finish initialization of an object, once
118     /// `INSTANCE_INIT` functions have been called.
119     const INSTANCE_POST_INIT: Option<fn(&mut Self)> = None;
120 
121     /// Called on descendent classes after all parent class initialization
122     /// has occurred, but before the class itself is initialized.  This
123     /// is only useful if a class is not a leaf, and can be used to undo
124     /// the effects of copying the contents of the parent's class struct
125     /// to the descendants.
126     const CLASS_BASE_INIT: Option<
127         unsafe extern "C" fn(klass: *mut ObjectClass, data: *mut c_void),
128     > = None;
129 
130     const TYPE_INFO: TypeInfo = TypeInfo {
131         name: Self::TYPE_NAME.as_ptr(),
132         parent: Self::ParentType::TYPE_NAME.as_ptr(),
133         instance_size: core::mem::size_of::<Self>(),
134         instance_align: core::mem::align_of::<Self>(),
135         instance_init: match Self::INSTANCE_INIT {
136             None => None,
137             Some(_) => Some(rust_instance_init::<Self>),
138         },
139         instance_post_init: match Self::INSTANCE_POST_INIT {
140             None => None,
141             Some(_) => Some(rust_instance_post_init::<Self>),
142         },
143         instance_finalize: Self::INSTANCE_FINALIZE,
144         abstract_: Self::ABSTRACT,
145         class_size: core::mem::size_of::<Self::Class>(),
146         class_init: Some(rust_class_init::<Self>),
147         class_base_init: Self::CLASS_BASE_INIT,
148         class_data: core::ptr::null_mut(),
149         interfaces: core::ptr::null_mut(),
150     };
151 
152     // methods on ObjectClass
153     const UNPARENT: Option<fn(&Self)> = None;
154 }
155 
156 /// Internal trait used to automatically fill in a class struct.
157 ///
158 /// Each QOM class that has virtual methods describes them in a
159 /// _class struct_.  Class structs include a parent field corresponding
160 /// to the vtable of the parent class, all the way up to [`ObjectClass`].
161 /// Each QOM type has one such class struct; this trait takes care of
162 /// initializing the `T` part of the class struct, for the type that
163 /// implements the trait.
164 ///
165 /// Each struct will implement this trait with `T` equal to each
166 /// superclass.  For example, a device should implement at least
167 /// `ClassInitImpl<`[`DeviceClass`](crate::bindings::DeviceClass)`>` and
168 /// `ClassInitImpl<`[`ObjectClass`](crate::bindings::ObjectClass)`>`.
169 /// Such implementations are made in one of two ways.
170 ///
171 /// For most superclasses, `ClassInitImpl` is provided by the `qemu-api`
172 /// crate itself.  The Rust implementation of methods will come from a
173 /// trait like [`ObjectImpl`] or [`DeviceImpl`](crate::qdev::DeviceImpl),
174 /// and `ClassInitImpl` is provided by blanket implementations that
175 /// operate on all implementors of the `*Impl`* trait.  For example:
176 ///
177 /// ```ignore
178 /// impl<T> ClassInitImpl<DeviceClass> for T
179 /// where
180 ///     T: ClassInitImpl<ObjectClass> + DeviceImpl,
181 /// ```
182 ///
183 /// The bound on `ClassInitImpl<ObjectClass>` is needed so that,
184 /// after initializing the `DeviceClass` part of the class struct,
185 /// the parent [`ObjectClass`] is initialized as well.
186 ///
187 /// The other case is when manual implementation of the trait is needed.
188 /// This covers the following cases:
189 ///
190 /// * if a class implements a QOM interface, the Rust code _has_ to define its
191 ///   own class struct `FooClass` and implement `ClassInitImpl<FooClass>`.
192 ///   `ClassInitImpl<FooClass>`'s `class_init` method will then forward to
193 ///   multiple other `class_init`s, for the interfaces as well as the
194 ///   superclass. (Note that there is no Rust example yet for using interfaces).
195 ///
196 /// * for classes implemented outside the ``qemu-api`` crate, it's not possible
197 ///   to add blanket implementations like the above one, due to orphan rules. In
198 ///   that case, the easiest solution is to implement
199 ///   `ClassInitImpl<YourSuperclass>` for each subclass and not have a
200 ///   `YourSuperclassImpl` trait at all.
201 ///
202 /// ```ignore
203 /// impl ClassInitImpl<YourSuperclass> for YourSubclass {
204 ///     fn class_init(klass: &mut YourSuperclass) {
205 ///         klass.some_method = Some(Self::some_method);
206 ///         <Self as ClassInitImpl<SysBusDeviceClass>>::class_init(&mut klass.parent_class);
207 ///     }
208 /// }
209 /// ```
210 ///
211 ///   While this method incurs a small amount of code duplication,
212 ///   it is generally limited to the recursive call on the last line.
213 ///   This is because classes defined in Rust do not need the same
214 ///   glue code that is needed when the classes are defined in C code.
215 ///   You may consider using a macro if you have many subclasses.
216 pub trait ClassInitImpl<T> {
217     /// Initialize `klass` to point to the virtual method implementations
218     /// for `Self`.  On entry, the virtual method pointers are set to
219     /// the default values coming from the parent classes; the function
220     /// can change them to override virtual methods of a parent class.
221     ///
222     /// The virtual method implementations usually come from another
223     /// trait, for example [`DeviceImpl`](crate::qdev::DeviceImpl)
224     /// when `T` is [`DeviceClass`](crate::bindings::DeviceClass).
225     ///
226     /// On entry, `klass`'s parent class is initialized, while the other fields
227     /// are all zero; it is therefore assumed that all fields in `T` can be
228     /// zeroed, otherwise it would not be possible to provide the class as a
229     /// `&mut T`.  TODO: add a bound of [`Zeroable`](crate::zeroable::Zeroable)
230     /// to T; this is more easily done once Zeroable does not require a manual
231     /// implementation (Rust 1.75.0).
232     fn class_init(klass: &mut T);
233 }
234 
235 /// # Safety
236 ///
237 /// We expect the FFI user of this function to pass a valid pointer that
238 /// can be downcasted to type `T`. We also expect the device is
239 /// readable/writeable from one thread at any time.
240 unsafe extern "C" fn rust_unparent_fn<T: ObjectImpl>(dev: *mut Object) {
241     unsafe {
242         assert!(!dev.is_null());
243         let state = core::ptr::NonNull::new_unchecked(dev.cast::<T>());
244         T::UNPARENT.unwrap()(state.as_ref());
245     }
246 }
247 
248 impl<T> ClassInitImpl<ObjectClass> for T
249 where
250     T: ObjectImpl,
251 {
252     fn class_init(oc: &mut ObjectClass) {
253         if <T as ObjectImpl>::UNPARENT.is_some() {
254             oc.unparent = Some(rust_unparent_fn::<T>);
255         }
256     }
257 }
258 
259 unsafe impl ObjectType for Object {
260     type Class = ObjectClass;
261     const TYPE_NAME: &'static CStr =
262         unsafe { CStr::from_bytes_with_nul_unchecked(bindings::TYPE_OBJECT) };
263 }
264