Skip to contentSkip to conversation

rust: add qdev DeviceProperties derive macro

RFC PATCH Superseded Manos Pitsidianakis 3 participants 5 messages May 22, 2025 – May 28, 2025 Rust

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

RFC PATCH 1/1 rust: add qdev DeviceProperties derive macro

Add derive macro for declaring qdev properties directly above the field definitions. To do this, we split DeviceImpl::properties method on a separate trait so we can implement only that part in the derive macro expansion (we cannot partially implement the DeviceImpl trait).

Adding a property attribute above the field declaration will generate a qemu_api::bindings::Property array member in the device's property list.

As a proof of concept, I added a typed alias for booleans, bool_property that allows you to skip specifying qdev_prop_bool.

This is unnecessary though, because once we have the const_refs_to_static feature we can introduce a QdevProp trait that returns a reference to a type's qdev_prop_* global variable. We cannot do this now because for our minimum Rust version we cannot refer to statics from const values.

It'd look like this:

  pub trait QDevProp {
    const VALUE: &'static bindings::PropertyInfo;
  }

  impl QDevProp for bool {
    const VALUE: &'static bindings::PropertyInfo = unsafe {
      &bindings::qdev_prop_bool };
  }

  impl QDevProp for u64 {
    const VALUE: &'static bindings::PropertyInfo = unsafe {
      &bindings::qdev_prop_uint64 };
  }

// etc.. for all basic types

So, this patch is not for merging yet, I will wait until we upgrade the Rust version and re-spin it with a proper trait-based implementation (and also split it into individual steps/patches).

---
 rust/hw/char/pl011/src/device.rs       |  13 +--
 rust/hw/char/pl011/src/device_class.rs |  26 +-----
 rust/hw/timer/hpet/src/hpet.rs         |   4 +-
 rust/qemu-api-macros/src/lib.rs        | 157 ++++++++++++++++++++++++++++++++-
 rust/qemu-api/src/qdev.rs              |  22 +++--
 rust/qemu-api/tests/tests.rs           |   9 +-
 6 files changed, 187 insertions(+), 44 deletions(-)
rust/hw/char/pl011/src/device.rs +8 -5
index bde3be65c5b0d9dbb117407734d93fff577ddecf..e22f5421dc5d9cd5c6fa8b11ab746e5c254bdb37 100644
@@ -10,7 +10,10 @@
     irq::{IRQState, InterruptSource},
     memory::{hwaddr, MemoryRegion, MemoryRegionOps, MemoryRegionOpsBuilder},
     prelude::*,
-    qdev::{Clock, ClockEvent, DeviceImpl, DeviceState, Property, ResetType, ResettablePhasesImpl},
+    qdev::{
+        Clock, ClockEvent, DeviceImpl, DevicePropertiesImpl, DeviceState, ResetType,
+        ResettablePhasesImpl,
+    },
     qom::{ObjectImpl, Owned, ParentField},
     static_assert,
     sysbus::{SysBusDevice, SysBusDeviceImpl},
@@ -98,12 +101,13 @@ pub struct PL011Registers {
 }
 
 #[repr(C)]
-#[derive(qemu_api_macros::Object)]
+#[derive(qemu_api_macros::Object, qemu_api_macros::DeviceProperties)]
 /// PL011 Device Model in QEMU
 pub struct PL011State {
     pub parent_obj: ParentField<SysBusDevice>,
     pub iomem: MemoryRegion,
     #[doc(alias = "chr")]
+    #[property(name = c"chardev", qdev_prop = qemu_api::bindings::qdev_prop_chr)]
     pub char_backend: CharBackend,
     pub regs: BqlRefCell<PL011Registers>,
     /// QEMU interrupts
@@ -122,6 +126,7 @@ pub struct PL011State {
     #[doc(alias = "clk")]
     pub clock: Owned<Clock>,
     #[doc(alias = "migrate_clk")]
+    #[bool_property(name = c"migrate-clk", default = true)]
     pub migrate_clock: bool,
 }
 
@@ -169,9 +174,6 @@ impl ObjectImpl for PL011State {
 }
 
 impl DeviceImpl for PL011State {
-    fn properties() -> &'static [Property] {
-        &device_class::PL011_PROPERTIES
-    }
     fn vmsd() -> Option<&'static VMStateDescription> {
         Some(&device_class::VMSTATE_PL011)
     }
@@ -703,6 +705,7 @@ impl PL011Impl for PL011Luminary {
     const DEVICE_ID: DeviceId = DeviceId(&[0x11, 0x00, 0x18, 0x01, 0x0d, 0xf0, 0x05, 0xb1]);
 }
 
+impl DevicePropertiesImpl for PL011Luminary {}
 impl DeviceImpl for PL011Luminary {}
 impl ResettablePhasesImpl for PL011Luminary {}
 impl SysBusDeviceImpl for PL011Luminary {}
rust/hw/char/pl011/src/device_class.rs +2 -24
index d328d846323f6080a9573053767e51481eb32941..83d70d7d82aac4a3252a0b4cb24af705b01d3635 100644
@@ -8,11 +8,8 @@
 };
 
 use qemu_api::{
-    bindings::{qdev_prop_bool, qdev_prop_chr},
-    prelude::*,
-    vmstate::VMStateDescription,
-    vmstate_clock, vmstate_fields, vmstate_of, vmstate_struct, vmstate_subsections, vmstate_unused,
-    zeroable::Zeroable,
+    prelude::*, vmstate::VMStateDescription, vmstate_clock, vmstate_fields, vmstate_of,
+    vmstate_struct, vmstate_subsections, vmstate_unused, zeroable::Zeroable,
 };
 
 use crate::device::{PL011Registers, PL011State};
@@ -82,22 +79,3 @@ extern "C" fn pl011_post_load(opaque: *mut c_void, version_id: c_int) -> c_int {
     },
     ..Zeroable::ZERO
 };
-
-qemu_api::declare_properties! {
-    PL011_PROPERTIES,
-    qemu_api::define_property!(
-        c"chardev",
-        PL011State,
-        char_backend,
-        unsafe { &qdev_prop_chr },
-        CharBackend
-    ),
-    qemu_api::define_property!(
-        c"migrate-clk",
-        PL011State,
-        migrate_clock,
-        unsafe { &qdev_prop_bool },
-        bool,
-        default = true
-    ),
-}
rust/hw/timer/hpet/src/hpet.rs +3 -1
index 779681d650998291f138e8cc61807612b8597961..21ebcfc9f22f8f5463812db218a1dc2039eda75b 100644
@@ -1033,11 +1033,13 @@ impl ObjectImpl for HPETState {
     ..Zeroable::ZERO
 };
 
-impl DeviceImpl for HPETState {
+impl qemu_api::qdev::DevicePropertiesImpl for HPETState {
     fn properties() -> &'static [Property] {
         &HPET_PROPERTIES
     }
+}
 
+impl DeviceImpl for HPETState {
     fn vmsd() -> Option<&'static VMStateDescription> {
         Some(&VMSTATE_HPET)
     }
rust/qemu-api-macros/src/lib.rs +154 -3

170 lines not on this page · raw message

rust/qemu-api/src/qdev.rs +13 -9
index 1279d7a58d50e1bf6c8d2e6f00d7229bbb19e003..2fd8b2750ffabcaa1065558d38a700e35fbc9136 100644
@@ -100,8 +100,19 @@ pub trait ResettablePhasesImpl {
     T::EXIT.unwrap()(unsafe { state.as_ref() }, typ);
 }
 
+pub trait DevicePropertiesImpl {
+    /// An array providing the properties that the user can set on the
+    /// device.  Not a `const` because referencing statics in constants
+    /// is unstable until Rust 1.83.0.
+    fn properties() -> &'static [Property] {
+        &[]
+    }
+}
+
 /// Trait providing the contents of [`DeviceClass`].
-pub trait DeviceImpl: ObjectImpl + ResettablePhasesImpl + IsA<DeviceState> {
+pub trait DeviceImpl:
+    ObjectImpl + ResettablePhasesImpl + DevicePropertiesImpl + IsA<DeviceState>
+{
     /// _Realization_ is the second stage of device creation. It contains
     /// all operations that depend on device properties and can fail (note:
     /// this is not yet supported for Rust devices).
@@ -110,13 +121,6 @@ pub trait DeviceImpl: ObjectImpl + ResettablePhasesImpl + IsA<DeviceState> {
     /// with the function pointed to by `REALIZE`.
     const REALIZE: Option<fn(&Self)> = None;
 
-    /// An array providing the properties that the user can set on the
-    /// device.  Not a `const` because referencing statics in constants
-    /// is unstable until Rust 1.83.0.
-    fn properties() -> &'static [Property] {
-        &[]
-    }
-
     /// A `VMStateDescription` providing the migration format for the device
     /// Not a `const` because referencing statics in constants is unstable
     /// until Rust 1.83.0.
@@ -171,7 +175,7 @@ pub fn class_init<T: DeviceImpl>(&mut self) {
         if let Some(vmsd) = <T as DeviceImpl>::vmsd() {
             self.vmsd = vmsd;
         }
-        let prop = <T as DeviceImpl>::properties();
+        let prop = <T as DevicePropertiesImpl>::properties();
         if !prop.is_empty() {
             unsafe {
                 bindings::device_class_set_props_n(self, prop.as_ptr(), prop.len());
rust/qemu-api/tests/tests.rs +7 -2
index a658a49fcfdda8fa4b9d139c10afb6ff3243790b..e8eadfd6e9add385ffc97de015b84aae825c18ee 100644
@@ -9,7 +9,7 @@
     cell::{self, BqlCell},
     declare_properties, define_property,
     prelude::*,
-    qdev::{DeviceImpl, DeviceState, Property, ResettablePhasesImpl},
+    qdev::{DeviceImpl, DevicePropertiesImpl, DeviceState, Property, ResettablePhasesImpl},
     qom::{ObjectImpl, ParentField},
     sysbus::SysBusDevice,
     vmstate::VMStateDescription,
@@ -68,10 +68,13 @@ impl ObjectImpl for DummyState {
 
 impl ResettablePhasesImpl for DummyState {}
 
-impl DeviceImpl for DummyState {
+impl DevicePropertiesImpl for DummyState {
     fn properties() -> &'static [Property] {
         &DUMMY_PROPERTIES
     }
+}
+
+impl DeviceImpl for DummyState {
     fn vmsd() -> Option<&'static VMStateDescription> {
         Some(&VMSTATE)
     }
@@ -85,6 +88,8 @@ pub struct DummyChildState {
 
 qom_isa!(DummyChildState: Object, DeviceState, DummyState);
 
+impl DevicePropertiesImpl for DummyChildState {}
+
 pub struct DummyChildClass {
     parent_class: <DummyState as ObjectType>::Class,
 }

---
base-commit: 2af4a82ab2cce3412ffc92cd4c96bd870e33bc8e
change-id: 20250522-rust-qdev-properties-728e8f6a468e

--
γαῖα πυρί μιχθήτω

#1 lore raw
Quoted 39 lines · Manos Pitsidianakis

Date: Thu, 22 May 2025 11:12:30 +0300
From: Manos Pitsidianakis <[email protected]>
Subject: [PATCH WIP RFC] rust: add qdev DeviceProperties derive macro
X-Mailer: b4 0.14.2

Add derive macro for declaring qdev properties directly above the field definitions. To do this, we split DeviceImpl::properties method on a separate trait so we can implement only that part in the derive macro expansion (we cannot partially implement the DeviceImpl trait).

Adding a property attribute above the field declaration will generate a qemu_api::bindings::Property array member in the device's property list.

As a proof of concept, I added a typed alias for booleans, bool_property that allows you to skip specifying qdev_prop_bool.

This is unnecessary though, because once we have the const_refs_to_static feature we can introduce a QdevProp trait that returns a reference to a type's qdev_prop_* global variable. We cannot do this now because for our minimum Rust version we cannot refer to statics from const values.

It'd look like this:

  pub trait QDevProp {
    const VALUE: &'static bindings::PropertyInfo;
  }

  impl QDevProp for bool {
    const VALUE: &'static bindings::PropertyInfo = unsafe {
      &bindings::qdev_prop_bool };
  }

  impl QDevProp for u64 {
    const VALUE: &'static bindings::PropertyInfo = unsafe {
      &bindings::qdev_prop_uint64 };
  }
Quoted 1 line

// etc.. for all basic types

Good idea! We can have something like current impl_vmstate_scalar.

Quoted 3 lines

So, this patch is not for merging yet, I will wait until we upgrade the Rust version and re-spin it with a proper trait-based implementation (and also split it into individual steps/patches).

I think this can be aligned with Paolo's optimization for vmstate [*]

[*]: https://lore.kernel.org/qemu-devel/[email protected]/

Quoted 9 lines
---
 rust/hw/char/pl011/src/device.rs       |  13 +--
 rust/hw/char/pl011/src/device_class.rs |  26 +-----
 rust/hw/timer/hpet/src/hpet.rs         |   4 +-
 rust/qemu-api-macros/src/lib.rs        | 157 ++++++++++++++++++++++++++++++++-
 rust/qemu-api/src/qdev.rs              |  22 +++--
 rust/qemu-api/tests/tests.rs           |   9 +-
 6 files changed, 187 insertions(+), 44 deletions(-)

...

rust/hw/char/pl011/src/device.rs pub struct PL011Registers { · line 110

Quoted 9 lines

#[repr(C)]

rust/hw/char/pl011/src/device.rs +2 -1
-#[derive(qemu_api_macros::Object)]
+#[derive(qemu_api_macros::Object, qemu_api_macros::DeviceProperties)]
 /// PL011 Device Model in QEMU
 pub struct PL011State {
     pub parent_obj: ParentField<SysBusDevice>,
     pub iomem: MemoryRegion,
     #[doc(alias = "chr")]
+    #[property(name = c"chardev", qdev_prop = qemu_api::bindings::qdev_prop_chr)]

This macro pattern looks good!

As you mentioned above, with QDevProp, this could be nicer so that user wouldn't have to bind type and PropertyInfo manually.

Quoted 29 lines

pub char_backend: CharBackend,
pub regs: BqlRefCell<PL011Registers>,
/// QEMU interrupts

rust/hw/char/pl011/src/device.rs +2 -3
@@ -122,6 +126,7 @@ pub struct PL011State {
     #[doc(alias = "clk")]
     pub clock: Owned<Clock>,
     #[doc(alias = "migrate_clk")]
+    #[bool_property(name = c"migrate-clk", default = true)]
     pub migrate_clock: bool,
 }
 
@@ -169,9 +174,6 @@ impl ObjectImpl for PL011State {
 }
 
 impl DeviceImpl for PL011State {
-    fn properties() -> &'static [Property] {
-        &device_class::PL011_PROPERTIES
-    }
     fn vmsd() -> Option<&'static VMStateDescription> {
         Some(&device_class::VMSTATE_PL011)
     }
@@ -703,6 +705,7 @@ impl PL011Impl for PL011Luminary {
     const DEVICE_ID: DeviceId = DeviceId(&[0x11, 0x00, 0x18, 0x01, 0x0d, 0xf0, 0x05, 0xb1]);
 }
 
+impl DevicePropertiesImpl for PL011Luminary {}
 impl DeviceImpl for PL011Luminary {}
 impl ResettablePhasesImpl for PL011Luminary {}
 impl SysBusDeviceImpl for PL011Luminary {}

...

Quoted 12 lines
rust/qemu-api/src/qdev.rs +4 -0
index 1279d7a58d50e1bf6c8d2e6f00d7229bbb19e003..2fd8b2750ffabcaa1065558d38a700e35fbc9136 100644
@@ -100,8 +100,19 @@ pub trait ResettablePhasesImpl {
     T::EXIT.unwrap()(unsafe { state.as_ref() }, typ);
 }
 
+pub trait DevicePropertiesImpl {
+    /// An array providing the properties that the user can set on the
+    /// device.  Not a `const` because referencing statics in constants
+    /// is unstable until Rust 1.83.0.

rust/qemu-api/src/qdev.rs pub trait ResettablePhasesImpl { · line 115

Quoted 10 lines
rust/qemu-api/src/qdev.rs +8 -1
+    fn properties() -> &'static [Property] {
+        &[]
+    }
+}
+
 /// Trait providing the contents of [`DeviceClass`].
-pub trait DeviceImpl: ObjectImpl + ResettablePhasesImpl + IsA<DeviceState> {
+pub trait DeviceImpl:
+    ObjectImpl + ResettablePhasesImpl + DevicePropertiesImpl + IsA<DeviceState>
+{

DeviceImpl has a new bound: DevicePropertiesImpl, which means that devices that don't need properties also need to implement the empty DevicePropertiesImpl.

We now have ResettablePhasesImpl that needs to do this, but I'm not sure if we should continue to add more examples?

Quoted 4 lines
rust/qemu-api/src/qdev.rs +0 -0
     /// _Realization_ is the second stage of device creation. It contains
     /// all operations that depend on device properties and can fail (note:
     /// this is not yet supported for Rust devices).

rust/qemu-api/src/qdev.rs pub trait DeviceImpl: ObjectImpl + ResettablePhasesImpl + IsA<DeviceState> { · line 119

Quoted 10 lines
rust/qemu-api/src/qdev.rs +0 -7
@@ -110,13 +121,6 @@ pub trait DeviceImpl: ObjectImpl + ResettablePhasesImpl + IsA<DeviceState> {
     /// with the function pointed to by `REALIZE`.
     const REALIZE: Option<fn(&Self)> = None;
 
-    /// An array providing the properties that the user can set on the
-    /// device.  Not a `const` because referencing statics in constants
-    /// is unstable until Rust 1.83.0.
-    fn properties() -> &'static [Property] {
-        &[]
-    }
-

This default empty Property array looks more convenient than this:

impl DevicePropertiesImpl for DummyChildState {}

However, if there's no way to avoid adding DevicePropertiesImpl, the cost of an empty trait could be acceptable relative to the benefit of this more friendly macro, I think!

Thanks,
Zhao

Quoted 12 lines
rust/qemu-api/src/qdev.rs +1 -1
     /// A `VMStateDescription` providing the migration format for the device
     /// Not a `const` because referencing statics in constants is unstable
     /// until Rust 1.83.0.
@@ -171,7 +175,7 @@ pub fn class_init<T: DeviceImpl>(&mut self) {
         if let Some(vmsd) = <T as DeviceImpl>::vmsd() {
             self.vmsd = vmsd;
         }
-        let prop = <T as DeviceImpl>::properties();
+        let prop = <T as DevicePropertiesImpl>::properties();
         if !prop.is_empty() {
             unsafe {
                 bindings::device_class_set_props_n(self, prop.as_ptr(), prop.len());
#2 lore raw
In reply to Manos Pitsidianakis

Il gio 22 mag 2025, 10:12 Manos Pitsidianakis <
[email protected]> ha scritto:

Quoted 6 lines

This is unnecessary though, because once we have the const_refs_to_static feature we can introduce a QdevProp trait that returns a reference to a type's qdev_prop_* global variable. We cannot do this now because for our minimum Rust version we cannot refer to statics from const values.

Why don't you already write it assuming const_refs_to_static? If needed we can add a hack to make the VALUE an enum, similar to what is already in vmstate.rs.

So, this patch is not for merging yet, I will wait until we upgrade the

Quoted 3 lines

Rust version and re-spin it with a proper trait-based implementation (and also split it into individual steps/patches).

It's not too large, overall.

#[repr(C)]

Review

Quoted 3 lines
(quoted diff) +1 -1
-#[derive(qemu_api_macros::Object)]
+#[derive(qemu_api_macros::Object, qemu_api_macros::DeviceProperties)]

Is there more to be derived that is useful for Devices? Maybe the macro can be DeviceState or Device.

+ #[property(name = c"chardev", qdev_prop =

Quoted 2 lines

qemu_api::bindings::qdev_prop_chr)]

Can you change the name to be a "normal" string and change it to a C literal in the macro?

(quoted diff) +0 -0
Quoted 20 lines

b/rust/hw/char/pl011/src/device_class.rs
index d328d846323f6080a9573053767e51481eb32941..83d70d7d82aac4a3252a0b4cb24af705b01d3635 100644

rust/hw/char/pl011/src/device_class.rs +2 -5
@@ -8,11 +8,8 @@
 };
 
 use qemu_api::{
-    bindings::{qdev_prop_bool, qdev_prop_chr},
-    prelude::*,
-    vmstate::VMStateDescription,
-    vmstate_clock, vmstate_fields, vmstate_of, vmstate_struct,
 vmstate_subsections, vmstate_unused,
-    zeroable::Zeroable,
+    prelude::*, vmstate::VMStateDescription, vmstate_clock,
 vmstate_fields, vmstate_of,
+    vmstate_struct, vmstate_subsections, vmstate_unused,
 zeroable::Zeroable,
Quoted 2 lines

};

I would also merge the files at this point, but no hurry.

+#[derive(Debug)]

rust/hw/char/pl011/src/device_class.rs

Quoted 10 lines
rust/hw/char/pl011/src/device_class.rs +9 -0
+struct DeviceProperty {
+    name: Option<syn::LitCStr>,
+    qdev_prop: Option<syn::Path>,
+    assert_type: Option<proc_macro2::TokenStream>,
+    bitnr: Option<syn::Expr>,
+    defval: Option<syn::Expr>,
+}
+
+impl Parse for DeviceProperty {

Can you look into using https://docs.rs/crate/attrs/latest for parsing?

(attrs doesn't support LitCStr btw)

+#[proc_macro_derive(DeviceProperties, attributes(property, bool_property))]

Quoted 2 lines

+pub fn derive_device_properties(input: TokenStream) -> TokenStream {

Do you need to handle errors in the parsing of attributes?...

+ _other => unreachable!(),

Quoted 1 line

... Yes, you do—there is code already in qemu_macros, used by derive_object_or_error(), to get the fields of a struct with proper error handling.

let prop_name = prop.name.as_ref().unwrap();

+ let field_name = field.ident.as_ref().unwrap();

+ let qdev_prop = prop.qdev_prop.as_ref().unwrap();

+ let bitnr = prop.bitnr.as_ref().unwrap_or(&zero);

+ let set_default = prop.defval.is_some();

+ let defval = prop.defval.as_ref().unwrap_or(&zero);+

Quoted 2 lines

bitnr: #bitnr,
+

You also need to use let...else here instead of unwrap(), since panicking provides worse error messages.

set_default: #set_default,

Quoted 3 lines

+ defval: ::qemu_api::bindings::Property__bindgen_ty_1 { u:
#defval as u64 },

If you like it, you can write this also as

#(bitnr: #bitnr,)?
#(set_default: true, defval: ...)?

and keep bitnr and defval as Options, since the None case is handled by the default below.

Paolo

+ ..::qemu_api::zeroable::Zeroable::ZERO

Quoted 127 lines
rust/hw/char/pl011/src/device_class.rs +9 -0
+            }
+        });
+    }
+    let properties_expanded = quote_spanned! {span.into()=>
+        #(#assertions)*
+
+        impl ::qemu_api::qdev::DevicePropertiesImpl for #name {
+            fn properties() -> &'static [::qemu_api::bindings::Property] {
+                static PROPERTIES: &'static

[::qemu_api::bindings::Property] = &[#(#properties_expanded),*];

rust/hw/char/pl011/src/device_class.rs +9 -0
+
+                PROPERTIES
+            }
+        }
+    };
+
+    TokenStream::from(properties_expanded)
+}
+
 #[proc_macro_derive(Wrapper)]
 pub fn derive_opaque(input: TokenStream) -> TokenStream {
     let input = parse_macro_input!(input as DeriveInput);
rust/qemu-api/src/qdev.rs +0 -0

index 1279d7a58d50e1bf6c8d2e6f00d7229bbb19e003..2fd8b2750ffabcaa1065558d38a700e35fbc9136 100644

rust/qemu-api/src/qdev.rs +11 -1
@@ -100,8 +100,19 @@ pub trait ResettablePhasesImpl {
     T::EXIT.unwrap()(unsafe { state.as_ref() }, typ);
 }
 
+pub trait DevicePropertiesImpl {
+    /// An array providing the properties that the user can set on the
+    /// device.  Not a `const` because referencing statics in constants
+    /// is unstable until Rust 1.83.0.
+    fn properties() -> &'static [Property] {
+        &[]
+    }
+}
+
 /// Trait providing the contents of [`DeviceClass`].
-pub trait DeviceImpl: ObjectImpl + ResettablePhasesImpl +
 IsA<DeviceState> {
+pub trait DeviceImpl:
+    ObjectImpl + ResettablePhasesImpl + DevicePropertiesImpl +

IsA<DeviceState>

+{
     /// _Realization_ is the second stage of device creation. It contains
     /// all operations that depend on device properties and can fail
(note:
     /// this is not yet supported for Rust devices).
rust/qemu-api/src/qdev.rs +0 -7
@@ -110,13 +121,6 @@ pub trait DeviceImpl: ObjectImpl +
 ResettablePhasesImpl + IsA<DeviceState> {
     /// with the function pointed to by `REALIZE`.
     const REALIZE: Option<fn(&Self)> = None;
 
-    /// An array providing the properties that the user can set on the
-    /// device.  Not a `const` because referencing statics in constants
-    /// is unstable until Rust 1.83.0.
-    fn properties() -> &'static [Property] {
-        &[]
-    }
-
     /// A `VMStateDescription` providing the migration format for the

device

     /// Not a `const` because referencing statics in constants is unstable
     /// until Rust 1.83.0.
rust/qemu-api/src/qdev.rs +1 -1
@@ -171,7 +175,7 @@ pub fn class_init<T: DeviceImpl>(&mut self) {
         if let Some(vmsd) = <T as DeviceImpl>::vmsd() {
             self.vmsd = vmsd;
         }
-        let prop = <T as DeviceImpl>::properties();
+        let prop = <T as DevicePropertiesImpl>::properties();
         if !prop.is_empty() {
             unsafe {
                 bindings::device_class_set_props_n(self, prop.as_ptr(),

prop.len());

rust/qemu-api/tests/tests.rs +0 -0

index a658a49fcfdda8fa4b9d139c10afb6ff3243790b..e8eadfd6e9add385ffc97de015b84aae825c18ee 100644

rust/qemu-api/tests/tests.rs +1 -1
@@ -9,7 +9,7 @@
     cell::{self, BqlCell},
     declare_properties, define_property,
     prelude::*,
-    qdev::{DeviceImpl, DeviceState, Property, ResettablePhasesImpl},
+    qdev::{DeviceImpl, DevicePropertiesImpl, DeviceState, Property,
 ResettablePhasesImpl},
     qom::{ObjectImpl, ParentField},
     sysbus::SysBusDevice,

vmstate::VMStateDescription,

rust/qemu-api/tests/tests.rs +6 -2
@@ -68,10 +68,13 @@ impl ObjectImpl for DummyState {
 
 impl ResettablePhasesImpl for DummyState {}
 
-impl DeviceImpl for DummyState {
+impl DevicePropertiesImpl for DummyState {
     fn properties() -> &'static [Property] {
         &DUMMY_PROPERTIES
     }
+}
+
+impl DeviceImpl for DummyState {
     fn vmsd() -> Option<&'static VMStateDescription> {
         Some(&VMSTATE)
     }
@@ -85,6 +88,8 @@ pub struct DummyChildState {
 
 qom_isa!(DummyChildState: Object, DeviceState, DummyState);
 
+impl DevicePropertiesImpl for DummyChildState {}
+
 pub struct DummyChildClass {
     parent_class: <DummyState as ObjectType>::Class,
 }
 
---

base-commit: 2af4a82ab2cce3412ffc92cd4c96bd870e33bc8e
change-id: 20250522-rust-qdev-properties-728e8f6a468e

--
γαῖα πυρί μιχθήτω

#3 lore raw
Quoted 19 lines · Paolo Bonzini

Il gio 22 mag 2025, 10:12 Manos Pitsidianakis <[email protected]> ha scritto:

Quoted 6 lines

This is unnecessary though, because once we have the const_refs_to_static feature we can introduce a QdevProp trait that returns a reference to a type's qdev_prop_* global variable. We cannot do this now because for our minimum Rust version we cannot refer to statics from const values.

Why don't you already write it assuming const_refs_to_static? If needed we can add a hack to make the VALUE an enum, similar to what is already in vmstate.rs.

Quoted 3 lines

So, this patch is not for merging yet, I will wait until we upgrade the Rust version and re-spin it with a proper trait-based implementation (and also split it into individual steps/patches).

Quoted 8 lines

It's not too large, overall.

Review

Quoted 3 lines

#[repr(C)]

(quoted diff) +1 -1
-#[derive(qemu_api_macros::Object)]
+#[derive(qemu_api_macros::Object, qemu_api_macros::DeviceProperties)]

Is there more to be derived that is useful for Devices? Maybe the macro can be DeviceState or Device.

VMStateDescription and the realize callback, I think.

Quoted 5 lines
Quoted 2 lines

+ #[property(name = c"chardev", qdev_prop = qemu_api::bindings::qdev_prop_chr)]

Can you change the name to be a "normal" string and change it to a C literal in the macro?

That'd be neat, it should be possible to create a cstr literal token and error out if the input str literal cannot be represented as a cstr.

Quoted 35 lines
Quoted 7 lines
rust/hw/char/pl011/src/device_class.rs +0 -0
index d328d846323f6080a9573053767e51481eb32941..83d70d7d82aac4a3252a0b4cb24af705b01d3635 100644
@@ -8,11 +8,8 @@
 };

rust/hw/char/pl011/src/device_class.rs line 13

Quoted 10 lines
rust/hw/char/pl011/src/device_class.rs +2 -5
 
 use qemu_api::{
-    bindings::{qdev_prop_bool, qdev_prop_chr},
-    prelude::*,
-    vmstate::VMStateDescription,
-    vmstate_clock, vmstate_fields, vmstate_of, vmstate_struct, vmstate_subsections, vmstate_unused,
-    zeroable::Zeroable,
+    prelude::*, vmstate::VMStateDescription, vmstate_clock, vmstate_fields, vmstate_of,
+    vmstate_struct, vmstate_subsections, vmstate_unused, zeroable::Zeroable,
 };

I would also merge the files at this point, but no hurry.

rust/hw/char/pl011/src/device_class.rs

Quoted 10 lines
rust/hw/char/pl011/src/device_class.rs +10 -0
+#[derive(Debug)]
+struct DeviceProperty {
+    name: Option<syn::LitCStr>,
+    qdev_prop: Option<syn::Path>,
+    assert_type: Option<proc_macro2::TokenStream>,
+    bitnr: Option<syn::Expr>,
+    defval: Option<syn::Expr>,
+}
+
+impl Parse for DeviceProperty {

Can you look into using https://docs.rs/crate/attrs/latest for parsing?

Quoted 1 line

(attrs doesn't support LitCStr btw)

I think we can do without it for now, even if this patch is not cleaned up (for example it has unwraps instead of proper panic messages or error handling) it does not end up very complex as far as attribute parsing is concerned.

I'm fine with either approach though.

Quoted 9 lines

rust/hw/char/pl011/src/device_class.rs

Quoted 3 lines
rust/hw/char/pl011/src/device_class.rs +2 -0
+#[proc_macro_derive(DeviceProperties, attributes(property, bool_property))]
+pub fn derive_device_properties(input: TokenStream) -> TokenStream {

Do you need to handle errors in the parsing of attributes?...

Quoted 1 line

+ _other => unreachable!(),

This should be literally unreachable IIUC, because only property names declared in the attributes part of #[proc_macro_derive(... attributes(__))] would get accepted by the compiler and passed to the derive macro.

Quoted 23 lines

... Yes, you do—there is code already in qemu_macros, used by derive_object_or_error(), to get the fields of a struct with proper error handling.

Quoted 4 lines

let prop_name = prop.name.as_ref().unwrap();

+ let field_name = field.ident.as_ref().unwrap();

Quoted 8 lines

+ let qdev_prop = prop.qdev_prop.as_ref().unwrap();

+ let bitnr = prop.bitnr.as_ref().unwrap_or(&zero);

+ let set_default = prop.defval.is_some();

+ let defval = prop.defval.as_ref().unwrap_or(&zero);+ bitnr: #bitnr,
+

You also need to use let...else here instead of unwrap(), since panicking provides worse error messages.

Quoted 2 lines

set_default: #set_default,
+ defval: ::qemu_api::bindings::Property__bindgen_ty_1 { u: #defval as u64 },

Quoted 8 lines

If you like it, you can write this also as

#(bitnr: #bitnr,)?
#(set_default: true, defval: ...)?

and keep bitnr and defval as Options, since the None case is handled by the default below.

Paolo

Thanks I will take another look!

Quoted 117 lines
Quoted 117 lines
rust/hw/char/pl011/src/device_class.rs +19 -0
+                ..::qemu_api::zeroable::Zeroable::ZERO
+            }
+        });
+    }
+    let properties_expanded = quote_spanned! {span.into()=>
+        #(#assertions)*
+
+        impl ::qemu_api::qdev::DevicePropertiesImpl for #name {
+            fn properties() -> &'static [::qemu_api::bindings::Property] {
+                static PROPERTIES: &'static [::qemu_api::bindings::Property] = &[#(#properties_expanded),*];
+
+                PROPERTIES
+            }
+        }
+    };
+
+    TokenStream::from(properties_expanded)
+}
+
 #[proc_macro_derive(Wrapper)]
 pub fn derive_opaque(input: TokenStream) -> TokenStream {
     let input = parse_macro_input!(input as DeriveInput);
rust/qemu-api/src/qdev.rs +13 -9
index 1279d7a58d50e1bf6c8d2e6f00d7229bbb19e003..2fd8b2750ffabcaa1065558d38a700e35fbc9136 100644
@@ -100,8 +100,19 @@ pub trait ResettablePhasesImpl {
     T::EXIT.unwrap()(unsafe { state.as_ref() }, typ);
 }
 
+pub trait DevicePropertiesImpl {
+    /// An array providing the properties that the user can set on the
+    /// device.  Not a `const` because referencing statics in constants
+    /// is unstable until Rust 1.83.0.
+    fn properties() -> &'static [Property] {
+        &[]
+    }
+}
+
 /// Trait providing the contents of [`DeviceClass`].
-pub trait DeviceImpl: ObjectImpl + ResettablePhasesImpl + IsA<DeviceState> {
+pub trait DeviceImpl:
+    ObjectImpl + ResettablePhasesImpl + DevicePropertiesImpl + IsA<DeviceState>
+{
     /// _Realization_ is the second stage of device creation. It contains
     /// all operations that depend on device properties and can fail (note:
     /// this is not yet supported for Rust devices).
@@ -110,13 +121,6 @@ pub trait DeviceImpl: ObjectImpl + ResettablePhasesImpl + IsA<DeviceState> {
     /// with the function pointed to by `REALIZE`.
     const REALIZE: Option<fn(&Self)> = None;
 
-    /// An array providing the properties that the user can set on the
-    /// device.  Not a `const` because referencing statics in constants
-    /// is unstable until Rust 1.83.0.
-    fn properties() -> &'static [Property] {
-        &[]
-    }
-
     /// A `VMStateDescription` providing the migration format for the device
     /// Not a `const` because referencing statics in constants is unstable
     /// until Rust 1.83.0.
@@ -171,7 +175,7 @@ pub fn class_init<T: DeviceImpl>(&mut self) {
         if let Some(vmsd) = <T as DeviceImpl>::vmsd() {
             self.vmsd = vmsd;
         }
-        let prop = <T as DeviceImpl>::properties();
+        let prop = <T as DevicePropertiesImpl>::properties();
         if !prop.is_empty() {
             unsafe {
                 bindings::device_class_set_props_n(self, prop.as_ptr(), prop.len());
rust/qemu-api/tests/tests.rs +7 -3
index a658a49fcfdda8fa4b9d139c10afb6ff3243790b..e8eadfd6e9add385ffc97de015b84aae825c18ee 100644
@@ -9,7 +9,7 @@
     cell::{self, BqlCell},
     declare_properties, define_property,
     prelude::*,
-    qdev::{DeviceImpl, DeviceState, Property, ResettablePhasesImpl},
+    qdev::{DeviceImpl, DevicePropertiesImpl, DeviceState, Property, ResettablePhasesImpl},
     qom::{ObjectImpl, ParentField},
     sysbus::SysBusDevice,
     vmstate::VMStateDescription,
@@ -68,10 +68,13 @@ impl ObjectImpl for DummyState {
 
 impl ResettablePhasesImpl for DummyState {}
 
-impl DeviceImpl for DummyState {
+impl DevicePropertiesImpl for DummyState {
     fn properties() -> &'static [Property] {
         &DUMMY_PROPERTIES
     }
+}
+
+impl DeviceImpl for DummyState {
     fn vmsd() -> Option<&'static VMStateDescription> {
         Some(&VMSTATE)
     }
@@ -85,6 +88,8 @@ pub struct DummyChildState {
 
 qom_isa!(DummyChildState: Object, DeviceState, DummyState);
 
+impl DevicePropertiesImpl for DummyChildState {}
+
 pub struct DummyChildClass {
     parent_class: <DummyState as ObjectType>::Class,
 }
 
---

base-commit: 2af4a82ab2cce3412ffc92cd4c96bd870e33bc8e
change-id: 20250522-rust-qdev-properties-728e8f6a468e

--
γαῖα πυρί μιχθήτω

#4 lore raw
Quoted 11 lines · Manos Pitsidianakis
Quoted 9 lines

It's not too large, overall.

Review

Quoted 3 lines

#[repr(C)]

(quoted diff) +1 -1
-#[derive(qemu_api_macros::Object)]
+#[derive(qemu_api_macros::Object, qemu_api_macros::DeviceProperties)]

Is there more to be derived that is useful for Devices? Maybe the macro can be DeviceState or Device.

VMStateDescription and the realize callback, I think.

Ok, pick the name that you prefer.

Quoted 5 lines
Quoted 1 line

Can you change the name to be a "normal" string and change it to a C literal in the macro?

That'd be neat, it should be possible to create a cstr literal token and error out if the input str literal cannot be represented as a cstr.

Yes, shouldn't be hard. If it is hard, you could resurrect the c_str module and use ::qemu_api::c_str!(#string).

Quoted 15 lines
Quoted 15 lines

I would also merge the files at this point, but no hurry.

Review

Quoted 10 lines
(quoted diff) +10 -0
+#[derive(Debug)]
+struct DeviceProperty {
+    name: Option<syn::LitCStr>,
+    qdev_prop: Option<syn::Path>,
+    assert_type: Option<proc_macro2::TokenStream>,
+    bitnr: Option<syn::Expr>,
+    defval: Option<syn::Expr>,
+}
+
+impl Parse for DeviceProperty {

Can you look into using https://docs.rs/crate/attrs/latest for parsing?

Quoted 8 lines
Quoted 1 line

(attrs doesn't support LitCStr btw)

I think we can do without it for now, even if this patch is not cleaned up (for example it has unwraps instead of proper panic messages or error handling) it does not end up very complex as far as attribute parsing is concerned.

I'm fine with either approach though.

Ok, I'm fine with the manual parsing as well; just use Result<> instead of panicking.

Quoted 6 lines
Quoted 6 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+#[proc_macro_derive(DeviceProperties, attributes(property, bool_property))]
+pub fn derive_device_properties(input: TokenStream) -> TokenStream {

Do you need to handle errors in the parsing of attributes?...

Quoted 6 lines
Quoted 1 line
Quoted 1 line

+ _other => unreachable!(),

This should be literally unreachable IIUC, because only property names declared in the attributes part of #[proc_macro_derive(... attributes(__))] would get accepted by the compiler and passed to the derive macro.

You're referring to

+ other => unreachable!("Got unexpected DeviceProperty attribute {}", other),

and indeed this one is good as is. The "_other => unreachable!()" line above, instead, comes from matching on input.data and it can be replaced with the existing function get_fields().

Paolo