Skip to contentSkip to conversation

rust: Make common::Wrapper work with non-tuple structs

RFC PATCH New Martin Kletzander 1 participant 3 messages Oct 23, 2025 Rust

lore
Share & tools
lore
#0 lore raw

cover rust: Make common::Wrapper work with non-tuple structs

As part of my "investigation" [0] into safer object initialization using pinned-init, I found out that pinned-init will probably not work with tuple structs for some time [1]. So I figured out how to change QEMU's Wrapper derive macro so that both tuple structs and classic structs (still #[repr(transparent)] and having only one member) are supported.

The second patch is there just to show that it works, I also checked the result with cargo expand to make sure.

This is just to see if the patch makes sense the way it is. I'm still trying to see the best way forward with this pinning effort. Many thanks for Paolo's patience with me. I'm using what I learn to also try and make a proof of concept of something similar to the RustInQEMU effort (although way smaller in scope) in libvirt, so it takes a bit more time.

[0] read: learning QEMU internals and possible Rust usage
[1] https://github.com/Rust-for-Linux/pin-init/issues/85

Martin Kletzander (2):
rust: Make common::Wrapper work with non-tuple structs as well rust/util: Change Timer and TimerListGroup to normal structs

 rust/qemu-macros/src/lib.rs | 49 ++++++++++++++++++++++++++++---------
 rust/util/src/timer.rs      | 10 +++++---
 2 files changed, 44 insertions(+), 15 deletions(-)
Signature · 1 line
2.51.0
#1 lore raw

RFC PATCH 1/2 rust: Make common::Wrapper work with non-tuple structs as well

From: Martin Kletzander <[email protected]>

---
 rust/qemu-macros/src/lib.rs | 49 ++++++++++++++++++++++++++++---------
 1 file changed, 37 insertions(+), 12 deletions(-)
rust/qemu-macros/src/lib.rs +37 -12
index 50239f228be2..074ba2189eec 100644
@@ -10,8 +10,8 @@
     punctuated::Punctuated,
     spanned::Spanned,
     token::Comma,
-    Attribute, Data, DeriveInput, Error, Field, Fields, FieldsUnnamed, Ident, Meta, Path, Token,
-    Variant,
+    Attribute, Data, DeriveInput, Error, Field, Fields, FieldsNamed,
+    FieldsUnnamed, Ident, Index, Member, Meta, Path, Token, Type, Variant,
 };
 
 mod bits;
@@ -42,26 +42,52 @@ fn get_fields<'a>(
     Ok(&fs.named)
 }
 
-fn get_unnamed_field<'a>(input: &'a DeriveInput, msg: &str) -> Result<&'a Field, Error> {
+fn get_wrapped_field<'a>(input: &'a DeriveInput, msg: &str) -> Result<(Member, &'a Type), Error> {
     let Data::Struct(ref s) = &input.data else {
         return Err(Error::new(
             input.ident.span(),
             format!("Struct required for {msg}"),
         ));
     };
-    let Fields::Unnamed(FieldsUnnamed { ref unnamed, .. }) = &s.fields else {
+    if let Fields::Unnamed(FieldsUnnamed { ref unnamed, .. }) = &s.fields {
+        if unnamed.len() != 1 {
+            return Err(Error::new(
+                s.fields.span(),
+                format!("A single field is required for {msg}"),
+            ));
+        }
+        return Ok((Member::Unnamed(Index::from(0)), &unnamed[0].ty));
+    }
+
+    let Fields::Named(FieldsNamed { ref named, .. }) = &s.fields else {
         return Err(Error::new(
             s.fields.span(),
-            format!("Tuple struct required for {msg}"),
+            format!("A tuple struct or a single field named 'inner' is required for {msg}"),
         ));
     };
-    if unnamed.len() != 1 {
+
+    if named.len() != 1 {
         return Err(Error::new(
             s.fields.span(),
             format!("A single field is required for {msg}"),
         ));
     }
-    Ok(&unnamed[0])
+
+    if let Field{ ident: Some(ref ident), .. } = named[0] {
+        if ident != "inner" {
+            return Err(Error::new(
+                ident.span(),
+                format!("The only field must be named 'inner': {msg}"),
+            ));
+        }
+
+        return Ok((Member::Named(ident.clone()), &named[0].ty))
+    }
+
+    Err(Error::new(
+        s.fields.span(),
+        format!("A single field struct is requried for {msg}"),
+    ))
 }
 
 fn is_c_repr(input: &DeriveInput, msg: &str) -> Result<(), Error> {
@@ -129,8 +155,7 @@ fn derive_opaque_or_error(input: DeriveInput) -> Result<proc_macro2::TokenStream
     is_transparent_repr(&input, "#[derive(Wrapper)]")?;
 
     let name = &input.ident;
-    let field = &get_unnamed_field(&input, "#[derive(Wrapper)]")?;
-    let typ = &field.ty;
+    let (member, typ) = &get_wrapped_field(&input, "#[derive(Wrapper)]")?;
 
     Ok(quote! {
         unsafe impl ::common::opaque::Wrapper for #name {
@@ -143,15 +168,15 @@ pub unsafe fn from_raw<'a>(ptr: *mut <Self as ::common::opaque::Wrapper>::Wrappe
             }
 
             pub const fn as_mut_ptr(&self) -> *mut <Self as ::common::opaque::Wrapper>::Wrapped {
-                self.0.as_mut_ptr()
+                self.#member.as_mut_ptr()
             }
 
             pub const fn as_ptr(&self) -> *const <Self as ::common::opaque::Wrapper>::Wrapped {
-                self.0.as_ptr()
+                self.#member.as_ptr()
             }
 
             pub const fn as_void_ptr(&self) -> *mut ::core::ffi::c_void {
-                self.0.as_void_ptr()
+                self.#member.as_void_ptr()
             }
 
             pub const fn raw_get(slot: *mut Self) -> *mut <Self as ::common::opaque::Wrapper>::Wrapped {
Signature · 1 line
2.51.0
#2 lore raw

RFC PATCH 2/2 rust/util: Change Timer and TimerListGroup to normal structs

In reply to Martin Kletzander

From: Martin Kletzander <[email protected]>

This will allow the use of pinned_init crate which does not support tuple structs.

---
 rust/util/src/timer.rs | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
rust/util/src/timer.rs +7 -3
index a99ff5e7ef7a..bc6297214525 100644
@@ -17,14 +17,18 @@
 /// A safe wrapper around [`bindings::QEMUTimer`].
 #[repr(transparent)]
 #[derive(Debug, common::Wrapper)]
-pub struct Timer(Opaque<bindings::QEMUTimer>);
+pub struct Timer {
+    inner: Opaque<bindings::QEMUTimer>,
+}
 
 unsafe impl Send for Timer {}
 unsafe impl Sync for Timer {}
 
 #[repr(transparent)]
 #[derive(common::Wrapper)]
-pub struct TimerListGroup(Opaque<bindings::QEMUTimerListGroup>);
+pub struct TimerListGroup {
+    inner: Opaque<bindings::QEMUTimerListGroup>,
+}
 
 unsafe impl Send for TimerListGroup {}
 unsafe impl Sync for TimerListGroup {}
@@ -42,7 +46,7 @@ impl Timer {
     /// [`modify`](Self::modify).
     pub const unsafe fn new() -> Self {
         // SAFETY: requirements relayed to callers of Timer::new
-        Self(unsafe { Opaque::zeroed() })
+        Self { inner: unsafe { Opaque::zeroed() } }
     }
 
     /// Create a new timer with the given attributes.
Signature · 1 line
2.51.0