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