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