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