rust: qom: add casting functionality

Add traits that let client cast typecast safely between object types.
In particular, an upcast is compile-time guaranteed to succeed, and a
YOLO C-style downcast must be marked as unsafe.

The traits are based on an IsA<> trait that declares what
is a subclass of what, which is an idea taken from glib-rs
(https://docs.rs/glib/latest/glib/object/trait.IsA.html).
The four primitives are also taken from there
(https://docs.rs/glib/latest/glib/object/trait.Cast.html).  However,
the implementation of casting itself is a bit different and uses the
Deref trait.

This removes some pointer arithmetic from the pl011 device; it is also a
prerequisite for the definition of methods, so that they can be invoked
on all subclass structs.  This will use the IsA<> trait to detect the
structs that support the methods.

glib also has a "monadic" casting trait which could be implemented on
Option (as in https://docs.rs/glib/latest/glib/object/trait.CastNone.html)
and perhaps even Result.  For now I'm leaving it out, as the patch is
already big enough and the benefit seems debatable.

Reviewed-by: Zhao Liu <zhao1.liu@intel.com>
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
This commit is contained in:
Paolo Bonzini 2024-12-19 14:32:16 +01:00
parent c2f41c1b15
commit f50cd85c84
7 changed files with 366 additions and 13 deletions

View file

@ -106,6 +106,8 @@ pub struct PL011State {
device_id: DeviceId,
}
qom_isa!(PL011State : SysBusDevice, DeviceState, Object);
unsafe impl ObjectType for PL011State {
type Class = <SysBusDevice as ObjectType>::Class;
const TYPE_NAME: &'static CStr = crate::TYPE_PL011;
@ -140,8 +142,6 @@ impl PL011State {
unsafe fn init(&mut self) {
const CLK_NAME: &CStr = c_str!("clk");
let sbd = unsafe { &mut *(addr_of_mut!(*self).cast::<SysBusDevice>()) };
// SAFETY:
//
// self and self.iomem are guaranteed to be valid at this point since callers
@ -155,15 +155,16 @@ impl PL011State {
Self::TYPE_NAME.as_ptr(),
0x1000,
);
let sbd: &mut SysBusDevice = self.upcast_mut();
sysbus_init_mmio(sbd, addr_of_mut!(self.iomem));
}
for irq in self.interrupts.iter() {
let sbd: &SysBusDevice = self.upcast();
sbd.init_irq(irq);
}
let dev = addr_of_mut!(*self).cast::<DeviceState>();
// SAFETY:
//
// self.clock is not initialized at this point; but since `NonNull<_>` is Copy,
@ -172,6 +173,7 @@ impl PL011State {
// calls this function to initialize the fields; therefore no code is
// able to access an invalid self.clock value.
unsafe {
let dev: &mut DeviceState = self.upcast_mut();
self.clock = NonNull::new(qdev_init_clock_in(
dev,
CLK_NAME.as_ptr(),
@ -632,6 +634,8 @@ impl PL011Luminary {
}
}
qom_isa!(PL011Luminary : PL011State, SysBusDevice, DeviceState, Object);
unsafe impl ObjectType for PL011Luminary {
type Class = <PL011State as ObjectType>::Class;
const TYPE_NAME: &'static CStr = crate::TYPE_PL011_LUMINARY;