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