rust: migration: add high-level migration wrappers
Subsystems (2)
cover rust: migration: add high-level migration wrappers
This series adds high-level wrappers to handle migration state; they consist of a Migratable<> type that implements the snapshotting technique mentioned in Zhao and my KVM Forum presentation.
The wrappers (should) make it possible to easily implement migration of thread-safe devices. I say "should" because, even though there are tests included in the series, they are anything but "battle tested"; for this reason they are marked as "proof of concept" in docs/devel/rust.rst. The first device to use this will be HPET.
This is an interesting step in enabling usage of Rust in QEMU; instead of just wrapping existing C APIs, it provides a new interface that deals better with unique features of the Rust language. In other words, something like Migratable<> and ToMigrationState might hypothetically exist even if QEMU was written in Rust from scratch.
Paolo
RFC->v1:
new patches
- rust: migration: do not pass raw pointer to VMStateDescription::fields
- rust: migration: do not store raw pointers into VMStateSubsectionsWrapper
- rust: migration: validate termination of subsection arrays
- timer: constify some functions
changes
- use UnsafeCell::get_mut()
- add and use Timer::expire_time_ns()
- small reordering of the implementations of ToMigrationState/ToMigrationStateShared
- list migration::migratable in docs/devel/rust.rst
Paolo Bonzini (11):
rust: bql: add BqlRefCell::get_mut()
rust: migration: do not pass raw pointer to VMStateDescription::fields
rust: migration: do not store raw pointers into
VMStateSubsectionsWrapper
rust: migration: validate termination of subsection arrays
rust: migration: extract vmstate_fields_ref
rust: move VMState from bql to migration
rust: migration: add high-level migration wrappers
rust: qemu-macros: add ToMigrationState derive macro
timer: constify some functions
rust: migration: implement ToMigrationState for Timer
rust: migration: implement ToMigrationState as part of
impl_vmstate_bitsized
docs/devel/rust.rst | 1 + include/qemu/timer.h | 6 +- util/qemu-timer.c | 8 +- rust/Cargo.lock | 5 +- rust/bql/Cargo.toml | 3 - rust/bql/meson.build | 1 - rust/bql/src/cell.rs | 23 +- rust/meson.build | 2 +- rust/migration/Cargo.toml | 2 + rust/migration/meson.build | 7 +- rust/migration/src/lib.rs | 5 + rust/migration/src/migratable.rs | 473 ++++++++++++++++++++++++ rust/migration/src/vmstate.rs | 85 +++-- rust/qemu-macros/src/lib.rs | 88 +++++ rust/qemu-macros/src/migration_state.rs | 296 +++++++++++++++ rust/qemu-macros/src/tests.rs | 112 +++++- rust/util/src/timer.rs | 10 +- 17 files changed, 1071 insertions(+), 56 deletions(-) create mode 100644 rust/migration/src/migratable.rs create mode 100644 rust/qemu-macros/src/migration_state.rs
Signature · 1 line
2.51.0
PATCH 1/11 rust: bql: add BqlRefCell::get_mut()
This method is rarely useful in QEMU due to the pervasiveness of shared references, but add it for when a &mut BqlRefCell<> is used.
--- rust/bql/src/cell.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+)
rust/bql/src/cell.rs +17 -0
@@ -580,6 +580,23 @@ pub fn borrow_mut(&self) -> BqlRefMut<'_, T> { } } +/// Returns a mutable reference to the underlying data in this cell, +/// while the owner already has a mutable reference to the cell. +/// +/// # Examples +/// +/// ``` +/// use bql::BqlRefCell; +/// +/// let mut c = BqlRefCell::new(5); +/// +/// *c.get_mut() = 10; +/// ``` +#[inline] +pub const fn get_mut (&mut self) -> &mut T { + self.value.get_mut () + } +/// Returns a raw pointer to the underlying data in this cell. /// /// # Examples
Signature · 1 line
2.51.0
Re: [PATCH 01/11] rust: bql: add BqlRefCell::get_mut()
Quoted 5 lines · Paolo Bonzini
Date: Wed, 1 Oct 2025 09:52:00 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 01/11] rust: bql: addBqlRefCell::get_mut()
X-Mailer: git-send-email 2.51.0
Quoted 7 lines
This method is rarely useful in QEMU due to the pervasiveness of shared references, but add it for when a &mut BqlRefCell<> is used.
Signed-off-by Paolo Bonzini <[email protected]>--- rust/bql/src/cell.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+)
PATCH 2/11 rust: migration: do not pass raw pointer to VMStateDescription::fields
In reply to Paolo BonziniPass a slice instead; a function that accepts a raw pointer should arguably be declared as unsafe.
But since it is now much easier to forget vmstate_fields!, validate the value (at least to some extent) before passing it to C. (Unfortunately, doing the same for subsections would require const ptr::is_null(), which is only stable in Rust 1.84).
--- rust/migration/src/vmstate.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
rust/migration/src/vmstate.rs +6 -3
@@ -424,7 +424,7 @@ macro_rules! vmstate_fields { ..::common::zeroable::Zeroable ::ZERO } ]; - _FIELDS.as_ptr () + _FIELDS }} }
@@ -676,8 +676,11 @@ pub const fn unplug_pending<F: for<'a> FnCall<(&'a T,), bool>>(mut self, _f: &F) }#[must_use] -pub const fn fields (mut self, fields: *const VMStateField ) ->Self { - self.0 .fields = fields; +pub const fn fields (mut self, fields: &'static [VMStateField ]) ->Self { +if fields[fields.len () -1 ].flags.0 !=VMStateFlags ::VMS_END .0 { +panic! ("fields are not terminated, use vmstate_fields!" ); + } + self.0 .fields = fields.as_ptr (); self }
Signature · 1 line
2.51.0
Re: [PATCH 02/11] rust: migration: do not pass raw pointer to VMStateDescription::fields
Quoted 14 lines · Paolo Bonzini
Date: Wed, 1 Oct 2025 09:52:01 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 02/11] rust: migration: do not pass raw pointer to
VMStateDescription::fields
X-Mailer: git-send-email 2.51.0Pass a slice instead; a function that accepts a raw pointer should arguably be declared as unsafe.
But since it is now much easier to forget
vmstate_fields!, validate the value (at least to some extent) before passing it to C. (Unfortunately, doing the same for subsections would require constptr::is_null(), which is only stable in Rust 1.84).
Quoted 5 lines
Suggested-by Zhao Liu <[email protected]>Signed-off-by Paolo Bonzini <[email protected]>--- rust/migration/src/vmstate.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
PATCH 3/11 rust: migration: do not store raw pointers into VMStateSubsectionsWrapper
In reply to Paolo BonziniRaw pointers were used to insert a NULL one at the end of the array. However, Option<&...> has the same layout and does not remove Sync from the type of the array.
As an extra benefit, this enables validation of the terminator of the subsection array, because is_null() in const context would not be stable until Rust 1.84.
--- rust/migration/src/vmstate.rs | 29 +++++++++-------------------- 1 file changed, 9 insertions(+), 20 deletions(-)
rust/migration/src/vmstate.rs +9 -20
@@ -469,33 +469,21 @@ unsafe impl $crate::vmstate::VMState for $type { }; } -/// A transparent wrapper type for the `subsections` field of -/// [`VMStateDescription`]. -/// -/// This is necessary to be able to declare subsection descriptions as statics, -/// because the only way to implement `Sync` for a foreign type (and `*const` -/// pointers are foreign types in Rust) is to create a wrapper struct and -/// `unsafe impl Sync` for it. -/// -/// This struct is used in the -/// [`vm_state_subsections`](crate::vmstate_subsections) macro implementation. -#[repr(transparent)] -pub struct VMStateSubsectionsWrapper (pub &'static [*const crate ::bindings::VMStateDescription ]); - -unsafe impl Sync for VMStateSubsectionsWrapper {} +/// The type returned by [`vmstate_subsections!`]. +pub type VMStateSubsections = &'static [Option <&'staticcrate ::bindings::VMStateDescription >];/// Helper macro to declare a list of subsections ([`VMStateDescription`]) /// into a static and return a pointer to the array of pointers it created. #[macro_export] macro_rules! vmstate_subsections { ($($subsection:expr),*$(,)*) => {{ -static _SUBSECTIONS: $crate::vmstate::VMStateSubsectionsWrapper = $crate::vmstate::VMStateSubsectionsWrapper (&[ +static _SUBSECTIONS: $crate::vmstate::VMStateSubsections = &[ $({static _SUBSECTION: $crate::bindings::VMStateDescription = $subsection.get (); - ::core::ptr::addr_of!(_SUBSECTION) +Some (&_SUBSECTION) }),*, - ::core::ptr::null () - ]); +None , + ]; &_SUBSECTIONS }} }
@@ -685,8 +673,9 @@ pub const fn fields(mut self, fields: &'static [VMStateField]) -> Self { }#[must_use] -pub const fn subsections (mut self, subs: &'staticVMStateSubsectionsWrapper ) ->Self { - self.0 .subsections = subs.0 .as_ptr (); +pub const fn subsections (mut self, subs: &'staticVMStateSubsections ) ->Self { +let subs: *const Option <&bindings::VMStateDescription > = subs.as_ptr (); + self.0 .subsections = subs.cast ::<*const bindings::VMStateDescription >(); self }
Signature · 1 line
2.51.0
Re: [PATCH 03/11] rust: migration: do not store raw pointers into VMStateSubsectionsWrapper
Quoted 10 lines · Paolo Bonzini
Date: Wed, 1 Oct 2025 09:52:02 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 03/11] rust: migration: do not store raw pointers into
VMStateSubsectionsWrapper
X-Mailer: git-send-email 2.51.0Raw pointers were used to insert a NULL one at the end of the array. However, Option<&...> has the same layout and does not remove Sync from the type of the array.
Quoted 8 lines
As an extra benefit, this enables validation of the terminator of the subsection array, because
is_null()in const context would not be stable until Rust 1.84.Signed-off-by Paolo Bonzini <[email protected]>--- rust/migration/src/vmstate.rs | 29 +++++++++-------------------- 1 file changed, 9 insertions(+), 20 deletions(-)
PATCH 4/11 rust: migration: validate termination of subsection arrays
In reply to Paolo BonziniFor consistency with fields(), validate the value (at least to some extent) before passing it to C.
--- rust/migration/src/vmstate.rs | 3 +++ 1 file changed, 3 insertions(+)
rust/migration/src/vmstate.rs +3 -0
@@ -674,6 +674,9 @@ pub const fn fields(mut self, fields: &'static [VMStateField]) -> Self {#[must_use] pub const fn subsections (mut self, subs: &'staticVMStateSubsections ) ->Self { +if subs[subs.len () -1 ].is_some () { +panic! ("subsections are not terminated, use vmstate_subsections!" ); + }let subs: *const Option <&bindings::VMStateDescription > = subs.as_ptr (); self.0 .subsections = subs.cast ::<*const bindings::VMStateDescription >(); self
Signature · 1 line
2.51.0
Re: [PATCH 04/11] rust: migration: validate termination of subsection arrays
Quoted 6 lines · Paolo Bonzini
Date: Wed, 1 Oct 2025 09:52:03 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 04/11] rust: migration: validate termination of subsection
arrays
X-Mailer: git-send-email 2.51.0
Quoted 7 lines
For consistency with
fields(), validate the value (at least to some extent) before passing it to C.Signed-off-by Paolo Bonzini <[email protected]>--- rust/migration/src/vmstate.rs | 3 +++ 1 file changed, 3 insertions(+)
PATCH 5/11 rust: migration: extract vmstate_fields_ref
In reply to Paolo BonziniThis is useful when building a VMState for generic structs, because you have to avoid nested statics. Using vmstate_fields! will fail in the likely case where the _FIELDS static uses Self from an outer item, because that is forbidden.
The separate macros are needed because you cannot just do
.fields(vmstate_fields_ref! {
vmstate_of!(PL011State, clock),
})The value returned by vmstate_fields_ref! is not promoted to static, which is unfortunate but intentional (https://github.com/rust-lang/rust/issues/60502):
error[E0716]: temporary value dropped while borrowed
--> rust/hw/char/pl011/libpl011.rlib.p/structured/device.rs:743:17
|
738 | / VMStateDescriptionBuilder::<PL011State>::new()
739 | | .name(c"pl011/clock")
740 | | .version_id(1)
741 | | .minimum_version_id(1)
742 | | .needed(&PL011State::clock_needed)
743 | | .fields(vmstate_fields_ref! {
| | _________________^
744 | || vmstate_of!(PL011State, clock),
745 | || })
| ||_________^- argument requires that borrow lasts for `'static`
| |_________|
| creates a temporary value which is freed while still in use
746 | .build();
| - temporary value is freed at the end of this statementThus it is necessary to use the "static", whether explicitly or hidden by vmstate_fields.
--- rust/migration/src/vmstate.rs | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-)
rust/migration/src/vmstate.rs +17 -6
@@ -411,19 +411,30 @@ const fn phantom__<T>(_: &T) -> ::core::marker::PhantomData<T> { }}; } +/// Add a terminator to the fields in the arguments, and return +/// a reference to the resulting array of values. +#[macro_export] +macro_rules! vmstate_fields_ref { + ($($field:expr),*$(,)*) => { + &[ + $($field),*, + $crate::bindings::VMStateField { + flags: $crate::bindings::VMStateFlags ::VMS_END , + ..::common::zeroable::Zeroable ::ZERO + } + ] + } +} +/// Helper macro to declare a list of /// ([`VMStateField`](`crate::bindings::VMStateField`)) into a static and return /// a pointer to the array of values it created. #[macro_export] macro_rules! vmstate_fields { ($($field:expr),*$(,)*) => {{ -static _FIELDS: &[$crate::bindings::VMStateField ] = &[ +static _FIELDS: &[$crate::bindings::VMStateField ] = $crate::vmstate_fields_ref!( $($field),*, - $crate::bindings::VMStateField { - flags: $crate::bindings::VMStateFlags ::VMS_END , - ..::common::zeroable::Zeroable ::ZERO - } - ]; + ); _FIELDS }} }
Signature · 1 line
2.51.0
Re: [PATCH 05/11] rust: migration: extract vmstate_fields_ref
Quoted 37 lines · Paolo Bonzini
Date: Wed, 1 Oct 2025 09:52:04 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 05/11] rust: migration: extractvmstate_fields_ref
X-Mailer: git-send-email 2.51.0This is useful when building a VMState for generic structs, because you have to avoid nested statics. Using
vmstate_fields! will fail in the likely case where the_FIELDSstatic uses Self from an outer item, because that is forbidden.The separate macros are needed because you cannot just do
.fields(vmstate_fields_ref! { vmstate_of!(PL011State, clock), })The value returned by
vmstate_fields_ref! is not promoted to static, which is unfortunate but intentional (https://github.com/rust-lang/rust/issues/60502):error[E0716]: temporary value dropped while borrowed
-->rust/hw/char/pl011/libpl011.rlib.p/structured/device.rs:743:17| 738 | / VMStateDescriptionBuilder::<PL011State>::new() 739 | | .name(c"pl011/clock") 740 | | .version_id(1) 741 | | .minimum_version_id(1) 742 | | .needed(&PL011State::clock_needed) 743 | | .fields(vmstate_fields_ref! { | | _________________^ 744 | || vmstate_of!(PL011State, clock), 745 | || }) | ||_________^- argument requires that borrow lasts for `'static` | |_________| | creates a temporary value which is freed while still in use 746 | .build(); | - temporary value is freed at the end of this statement
Quoted 7 lines
Thus it is necessary to use the "static", whether explicitly or hidden by
vmstate_fields.Signed-off-by Paolo Bonzini <[email protected]>--- rust/migration/src/vmstate.rs | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-)
PATCH 6/11 rust: move VMState from bql to migration
In reply to Paolo BonziniThe high-level wrapper Migratable<T> will contain a BqlCell, which would introduce a circular dependency betwen the bql and migration crates. Move the implementation of VMState for cells to "migration", together with the implementation for std types.
--- rust/Cargo.lock | 4 +--- rust/bql/Cargo.toml | 3 --- rust/bql/meson.build | 1 - rust/bql/src/cell.rs | 6 ------ rust/meson.build | 2 +- rust/migration/Cargo.toml | 1 + rust/migration/meson.build | 4 ++-- rust/migration/src/vmstate.rs | 2 ++ 8 files changed, 7 insertions(+), 16 deletions(-)
rust/Cargo.lock +1 -3
@@ -57,9 +57,6 @@ dependencies = [ [[package]] name = "bql" version = "0.1.0" -dependencies = [ - "migration", -] [[package]] name = "chardev"
@@ -141,6 +138,7 @@ checksum = "18d287de67fe55fd7e1581fe933d965a5a9477b38e949cfa9f8574ef01506398" name = "migration" version = "0.1.0" dependencies = [ + "bql", "common", "util", ]
rust/bql/Cargo.toml +0 -3
@@ -12,9 +12,6 @@ license.workspace = true repository.workspace = true rust-version.workspace = true -[dependencies] -migration = { path = "../migration" } - [features] default = ["debug_cell"] debug_cell = []
rust/bql/meson.build +0 -1
@@ -37,7 +37,6 @@ _bql_rs = static_library( override_options: ['rust_std=2021', 'build.rust_std=2021'], rust_abi: 'rust', rust_args: _bql_cfg, - link_with: [_migration_rs], ) bql_rs = declare_dependency(link_with: [_bql_rs],
rust/bql/src/cell.rs +0 -6
@@ -151,8 +151,6 @@ ptr::NonNull, }; -use migration::impl_vmstate_transparent; -/// A mutable memory location that is protected by the Big QEMU Lock. /// /// # Memory layout
@@ -364,8 +362,6 @@ pub fn take(&self) -> T { } } -impl_vmstate_transparent! (crate ::cell::BqlCell <T >where T :VMState ); -/// A mutable memory location with dynamically checked borrow rules, /// protected by the Big QEMU Lock. ///
@@ -691,8 +687,6 @@ fn from(t: T) -> BqlRefCell<T> { } } -impl_vmstate_transparent! (crate ::cell::BqlRefCell <T >where T :VMState ); -struct BorrowRef <'b> { borrow: &'bCell <BorrowFlag >, }
rust/meson.build +1 -1
@@ -27,8 +27,8 @@ subdir('qemu-macros') subdir('common') subdir('bits') subdir('util') -subdir('migration') subdir('bql') +subdir('migration') subdir('qom') subdir('system') subdir('chardev')
rust/migration/Cargo.toml +1 -0
@@ -13,6 +13,7 @@ repository.workspace = true rust-version.workspace = true [dependencies] +bql = { path = "../bql" } common = { path = "../common" } util = { path = "../util" }
rust/migration/meson.build +2 -2
@@ -37,12 +37,12 @@ _migration_rs = static_library( ), override_options: ['rust_std=2021', 'build.rust_std=2021'], rust_abi: 'rust', - link_with: [_util_rs], + link_with: [_util_rs, _bql_rs], dependencies: [common_rs], ) migration_rs = declare_dependency(link_with: [_migration_rs], - dependencies: [migration, qemuutil]) + dependencies: [bql_rs, migration, qemuutil]) # Doctests are essentially integration tests, so they need the same dependencies. # Note that running them requires the object files for C code, so place them
rust/migration/src/vmstate.rs +2 -0
@@ -275,6 +275,8 @@ unsafe impl<$base> $crate::vmstate::VMState for $type where $base: $crate::vmsta }; } +impl_vmstate_transparent! (bql::BqlCell <T >where T :VMState ); +impl_vmstate_transparent! (bql::BqlRefCell <T >where T :VMState );impl_vmstate_transparent! (std::cell::Cell <T >where T :VMState );impl_vmstate_transparent! (std::cell::UnsafeCell <T >where T :VMState );impl_vmstate_transparent! (std::pin::Pin <T >where T :VMState );
Signature · 1 line
2.51.0
Re: [PATCH 06/11] rust: move VMState from bql to migration
Quoted 11 lines · Paolo Bonzini
Date: Wed, 1 Oct 2025 09:52:05 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 06/11] rust: move VMState from bql to migration
X-Mailer: git-send-email 2.51.0The high-level wrapper Migratable<T> will contain a BqlCell, which would introduce a circular dependency betwen the bql and migration crates. Move the implementation of VMState for cells to "migration", together with the implementation for std types.
Signed-off-by Paolo Bonzini <[email protected]>
Quoted 10 lines
--- rust/Cargo.lock | 4 +--- rust/bql/Cargo.toml | 3 --- rust/bql/meson.build | 1 - rust/bql/src/cell.rs | 6 ------ rust/meson.build | 2 +- rust/migration/Cargo.toml | 1 + rust/migration/meson.build | 4 ++-- rust/migration/src/vmstate.rs | 2 ++ 8 files changed, 7 insertions(+), 16 deletions(-)
PATCH 7/11 rust: migration: add high-level migration wrappers
In reply to Paolo BonziniInstead of dealing with pre/post callbacks, allow devices to implement a snapshot/restore mechanism; this has two main advantages:
- it can be easily implemented via procedural macros
- there can be generic implementations to deal with various kinds of interior-mutable containers, from BqlRefCell to Mutex, so that C code does not see Rust concepts such as Mutex<>.
Using it is easy; you can implement the snapshot/restore trait ToMigrationState and declare your state like:
regs: Migratable<Mutex<MyDeviceRegisters>>
Migratable<> allows dereferencing to the underlying object with no run-time cost.
Note that Migratable<> actually does not accept ToMigrationState, only the similar ToMigrationStateShared trait that the user will mostly not care about. This is required by the fact that pre/post callbacks take a &self, and ensures that the argument is a Mutex or BqlRefCell (including an array or Arc<> thereof).
--- docs/devel/rust.rst | 1 + rust/migration/meson.build | 1 + rust/migration/src/lib.rs | 3 + rust/migration/src/migratable.rs | 434 +++++++++++++++++++++++++++++++ 4 files changed, 439 insertions(+) create mode 100644 rust/migration/src/migratable.rs
docs/devel/rust.rst +1 -0
@@ -155,6 +155,7 @@ module status ``hwcore::irq`` complete ``hwcore::qdev`` stable ``hwcore::sysbus`` stable +``migration::migratable`` proof of concept ``migration::vmstate`` stable ``qom`` stable ``system::memory`` stable
rust/migration/meson.build +1 -0
@@ -31,6 +31,7 @@ _migration_rs = static_library( [ 'src/lib.rs', 'src/bindings.rs', + 'src/migratable.rs', 'src/vmstate.rs', ], {'.' : _migration_bindings_inc_rs},
rust/migration/src/lib.rs +3 -0
@@ -2,5 +2,8 @@pub mod bindings; +pub mod migratable; +pub use migratable::*; +pub mod vmstate;pub use vmstate::*;
rust/migration/src/migratable.rs new file +434 -0
434 lines not on this page · raw message
Signature · 1 line
2.51.0
Quoted 29 lines · Paolo Bonzini
Date: Wed, 1 Oct 2025 09:52:06 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 07/11] rust: migration: add high-level migration wrappers
X-Mailer: git-send-email 2.51.0Instead of dealing with pre/post callbacks, allow devices to implement a snapshot/restore mechanism; this has two main advantages:
- it can be easily implemented via procedural macros
- there can be generic implementations to deal with various kinds of interior-mutable containers, from BqlRefCell to Mutex, so that C code does not see Rust concepts such as Mutex<>.
Using it is easy; you can implement the snapshot/restore trait ToMigrationState and declare your state like:
regs: Migratable<Mutex<MyDeviceRegisters>>
Migratable<> allows dereferencing to the underlying object with no run-time cost.
Note that Migratable<> actually does not accept ToMigrationState, only the similar ToMigrationStateShared trait that the user will mostly not care about. This is required by the fact that pre/post callbacks take a &self, and ensures that the argument is a Mutex or BqlRefCell (including an array or Arc<> thereof).
Quoted 8 lines
Signed-off-by Paolo Bonzini <[email protected]>--- docs/devel/rust.rst | 1 + rust/migration/meson.build | 1 + rust/migration/src/lib.rs | 3 + rust/migration/src/migratable.rs | 434 +++++++++++++++++++++++++++++++ 4 files changed, 439 insertions(+) create mode 100644 rust/migration/src/migratable.rs
PATCH 8/11 rust: qemu-macros: add ToMigrationState derive macro
In reply to Paolo BonziniAdd a macro that recursively builds the "migrated" version of a struct.
--- rust/Cargo.lock | 1 + rust/migration/Cargo.toml | 1 + rust/migration/meson.build | 2 +- rust/migration/src/lib.rs | 2 + rust/migration/src/migratable.rs | 12 +- rust/qemu-macros/src/lib.rs | 88 +++++++ rust/qemu-macros/src/migration_state.rs | 296 ++++++++++++++++++++++++ rust/qemu-macros/src/tests.rs | 112 ++++++++- 8 files changed, 509 insertions(+), 5 deletions(-) create mode 100644 rust/qemu-macros/src/migration_state.rs
rust/Cargo.lock +1 -0
@@ -140,6 +140,7 @@ version = "0.1.0" dependencies = [ "bql", "common", + "qemu_macros", "util", ]
rust/migration/Cargo.toml +1 -0
@@ -15,6 +15,7 @@ rust-version.workspace = true [dependencies] bql = { path = "../bql" } common = { path = "../common" } +qemu_macros = { path = "../qemu-macros" } util = { path = "../util" } [lints]
rust/migration/meson.build +1 -1
@@ -39,7 +39,7 @@ _migration_rs = static_library( override_options: ['rust_std=2021', 'build.rust_std=2021'], rust_abi: 'rust', link_with: [_util_rs, _bql_rs], - dependencies: [common_rs], + dependencies: [common_rs, qemu_macros], ) migration_rs = declare_dependency(link_with: [_migration_rs],
rust/migration/src/lib.rs +2 -0
@@ -2,6 +2,8 @@pub mod bindings; +pub use qemu_macros::ToMigrationState ; +pub mod migratable;pub use migratable::*;
rust/migration/src/migratable.rs +10 -2
@@ -79,6 +79,10 @@/// # dev2.restore_migrated_state_mut(*mig, 1).unwrap(); /// # assert_eq!(dev2, dev); /// ``` +/// +/// More commonly, the trait is derived through the +/// [`derive(ToMigrationState)`](qemu_macros::ToMigrationState) procedural +/// macro. pub trait ToMigrationState {/// The type used to represent the migrated state. type Migrated :Default +VMState ;
@@ -309,13 +313,17 @@ fn restore_migrated_state(/// It manages the lifecycle of migration state and provides automatic /// conversion between runtime and migration representations. /// -/// ```ignore +/// ``` /// # use std::sync::Mutex; -/// # use migration::Migratable; +/// # use migration::{Migratable, ToMigrationState, VMState, VMStateField}; /// +/// #[derive(ToMigrationState)] /// pub struct DeviceRegs { /// status: u32, /// } +/// # unsafe impl VMState for DeviceRegsMigration { +/// # const BASE: VMStateField = ::common::Zeroable::ZERO; +/// # } /// /// pub struct SomeDevice { /// // ...
rust/qemu-macros/src/lib.rs +88 -0
100 lines not on this page · raw message
rust/qemu-macros/src/migration_state.rs new file +296 -0
296 lines not on this page · raw message
rust/qemu-macros/src/tests.rs +110 -2
127 lines not on this page · raw message
Signature · 1 line
2.51.0
Re: [PATCH 08/11] rust: qemu-macros: add ToMigrationState derive macro
Quoted 9 lines · Paolo Bonzini
Date: Wed, 1 Oct 2025 09:52:07 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 08/11] rust: qemu-macros: add ToMigrationState derive macro
X-Mailer: git-send-email 2.51.0Add a macro that recursively builds the "migrated" version of a struct.
Signed-off-by Paolo Bonzini <[email protected]>
Quoted 11 lines
--- rust/Cargo.lock | 1 + rust/migration/Cargo.toml | 1 + rust/migration/meson.build | 2 +- rust/migration/src/lib.rs | 2 + rust/migration/src/migratable.rs | 12 +- rust/qemu-macros/src/lib.rs | 88 +++++++ rust/qemu-macros/src/migration_state.rs | 296 ++++++++++++++++++++++++ rust/qemu-macros/src/tests.rs | 112 ++++++++- 8 files changed, 509 insertions(+), 5 deletions(-) create mode 100644 rust/qemu-macros/src/migration_state.rs
Re: [PATCH 08/11] rust: qemu-macros: add ToMigrationState derive macro
In reply to Paolo BonziniHi Paolo,
Review
Quoted 11 lines
/// # use
std::sync::Mutex;(quoted diff) +5
-1-/// # use migration::Migratable; +/// # use migration::{Migratable, ToMigrationState, VMState, VMStateField}; /// +/// #[derive(ToMigrationState)] /// pub struct DeviceRegs { /// status: u32, /// } +/// # unsafe impl VMState for DeviceRegsMigration { +/// # const BASE: VMStateField = ::common::Zeroable::ZERO; +/// # }
did you miss something like the following?
rust/qemu-macros/src/migration_state.rs +13 -0
@@ -236,6 +236,16 @@ pub struct #name { } } +fn generate_vmstate_impl (&self) ->TokenStream { +let name = self.migration_state_name (); + +quote! { +unsafe impl ::migration::VMState for #name { +const BASE : ::migration::VMStateField = ::common::Zeroable ::ZERO ; + } + } + } +fn generate_snapshot_migration_state (&self) ->TokenStream {let fields = self .fields
@@ -275,12 +285,15 @@ fn generate(&self) -> TokenStream {let (impl_generics, ty_generics, where_clause) = generics.split_for_impl ();let name = self.migration_state_name ();let migration_state_struct = self.generate_migration_state_struct (); +let vmstate_impl = self.generate_vmstate_impl ();let snapshot_impl = self.generate_snapshot_migration_state ();let restore_impl = self.generate_restore_migrated_state ();quote! { #migration_state_struct + #vmstate_impl +impl #impl_genericsToMigrationState for #struct_name #ty_generics #where_clause {type Migrated = #name ;
Re: [PATCH 08/11] rust: qemu-macros: add ToMigrationState derive macro
Quoted 27 lines · Zhao Liu
Date: Mon, 3 Nov 2025 18:25:26 +0800
From: Zhao Liu <[email protected]>
Subject: Re: [PATCH 08/11] rust: qemu-macros: add ToMigrationState derive
macroHi Paolo,
Review
Quoted 11 lines
/// # use
std::sync::Mutex;(quoted diff) +5
-1-/// # use migration::Migratable; +/// # use migration::{Migratable, ToMigrationState, VMState, VMStateField}; /// +/// #[derive(ToMigrationState)] /// pub struct DeviceRegs { /// status: u32, /// } +/// # unsafe impl VMState for DeviceRegsMigration { +/// # const BASE: VMStateField = ::common::Zeroable::ZERO; +/// # }did you miss something like the following?
rust/qemu-macros/src/migration_state.rs +0
-0
rust/qemu-macros/src/migration_state.rs pub struct #name { · line 244
Quoted 9 lines
rust/qemu-macros/src/migration_state.rs +6
-0@@ -236,6 +236,16 @@ pub struct #name { } } +fn generate_vmstate_impl (&self) ->TokenStream { +let name = self.migration_state_name (); + +quote! { +unsafe impl ::migration::VMState for #name { +const BASE : ::migration::VMStateField = ::common::Zeroable ::ZERO ;
It seems the generated migration_state_struct needs a complete VMSD:
collect all its fields and build a VMSD.
And then apply impl_vmstate_struct! to this migration_state_struct.
If we zero the BASE, then vmstate_of!(Self, migration_state) seems can't migrate its fields.
Thanks,
Zhao
Re: [PATCH 08/11] rust: qemu-macros: add ToMigrationState derive macro
Quoted 7 lines
It seems the generated
migration_state_structneeds a complete VMSD:
collect all its fields and build a VMSD.And then apply
impl_vmstate_struct! to thismigration_state_struct.If we zero the BASE, then
vmstate_of!(Self, migration_state)seems can't migrate its fields.
I think the following generated vmstate implementation should be what we need:
rust/qemu-macros/src/migration_state.rs +41 -1
@@ -1,6 +1,6 @@use std::borrow::Cow ; -use proc_macro2::TokenStream ; +use proc_macro2::{Literal ,TokenStream };use quote::{format_ident, quote,ToTokens };use syn::{spanned::Spanned ,DeriveInput ,Error ,Field ,Ident ,Result ,Type };
@@ -236,6 +236,43 @@ pub struct #name { } } +fn generate_vmstate_impl (&self) ->TokenStream { +let name = self.migration_state_name (); +let name_str = name.to_string (); +// Most of the time, const variables use uppercase snake case style, +// while VMStateDescription.name uses lowercase snake case. But we're +// not strictly following the usual snake case conventions here because +// what we have is good enough for the generated code right now. +// +// QEMU struct names are typically in camel case, but there are exceptions +// - like non-standard camel case such as HPETState. So converting from +// camel to snake case would need an extra helper. +let vmsd_name =format_ident! ("VMSTATE_{}" , name_str); +// C-string literal "c" can't be used in quote! directly. +let vmsd_c_name =Literal ::c_string (&std::ffi::CString ::new (name_str).unwrap ()); + +let vmstate_fields = self.fields.iter ().map (|field| { +let field_name = &field.name; +quote! { +vmstate_of! (#name, #field_name), + } + }); + +quote! { +const #vmsd_name:VMStateDescription <#name > = +VMStateDescriptionBuilder ::<#name >::new () + .name (#vmsd_c_name) + .version_id (0 ) + .minimum_version_id (0 ) + .fields (vmstate_fields! { + #(#vmstate_fields)* + }) + .build (); + +impl_vmstate_struct! (#name, #vmsd_name); + } + } +fn generate_snapshot_migration_state (&self) ->TokenStream {let fields = self .fields
@@ -275,12 +312,15 @@ fn generate(&self) -> TokenStream {let (impl_generics, ty_generics, where_clause) = generics.split_for_impl ();let name = self.migration_state_name ();let migration_state_struct = self.generate_migration_state_struct (); +let vmstate_impl = self.generate_vmstate_impl ();let snapshot_impl = self.generate_snapshot_migration_state ();let restore_impl = self.generate_restore_migrated_state ();quote! { #migration_state_struct + #vmstate_impl +impl #impl_genericsToMigrationState for #struct_name #ty_generics #where_clause {type Migrated = #name ;
rust/qemu-macros/src/tests.rs +14 -0
@@ -408,6 +408,20 @@ pub struct CustomMigration { pub nested_field: <NestedStruct as ToMigrationState>::Migrated, pub simple_field: <u32 as ToMigrationState>::Migrated, } +const VMSTATE_CustomMigration :VMStateDescription <CustomMigration > = +VMStateDescriptionBuilder ::<CustomMigration >::new () + .name (c"CustomMigration" ) + .version_id (0 ) + .minimum_version_id (0 ) + .fields (vmstate_fields! { +vmstate_of! (CustomMigration , shared_data), +vmstate_of! (CustomMigration , converted_field), +vmstate_of! (CustomMigration , fallible_field), +vmstate_of! (CustomMigration , nested_field), +vmstate_of! (CustomMigration , simple_field), + }) + .build (); +impl_vmstate_struct! (CustomMigration ,VMSTATE_CustomMigration );impl ToMigrationState for MyStruct {type Migrated =CustomMigration ; fn snapshot_migration_state(
Re: [PATCH 08/11] rust: qemu-macros: add ToMigrationState derive macro
In reply to Zhao LiuQuoted 21 lines · Zhao Liu
Quoted 8 lines
did you miss something like the following?
rust/qemu-macros/src/migration_state.rs +0
-0rust/qemu-macros/src/migration_state.rs pub struct #name { · line 244
Quoted 9 lines
rust/qemu-macros/src/migration_state.rs +6
-0@@ -236,6 +236,16 @@ pub struct #name { } } +fn generate_vmstate_impl (&self) ->TokenStream { +let name = self.migration_state_name (); + +quote! { +unsafe impl ::migration::VMState for #name { +const BASE : ::migration::VMStateField = ::common::Zeroable ::ZERO ;It seems the generated
migration_state_structneeds a complete VMSD:
collect all its fields and build a VMSD.
Quoted 4 lines
And then apply
impl_vmstate_struct! to thismigration_state_struct.If we zero the BASE, then
vmstate_of!(Self, migration_state)seems can't migrate its fields.
The VMStateDescription for the inner struct is indeed missing, but you need to write it yourself and apply impl_vmstate_struct, because the derive macro cannot know the checks or version_ids for each field, or the subsections.
The VMStateDescription for Migratable<> however is automatic (of course), and the outer VMStateDescription for the device is simple---it consists only of the parent class if applicable, and the Migratable<>, similar to VMSTATE_PL011.
For HPET, you'll have to move the subsections from VMSTATE_HPET to the inner VMState.
Paolo
PATCH 9/11 timer: constify some functions
In reply to Paolo Bonzini--- include/qemu/timer.h | 6 +++--- util/qemu-timer.c | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-)
include/qemu/timer.h +3 -3
@@ -699,7 +699,7 @@ void timer_mod_anticipate(QEMUTimer *ts, int64_t expire_time);* * Returns: true if the timer is pending */ -bool timer_pending (QEMUTimer *ts); +bool timer_pending (const QEMUTimer *ts);/** * timer_expired:
@@ -710,7 +710,7 @@ bool timer_pending(QEMUTimer *ts);* * Returns: true if the timer has expired */ -bool timer_expired (QEMUTimer *timer_head,int64_t current_time); +bool timer_expired (const QEMUTimer *timer_head,int64_t current_time);/** * timer_expire_time_ns:
@@ -720,7 +720,7 @@ bool timer_expired(QEMUTimer *timer_head, int64_t current_time);* * Returns: the expiry time in nanoseconds */ -uint64_t timer_expire_time_ns (QEMUTimer *ts); +uint64_t timer_expire_time_ns (const QEMUTimer *ts);/** * timer_get:
util/qemu-timer.c +4 -4
@@ -89,7 +89,7 @@ static inline QEMUClock *qemu_clock_ptr(QEMUClockType type)return &qemu_clocks[type]; } -static bool timer_expired_ns (QEMUTimer *timer_head,int64_t current_time) +static bool timer_expired_ns (const QEMUTimer *timer_head,int64_t current_time) {return timer_head && (timer_head->expire_time <= current_time); }
@@ -475,12 +475,12 @@ void timer_mod_anticipate(QEMUTimer *ts, int64_t expire_time)timer_mod_anticipate_ns (ts, expire_time * ts->scale); } -bool timer_pending (QEMUTimer *ts) +bool timer_pending (const QEMUTimer *ts) {return ts->expire_time >=0 ; } -bool timer_expired (QEMUTimer *timer_head,int64_t current_time) +bool timer_expired (const QEMUTimer *timer_head,int64_t current_time) {return timer_expired_ns (timer_head, current_time * timer_head->scale); }
@@ -649,7 +649,7 @@ void init_clocks(QEMUTimerListNotifyCB *notify_cb)#endif } -uint64_t timer_expire_time_ns (QEMUTimer *ts) +uint64_t timer_expire_time_ns (const QEMUTimer *ts) {return timer_pending (ts) ? ts->expire_time :-1 ; }
Signature · 1 line
2.51.0
Re: [PATCH 09/11] timer: constify some functions
Quoted 10 lines · Paolo Bonzini
Date: Wed, 1 Oct 2025 09:52:08 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 09/11] timer: constify some functions
X-Mailer: git-send-email 2.51.0Signed-off-by Paolo Bonzini <[email protected]>--- include/qemu/timer.h | 6 +++--- util/qemu-timer.c | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-)
PATCH 10/11 rust: migration: implement ToMigrationState for Timer
In reply to Paolo BonziniTimer is a complex struct, allow adding it to a struct that uses #[derive(ToMigrationState)]; similar to vmstate_timer, only the expiration time has to be preserved.
In fact, because it is thread-safe, ToMigrationStateShared can also be implemented without needing a cell or mutex that wraps the timer.
--- rust/migration/src/migratable.rs | 31 +++++++++++++++++++++++++++++++ rust/util/src/timer.rs | 10 +++++++++- 2 files changed, 40 insertions(+), 1 deletion(-)
rust/migration/src/migratable.rs +31 -0
@@ -140,6 +140,26 @@ fn restore_migrated_state_mut(impl_for_primitive! (u8 ,u16 ,u32 ,u64 ,i8 ,i16 ,i32 ,i64 ,bool ); +impl ToMigrationState for util::timer::Timer { +type Migrated =i64 ; + +fn snapshot_migration_state (&self, target: &mut i64 ) ->Result <(),InvalidError > { +// SAFETY: as_ptr() is unsafe to ensure that the caller reasons about +// the pinning of the data inside the Opaque<>. Here all we do is +// access a field. + *target = self.expire_time_ns ().unwrap_or (-1 ); +Ok (()) + } + +fn restore_migrated_state_mut ( + &mut self, + source:Self ::Migrated , + version_id:u8 , + ) ->Result <(),InvalidError > { + self.restore_migrated_state (source, version_id) + } +} +impl <T :ToMigrationState ,const N :usize >ToMigrationState for [T ;N ]where [T ::Migrated ;N ]:Default ,
@@ -237,6 +257,17 @@ fn restore_migrated_state( ) -> Result<(), InvalidError>; } +impl ToMigrationStateShared for util::timer::Timer { +fn restore_migrated_state (&self, source:i64 , _version_id:u8 ) ->Result <(),InvalidError > { +if source >=0 { + self.modify (sourceas u64 ); + }else { + self.delete (); + } +Ok (()) + } +} +impl <T :ToMigrationStateShared ,const N :usize >ToMigrationStateShared for [T ;N ]where [T ::Migrated ;N ]:Default ,
rust/util/src/timer.rs +9 -1
@@ -10,7 +10,8 @@use common::{callbacks::FnCall ,Opaque };use crate ::bindings::{ - self, qemu_clock_get_ns, timer_del, timer_init_full, timer_mod,QEMUClockType , + self, qemu_clock_get_ns, timer_del, timer_expire_time_ns, timer_init_full, timer_mod, +QEMUClockType , };/// A safe wrapper around [`bindings::QEMUTimer`].
@@ -86,6 +87,13 @@ pub fn init_full<'timer, 'opaque: 'timer, T, F>( } } +pub fn expire_time_ns (&self) ->Option <i64 > { +// SAFETY: the only way to obtain a Timer safely is via methods that +// take a Pin<&mut Self>, therefore the timer is pinned +let ret =unsafe {timer_expire_time_ns (self.as_ptr ()) }; + i64::try_from (ret).ok () + } +pub fn modify (&self, expire_time:u64 ) {// SAFETY: the only way to obtain a Timer safely is via methods that // take a Pin<&mut Self>, therefore the timer is pinned
Signature · 1 line
2.51.0
Re: [PATCH 10/11] rust: migration: implement ToMigrationState for Timer
Quoted 51 lines · Paolo Bonzini
Date: Wed, 1 Oct 2025 09:52:09 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 10/11] rust: migration: implement ToMigrationState for Timer
X-Mailer: git-send-email 2.51.0Timer is a complex struct, allow adding it to a struct that uses #[derive(ToMigrationState)]; similar to
vmstate_timer, only the expiration time has to be preserved.In fact, because it is thread-safe, ToMigrationStateShared can also be implemented without needing a cell or mutex that wraps the timer.
Signed-off-by Paolo Bonzini <[email protected]>--- rust/migration/src/migratable.rs | 31 +++++++++++++++++++++++++++++++ rust/util/src/timer.rs | 10 +++++++++- 2 files changed, 40 insertions(+), 1 deletion(-)rust/migration/src/migratable.rs +20
-0@@ -140,6 +140,26 @@ fn restore_migrated_state_mut(impl_for_primitive! (u8 ,u16 ,u32 ,u64 ,i8 ,i16 ,i32 ,i64 ,bool ); +impl ToMigrationState for util::timer::Timer { +type Migrated =i64 ; + +fn snapshot_migration_state (&self, target: &mut i64 ) ->Result <(),InvalidError > { +// SAFETY: as_ptr() is unsafe to ensure that the caller reasons about +// the pinning of the data inside the Opaque<>. Here all we do is +// access a field. + *target = self.expire_time_ns ().unwrap_or (-1 ); +Ok (()) + } + +fn restore_migrated_state_mut ( + &mut self, + source:Self ::Migrated , + version_id:u8 , + ) ->Result <(),InvalidError > { + self.restore_migrated_state (source, version_id) + } +} +impl <T :ToMigrationState ,const N :usize >ToMigrationState for [T ;N ]where [T ::Migrated ;N ]:Default ,
rust/migration/src/migratable.rs fn restore_migrated_state( · line 263
Quoted 7 lines
rust/migration/src/migratable.rs +4
-0@@ -237,6 +257,17 @@ fn restore_migrated_state( ) -> Result<(), InvalidError>; } +impl ToMigrationStateShared for util::timer::Timer { +fn restore_migrated_state (&self, source:i64 , _version_id:u8 ) ->Result <(),InvalidError > { +if source >=0 { + self.modify (sourceas u64 );
Timer::modify() is the wrapper of timer_mod(), and timer_mod() will re-compute the expire time with scale factor.
So here we should use a binding of timer_mod_ns() - Timer::modify_ns() instead of Timer::modify(), just like C side did.
Moreover, for Timer::modify_ns() & Timer::modify(), the simplest way is to build them based on timer_mod_ns() & timer_mod() (but this sounds like shifting the responsibility for type checking and overflow checking to the C side :-( ).
Alternative, we can make Timer::modify() based on Timer::modify_ns(), but then it involves many numeric type conversions: scale is i32 but expire_time is u64, and Timer::modify_ns() may accept a u64 argument.
Fortunately,, we can make Timer's modify() accept i64 to reduce type conversions.
Quoted 25 lines
rust/migration/src/migratable.rs +7
-0+ }else { + self.delete (); + } +Ok (()) + } +} +impl <T :ToMigrationStateShared ,const N :usize >ToMigrationStateShared for [T ;N ]where [T ::Migrated ;N ]:Default ,rust/util/src/timer.rs +2
-1@@ -10,7 +10,8 @@use common::{callbacks::FnCall ,Opaque };use crate ::bindings::{ - self, qemu_clock_get_ns, timer_del, timer_init_full, timer_mod,QEMUClockType , + self, qemu_clock_get_ns, timer_del, timer_expire_time_ns, timer_init_full, timer_mod, +QEMUClockType , };/// A safe wrapper around [`bindings::QEMUTimer`].
rust/util/src/timer.rs pub fn init_full<'timer, 'opaque: 'timer, T, F>( · line 94
Quoted 8 lines
rust/util/src/timer.rs +5
-0@@ -86,6 +87,13 @@ pub fn init_full<'timer, 'opaque: 'timer, T, F>( } } +pub fn expire_time_ns (&self) ->Option <i64 > { +// SAFETY: the only way to obtain a Timer safely is via methods that +// take a Pin<&mut Self>, therefore the timer is pinned +let ret =unsafe {timer_expire_time_ns (self.as_ptr ()) }; + i64::try_from (ret).ok ()
Good! This detects all negative values.
Quoted 8 lines
rust/util/src/timer.rs +2
-0+ } +pub fn modify (&self, expire_time:u64 ) {// SAFETY: the only way to obtain a Timer safely is via methods that // take a Pin<&mut Self>, therefore the timer is pinned Signature · 1 line
2.51.0
PATCH 1/2 rust/timer: Make Timer::modify() accept an i64 expire_time Timer
At C side, timer_mod() accepts the int64_t expire_time as an argument.
In fact, int64_t defines the positive value range accepted by expire_timer is (0, INT64_MAX].
But at Rust side, Timer::modify() accepts an u64 expire_time and convert it to i64 internally. This is a lazy approach, assuming no one would use negative values to modify the timer. However, logically speaking, a negative expire_time is acceptable - it means that the current timer should fire immediately.
Moreover, specifying expire_time as i64 allows callers to more clearly understand the accepted value range, preventing them from unexpectedly finding a u64 (> i64::MAX) silently converted to a negative value.
Make Timer::modify() accept an i64 expire_time.
--- rust/hw/timer/hpet/src/device.rs | 2 +- rust/util/src/timer.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-)
rust/hw/timer/hpet/src/device.rs +1 -1
@@ -365,7 +365,7 @@ fn arm_timer(&mut self, tick: u64) { } self.last = ns; - self.qemu_timer.modify (self.last); + self.qemu_timer.modify (self.last.try_into ().unwrap ()); }fn set_timer (&mut self) {
rust/util/src/timer.rs +2 -2
@@ -86,10 +86,10 @@ pub fn init_full<'timer, 'opaque: 'timer, T, F>( } } -pub fn modify (&self, expire_time:u64 ) { +pub fn modify (&self, expire_time:i64 ) {// SAFETY: the only way to obtain a Timer safely is via methods that // take a Pin<&mut Self>, therefore the timer is pinned -unsafe {timer_mod (self.as_mut_ptr (), expire_timeas i64 ) } +unsafe {timer_mod (self.as_mut_ptr (), expire_time) } }pub fn delete (&self) {
--
2.34.1
PATCH 2/2 rust/timer: Add Timer::modify_ns()
In reply to Zhao LiuAdd the binding of timer_mod_ns(), and re-implement Timer::modify() based on Timer::modify_ns().
--- rust/util/src/timer.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-)
rust/util/src/timer.rs +11 -3
@@ -10,7 +10,7 @@use common::{callbacks::FnCall ,Opaque };use crate ::bindings::{ - self, qemu_clock_get_ns, timer_del, timer_init_full, timer_mod,QEMUClockType , + self, qemu_clock_get_ns, timer_del, timer_init_full, timer_mod_ns,QEMUClockType , };/// A safe wrapper around [`bindings::QEMUTimer`].
@@ -86,10 +86,18 @@ pub fn init_full<'timer, 'opaque: 'timer, T, F>( } } -pub fn modify (&self, expire_time:i64 ) { +pub fn modify_ns (&self, expire_time:i64 ) {// SAFETY: the only way to obtain a Timer safely is via methods that // take a Pin<&mut Self>, therefore the timer is pinned -unsafe {timer_mod (self.as_mut_ptr (), expire_time) } +unsafe {timer_mod_ns (self.as_mut_ptr (), expire_time) } + } + +pub fn modify (&self, expire_time:i64 ) { +// SAFETY: the only way to obtain a Timer safely is via methods that +// take a Pin<&mut Self>, therefore the timer is pinned and is valid +let scale =unsafe { *self.as_ptr () }.scaleas i64 ; +// Following C's behavior, scale expire_time even when it is negative. + self.modify_ns (expire_time * scale); }pub fn delete (&self) {
--
2.34.1
Re: [PATCH 10/11] rust: migration: implement ToMigrationState for Timer
In reply to Zhao LiuQuoted 7 lines · Zhao Liu
rust/migration/src/migratable.rs fn restore_migrated_state( · line 263
Quoted 4 lines
rust/migration/src/migratable.rs +4
-0+impl ToMigrationStateShared for util::timer::Timer { +fn restore_migrated_state (&self, source:i64 , _version_id:u8 ) ->Result <(),InvalidError > { +if source >=0 { + self.modify (sourceas u64 );
Timer::modify()is the wrapper oftimer_mod(), andtimer_mod()will re-compute the expire time with scale factor.
Ouch, of course you're right.
Quoted 8 lines
So here we should use a binding of
timer_mod_ns()-Timer::modify_ns()instead ofTimer::modify(), just like C side did.Moreover, for
Timer::modify_ns()&Timer::modify(), the simplest way is to build them based ontimer_mod_ns()&timer_mod()(but this sounds like shifting the responsibility for type checking and overflow checking to the C side :-( ).
Quoted 6 lines
Alternative, we can make
Timer::modify()based onTimer::modify_ns(), but then it involves many numeric type conversions: scale is i32 butexpire_timeis u64, andTimer::modify_ns()may accept a u64 argument.Fortunately,, we can make Timer's
modify()accept i64 to reduce type conversions.
I think it's better to make it accept u64 and assert that it's not above i64::MAX (with .try_into().unwrap()). Anyway I left out this patch, and it can be picked up when HPET starts using ToMigrationState.
Paolo
PATCH 11/11 rust: migration: implement ToMigrationState as part of impl_vmstate_bitsized
In reply to Paolo BonziniThis is most likely desirable, and is the easiest way to migrate a bit-sized value without peeking at the innards of the bilge crate.
--- rust/migration/src/vmstate.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+)
rust/migration/src/vmstate.rs +19 -0
@@ -295,6 +295,25 @@ unsafe impl $crate::vmstate::VMState for $type { as ::bilge::prelude::Number >::UnderlyingType as $crate::vmstate::VMState >::VARRAY_FLAG ; } + +impl $crate::migratable::ToMigrationState for $type { +type Migrated = <<$typeas ::bilge::prelude::Bitsized >::ArbitraryInt +as ::bilge::prelude::Number >::UnderlyingType ; + +fn snapshot_migration_state (&self, target: &mut Self ::Migrated ) ->Result <(), $crate::InvalidError > { + *target =Self ::Migrated ::from (*self); +Ok (()) + } + +fn restore_migrated_state_mut ( + &mut self, + source:Self ::Migrated , + version_id:u8 , + ) ->Result <(), $crate::InvalidError > { + *self =Self ::from (source); +Ok (()) + } + } }; }
Signature · 1 line
2.51.0
Re: [PATCH 11/11] rust: migration: implement ToMigrationState as part of impl_vmstate_bitsized
Quoted 6 lines · Paolo Bonzini
Date: Wed, 1 Oct 2025 09:52:10 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 11/11] rust: migration: implement ToMigrationState as part
ofimpl_vmstate_bitsized
X-Mailer: git-send-email 2.51.0
Quoted 7 lines
This is most likely desirable, and is the easiest way to migrate a bit-sized value without peeking at the innards of the bilge crate.
Signed-off-by Paolo Bonzini <[email protected]>--- rust/migration/src/vmstate.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+)
PATCH 1/14 qobject: make refcount atomic
In reply to Paolo BonziniThe Rust bindings for QObject will only share a complete object and treat it as immutable from that point on. With that constraint, it is trivial to make QObjects thread-safe just by making reference count operations atomic. Do the same when the C code adds or removes references.
--- include/qobject/qobject.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
include/qobject/qobject.h +3 -2
@@ -32,6 +32,7 @@#ifndef QOBJECT_H #define QOBJECT_H +#include "qemu/atomic.h" #include "qapi/qapi-builtin-types.h" /* Not for use outside include/qobject/ */
@@ -73,7 +74,7 @@ QEMU_BUILD_BUG_MSG(QTYPE__MAX != 7,static inline void qobject_ref_impl (QObject *obj) {if (obj) { - obj->base.refcnt++; +qatomic_inc (&obj->base.refcnt); } }
@@ -95,7 +96,7 @@ void qobject_destroy(QObject *obj);static inline void qobject_unref_impl (QObject *obj) {assert (!obj || obj->base.refcnt); -if (obj && --obj->base.refcnt ==0 ) { +if (obj &&qatomic_fetch_dec (&obj->base.refcnt) ==1 ) {qobject_destroy (obj); } }
Signature · 1 line
2.51.0
Re: [PATCH 01/14] qobject: make refcount atomic
Quoted 11 lines · Paolo Bonzini
Date: Wed, 1 Oct 2025 10:00:38 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 01/14] qobject: make refcount atomic
X-Mailer: git-send-email 2.51.0The Rust bindings for QObject will only share a complete object and treat it as immutable from that point on. With that constraint, it is trivial to make QObjects thread-safe just by making reference count operations atomic. Do the same when the C code adds or removes references.
Quoted 4 lines
Signed-off-by Paolo Bonzini <[email protected]>--- include/qobject/qobject.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
PATCH 2/14 rust: add basic QObject bindings
In reply to Paolo BonziniThis is only a basic API, intended to be used by the serde traits.
--- rust/util/wrapper.h | 7 + rust/util/meson.build | 6 +- rust/util/src/lib.rs | 2 + rust/util/src/qobject/mod.rs | 309 +++++++++++++++++++++++++++++++++++ 4 files changed, 322 insertions(+), 2 deletions(-) create mode 100644 rust/util/src/qobject/mod.rs
rust/util/wrapper.h +7 -0
@@ -30,3 +30,10 @@ typedef enum memory_order {#include "qemu/log.h" #include "qemu/module.h" #include "qemu/timer.h" +#include "qobject/qnull.h" +#include "qobject/qbool.h" +#include "qobject/qnum.h" +#include "qobject/qstring.h" +#include "qobject/qobject.h" +#include "qobject/qlist.h" +#include "qobject/qdict.h"
rust/util/meson.build +4 -2
@@ -36,8 +36,10 @@ _util_rs = static_library( 'src/module.rs', 'src/timer.rs', ], - {'.': _util_bindings_inc_rs} - ), + {'.': _util_bindings_inc_rs, + 'qobject': [ + 'src/qobject/mod.rs', + ]}), override_options: ['rust_std=2021', 'build.rust_std=2021'], rust_abi: 'rust', dependencies: [anyhow_rs, libc_rs, foreign_rs, glib_sys_rs, common_rs, qom, qemuutil],
rust/util/src/lib.rs +2 -0
@@ -4,6 +4,8 @@pub mod error;pub mod log;pub mod module; +#[macro_use] +pub mod qobject;pub mod timer;pub use error::{Error ,Result };
rust/util/src/qobject/mod.rs new file +309 -0
309 lines not on this page · raw message
Signature · 1 line
2.51.0
Re: [PATCH 02/14] rust: add basic QObject bindings
rust/util/src/qobject/mod.rs line 7
Quoted 13 lines
rust/util/src/qobject/mod.rs new file +7
-0@@ -0,0 +1,309 @@ +//! `QObject` bindings +//! +//! This module implements bindings for QEMU's `QObject` data structure. +//! The bindings integrate with `serde`, which take the role of visitors +//! in Rust code. + +#![deny(clippy::unwrap_used)]
Are there are any specific considerations for this lint rule?
Quoted 12 lines
rust/util/src/qobject/mod.rs new file +12
-0+use std::{ + cell::UnsafeCell , + ffi::{c_char,CString }, + mem::ManuallyDrop , + ptr::{addr_of, addr_of_mut}, + sync::atomic::{AtomicUsize ,Ordering }, +}; + +use common::assert_field_type; + +use crate ::bindings; +
rust/util/src/qobject/mod.rs line 29
Quoted 10 lines
rust/util/src/qobject/mod.rs new file +10
-0+/// A wrapper for a C `QObject`. +/// +/// Because `QObject` is not thread-safe, the safety of these bindings +/// right now hinges on treating them as immutable. It is part of the +/// contract with the `QObject` constructors that the Rust struct is +/// only built after the contents are stable. +/// +/// Only a bare bones API is public; production and consumption of `QObject` +/// generally goes through `serde`. +pub struct QObject (&'staticUnsafeCell <bindings::QObject >);
It seems Opaque<> feels more natural than UnsafeCell<>.
Opaque::from_raw() requires *mut T, but QObject::from_raw() and QObject::clone_from_raw() mainly play with C bindings which usually use *mut pointer. So it seems unnecessary to convert *mut to *const in the middle.
And furthermore, I think QObject(Opaque<bindings::QObject>) is better than QObject(&'static Opaque<bindings::QObject>). From a semantic view, C's QObject is a struct, while Rust's QObject is a reference, which seems somewhat mismatched.
I'm not sure yet if there may be gaps when remove &'static, but it looks like using &'static Opaque<> instead of &'static UnsafeCell<> is Okay in code?
Quoted 13 lines
rust/util/src/qobject/mod.rs new file +13
-0+/// Construct a [`QObject`] from a C `QObject` pointer. +/// The caller *does not* cede its reference to the returned struct. +/// +/// # Safety +/// +/// The `QObjectBase` must not be changed from C code while +/// the Rust `QObject` lives +unsafe fn cloned_from_base (p: *const bindings::QObjectBase_ ) ->Self { +let orig =unsafe {ManuallyDrop ::new (QObject ::from_base (p)) }; + (*orig).clone () + } + +/// Construct a [`QObject`] from a C `QObject` pointer.
rust/util/src/qobject/mod.rs line 52
Quoted 10 lines
rust/util/src/qobject/mod.rs new file +10
-0+/// The caller *does not* cede its reference to the returned struct. +/// +/// # Safety +/// +/// The `QObject` must not be changed from C code while +/// the Rust `QObject` lives +pub unsafe fn cloned_from_raw (p: *const bindings::QObject ) ->Self { +let orig =unsafe {ManuallyDrop ::new (QObject ::from_raw (p)) }; + (*orig).clone () + }
These 2 methods are the clone, but it seems they're actually similar to Owned<>, i.e., increase refcnt when Rust side wants to "own" or ensure to use this safely.
However, there indeed isn't a non-object version of Owned for now, so I think this kind of clone should be okay. Hmm, for long-term, is it valuable to consider a more generic Owned<>?
rust/util/src/qobject/mod.rs line 57
Quoted 5 lines
rust/util/src/qobject/mod.rs new file +5
-0+impl <A >FromIterator <A >for QObject +where +Self :From <A >, +{ +fn from_iter <I :IntoIterator <Item =A >>(it:I ) ->Self {
nit: maybe the name "iter" is better than "it"?
Quoted 7 lines
rust/util/src/qobject/mod.rs new file +7
-0+let qlist =unsafe { &mut *bindings::qlist_new () }; +for elemin it { +let elem:QObject = elem.into (); +let elem: *mut bindings::QObject = elem.0 .get (); +unsafe { + bindings::qlist_append_obj (qlist, elem); + }
rust/util/src/qobject/mod.rs line 74
Quoted 10 lines
rust/util/src/qobject/mod.rs new file +10
-0+ } +unsafe {QObject ::from_base (addr_of! (qlist.base)) } + } +} + +impl <A >FromIterator <(CString ,A )>for QObject +where +Self :From <A >, +{ +fn from_iter <I :IntoIterator <Item = (CString ,A )>>(it:I ) ->Self {
ditto.
rust/util/src/qobject/mod.rs line 85
Quoted 11 lines
rust/util/src/qobject/mod.rs new file +11
-0+let qdict =unsafe { &mut *bindings::qdict_new () }; +for (key, val)in it { +let val:QObject = val.into (); +let val = val.into_raw (); +unsafe { + bindings::qdict_put_obj (qdict, key.as_ptr ().cast ::<c_char >(), val); + } + } +unsafe {QObject ::from_base (addr_of! (qdict.base)) } + } +}
I think these the mappings of qdict and qlist look quite good.
Quoted 38 lines
rust/util/src/qobject/mod.rs new file +38
-0+#[allow(unused)] +macro_rules! match_qobject { + (@internal ($qobj:expr) => + $(() => $unit:expr,)? + $(bool ($boolvar:tt) => $bool:expr,)? + $(i64 ($i64var:tt) => $i64:expr,)? + $(u64 ($u64var:tt) => $u64:expr,)? + $(f64 ($f64var:tt) => $f64:expr,)? + $(CStr ($cstrvar:tt) => $cstr:expr,)? + $(QList ($qlistvar:tt) => $qlist:expr,)? + $(QDict ($qdictvar:tt) => $qdict:expr,)? + $(_ => $other:expr,)? + ) => { +loop { +let qobj_ = $qobj.0 .get (); +match unsafe { &* qobj_ }.base.type_ { + $($crate::bindings::QTYPE_QNULL =>break $unit,)? + $($crate::bindings::QTYPE_QBOOL =>break { +let qbool__: *mut $crate::bindings::QBool = qobj_.cast(); +let $boolvar =unsafe { (&*qbool__).value }; + $bool + },)? + $crate::bindings::QTYPE_QNUM => { +let qnum__: *mut $crate::bindings::QNum = qobj_.cast(); +let qnum__ =unsafe { &*qnum__ }; +match qnum__.kind { + $crate::bindings::QNUM_I64 | + $crate::bindings::QNUM_U64 | + $crate::bindings::QNUM_DOUBLE => {} + _ => { +panic! ("unreachable" ); + } + } + +match qnum__.kind { + $($crate::bindings::QNUM_I64 => break { + let $i64var = unsafe { qnum__.u.i64_ }; + $i64
rust/util/src/qobject/mod.rs line 133
Quoted 10 lines
rust/util/src/qobject/mod.rs new file +10
-0+ },)? + $($crate::bindings::QNUM_U64 => break { + let $u64var = unsafe { qnum__.u.u64_ }; + $u64 + },)? + $($crate::bindings::QNUM_DOUBLE => break { + let $f64var = unsafe { qnum__.u.dbl }; + $f64 + },)? + _ => {}
I think this doesn't handle a special case: qobj's QNUM type doesn't macth the value type, for example, qobj is QNUM_U64 but value is i64.
Though external code won't use this macro, I think panic may be better than {}?
rust/util/src/qobject/mod.rs line 134
Quoted 1 line
rust/util/src/qobject/mod.rs new file +1
-0+ }
Thurther, there're 2 match blocks. Could we merge them as one?
rust/util/src/qobject/mod.rs +3 -9
@@ -280,14 +280,6 @@ macro_rules! match_qobject { $crate::bindings::QTYPE_QNUM => {let qnum__: *mut $crate::bindings::QNum = qobj_.cast ();let qnum__ =unsafe { &*qnum__ }; -match qnum__.kind { - $crate::bindings::QNUM_I64 | - $crate::bindings::QNUM_U64 | - $crate::bindings::QNUM_DOUBLE => {} - _ => { -panic! ("unreachable" ); - } - }match qnum__.kind { $($crate::bindings::QNUM_I64 => break {
@@ -302,7 +294,9 @@ macro_rules! match_qobject { let $f64var = unsafe { qnum__.u.dbl }; $f64 },)? - _ => {} + _ => { + panic!("unreachable"); + } } }, $($crate::bindings::QTYPE_QSTRING => break {
Regards,
Zhao
Re: [PATCH 02/14] rust: add basic QObject bindings
Quoted 7 lines · Zhao Liu
Quoted 7 lines
rust/util/src/qobject/mod.rs new file +1
-0@@ -0,0 +1,309 @@ +//! `QObject` bindings
Quoted 8 lines
rust/util/src/qobject/mod.rs line 7
Quoted 6 lines
rust/util/src/qobject/mod.rs new file +6
-0+//! +//! This module implements bindings for QEMU's `QObject` data structure. +//! The bindings integrate with `serde`, which take the role of visitors +//! in Rust code. + +#![deny(clippy::unwrap_used)] Are there are any specific considerations for this lint rule?
It ensures that all conversion errors (e.g. from try_into()) are propagated.
Quoted 9 lines
rust/util/src/qobject/mod.rs line 8
Quoted 1 line
rust/util/src/qobject/mod.rs new file +1
-0+pub struct QObject (&'staticUnsafeCell <bindings::QObject >);It seems Opaque<> feels more natural than UnsafeCell<>.
Opaque::from_raw()requires *mut T, butQObject::from_raw()andQObject::clone_from_raw()mainly play with C bindings which usually use *mut pointer. So it seems unnecessary to convert *mut to *const in the middle.
Quoted 8 lines
And furthermore, I think QObject(Opaque<bindings::QObject>) is better than
QObject(&'static Opaque<bindings::QObject>). From a semantic view, C's QObject is a struct, while Rust's QObject is a reference, which seems somewhat mismatched.I'm not sure yet if there may be gaps when remove &'static, but it looks like using &'static Opaque<> instead of &'static UnsafeCell<> is Okay in code?
I am using UnsafeCell because the QObject here is always valid, i.e. MaybeUninit is explicitly not necessary. Opaque explicitly allows it to be invalid, here instead the API is "create via C code or FFI and only then create the QObject".
However, while it is possible to use Opaque<> instead of UnsafeCell<>, it is not possible to make this a simple wrapper because QObject is unmovable and reference counted. That is, QObject is the equivalent of (for example) Owned<DeviceState>.
Quoted 7 lines
These 2 methods are the clone, but it seems they're actually similar to Owned<>, i.e., increase refcnt when Rust side wants to "own" or ensure to use this safely.
However, there indeed isn't a non-object version of Owned for now, so I think this kind of clone should be okay. Hmm, for long-term, is it valuable to consider a more generic Owned<>?
Linux has ARef<> I think. But it seems overkill for now.
Quoted 7 lines
rust/util/src/qobject/mod.rs line 13
Quoted 5 lines
rust/util/src/qobject/mod.rs new file +5
-0+impl <A >FromIterator <A >for QObject +where +Self :From <A >, +{ +fn from_iter <I :IntoIterator <Item =A >>(it:I ) ->Self {nit: maybe the name "iter" is better than "it"?
Sure.
Quoted 15 lines
Quoted 4 lines
rust/util/src/qobject/mod.rs new file +4
-0+ match qnum__.kind { + $($crate::bindings::QNUM_I64 => break { + let $i64var = unsafe { qnum__.u.i64_ }; + $i64rust/util/src/qobject/mod.rs line 27
Quoted 10 lines
rust/util/src/qobject/mod.rs new file +10
-0+ },)? + $($crate::bindings::QNUM_U64 => break { + let $u64var = unsafe { qnum__.u.u64_ }; + $u64 + },)? + $($crate::bindings::QNUM_DOUBLE => break { + let $f64var = unsafe { qnum__.u.dbl }; + $f64 + },)? + _ => {}
Quoted 5 lines
I think this doesn't handle a special case: qobj's QNUM type doesn't macth the value type, for example, qobj is
QNUM_U64but value is i64.Though external code won't use this macro, I think panic may be better than {}?> Thurther, there're 2 match blocks. Could we merge them as one?
Yes, that works because all callers specify all three of i64/u64/f64.
Paolo
Re: [PATCH 02/14] rust: add basic QObject bindings
Quoted 14 lines
Quoted 14 lines
Quoted 1 line
+pub struct
QObject(&'static UnsafeCell<bindings::QObject>);It seems Opaque<> feels more natural than UnsafeCell<>.
Opaque::from_raw()requires *mut T, butQObject::from_raw()andQObject::clone_from_raw()mainly play with C bindings which usually use *mut pointer. So it seems unnecessary to convert *mut to *const in the middle.And furthermore, I think QObject(Opaque<bindings::QObject>) is better than
QObject(&'static Opaque<bindings::QObject>). From a semantic view, C's QObject is a struct, while Rust's QObject is a reference, which seems somewhat mismatched.
Quoted 8 lines
Quoted 3 lines
I'm not sure yet if there may be gaps when remove &'static, but it looks like using &'static Opaque<> instead of &'static UnsafeCell<> is Okay in code?
I am using UnsafeCell because the QObject here is always valid, i.e. MaybeUninit is explicitly not necessary. Opaque explicitly allows it to be invalid, here instead the API is "create via C code or FFI and only then create the QObject".
Just want to clarify the use for Opaque, we've already used Opaque<>::from_raw() for the case "create via C code or FFI and only then create the" something? In DeviceState::init_clock_[in|out](), and ObjectClassMethods::new().
But I also agree, for this case MaybeUninit is not necessary. And PhantomPinned is simply replaced by &'static.
Quoted 4 lines
However, while it is possible to use Opaque<> instead of UnsafeCell<>, it is not possible to make this a simple wrapper because QObject is unmovable and reference counted. That is, QObject is the equivalent of (for example) Owned<DeviceState>.
Got it, if Rust owns data by QObject(Opaque<>) but without Owned<>, this can't work since it's no way to handle refcnt.
So &'static UnsafeCell<> is the simplest way to meet both unmovable & refcnt rquirements.
I'm good with this design. Thanks!
Regards,
Zhao
Re: [PATCH 02/14] rust: add basic QObject bindings
In reply to Paolo BonziniQuoted 61 lines · Paolo Bonzini
Quoted 9 lines · Zhao Liu
Quoted 9 lines
rust/util/src/qobject/mod.rs new file +3
-0@@ -0,0 +1,309 @@ +//! `QObject` bindings +//! +//! This module implements bindings for QEMU's `QObject` data Quoted 8 lines
rust/util/src/qobject/mod.rs
Quoted 6 lines
structure.
+//! The bindings integrate withserde, which take the role of visitorsrust/util/src/qobject/mod.rs new file +3
-0+//! in Rust code. + +#![deny(clippy::unwrap_used)] Are there are any specific considerations for this lint rule?
It ensures that all conversion errors (e.g. from
try_into()) are propagated.Quoted 9 lines
Quoted 1 line
+pub struct
QObject(&'static UnsafeCell<bindings::QObject>);It seems Opaque<> feels more natural than UnsafeCell<>.
Opaque::from_raw()requires *mut T, butQObject::from_raw()andQObject::clone_from_raw()mainly play with C bindings which usually use *mut pointer. So it seems unnecessary to convert *mut to *const in the middle.Quoted 8 lines
And furthermore, I think QObject(Opaque<bindings::QObject>) is better than
QObject(&'static Opaque<bindings::QObject>). From a semantic view, C's QObject is a struct, while Rust's QObject is a reference, which seems somewhat mismatched.I'm not sure yet if there may be gaps when remove &'static, but it looks like using &'static Opaque<> instead of &'static UnsafeCell<> is Okay in code?
I am using UnsafeCell because the QObject here is always valid, i.e. MaybeUninit is explicitly not necessary. Opaque explicitly allows it to be invalid, here instead the API is "create via C code or FFI and only then create the QObject".
However, while it is possible to use Opaque<> instead of UnsafeCell<>, it is not possible to make this a simple wrapper because QObject is unmovable and reference counted. That is, QObject is the equivalent of (for example) Owned<DeviceState>.
Quoted 7 lines
These 2 methods are the clone, but it seems they're actually similar to Owned<>, i.e., increase refcnt when Rust side wants to "own" or ensure to use this safely.
However, there indeed isn't a non-object version of Owned for now, so I think this kind of clone should be okay. Hmm, for long-term, is it valuable to consider a more generic Owned<>?
Linux has ARef<> I think. But it seems overkill for now.
Quoted 7 lines
rust/util/src/qobject/mod.rs
Quoted 5 lines
rust/util/src/qobject/mod.rs new file +5
-0+impl <A >FromIterator <A >for QObject +where + Self: From<A>, +{ + fn from_iter<I: IntoIterator<Item = A>>(it: I) -> Self {nit: maybe the name "iter" is better than "it"?
Quoted 22 lines
Sure.
Quoted 20 lines
Quoted 6 lines
+ match qnum__.kind {
+ $($crate::bindings::QNUM_I64 => break { + let $i64var = unsafe { qnum__.u.i64_ }; + $i64
+ },)?
+ $($crate::bindings::QNUM_U64 => break {Quoted 8 lines
+ let $u64var = unsafe { qnum__.u.u64_ }; + $u64
+ },)?
+ $($crate::bindings::QNUM_DOUBLE => break { + let $f64var = unsafe { qnum__.u.dbl }; + $f64
+ },)?
+ _ => {}I think this doesn't handle a special case: qobj's QNUM type doesn't macth the value type, for example, qobj is
QNUM_U64but value is i64.Though external code won't use this macro, I think panic may be better than {}?> Thurther, there're 2 match blocks. Could we merge them as one?
Just one thing: it's not returning {}, it's returning the value expressed in $(_ => $other:expr,)?. So I think it's better to keep it this way.
Paolo
PATCH 3/14 subprojects: add serde
In reply to Paolo Bonzini--- rust/Cargo.toml | 2 ++ rust/meson.build | 2 ++ scripts/archive-source.sh | 3 ++ scripts/make-release | 2 +- subprojects/.gitignore | 3 ++ .../packagefiles/serde-1-rs/meson.build | 36 +++++++++++++++++++ .../packagefiles/serde-1.0.226-include.patch | 16 +++++++++ .../packagefiles/serde_core-1-rs/meson.build | 25 +++++++++++++ .../serde_core-1.0.226-include.patch | 15 ++++++++ .../serde_derive-1-rs/meson.build | 35 ++++++++++++++++++ .../serde_derive-1.0.226-include.patch | 11 ++++++ subprojects/serde-1-rs.wrap | 11 ++++++ subprojects/serde_core-1-rs.wrap | 11 ++++++ subprojects/serde_derive-1-rs.wrap | 11 ++++++ 14 files changed, 182 insertions(+), 1 deletion(-) create mode 100644 subprojects/packagefiles/serde-1-rs/meson.build create mode 100644 subprojects/packagefiles/serde-1.0.226-include.patch create mode 100644 subprojects/packagefiles/serde_core-1-rs/meson.build create mode 100644 subprojects/packagefiles/serde_core-1.0.226-include.patch create mode 100644 subprojects/packagefiles/serde_derive-1-rs/meson.build create mode 100644 subprojects/packagefiles/serde_derive-1.0.226-include.patch create mode 100644 subprojects/serde-1-rs.wrap create mode 100644 subprojects/serde_core-1-rs.wrap create mode 100644 subprojects/serde_derive-1-rs.wrap
rust/Cargo.toml +2 -0
@@ -30,6 +30,8 @@ anyhow = "~1.0" foreign = "~0.3.1" libc = "0.2.162" glib-sys = { version = "0.21.2", features = ["v2_66"] } +serde = "1.0.226" +serde_derive = "1.0.226" [workspace.lints.rust] unexpected_cfgs = { level = "deny", check-cfg = ['cfg(MESON)'] }
rust/meson.build +2 -0
@@ -4,6 +4,7 @@ subproject('bilge-impl-0.2-rs', required: true) subproject('foreign-0.3-rs', required: true) subproject('glib-sys-0.21-rs', required: true) subproject('libc-0.2-rs', required: true) +subproject('serde-1-rs', required: true) anyhow_rs = dependency('anyhow-1-rs') bilge_rs = dependency('bilge-0.2-rs')
@@ -11,6 +12,7 @@ bilge_impl_rs = dependency('bilge-impl-0.2-rs') foreign_rs = dependency('foreign-0.3-rs') glib_sys_rs = dependency('glib-sys-0.21-rs') libc_rs = dependency('libc-0.2-rs') +serde_rs = dependency('serde-1-rs') subproject('proc-macro2-1-rs', required: true) subproject('quote-1-rs', required: true)
scripts/archive-source.sh +3 -0
@@ -45,6 +45,9 @@ subprojects=( proc-macro-error-attr-1-rs proc-macro2-1-rs quote-1-rs + serde-1-rs + serde_core-1-rs + serde_derive-1-rs syn-2-rs unicode-ident-1-rs )
scripts/make-release +1 -1
@@ -44,7 +44,7 @@ SUBPROJECTS="libvfio-user keycodemapdb berkeley-softfloat-3 bilge-impl-0.2-rs either-1-rs foreign-0.3-rs itertools-0.11-rs libc-0.2-rs proc-macro2-1-rs proc-macro-error-1-rs proc-macro-error-attr-1-rs quote-1-rs - syn-2-rs unicode-ident-1-rs" + serde-1-rs serde_core-1-rs serde_derive-1-rs syn-2-rs unicode-ident-1-rs" src="$1" version="$2"
subprojects/.gitignore +3 -0
@@ -20,6 +20,9 @@ /proc-macro-error-attr-* /proc-macro* /quote-* +/serde-* +/serde_core-* +/serde_derive-* /syn-* /unicode-ident-*
subprojects/packagefiles/serde-1-rs/meson.build new file +36 -0
@@ -0,0 +1,36 @@ +project('serde-1-rs', 'rust', + meson_version: '>=1.5.0', + version: '1.0.226', + license: 'MIT OR Apache-2.0', + default_options: []) + +subproject('serde_core-1-rs', required: true) +subproject('serde_derive-1-rs', required: true) + +serde_core_dep = dependency('serde_core-1-rs') +serde_derive_dep = dependency('serde_derive-1-rs') + +_serde_rs = static_library( + 'serde', + files('src/lib.rs'), + gnu_symbol_visibility: 'hidden', + override_options: ['rust_std=2021', 'build.rust_std=2021'], + rust_abi: 'rust', + rust_args: [ + '--cap-lints', 'allow', + '--cfg', 'feature="alloc"', + '--cfg', 'feature="std"', + '--cfg', 'feature="derive"', + ], + dependencies: [ + serde_core_dep, + serde_derive_dep, + ] +) + +serde_dep = declare_dependency( + link_with: _serde_rs, + dependencies: serde_derive_dep, +) + +meson.override_dependency('serde-1-rs', serde_dep, native: true)
subprojects/packagefiles/serde-1.0.226-include.patch new file +16 -0
@@ -0,0 +1,16 @@ +--- a/src/lib.rs 2025-09-23 13:41:09.327582205 +0200 ++++ b/src/lib.rs 2025-09-23 13:41:23.043271856 +0200 +@@ -241,7 +241,12 @@ + #[doc(hidden)] + mod private; + +-include!(concat!(env!("OUT_DIR"), "/private.rs")); ++#[doc(hidden)] ++pub mod __private_MESON { ++ #[doc(hidden)] ++ pub use crate::private::*; ++} ++use serde_core::__private_MESON as serde_core_private; + + // Re-export #[derive(Serialize, Deserialize)]. + //
subprojects/packagefiles/serde_core-1-rs/meson.build new file +25 -0
@@ -0,0 +1,25 @@ +project('serde_core-1-rs', 'rust', + meson_version: '>=1.5.0', + version: '1.0.226', + license: 'MIT OR Apache-2.0', + default_options: []) + +_serde_core_rs = static_library( + 'serde_core', + files('src/lib.rs'), + gnu_symbol_visibility: 'hidden', + override_options: ['rust_std=2021', 'build.rust_std=2021'], + rust_abi: 'rust', + rust_args: [ + '--cap-lints', 'allow', + '--cfg', 'feature="alloc"', + '--cfg', 'feature="result"', + '--cfg', 'feature="std"', + ], +) + +serde_core_dep = declare_dependency( + link_with: _serde_core_rs, +) + +meson.override_dependency('serde_core-1-rs', serde_core_dep, native: true)
subprojects/packagefiles/serde_core-1.0.226-include.patch new file +15 -0
@@ -0,0 +1,15 @@ +--- a/src/lib.rs 2025-09-23 13:32:40.872421170 +0200 ++++ b/src/lib.rs 2025-09-23 13:32:52.181098856 +0200 +@@ -263,7 +263,11 @@ + pub use core::result::Result; + } + +-include!(concat!(env!("OUT_DIR"), "/private.rs")); ++#[doc(hidden)] ++pub mod __private_MESON { ++ #[doc(hidden)] ++ pub use crate::private::*; ++} + + #[cfg(all(not(feature = "std"), no_core_error))] + mod std_error;
subprojects/packagefiles/serde_derive-1-rs/meson.build new file +35 -0
@@ -0,0 +1,35 @@ +project('serde_derive-1-rs', 'rust', + meson_version: '>=1.5.0', + version: '1.0.226', + license: 'MIT OR Apache-2.0', + default_options: []) + +subproject('quote-1-rs', required: true) +subproject('syn-2-rs', required: true) +subproject('proc-macro2-1-rs', required: true) + +quote_dep = dependency('quote-1-rs', native: true) +syn_dep = dependency('syn-2-rs', native: true) +proc_macro2_dep = dependency('proc-macro2-1-rs', native: true) + +rust = import('rust') + +_serde_derive_rs = rust.proc_macro( + 'serde_derive', + files('src/lib.rs'), + override_options: ['rust_std=2021', 'build.rust_std=2021'], + rust_args: [ + '--cap-lints', 'allow', + ], + dependencies: [ + quote_dep, + syn_dep, + proc_macro2_dep, + ], +) + +serde_derive_dep = declare_dependency( + link_with: _serde_derive_rs, +) + +meson.override_dependency('serde_derive-1-rs', serde_derive_dep)
subprojects/packagefiles/serde_derive-1.0.226-include.patch new file +11 -0
@@ -0,0 +1,11 @@ +--- a/src/lib.rs 2025-09-23 13:51:51.540191923 +0200 ++++ b/src/lib.rs 2025-09-23 13:52:07.690060195 +0200 +@@ -98,7 +98,7 @@ + impl private { + fn ident(&self) -> Ident { + Ident::new( +- concat!("__private", env!("CARGO_PKG_VERSION_PATCH")), ++ "__private_MESON", + Span::call_site(), + ) + }
subprojects/serde-1-rs.wrap new file +11 -0
@@ -0,0 +1,11 @@ +[wrap-file] +directory = serde-1.0.226 +source_url = https://crates.io/api/v1/crates/serde/1.0.226/download +source_filename = serde-1.0.226.0.tar.gz +source_hash = 0dca6411025b24b60bfa7ec1fe1f8e710ac09782dca409ee8237ba74b51295fd +#method = cargo +diff_files = serde-1.0.226-include.patch +patch_directory = serde-1-rs + +# bump this version number on every change to meson.build or the patches: +# v1
subprojects/serde_core-1-rs.wrap new file +11 -0
@@ -0,0 +1,11 @@ +[wrap-file] +directory = serde_core-1.0.226 +source_url = https://crates.io/api/v1/crates/serde_core/1.0.226/download +source_filename = serde_core-1.0.226.0.tar.gz +source_hash = ba2ba63999edb9dac981fb34b3e5c0d111a69b0924e253ed29d83f7c99e966a4 +#method = cargo +diff_files = serde_core-1.0.226-include.patch +patch_directory = serde_core-1-rs + +# bump this version number on every change to meson.build or the patches: +# v1
subprojects/serde_derive-1-rs.wrap new file +11 -0
@@ -0,0 +1,11 @@ +[wrap-file] +directory = serde_derive-1.0.226 +source_url = https://crates.io/api/v1/crates/serde_derive/1.0.226/download +source_filename = serde_derive-1.0.226.0.tar.gz +source_hash = 8db53ae22f34573731bafa1db20f04027b2d25e02d8205921b569171699cdb33 +#method = cargo +diff_files = serde_derive-1.0.226-include.patch +patch_directory = serde_derive-1-rs + +# bump this version number on every change to meson.build or the patches: +# v1
Signature · 1 line
2.51.0
Re: [PATCH 03/14] subprojects: add serde
Quoted 23 lines · Paolo Bonzini
Date: Wed, 1 Oct 2025 10:00:40 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 03/14] subprojects: add serde
X-Mailer: git-send-email 2.51.0Signed-off-by Paolo Bonzini <[email protected]>--- rust/Cargo.toml | 2 ++ rust/meson.build | 2 ++ scripts/archive-source.sh | 3 ++ scripts/make-release | 2 +- subprojects/.gitignore | 3 ++ .../packagefiles/serde-1-rs/meson.build | 36 +++++++++++++++++++ .../packagefiles/serde-1.0.226-include.patch | 16 +++++++++ .../packagefiles/serde_core-1-rs/meson.build | 25 +++++++++++++ .../serde_core-1.0.226-include.patch | 15 ++++++++ .../serde_derive-1-rs/meson.build | 35 ++++++++++++++++++ .../serde_derive-1.0.226-include.patch | 11 ++++++ subprojects/serde-1-rs.wrap | 11 ++++++ subprojects/serde_core-1-rs.wrap | 11 ++++++ subprojects/serde_derive-1-rs.wrap | 11 ++++++ 14 files changed, 182 insertions(+), 1 deletion(-) create mode 100644 subprojects/packagefiles/serde-1-rs/meson.build
Quoted 8 lines
create mode 100644 subprojects/packagefiles/serde-1.0.226-include.patch create mode 100644 subprojects/packagefiles/serde_core-1-rs/meson.build create mode 100644 subprojects/packagefiles/serde_core-1.0.226-include.patch create mode 100644 subprojects/packagefiles/serde_derive-1-rs/meson.build create mode 100644 subprojects/packagefiles/serde_derive-1.0.226-include.patch create mode 100644 subprojects/serde-1-rs.wrap create mode 100644 subprojects/serde_core-1-rs.wrap create mode 100644 subprojects/serde_derive-1-rs.wrap
PATCH 4/14 rust: add Serialize implementation for QObject
In reply to Paolo BonziniThis allows QObject to be converted to other formats, for example JSON via serde_json.
This is not too useful, since QObjects are consumed by
C code or deserialized into structs, but it can be used for testing and it is part of the full implementation of a serde format.
--- rust/Cargo.lock | 1 + rust/util/Cargo.toml | 1 + rust/util/meson.build | 3 +- rust/util/src/qobject/mod.rs | 4 +- rust/util/src/qobject/serialize.rs | 59 ++++++++++++++++++++++++++++++ 5 files changed, 65 insertions(+), 3 deletions(-) create mode 100644 rust/util/src/qobject/serialize.rs
rust/Cargo.lock +1 -0
@@ -446,6 +446,7 @@ dependencies = [ "foreign", "glib-sys", "libc", + "serde", ] [[package]]
rust/util/Cargo.toml +1 -0
@@ -17,6 +17,7 @@ anyhow = { workspace = true } foreign = { workspace = true } glib-sys = { workspace = true } libc = { workspace = true } +serde = { workspace = true } common = { path = "../common" } [lints]
rust/util/meson.build +2 -1
@@ -39,10 +39,11 @@ _util_rs = static_library( {'.': _util_bindings_inc_rs, 'qobject': [ 'src/qobject/mod.rs', + 'src/qobject/serialize.rs', ]}), override_options: ['rust_std=2021', 'build.rust_std=2021'], rust_abi: 'rust', - dependencies: [anyhow_rs, libc_rs, foreign_rs, glib_sys_rs, common_rs, qom, qemuutil], + dependencies: [anyhow_rs, libc_rs, foreign_rs, glib_sys_rs, common_rs, serde_rs, qom, qemuutil], ) util_rs = declare_dependency(link_with: [_util_rs], dependencies: [qemuutil, qom])
rust/util/src/qobject/mod.rs +2 -2
@@ -6,6 +6,8 @@#![deny(clippy::unwrap_used)] +mod serialize; +use std::{ cell::UnsafeCell , ffi::{c_char,CString },
@@ -222,7 +224,6 @@ fn drop(&mut self) { } } -#[allow(unused)] macro_rules! match_qobject { (@internal ($qobj:expr) => $(() => $unit:expr,)?
@@ -305,5 +306,4 @@ macro_rules! match_qobject { $($type $(($val))? => $code,)+) }; } -#[allow(unused_imports)] use match_qobject;
rust/util/src/qobject/serialize.rs new file +59 -0
59 lines not on this page · raw message
Signature · 1 line
2.51.0
Re: [PATCH 04/14] rust: add Serialize implementation for QObject
Quoted 23 lines · Paolo Bonzini
Date: Wed, 1 Oct 2025 10:00:41 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 04/14] rust: add Serialize implementation for QObject
X-Mailer: git-send-email 2.51.0This allows QObject to be converted to other formats, for example JSON via
serde_json.This is not too useful, since QObjects are consumed by
C code or deserialized into structs, but it can be used for testing and it is part of the full implementation of a serde format.Co-authored-by Marc-André Lureau <[email protected]>Signed-off-by Marc-André Lureau <[email protected]>Signed-off-by Paolo Bonzini <[email protected]>--- rust/Cargo.lock | 1 + rust/util/Cargo.toml | 1 + rust/util/meson.build | 3 +- rust/util/src/qobject/mod.rs | 4 +- rust/util/src/qobject/serialize.rs | 59 ++++++++++++++++++++++++++++++ 5 files changed, 65 insertions(+), 3 deletions(-) create mode 100644 rust/util/src/qobject/serialize.rs
...
Quoted 13 lines
rust/util/src/qobject/serialize.rs new file +13
-0+impl Serialize for QObject { +#[inline] +fn serialize <S >(&self, serializer:S ) ->Result <S ::Ok ,S ::Error > +where +S : ::serde::Serializer , + { +match_qobject! { (self) => + () => serializer.serialize_unit (), +bool (b) => serializer.serialize_bool (b), +i64 (i) => serializer.serialize_i64 (i), +u64 (u) => serializer.serialize_u64 (u), +f64 (f) => serializer.serialize_f64 (f), +CStr (cstr) => cstr.to_str ().map_or_else(
rust/util/src/qobject/serialize.rs line 36
Quoted 10 lines
rust/util/src/qobject/serialize.rs new file +10
-0+ |_| Err(ser::Error::custom("invalid UTF-8 in QString")), + |s| serializer.serialize_str(s), + ), + QList(l) => { +let mut node_ptr =unsafe { l.head.tqh_first }; +let mut state = serializer.serialize_seq (None )?; +while !node_ptr.is_null () { +let node =unsafe { &*node_ptr }; +let elem =unsafe {ManuallyDrop ::new (QObject ::from_raw (addr_of! (*node.value))) }; + state.serialize_element (&*elem)?;
QObject here is always valid so it's not necessary to concern about it is destroied by C side, and so that it's not necessary to use cloned_from_raw here.
PATCH 5/14 rust: add Serializer (to_qobject) implementation for QObject
In reply to Paolo BonziniThis allows creating QObject from any serializable data structure.
--- rust/util/meson.build | 2 + rust/util/src/qobject/error.rs | 52 +++ rust/util/src/qobject/mod.rs | 4 + rust/util/src/qobject/serializer.rs | 585 ++++++++++++++++++++++++++++ 4 files changed, 643 insertions(+) create mode 100644 rust/util/src/qobject/error.rs create mode 100644 rust/util/src/qobject/serializer.rs
rust/util/meson.build +2 -0
@@ -39,6 +39,8 @@ _util_rs = static_library( {'.': _util_bindings_inc_rs, 'qobject': [ 'src/qobject/mod.rs', + 'src/qobject/error.rs', + 'src/qobject/serializer.rs', 'src/qobject/serialize.rs', ]}), override_options: ['rust_std=2021', 'build.rust_std=2021'],
rust/util/src/qobject/error.rs new file +52 -0
52 lines not on this page · raw message
rust/util/src/qobject/mod.rs +4 -0
@@ -6,7 +6,9 @@#![deny(clippy::unwrap_used)] +mod error;mod serialize; +mod serializer;use std::{ cell::UnsafeCell ,
@@ -17,6 +19,8 @@ };use common::assert_field_type; +pub use error::{Error ,Result }; +pub use serializer::to_qobject;use crate ::bindings;
rust/util/src/qobject/serializer.rs new file +585 -0
585 lines not on this page · raw message
Signature · 1 line
2.51.0
Re: [PATCH 05/14] rust: add Serializer (to_qobject) implementation for QObject
Quoted 11 lines · Paolo Bonzini
Date: Wed, 1 Oct 2025 10:00:42 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 05/14] rust: add Serializer (to_qobject) implementation for
QObject
X-Mailer: git-send-email 2.51.0This allows creating QObject from any serializable data structure.
Co-authored-by Marc-André Lureau <[email protected]>Signed-off-by Marc-André Lureau <[email protected]>Signed-off-by Paolo Bonzini <[email protected]>
Quoted 8 lines
--- rust/util/meson.build | 2 + rust/util/src/qobject/error.rs | 52 +++ rust/util/src/qobject/mod.rs | 4 + rust/util/src/qobject/serializer.rs | 585 ++++++++++++++++++++++++++++ 4 files changed, 643 insertions(+) create mode 100644 rust/util/src/qobject/error.rs create mode 100644 rust/util/src/qobject/serializer.rs
Good implementation,
cover rust: QObject and QAPI bindings
In reply to Paolo BonziniThis adds two related parts of the Rust bindings:
- QAPI code generator that creates Rust structs from the JSON description. The structs are *not* ABI compatible with the C ones, instead they use native Rust data types.
- QObject bindings and (de)serialization support, which can be used to convert QObjects to and from QAPI structs.
Unfortunately Rust code is not able to use visitors, other than by creating an intermediate QObject. This is because of the different architecture of serde vs. QAPI visitors, and because visitor's dual-purpose functions, where the same function is used by both input and output visitors, rely heavily on the structs using the same representation as the visitor arguments (for example NUL-terminated strings.
The serde format implementation was co-authored by me and Marc-André. Marc-André did all the bug fixing and integration testing; and there are a lot more bugs to be fixed / tests to be written, so this is just a preview.
Paolo
Marc-André Lureau (7):
rust/qobject: add Display/Debug
scripts/qapi: add QAPISchemaIfCond.rsgen()
scripts/qapi: generate high-level Rust bindings
scripts/qapi: strip trailing whitespaces
scripts/rustc_args: add --no-strict-cfg
rust/util: build QAPI types
rust: start qapi tests
Paolo Bonzini (7):
qobject: make refcount atomic
rust: add basic QObject bindings
subprojects: add serde
rust: add Serialize implementation for QObject
rust: add Serializer (to_qobject) implementation for QObject
rust: add Deserialize implementation for QObject
rust: add Deserializer (from_qobject) implementation for QObject
docs/devel/rust.rst | 1 + meson.build | 4 +- include/qobject/qobject.h | 5 +- rust/util/wrapper.h | 8 + qapi/meson.build | 6 + rust/Cargo.lock | 2 + rust/Cargo.toml | 2 + rust/meson.build | 2 + rust/tests/meson.build | 10 +- rust/tests/tests/integration.rs | 2 + rust/tests/tests/qapi.rs | 35 ++ rust/util/Cargo.toml | 2 + rust/util/meson.build | 31 +- rust/util/src/lib.rs | 2 + rust/util/src/qobject/deserialize.rs | 134 ++++ rust/util/src/qobject/deserializer.rs | 373 +++++++++++ rust/util/src/qobject/error.rs | 58 ++ rust/util/src/qobject/mod.rs | 353 +++++++++++ rust/util/src/qobject/serialize.rs | 59 ++ rust/util/src/qobject/serializer.rs | 585 ++++++++++++++++++ scripts/archive-source.sh | 3 + scripts/make-release | 2 +- scripts/qapi/backend.py | 28 +- scripts/qapi/common.py | 16 + scripts/qapi/gen.py | 6 +- scripts/qapi/main.py | 4 +- scripts/qapi/rs.py | 176 ++++++ scripts/qapi/rs_types.py | 354 +++++++++++ scripts/qapi/schema.py | 4 + scripts/rust/rustc_args.py | 16 +- subprojects/.gitignore | 3 + .../packagefiles/serde-1-rs/meson.build | 36 ++ .../packagefiles/serde-1.0.226-include.patch | 16 + .../packagefiles/serde_core-1-rs/meson.build | 25 + .../serde_core-1.0.226-include.patch | 15 + .../serde_derive-1-rs/meson.build | 35 ++ .../serde_derive-1.0.226-include.patch | 11 + subprojects/serde-1-rs.wrap | 11 + subprojects/serde_core-1-rs.wrap | 11 + subprojects/serde_derive-1-rs.wrap | 11 + 40 files changed, 2438 insertions(+), 19 deletions(-) create mode 100644 rust/tests/tests/integration.rs create mode 100644 rust/tests/tests/qapi.rs create mode 100644 rust/util/src/qobject/deserialize.rs create mode 100644 rust/util/src/qobject/deserializer.rs create mode 100644 rust/util/src/qobject/error.rs create mode 100644 rust/util/src/qobject/mod.rs create mode 100644 rust/util/src/qobject/serialize.rs create mode 100644 rust/util/src/qobject/serializer.rs create mode 100644 scripts/qapi/rs.py create mode 100644 scripts/qapi/rs_types.py create mode 100644 subprojects/packagefiles/serde-1-rs/meson.build create mode 100644 subprojects/packagefiles/serde-1.0.226-include.patch create mode 100644 subprojects/packagefiles/serde_core-1-rs/meson.build create mode 100644 subprojects/packagefiles/serde_core-1.0.226-include.patch create mode 100644 subprojects/packagefiles/serde_derive-1-rs/meson.build create mode 100644 subprojects/packagefiles/serde_derive-1.0.226-include.patch create mode 100644 subprojects/serde-1-rs.wrap create mode 100644 subprojects/serde_core-1-rs.wrap create mode 100644 subprojects/serde_derive-1-rs.wrap
Signature · 1 line
2.51.0
PATCH 6/14 rust: add Deserialize implementation for QObject
In reply to Paolo BonziniThis allows QObject to be created from any serializable format, for example JSON via serde_json.
This is not too useful, since QObjects are produced by C code or by serializing structs, but it can be used for testing and it is part of the full implementation of a serde format.
--- rust/util/meson.build | 1 + rust/util/src/qobject/deserialize.rs | 134 +++++++++++++++++++++++++++ rust/util/src/qobject/mod.rs | 1 + 3 files changed, 136 insertions(+) create mode 100644 rust/util/src/qobject/deserialize.rs
rust/util/meson.build +1 -0
@@ -39,6 +39,7 @@ _util_rs = static_library( {'.': _util_bindings_inc_rs, 'qobject': [ 'src/qobject/mod.rs', + 'src/qobject/deserialize.rs', 'src/qobject/error.rs', 'src/qobject/serializer.rs', 'src/qobject/serialize.rs',
rust/util/src/qobject/deserialize.rs new file +134 -0
134 lines not on this page · raw message
rust/util/src/qobject/mod.rs +1 -0
@@ -6,6 +6,7 @@#![deny(clippy::unwrap_used)] +mod deserialize;mod error;mod serialize;mod serializer;
Signature · 1 line
2.51.0
Re: [PATCH 06/14] rust: add Deserialize implementation for QObject
Quoted 15 lines · Paolo Bonzini
Date: Wed, 1 Oct 2025 10:00:43 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 06/14] rust: add Deserialize implementation for QObject
X-Mailer: git-send-email 2.51.0This allows QObject to be created from any serializable format, for example JSON via
serde_json.This is not too useful, since QObjects are produced by C code or by serializing structs, but it can be used for testing and it is part of the full implementation of a serde format.
Co-authored-by Marc-André Lureau <[email protected]>Signed-off-by Marc-André Lureau <[email protected]>Signed-off-by Paolo Bonzini <[email protected]>
Quoted 6 lines
--- rust/util/meson.build | 1 + rust/util/src/qobject/deserialize.rs | 134 +++++++++++++++++++++++++++ rust/util/src/qobject/mod.rs | 1 + 3 files changed, 136 insertions(+) create mode 100644 rust/util/src/qobject/deserialize.rs
PATCH 7/14 rust: add Deserializer (from_qobject) implementation for QObject
In reply to Paolo BonziniThis allows creating any serializable data structure from QObject.
--- docs/devel/rust.rst | 1 + rust/util/meson.build | 1 + rust/util/src/qobject/deserializer.rs | 373 ++++++++++++++++++++++++++ rust/util/src/qobject/error.rs | 8 +- rust/util/src/qobject/mod.rs | 2 + 5 files changed, 384 insertions(+), 1 deletion(-) create mode 100644 rust/util/src/qobject/deserializer.rs
docs/devel/rust.rst +1 -0
@@ -162,6 +162,7 @@ module status ``util::error`` stable ``util::log`` proof of concept ``util::module`` complete +``util::qobject`` stable ``util::timer`` stable ========================== ======================
rust/util/meson.build +1 -0
@@ -39,6 +39,7 @@ _util_rs = static_library( {'.': _util_bindings_inc_rs, 'qobject': [ 'src/qobject/mod.rs', + 'src/qobject/deserializer.rs', 'src/qobject/deserialize.rs', 'src/qobject/error.rs', 'src/qobject/serializer.rs',
rust/util/src/qobject/deserializer.rs new file +373 -0
373 lines not on this page · raw message
rust/util/src/qobject/error.rs +7 -1
@@ -6,7 +6,7 @@ str::Utf8Error, }; -use serde::ser; +use serde::{de, ser};#[derive( Debug )] pub enum Error {
@@ -23,6 +23,12 @@ fn custom<T: Display>(msg: T) -> Self { } } +impl de::Error for Error { +fn custom <T :Display >(msg:T ) ->Self { +Error ::Custom (msg.to_string ()) + } +} +impl From <NulError >for Error {fn from (_:NulError ) ->Self {Error ::NulEncountered
rust/util/src/qobject/mod.rs +2 -0
@@ -7,6 +7,7 @@#![deny(clippy::unwrap_used)] mod deserialize; +mod deserializer;mod error;mod serialize;mod serializer;
@@ -20,6 +21,7 @@ };use common::assert_field_type; +pub use deserializer::from_qobject;pub use error::{Error ,Result };pub use serializer::to_qobject;
Signature · 1 line
2.51.0
Re: [PATCH 07/14] rust: add Deserializer (from_qobject) implementation for QObject
Quoted 19 lines · Paolo Bonzini
Date: Wed, 1 Oct 2025 10:00:44 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 07/14] rust: add Deserializer (from_qobject) implementation
for QObject
X-Mailer: git-send-email 2.51.0This allows creating any serializable data structure from QObject.
Co-authored-by Marc-André Lureau <[email protected]>Signed-off-by Marc-André Lureau <[email protected]>Signed-off-by Paolo Bonzini <[email protected]>--- docs/devel/rust.rst | 1 + rust/util/meson.build | 1 + rust/util/src/qobject/deserializer.rs | 373 ++++++++++++++++++++++++++ rust/util/src/qobject/error.rs | 8 +- rust/util/src/qobject/mod.rs | 2 + 5 files changed, 384 insertions(+), 1 deletion(-) create mode 100644 rust/util/src/qobject/deserializer.rs
...
rust/util/src/qobject/deserializer.rs line 4
Quoted 10 lines
rust/util/src/qobject/deserializer.rs new file +4
-0@@ -0,0 +1,373 @@ +//! `QObject` deserializer +//! +//! This module implements a [`Deserializer`](serde::de::Deserializer) that +//! produces `QObject`s, allowing them to be turned into deserializable data
^^^^^^^^
Only a nit,
This "produces" word puzzled me for a while. I think it should be "consumes".
Then the logic of 4 things did in this series should be the following?
serializer serialize
Rust struct ----------> QObject ---------> JSON
<---------- <--------- deserializer deserialize
Maybe we could have the similar documentation/decription in mod.rs or somewhere to provide a high-level overview :).
rust/util/src/qobject/deserializer.rs line 7
Quoted 3 lines
rust/util/src/qobject/deserializer.rs new file +3
-0+//! structures (such as primitive data types, or structs that implement +//! `Deserialize`). +
The implementation itself looks good,
PATCH 8/14 rust/qobject: add Display/Debug
In reply to Paolo BonziniFrom: Marc-André Lureau <[email protected]>
--- rust/util/src/qobject/mod.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+)
rust/util/src/qobject/mod.rs +28 -0
@@ -12,6 +12,7 @@mod serialize;mod serializer; +use core::fmt::{self,Debug ,Display };use std::{ cell::UnsafeCell , ffi::{c_char,CString },
@@ -231,6 +232,33 @@ fn drop(&mut self) { } } +impl Display for QObject { +fn fmt (&self, f: &mut fmt::Formatter <'_>) -> fmt::Result { +// replace with a plain serializer? +match_qobject! { (self) => + () =>write! (f,"QNull" ), +bool (b) =>write! (f,"QBool({})" ,if b {"true" }else {"false" }), +i64 (n) =>write! (f,"QNumI64({})" , n), +u64 (n) =>write! (f,"QNumU64({})" , n), +f64 (n) =>write! (f,"QNumDouble({})" , n), +CStr (s) =>write! (f,"QString({})" , s.to_str ().unwrap_or ("bad CStr" )), +QList (_) =>write! (f,"QList" ), +QDict (_) =>write! (f,"QDict" ), + } + } +} + +impl Debug for QObject { +fn fmt (&self, f: &mut fmt::Formatter <'_>) -> fmt::Result { +let val = self.to_string (); + f.debug_struct ("QObject" ) + .field ("ptr" , &self.0 .get ()) + .field ("refcnt()" , &self.refcnt ()) + .field ("to_string()" , &val) + .finish () + } +} +macro_rules! match_qobject { (@internal ($qobj:expr) => $(() => $unit:expr,)?
Signature · 1 line
2.51.0
PATCH 9/14 scripts/qapi: add QAPISchemaIfCond.rsgen()
In reply to Paolo BonziniFrom: Marc-André Lureau <[email protected]>
Generate Rust #[cfg(...)] guards from QAPI 'if' conditions.
--- scripts/qapi/common.py | 16 ++++++++++++++++ scripts/qapi/schema.py | 4 ++++ 2 files changed, 20 insertions(+)
scripts/qapi/common.py +16 -0
@@ -199,6 +199,22 @@ def guardend(name: str) -> str: name=c_fname(name).upper()) +def rsgen_ifcond(ifcond: Optional[Union[str, Dict[str, Any]]]) -> str: + + def cfg(ifcond: Union[str, Dict[str, Any]]) -> str: + if isinstance(ifcond, str): + return ifcond + if isinstance(ifcond, list): + return ', '.join([cfg(c) for c in ifcond]) + oper, operands = next(iter(ifcond.items())) + operands = cfg(operands) + return f'{oper}({operands})' + + if not ifcond: + return '' + return '#[cfg(%s)]' % cfg(ifcond) + + def gen_ifcond(ifcond: Optional[Union[str, Dict[str, Any]]], cond_fmt: str, not_fmt: str, all_operator: str, any_operator: str) -> str:
scripts/qapi/schema.py +4 -0
@@ -37,6 +37,7 @@ docgen_ifcond, gen_endif, gen_if, + rsgen_ifcond, ) from .error import QAPIError, QAPISemError, QAPISourceError from .expr import check_exprs
@@ -63,6 +64,9 @@ def gen_endif(self) -> str: def docgen(self) -> str: return docgen_ifcond(self.ifcond) + def rsgen(self) -> str: + return rsgen_ifcond(self.ifcond) + def is_present(self) -> bool: return bool(self.ifcond)
Signature · 1 line
2.51.0
PATCH 10/14 scripts/qapi: generate high-level Rust bindings
In reply to Paolo BonziniFrom: Marc-André Lureau <[email protected]>
Generate high-level native Rust declarations for the QAPI types.
- char* is mapped to String, scalars to there corresponding Rust types
- enums are simply aliased from FFI
- has_foo/foo members are mapped to Option<T>
- lists are represented as Vec<T>
- structures have Rust versions, with To/From FFI conversions
- alternate are represented as Rust enum
- unions are represented in a similar way as in C: a struct S with a "u" member (since S may have extra 'base' fields). However, the discriminant isn't a member of S, since Rust enum already include it.
--- meson.build | 4 +- scripts/qapi/backend.py | 28 +++- scripts/qapi/main.py | 4 +- scripts/qapi/rs.py | 176 +++++++++++++++++++ scripts/qapi/rs_types.py | 354 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 562 insertions(+), 4 deletions(-) create mode 100644 scripts/qapi/rs.py create mode 100644 scripts/qapi/rs_types.py
meson.build +3 -1
@@ -3559,12 +3559,14 @@ qapi_gen_depends = [ meson.current_source_dir() / 'scripts/qapi/__init__.py', meson.current_source_dir() / 'scripts/qapi/introspect.py', meson.current_source_dir() / 'scripts/qapi/main.py', meson.current_source_dir() / 'scripts/qapi/parser.py', + meson.current_source_dir() / 'scripts/qapi/rs_types.py', meson.current_source_dir() / 'scripts/qapi/schema.py', meson.current_source_dir() / 'scripts/qapi/source.py', meson.current_source_dir() / 'scripts/qapi/types.py', meson.current_source_dir() / 'scripts/qapi/features.py', meson.current_source_dir() / 'scripts/qapi/visit.py', - meson.current_source_dir() / 'scripts/qapi-gen.py' + meson.current_source_dir() / 'scripts/qapi-gen.py', + meson.current_source_dir() / 'scripts/qapi/rs.py', ] tracetool = [
scripts/qapi/backend.py +27 -1
@@ -7,6 +7,7 @@ from .events import gen_events from .features import gen_features from .introspect import gen_introspect +from .rs_types import gen_rs_types from .schema import QAPISchema from .types import gen_types from .visit import gen_visit
@@ -36,7 +37,7 @@ def generate(self, """ -class QAPICBackend(QAPIBackend): +class QAPICodeBackend(QAPIBackend): # pylint: disable=too-few-public-methods def generate(self,
@@ -63,3 +64,28 @@ def generate(self, gen_commands(schema, output_dir, prefix, gen_tracing) gen_events(schema, output_dir, prefix) gen_introspect(schema, output_dir, prefix, unmask) + + + +class QAPIRsBackend(QAPIBackend): + # pylint: disable=too-few-public-methods + + def generate(self, + schema: QAPISchema, + output_dir: str, + prefix: str, + unmask: bool, + builtins: bool, + gen_tracing: bool) -> None: + """ + Generate Rust code for the given schema into the target directory. + + :param schema_file: The primary QAPI schema file. + :param output_dir: The output directory to store generated code. + :param prefix: Optional C-code prefix for symbol names. + :param unmask: Expose non-ABI names through introspection? + :param builtins: Generate code for built-in types? + + :raise QAPIError: On failures. + """ + gen_rs_types(schema, output_dir, prefix, builtins)
scripts/qapi/main.py +2 -2
@@ -12,7 +12,7 @@ import sys from typing import Optional -from .backend import QAPIBackend, QAPICBackend +from .backend import QAPIBackend, QAPICodeBackend from .common import must_match from .error import QAPIError from .schema import QAPISchema
@@ -27,7 +27,7 @@ def invalid_prefix_char(prefix: str) -> Optional[str]: def create_backend(path: str) -> QAPIBackend: if path is None: - return QAPICBackend() + return QAPICodeBackend() module_path, dot, class_name = path.rpartition('.') if not dot:
scripts/qapi/rs.py new file +176 -0
176 lines not on this page · raw message
scripts/qapi/rs_types.py new file +354 -0
354 lines not on this page · raw message
Signature · 1 line
2.51.0
PATCH 11/14 scripts/qapi: strip trailing whitespaces
In reply to Paolo BonziniFrom: Marc-André Lureau <[email protected]>
This help workaround a rustfmt issue.
--- scripts/qapi/gen.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
scripts/qapi/gen.py +5 -1
@@ -58,7 +58,11 @@ def add(self, text: str) -> None: self._body += text def get_content(self) -> str: - return self._top() + self._preamble + self._body + self._bottom() + content = self._top() + self._preamble + self._body + self._bottom() + # delete trailing white-spaces (working around + # https://github.com/rust-lang/rustfmt/issues/4248) + content = re.sub(r'\s+$', '\n', content, 0, re.M) + return content def _top(self) -> str: # pylint: disable=no-self-use
Signature · 1 line
2.51.0
PATCH 12/14 scripts/rustc_args: add --no-strict-cfg
In reply to Paolo BonziniFrom: Marc-André Lureau <[email protected]>
Allow to generate all --cfg flags, regardless of Cargo.toml content. We can't easily list and include all the features used by QAPI types. Access via #[cfg()] then requires #![allow(unexpected_cfgs)].
--- scripts/rust/rustc_args.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-)
scripts/rust/rustc_args.py +12 -4
@@ -116,7 +116,7 @@ def generate_lint_flags(cargo_toml: CargoTOML, strict_lints: bool) -> Iterable[s yield from lint.flags -def generate_cfg_flags(header: str, cargo_toml: CargoTOML) -> Iterable[str]: +def generate_cfg_flags(header: str, cargo_toml: Optional[CargoTOML]) -> Iterable[str]: """Converts defines from config[..].h headers to rustc --cfg flags.""" with open(header, encoding="utf-8") as cfg:
@@ -125,8 +125,9 @@ def generate_cfg_flags(header: str, cargo_toml: CargoTOML) -> Iterable[str]: cfg_list = [] for cfg in config: name = cfg[0] - if f'cfg({name})' not in cargo_toml.check_cfg: - continue + if cargo_toml: + if f'cfg({name})' not in cargo_toml.check_cfg: + continue if len(cfg) >= 2 and cfg[1] != "1": continue cfg_list.append("--cfg")
@@ -194,6 +195,13 @@ def main() -> None: help="apply stricter checks (for nightly Rust)", default=False, ) + parser.add_argument( + "--no-strict-cfg", + help="only generate expected cfg", + action="store_false", + dest="strict_cfg", + default=True, + ) args = parser.parse_args() if args.verbose: logging.basicConfig(level=logging.DEBUG)
@@ -224,7 +232,7 @@ def main() -> None: print(f'cfg(feature,values("{feature}"))') for header in args.config_headers: - for tok in generate_cfg_flags(header, cargo_toml): + for tok in generate_cfg_flags(header, cargo_toml if args.strict_cfg else None): print(tok)
Signature · 1 line
2.51.0
PATCH 13/14 rust/util: build QAPI types
In reply to Paolo BonziniFrom: Marc-André Lureau <[email protected]>
--- rust/util/wrapper.h | 1 + qapi/meson.build | 6 ++++++ rust/Cargo.lock | 1 + rust/util/Cargo.toml | 1 + rust/util/meson.build | 18 +++++++++++++++++- rust/util/src/qobject/mod.rs | 9 +++++++++ 6 files changed, 35 insertions(+), 1 deletion(-)
rust/util/wrapper.h +1 -0
@@ -37,3 +37,4 @@ typedef enum memory_order {#include "qobject/qobject.h" #include "qobject/qlist.h" #include "qobject/qdict.h" +#include "qobject/qjson.h"
qapi/meson.build +6 -0
@@ -129,3 +129,9 @@ foreach output : qapi_outputs util_ss.add(qapi_files[i]) i = i + 1 endforeach + +qapi_rs_files = custom_target('QAPI Rust', + output: 'qapi-types.rs', + input: [ files('qapi-schema.json') ], + command: [ qapi_gen, '-o', 'qapi', '-b', '@INPUT0@', '-B', 'qapi.backend.QAPIRsBackend' ], + depend_files: [ qapi_inputs, qapi_gen_depends ])
rust/Cargo.lock +1 -0
@@ -447,6 +447,7 @@ dependencies = [ "glib-sys", "libc", "serde", + "serde_derive", ] [[package]]
rust/util/Cargo.toml +1 -0
@@ -18,6 +18,7 @@ foreign = { workspace = true } glib-sys = { workspace = true } libc = { workspace = true } serde = { workspace = true } +serde_derive = { workspace = true } common = { path = "../common" } [lints]
rust/util/meson.build +17 -1
@@ -50,7 +50,7 @@ _util_rs = static_library( dependencies: [anyhow_rs, libc_rs, foreign_rs, glib_sys_rs, common_rs, serde_rs, qom, qemuutil], ) -util_rs = declare_dependency(link_with: [_util_rs], dependencies: [qemuutil, qom]) +util_rs = declare_dependency(link_with: [_util_rs], dependencies: []) rust.test('rust-util-tests', _util_rs, dependencies: [qemuutil, qom],
@@ -64,3 +64,19 @@ rust.doctest('rust-util-rs-doctests', dependencies: util_rs, suite: ['doc', 'rust'] ) + +_qapi_cfg = run_command(rustc_args, + '--no-strict-cfg', + '--config-headers', config_host_h, + capture: true, check: true).stdout().strip().splitlines() + +_qapi_rs = static_library( + 'qapi', + qapi_rs_files, + rust_args: _qapi_cfg, + override_options: ['rust_std=2021', 'build.rust_std=2021'], + rust_abi: 'rust', + dependencies: [common_rs, util_rs, serde_rs], +) + +qapi_rs = declare_dependency(link_with: [_qapi_rs])
rust/util/src/qobject/mod.rs +9 -0
@@ -13,6 +13,7 @@mod serializer;use core::fmt::{self,Debug ,Display }; +use foreign::prelude::*;use std::{ cell::UnsafeCell , ffi::{c_char,CString },
@@ -104,6 +105,14 @@ fn refcnt(&self) -> &AtomicUsize {let qobj = self.0 .get ();unsafe {AtomicUsize ::from_ptr (addr_of_mut! ((*qobj).base.refcnt)) } } + +pub fn to_json (&self) ->String { +let qobj = self.0 .get (); +unsafe { +let json = bindings::qobject_to_json (qobj); + glib_sys::g_string_free (json, glib_sys::GFALSE ).into_native () + } + } }impl From <()>for QObject {
Signature · 1 line
2.51.0
PATCH 14/14 rust: start qapi tests
In reply to Paolo BonziniFrom: Marc-André Lureau <[email protected]>
--- rust/tests/meson.build | 10 +++++++--- rust/tests/tests/integration.rs | 2 ++ rust/tests/tests/qapi.rs | 35 +++++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+), 3 deletions(-) create mode 100644 rust/tests/tests/integration.rs create mode 100644 rust/tests/tests/qapi.rs
rust/tests/meson.build +7 -3
@@ -1,11 +1,15 @@ test('rust-integration', executable( 'rust-integration', - files('tests/vmstate_tests.rs'), + files( + 'tests/integration.rs', + 'tests/vmstate_tests.rs', + 'tests/qapi.rs', + ), override_options: ['rust_std=2021', 'build.rust_std=2021'], - rust_args: ['--test'], + rust_args: ['--test'] + _qapi_cfg, install: false, - dependencies: [bql_rs, common_rs, util_rs, migration_rs, qom_rs]), + dependencies: [bql_rs, common_rs, util_rs, migration_rs, qom_rs, qapi_rs]), args: [ '--test', '--test-threads', '1', '--format', 'pretty',
rust/tests/tests/integration.rs new file +2 -0
@@ -0,0 +1,2 @@ +mod qapi; +mod vmstate_tests;
rust/tests/tests/qapi.rs new file +35 -0
@@ -0,0 +1,35 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#![allow(unexpected_cfgs)] + +use qapi; +use util::qobject::{from_qobject, to_qobject}; + +#[test] +fn test_qapi () { +let sa = qapi::InetSocketAddress { + host:"host-val" .to_string (), + port:"port-val" .to_string (), + numeric:None , + to:None , + ipv4:None , + ipv6:None , + keep_alive:None , +#[cfg( HAVE_TCP_KEEPCNT )] + keep_alive_count:None , +#[cfg( HAVE_TCP_KEEPIDLE )] + keep_alive_idle:Some (42 ), +#[cfg( HAVE_TCP_KEEPINTVL )] + keep_alive_interval:None , +#[cfg( HAVE_IPPROTO_MPTCP )] + mptcp:None , + }; + +// let qi: QObject = 32.into(); +// dbg!(&qi); + +let qsa =to_qobject (&sa).unwrap (); +let _json = qsa.to_json (); +let sa: qapi::InetSocketAddress =from_qobject (qsa).unwrap (); +dbg! (sa); +}
Signature · 1 line
2.51.0