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