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