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