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