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