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