From nobody Sun Dec 14 01:59:44 2025 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=pass(p=none dis=none) header.from=linaro.org ARC-Seal: i=1; a=rsa-sha256; t=1752224598; cv=none; d=zohomail.com; s=zohoarc; b=NlIZnamrP89qgX1aP/ER2lbWJFI4KTUj1kntLyi238OuK9iYou49fuBwwNri3Nbz9ZIuoCvHW0FAYsVDc4N87GJmci2Dyw1KlTI5iHQm4zVkWX26oC0e4jfwov7Vm2MVrK9vLvPLjfp+SpSr7+YIfN4Aos/3wIUzShD4rRuFr9o= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1752224598; h=Content-Type:Content-Transfer-Encoding:Cc:Cc:Date:Date:From:From:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:Sender:Subject:Subject:To:To:Message-Id:Reply-To; bh=vhtYSIZwTks+U2FrcpwJn+n273C3qKLVoaZdAk37u2M=; b=Z9fg1AyNG1GzrZyyI/X/ztDIJGo/7KgK8VMHsudZI/nvm4bu86SNPaGzmS0z4c0kvEYjeN49SUL1yU/eM+Hq/gUBZKCHNxOloXYxmLBYeBP5kFL0tCqNMN9pCIzpUZ8r8oMHkG/9BPgICczeUMXBsM5uqW2jDUNOwDeIkMCbljw= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=pass header.from= (p=none dis=none) Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1752224598504894.7803514719769; Fri, 11 Jul 2025 02:03:18 -0700 (PDT) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1ua9Yy-00037n-0o; Fri, 11 Jul 2025 04:57:00 -0400 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1ua9S7-0001M0-6b for qemu-devel@nongnu.org; Fri, 11 Jul 2025 04:49:55 -0400 Received: from mail-wm1-x32a.google.com ([2a00:1450:4864:20::32a]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.90_1) (envelope-from ) id 1ua9Rz-0003NS-CA for qemu-devel@nongnu.org; Fri, 11 Jul 2025 04:49:52 -0400 Received: by mail-wm1-x32a.google.com with SMTP id 5b1f17b1804b1-455e6fb8057so3204785e9.3 for ; Fri, 11 Jul 2025 01:49:43 -0700 (PDT) Received: from [127.0.1.1] (athedsl-4440352.home.otenet.gr. [79.129.177.16]) by smtp.gmail.com with ESMTPSA id 5b1f17b1804b1-454dd537932sm40955625e9.20.2025.07.11.01.49.40 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 11 Jul 2025 01:49:41 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1752223782; x=1752828582; darn=nongnu.org; h=cc:to:message-id:content-transfer-encoding:mime-version:subject :date:from:from:to:cc:subject:date:message-id:reply-to; bh=vhtYSIZwTks+U2FrcpwJn+n273C3qKLVoaZdAk37u2M=; b=w+oB2D3eflyRG8ExXlRxYp9fTZdOiIh3+wN0oak4DV2yNLq4aEeDP2WtlbdQjhtKz5 QG3izTSwQ4/ipkMdH3lCGrc2be0c/DZoyh4f1pr04x85r6QkjyJbUadFvufSbegiXnjF n0nQyUbR7C7DJ6sxO0c8DYu7nCnS9o8qdJCQQkTkaDkccUTqfoSz1LiTjc1E/qZiePu1 qfb0+q9XGsyxmscqDDLn9tMWZx4/9keNaSj7FrvRPaVrvl3E9EyEuyXcU3GfT43e5EJl Joh+K7h20crVtC62H9jXBt8vwfI6FBo1x2Wt2Zxk/31SO8NK0pTEPLZq0qcyaBbUFB51 nEyA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1752223782; x=1752828582; h=cc:to:message-id:content-transfer-encoding:mime-version:subject :date:from:x-gm-message-state:from:to:cc:subject:date:message-id :reply-to; bh=vhtYSIZwTks+U2FrcpwJn+n273C3qKLVoaZdAk37u2M=; b=YbZf+aKMR5S/ZA8MWfRi5OvrdeVzdQTTiBf7BMxBsD2mXZ9H5XvpIobssWQR9gLhZW ip0Lt4dj2DhuVisufJRDRikb+CepRMVkIoeaUDMc5t8lHn4oqVv6BunDKdKvfkSK1Wg/ ocGxeUteDPCmJDPcm92NR8Isn4czILah9eoTPJew2cGnG/oaEpq/QfzJRQ/XUk/K53Gi Dcv8gGzOgtzo2q0dKTwn0AiPTnTXVbkrvOrFSujdQ/v+/ADVAcGFDG2LM/NGGC/PTZEf PRq4rmOwcRMVT1HNx0D6MZB2t3MF1qKbEWxFX6QDyqe8ELKPX9RZBWvvm1gTe3fU+K5A Oiyw== X-Gm-Message-State: AOJu0Yz/m5X0aDf069pv+gwE1lsiVBwI9r7KHlKMVf588RD3+dlQ9tIj S3djUeSEVyMDzHnGBLZ6rPZ5bdqeOD2LNVj0p7X4q7cxPtj2nk2wJ7DGJ4rdSrnw6As= X-Gm-Gg: ASbGncuHV+D9/6ZHrdz1ZvJac8HJfLEKtZ9Dl+OZo5jj+U6SzqxdBCNHDv2AsRhTHRg kWXLpsPaXRJHxdvqnVWuJOquwc517yzZTR/DGVKNGLiT7ZlKK3/iX6HoV6tvT69mjW2yMvQIPx1 lfnmiL8Pled9fJvueTA8D/mArqyrvTESMF+qHUnq/cjo5gvyii8kWfG6iwSJXHaO7uCOB6pXAO+ JIsMP1XHCixwI42QnJcB+c9RPSGt+OwvyTrNdEya3JxyRy+IiGAA2ihX9OxIfdXJGFtyVChPo/G APodPtUH38HvJiZXNKJc52R7apWVldN5nqvAnW5IX9DhWGuTHPktapnEM7GZK6NOASnaMfgapG2 OCAbDcY7oiOBRikvPNjIVVBRdGnFYDxnKYcsnJquz5/A5H0RPUTAfJZJe4ypxg7DpmWI= X-Google-Smtp-Source: AGHT+IGN7brDpnyy9cvqfu+icEwoQ7ujSBQHf9rxmzeECAho5I9ilK9ufMYuJDWcxviehJyFs/OJqQ== X-Received: by 2002:a05:600c:4589:b0:453:92b6:ff84 with SMTP id 5b1f17b1804b1-4556f8bd13dmr15621395e9.3.1752223781714; Fri, 11 Jul 2025 01:49:41 -0700 (PDT) From: Manos Pitsidianakis Date: Fri, 11 Jul 2025 11:49:26 +0300 Subject: [PATCH v3] rust: add qdev Device derive macro MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250711-rust-qdev-properties-v3-1-e198624416fb@linaro.org> X-B4-Tracking: v=1; b=H4sIABXQcGgC/4XRS27DIBAG4KtYrEsFmIftVe9RVRb2jFOkGBLAb qMody9J2qZZRF2wGKT/Y2Y4koTRYSJddSQRV5dc8KWonyoyvlu/Qeqg1EQwoZgSgsYlZboHXOk uhh3GXNLUiAabSVupGyQluos4uc8L+/pW6neXcoiHyysrP9/+A66ccqoG3gyiHAv8Zeu8jeE5x A05i6u4KYbVDxRRFJB2sqPRGlt5p5yujUbcL2XsfO32NnVX3eH94Dw4v0m93W7DR794jyOmZOO hz9H6NC+FoKC5hEEqbqzsyqh/9/gryqtoAXoo61+xn+0YQzFd7ouSE63RgJ1apkCLh853Z5dwo qqGFrVlQ8N+IoNNSMcwzy531WjKN9UACkzLZTtJNNgiAGOTVpLrUcsGUbVlM6cvI/HmrhgCAAA = X-Change-ID: 20250522-rust-qdev-properties-728e8f6a468e To: qemu-devel@nongnu.org Cc: qemu-rust@nongnu.org, =?utf-8?q?Alex_Benn=C3=A9e?= , Paolo Bonzini , Zhao Liu , Manos Pitsidianakis X-Mailer: b4 0.14.2 X-Developer-Signature: v=1; a=openpgp-sha256; l=24788; i=manos.pitsidianakis@linaro.org; h=from:subject:message-id; bh=wnTR/z95vLJb904rqMOXwFTZYuZ2sXw53+iriT2+OXk=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0VCYlFLUy9aQU5Bd0FLQVhjcHgzQi9mZ 25RQWNzbVlnQm9jTkFrc3ZmSDRocjBwOW5JYWdxWm5NcVBld1ZLCm5pc2lYdWJSa29DU0ovT1lU V2lKQWpNRUFBRUtBQjBXSVFUTVhCdE9SS0JXODRkd0hSQjNLY2R3ZjM0SjBBVUMKYUhEUUpBQUt DUkIzS2Nkd2YzNEowREZjRC85WlFrZEFWUkdxTERYTG5yeE9QVTF3YTFYQVlTd3ZqNWo3NW9ZVA puWURUVnA0SVc2dFB4ME1aU1p4cUc3Y0pUb0VBWktuR00ydzh6NEdSMWdGY1BpMnpSVEdRVjVDW FlURE1QQUxvCnJWenFWRVBCNVp6NDFUWHZaTS85b3BHWHRDK252TC9uR0tZQ3JpRjlLeUdqZERG NU94VVQrUUp4QllicmhTa1oKWjVCblZrR1RVZlF3MW51Z0wwL0cxNGdIZ0V2TDczZitPWjl4Z3J WeFY1bVYweUtWV1h3UzF2MFVVWGZLYjhNVQpTTThPUndTR21PMlhHYkVONHNZajlzNzVVVDNYZm 9oZTJ6bkwyVUJwVmc5T1VWRlRBRFk4anplaFdoS0RMMzBzCi9qemoyQnMzR2RaZk9sUDRVRHNJT UlWeUxZME81VFcyL014NVp4eWEyWXpqMm5xSTJwTnlLc1VBM3N5b2lMeVMKOWdSSG85a1prcFVH MFY0cUhEaGxsaDVjNHkrdGxEbDZzMTl5WFM1OEkvejdhZm9aT1owNm53UlVqa2NOVzJkSwovc0d SVTV3YmJEYm83ZVFUaXdYYS9Ud1A2RXpSajB5VnVMSmRiRWlDVHl5b3lkbXdCWlNQdmxOaG5GTn Q1MjB0CjlUZkp2aXJ4MFVCSk1oQStPRWtsQzlJVzQyc3FpYlpUYVR4SENyaUxkVEhOZDR3QldlW mRRcTRCUkplNWFsNVYKc3Z4cGxMVmNiTWF0ZnJXZlFEamRYMlRBZEoxSGpSdFl0SVkrcjRiQmhO UCtNdUJuNVFmRndWN1Y4RWFRK1l5awpRRWpVNERrYUpreHNYZUhHRlR3c0xoSlREY3lySVJLdUR Yd2RYdFFTbUgzL1pHdXdDUTZXalcweE8vc2RhZjZvCmoyTnJyZz09Cj1RaWZnCi0tLS0tRU5EIF BHUCBNRVNTQUdFLS0tLS0K X-Developer-Key: i=manos.pitsidianakis@linaro.org; a=openpgp; fpr=7C721DF9DB3CC7182311C0BF68BC211D47B421E1 Received-SPF: pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Received-SPF: pass client-ip=2a00:1450:4864:20::32a; envelope-from=manos.pitsidianakis@linaro.org; helo=mail-wm1-x32a.google.com X-Spam_score_int: -20 X-Spam_score: -2.1 X-Spam_bar: -- X-Spam_report: (-2.1 / 5.0 requ) BAYES_00=-1.9, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=unavailable autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: qemu-devel-bounces+importer=patchew.org@nongnu.org X-ZohoMail-DKIM: pass (identity @linaro.org) X-ZM-MESSAGEID: 1752224600345116600 Add derive macro for declaring qdev properties directly above the field definitions. To do this, we split DeviceImpl::properties method on a separate trait so we can implement only that part in the derive macro expansion (we cannot partially implement the DeviceImpl trait). Adding a `property` attribute above the field declaration will generate a `qemu_api::bindings::Property` array member in the device's property list. Signed-off-by: Manos Pitsidianakis --- This patch depends on patches that haven't been merged yet to master, so you can checkout this tree if you want to test it: https://gitlab.com/epilys/qemu/-/tree/b4/rust-qdev-properties TODOs: - Update hpet code to use the derive macro Changes in v3: - Change MacroError use to syn::Error, depends on <20250703-rust_macros-v1-1-b99f82febbbf@linaro.org> - Add derive macro unit test, depends on <20250704-rust_add_derive_macro_unit_tests-v1-0-ebd47fa7f78f@linaro.org> - Rename derive macro to just `Device` - Fixed clippy warnings (shadowing of var declarations etc) - Fixed unnecessary quote_spanned uses (thanks Paolo) - Removed unnecessary .as_ref() (Paolo) - Refactor CString conversion for property name (Paolo) - use Derive macro for empty property impls (Paolo) - Remove qdev_prop/bitnr attributes, add them in future work - Expand doc comment of QdevProp trait to explain about extern static refs - Mark DevicePropertiesImpl trait as unsafe - Link to v2: https://lore.kernel.org/qemu-devel/20250703-rust-qdev-propert= ies-v2-1-d4afac766e94@linaro.org Changes in v2: - Rewrite to take advantage of const_refs_to_static feature, we still need to update to a newer MSRV. - Use existing get_fields function (Paolo) - return errors instead of panicking (Paolo) - Link to v1: https://lore.kernel.org/qemu-devel/20250522-rust-qdev-propert= ies-v1-1-5b18b218bad1@linaro.org --- rust/hw/char/pl011/src/device.rs | 11 ++- rust/hw/char/pl011/src/device_class.rs | 26 +----- rust/hw/timer/hpet/src/device.rs | 5 +- rust/qemu-api-macros/src/lib.rs | 151 +++++++++++++++++++++++++++++= +++- rust/qemu-api-macros/src/tests.rs | 111 ++++++++++++++++++++++++ rust/qemu-api/src/qdev.rs | 68 +++++++++++++-- rust/qemu-api/tests/tests.rs | 24 ++---- 7 files changed, 334 insertions(+), 62 deletions(-) diff --git a/rust/hw/char/pl011/src/device.rs b/rust/hw/char/pl011/src/devi= ce.rs index 5b53f2649f161287f40f79075afba47db6d9315c..4338ba80a698bb9150cffb38888= d13ffa861d5d4 100644 --- a/rust/hw/char/pl011/src/device.rs +++ b/rust/hw/char/pl011/src/device.rs @@ -12,7 +12,7 @@ log_mask_ln, memory::{hwaddr, MemoryRegion, MemoryRegionOps, MemoryRegionOpsBuilder= }, prelude::*, - qdev::{Clock, ClockEvent, DeviceImpl, DeviceState, Property, ResetType= , ResettablePhasesImpl}, + qdev::{Clock, ClockEvent, DeviceImpl, DeviceState, ResetType, Resettab= lePhasesImpl}, qom::{ObjectImpl, Owned, ParentField, ParentInit}, static_assert, sysbus::{SysBusDevice, SysBusDeviceImpl}, @@ -101,12 +101,13 @@ pub struct PL011Registers { } =20 #[repr(C)] -#[derive(qemu_api_macros::Object)] +#[derive(qemu_api_macros::Object, qemu_api_macros::Device)] /// PL011 Device Model in QEMU pub struct PL011State { pub parent_obj: ParentField, pub iomem: MemoryRegion, #[doc(alias =3D "chr")] + #[property(rename =3D "chardev")] pub char_backend: CharBackend, pub regs: BqlRefCell, /// QEMU interrupts @@ -125,6 +126,7 @@ pub struct PL011State { #[doc(alias =3D "clk")] pub clock: Owned, #[doc(alias =3D "migrate_clk")] + #[property(rename =3D "migrate-clk", default =3D true)] pub migrate_clock: bool, } =20 @@ -172,9 +174,6 @@ impl ObjectImpl for PL011State { } =20 impl DeviceImpl for PL011State { - fn properties() -> &'static [Property] { - &device_class::PL011_PROPERTIES - } fn vmsd() -> Option<&'static VMStateDescription> { Some(&device_class::VMSTATE_PL011) } @@ -686,7 +685,7 @@ pub fn post_load(&self, _version_id: u32) -> Result<(),= ()> { } =20 #[repr(C)] -#[derive(qemu_api_macros::Object)] +#[derive(qemu_api_macros::Object, qemu_api_macros::Device)] /// PL011 Luminary device model. pub struct PL011Luminary { parent_obj: ParentField, diff --git a/rust/hw/char/pl011/src/device_class.rs b/rust/hw/char/pl011/sr= c/device_class.rs index d328d846323f6080a9573053767e51481eb32941..83d70d7d82aac4a3252a0b4cb24= af705b01d3635 100644 --- a/rust/hw/char/pl011/src/device_class.rs +++ b/rust/hw/char/pl011/src/device_class.rs @@ -8,11 +8,8 @@ }; =20 use qemu_api::{ - bindings::{qdev_prop_bool, qdev_prop_chr}, - prelude::*, - vmstate::VMStateDescription, - vmstate_clock, vmstate_fields, vmstate_of, vmstate_struct, vmstate_sub= sections, vmstate_unused, - zeroable::Zeroable, + prelude::*, vmstate::VMStateDescription, vmstate_clock, vmstate_fields= , vmstate_of, + vmstate_struct, vmstate_subsections, vmstate_unused, zeroable::Zeroabl= e, }; =20 use crate::device::{PL011Registers, PL011State}; @@ -82,22 +79,3 @@ extern "C" fn pl011_post_load(opaque: *mut c_void, versi= on_id: c_int) -> c_int { }, ..Zeroable::ZERO }; - -qemu_api::declare_properties! { - PL011_PROPERTIES, - qemu_api::define_property!( - c"chardev", - PL011State, - char_backend, - unsafe { &qdev_prop_chr }, - CharBackend - ), - qemu_api::define_property!( - c"migrate-clk", - PL011State, - migrate_clock, - unsafe { &qdev_prop_bool }, - bool, - default =3D true - ), -} diff --git a/rust/hw/timer/hpet/src/device.rs b/rust/hw/timer/hpet/src/devi= ce.rs index acf7251029e912f18a5690b0d6cf04ea8151c5e1..cffd20c471f1524f8a41b3a5b8c= 9309f3b59c61c 100644 --- a/rust/hw/timer/hpet/src/device.rs +++ b/rust/hw/timer/hpet/src/device.rs @@ -1031,11 +1031,14 @@ impl ObjectImpl for HPETState { ..Zeroable::ZERO }; =20 -impl DeviceImpl for HPETState { +// SAFETY: HPET_PROPERTIES is a valid Property array constructed with the = qemu_api::declare_properties macro. +unsafe impl qemu_api::qdev::DevicePropertiesImpl for HPETState { fn properties() -> &'static [Property] { &HPET_PROPERTIES } +} =20 +impl DeviceImpl for HPETState { fn vmsd() -> Option<&'static VMStateDescription> { Some(&VMSTATE_HPET) } diff --git a/rust/qemu-api-macros/src/lib.rs b/rust/qemu-api-macros/src/lib= .rs index b525d89c09e496a1f7f5582dc6d994e318f62bca..c95c0b612129f1460bb532d17f6= acb40d31bcd5d 100644 --- a/rust/qemu-api-macros/src/lib.rs +++ b/rust/qemu-api-macros/src/lib.rs @@ -3,10 +3,11 @@ // SPDX-License-Identifier: GPL-2.0-or-later =20 use proc_macro::TokenStream; -use quote::quote; +use quote::{quote, quote_spanned, ToTokens}; use syn::{ - parse_macro_input, parse_quote, punctuated::Punctuated, spanned::Spann= ed, token::Comma, Data, - DeriveInput, Error, Field, Fields, FieldsUnnamed, Ident, Meta, Path, T= oken, Variant, + parse::Parse, parse_macro_input, parse_quote, punctuated::Punctuated, = spanned::Spanned, + token::Comma, Data, DeriveInput, Error, Field, Fields, FieldsUnnamed, = Ident, Meta, Path, Token, + Variant, }; mod bits; use bits::BitsConstInternal; @@ -146,6 +147,150 @@ pub const fn raw_get(slot: *mut Self) -> *mut ::Wr }) } =20 +#[derive(Debug)] +enum DevicePropertyName { + CStr(syn::LitCStr), + Str(syn::LitStr), +} + +#[derive(Debug)] +struct DeviceProperty { + rename: Option, + defval: Option, +} + +impl Parse for DeviceProperty { + fn parse(input: syn::parse::ParseStream) -> syn::Result { + let _: syn::Token![#] =3D input.parse()?; + let bracketed; + _ =3D syn::bracketed!(bracketed in input); + let attribute =3D bracketed.parse::()?; + debug_assert_eq!(&attribute.to_string(), "property"); + let mut retval =3D Self { + rename: None, + defval: None, + }; + let content; + _ =3D syn::parenthesized!(content in bracketed); + while !content.is_empty() { + let value: syn::Ident =3D content.parse()?; + if value =3D=3D "rename" { + let _: syn::Token![=3D] =3D content.parse()?; + if retval.rename.is_some() { + return Err(syn::Error::new( + value.span(), + "`rename` can only be used at most once", + )); + } + if content.peek(syn::LitStr) { + retval.rename =3D Some(DevicePropertyName::Str(content= .parse::()?)); + } else { + retval.rename =3D + Some(DevicePropertyName::CStr(content.parse::()?)); + } + } else if value =3D=3D "default" { + let _: syn::Token![=3D] =3D content.parse()?; + if retval.defval.is_some() { + return Err(syn::Error::new( + value.span(), + "`default` can only be used at most once", + )); + } + retval.defval =3D Some(content.parse()?); + } else { + return Err(syn::Error::new( + value.span(), + format!("unrecognized field `{value}`"), + )); + } + + if !content.is_empty() { + let _: syn::Token![,] =3D content.parse()?; + } + } + Ok(retval) + } +} + +#[proc_macro_derive(Device, attributes(property))] +pub fn derive_device(input: TokenStream) -> TokenStream { + let input =3D parse_macro_input!(input as DeriveInput); + + derive_device_or_error(input) + .unwrap_or_else(syn::Error::into_compile_error) + .into() +} + +fn derive_device_or_error(input: DeriveInput) -> Result { + is_c_repr(&input, "#[derive(Device)]")?; + let properties: Vec<(syn::Field, DeviceProperty)> =3D get_fields(&inpu= t, "#[derive(Device)]")? + .iter() + .flat_map(|f| { + f.attrs + .iter() + .filter(|a| a.path().is_ident("property")) + .map(|a| Ok((f.clone(), syn::parse2(a.to_token_stream())?)= )) + }) + .collect::, Error>>()?; + let name =3D &input.ident; + let mut properties_expanded =3D vec![]; + + for (field, prop) in properties { + let DeviceProperty { rename, defval } =3D prop; + let field_name =3D field.ident.unwrap(); + macro_rules! str_to_c_str { + ($value:expr, $span:expr) =3D> {{ + let (value, span) =3D ($value, $span); + let cstr =3D std::ffi::CString::new(value.as_str()) + .map_err(|err| { + Error::new( + span, + format!("Property name `{value}` cannot be rep= resented as a C string: {err}"), + ) + })?; + let cstr_lit =3D syn::LitCStr::new(&cstr, span); + Ok(quote! { #cstr_lit }) + }}; + } + + let prop_name =3D rename.map_or_else( + || str_to_c_str!(field_name.to_string(), field_name.span()), + |rename| -> Result { + match rename { + DevicePropertyName::CStr(cstr_lit) =3D> Ok(quote! { #c= str_lit }), + DevicePropertyName::Str(str_lit) =3D> { + str_to_c_str!(str_lit.value(), str_lit.span()) + } + } + }, + )?; + let field_ty =3D field.ty.clone(); + let qdev_prop =3D quote! { <#field_ty as ::qemu_api::qdev::QDevPro= p>::VALUE }; + let set_default =3D defval.is_some(); + let defval =3D defval.unwrap_or(syn::Expr::Verbatim(quote! { 0 })); + properties_expanded.push(quote! { + ::qemu_api::bindings::Property { + name: ::std::ffi::CStr::as_ptr(#prop_name), + info: #qdev_prop , + offset: ::core::mem::offset_of!(#name, #field_name) as isi= ze, + set_default: #set_default, + defval: ::qemu_api::bindings::Property__bindgen_ty_1 { u: = #defval as u64 }, + ..::qemu_api::zeroable::Zeroable::ZERO + } + }); + } + + Ok(quote_spanned! {input.span() =3D> + unsafe impl ::qemu_api::qdev::DevicePropertiesImpl for #name { + fn properties() -> &'static [::qemu_api::bindings::Property] { + static PROPERTIES: &[::qemu_api::bindings::Property] =3D &= [#(#properties_expanded),*]; + + PROPERTIES + } + } + }) +} + #[proc_macro_derive(Wrapper)] pub fn derive_opaque(input: TokenStream) -> TokenStream { let input =3D parse_macro_input!(input as DeriveInput); diff --git a/rust/qemu-api-macros/src/tests.rs b/rust/qemu-api-macros/src/t= ests.rs index b75b6fbb98956583826eca51aee7b48bb06aab21..5bcabe6823e22985129a82e89a5= 4533e6ace6778 100644 --- a/rust/qemu-api-macros/src/tests.rs +++ b/rust/qemu-api-macros/src/tests.rs @@ -32,6 +32,117 @@ macro_rules! derive_compile { } =20 #[test] +fn test_derive_device() { + // Check that repr(C) is used + derive_compile_fail!( + derive_device_or_error, + quote! { + #[derive(Device)] + struct Foo { + _unused: [u8; 0], + } + }, + "#[repr(C)] required for #[derive(Device)]" + ); + // Check that invalid/misspelled attributes raise an error + derive_compile_fail!( + derive_device_or_error, + quote! { + #[repr(C)] + #[derive(Device)] + struct DummyState { + #[property(defalt =3D true)] + migrate_clock: bool, + } + }, + "unrecognized field `defalt`" + ); + // Check that repeated attributes are not allowed: + derive_compile_fail!( + derive_device_or_error, + quote! { + #[repr(C)] + #[derive(Device)] + struct DummyState { + #[property(rename =3D "migrate-clk", rename =3D "migrate-c= lk", default =3D true)] + migrate_clock: bool, + } + }, + "`rename` can only be used at most once" + ); + derive_compile_fail!( + derive_device_or_error, + quote! { + #[repr(C)] + #[derive(Device)] + struct DummyState { + #[property(default =3D true, default =3D true)] + migrate_clock: bool, + } + }, + "`default` can only be used at most once" + ); + // Check that the field name is preserved when `rename` isn't used: + derive_compile!( + derive_device_or_error, + quote! { + #[repr(C)] + #[derive(Device)] + pub struct DummyState { + parent: ParentField, + #[property(default =3D true)] + migrate_clock: bool, + } + }, + quote! { + unsafe impl ::qemu_api::qdev::DevicePropertiesImpl for DummySt= ate { + fn properties() -> &'static [::qemu_api::bindings::Propert= y] { + static PROPERTIES: &[::qemu_api::bindings::Property] = =3D + &[::qemu_api::bindings::Property { + name: ::std::ffi::CStr::as_ptr(c"migrate_clock= "), + info: ::VA= LUE, + offset: ::core::mem::offset_of!(DummyState, mi= grate_clock) as isize, + set_default: true, + defval: ::qemu_api::bindings::Property__bindge= n_ty_1 { u: true as u64 }, + ..::qemu_api::zeroable::Zeroable::ZERO + }]; + PROPERTIES + } + } + } + ); + // Check that `rename` value is used for the property name when used: + derive_compile!( + derive_device_or_error, + quote! { + #[repr(C)] + #[derive(Device)] + pub struct DummyState { + parent: ParentField, + #[property(rename =3D "migrate-clk", default =3D true)] + migrate_clock: bool, + } + }, + quote! { + unsafe impl ::qemu_api::qdev::DevicePropertiesImpl for DummySt= ate { + fn properties() -> &'static [::qemu_api::bindings::Propert= y] { + static PROPERTIES: &[::qemu_api::bindings::Property] = =3D + &[::qemu_api::bindings::Property { + name: ::std::ffi::CStr::as_ptr(c"migrate-clk"), + info: ::VA= LUE, + offset: ::core::mem::offset_of!(DummyState, mi= grate_clock) as isize, + set_default: true, + defval: ::qemu_api::bindings::Property__bindge= n_ty_1 { u: true as u64 }, + ..::qemu_api::zeroable::Zeroable::ZERO + }]; + PROPERTIES + } + } + } + ); +} + +#[test] fn test_derive_object() { derive_compile_fail!( derive_object_or_error, diff --git a/rust/qemu-api/src/qdev.rs b/rust/qemu-api/src/qdev.rs index 36f02fb57dbffafb21a2e7cc96419ca42e865269..f1dcb14f6ea76e9457e0a5b18f9= 2df7f18c54436 100644 --- a/rust/qemu-api/src/qdev.rs +++ b/rust/qemu-api/src/qdev.rs @@ -101,8 +101,65 @@ pub trait ResettablePhasesImpl { T::EXIT.unwrap()(unsafe { state.as_ref() }, typ); } =20 +/// Helper trait to return pointer to a [`bindings::PropertyInfo`] for a t= ype. +/// +/// This trait is used by [`qemu_api_macros::Device`] derive macro. +/// +/// Base types that already have `qdev_prop_*` globals in the QEMU API sho= uld use those values as +/// exported by the [`bindings`] module, instead of redefining them. +/// +/// # Safety +/// +/// This trait is marked as `unsafe` because currently having a `const` re= fer to an `extern static` +/// as a reference instead of a raw pointer results in this compiler error: +/// +/// ```text +/// constructing invalid value: encountered reference to `extern` static i= n `const` +/// ``` +/// +/// This is because the compiler generally might dereference a normal refe= rence during const +/// evaluation, but not in this case (if it did, it'd need to dereference = the raw pointer so this +/// would fail to compile). +/// +/// It is the implementer's responsibility to provide a valid [`bindings::= PropertyInfo`] pointer +/// for the trait implementation to be safe. +pub unsafe trait QDevProp { + const VALUE: *const bindings::PropertyInfo; +} + +/// Use [`bindings::qdev_prop_bool`] for `bool`. +unsafe impl QDevProp for bool { + const VALUE: *const bindings::PropertyInfo =3D unsafe { &bindings::qde= v_prop_bool }; +} + +/// Use [`bindings::qdev_prop_uint64`] for `u64`. +unsafe impl QDevProp for u64 { + const VALUE: *const bindings::PropertyInfo =3D unsafe { &bindings::qde= v_prop_uint64 }; +} + +/// Use [`bindings::qdev_prop_chr`] for [`crate::chardev::CharBackend`]. +unsafe impl QDevProp for crate::chardev::CharBackend { + const VALUE: *const bindings::PropertyInfo =3D unsafe { &bindings::qde= v_prop_chr }; +} + +/// Trait to define device properties. +/// +/// # Safety +/// +/// Caller is responsible for the validity of properties array. +pub unsafe trait DevicePropertiesImpl { + /// An array providing the properties that the user can set on the + /// device. Not a `const` because referencing statics in constants + /// is unstable until Rust 1.83.0. + fn properties() -> &'static [Property] { + &[] + } +} + /// Trait providing the contents of [`DeviceClass`]. -pub trait DeviceImpl: ObjectImpl + ResettablePhasesImpl + IsA= { +pub trait DeviceImpl: + ObjectImpl + ResettablePhasesImpl + DevicePropertiesImpl + IsA +{ /// _Realization_ is the second stage of device creation. It contains /// all operations that depend on device properties and can fail (note: /// this is not yet supported for Rust devices). @@ -111,13 +168,6 @@ pub trait DeviceImpl: ObjectImpl + ResettablePhasesImp= l + IsA { /// with the function pointed to by `REALIZE`. const REALIZE: Option Result<()>> =3D None; =20 - /// An array providing the properties that the user can set on the - /// device. Not a `const` because referencing statics in constants - /// is unstable until Rust 1.83.0. - fn properties() -> &'static [Property] { - &[] - } - /// A `VMStateDescription` providing the migration format for the devi= ce /// Not a `const` because referencing statics in constants is unstable /// until Rust 1.83.0. @@ -175,7 +225,7 @@ pub fn class_init(&mut self) { if let Some(vmsd) =3D ::vmsd() { self.vmsd =3D vmsd; } - let prop =3D ::properties(); + let prop =3D ::properties(); if !prop.is_empty() { unsafe { bindings::device_class_set_props_n(self, prop.as_ptr(), pr= op.len()); diff --git a/rust/qemu-api/tests/tests.rs b/rust/qemu-api/tests/tests.rs index a658a49fcfdda8fa4b9d139c10afb6ff3243790b..aff3eecd654e14952884d96cc79= 3548df4e390b0 100644 --- a/rust/qemu-api/tests/tests.rs +++ b/rust/qemu-api/tests/tests.rs @@ -5,11 +5,10 @@ use std::{ffi::CStr, ptr::addr_of}; =20 use qemu_api::{ - bindings::{module_call_init, module_init_type, qdev_prop_bool}, + bindings::{module_call_init, module_init_type}, cell::{self, BqlCell}, - declare_properties, define_property, prelude::*, - qdev::{DeviceImpl, DeviceState, Property, ResettablePhasesImpl}, + qdev::{DeviceImpl, DeviceState, ResettablePhasesImpl}, qom::{ObjectImpl, ParentField}, sysbus::SysBusDevice, vmstate::VMStateDescription, @@ -26,9 +25,10 @@ }; =20 #[repr(C)] -#[derive(qemu_api_macros::Object)] +#[derive(qemu_api_macros::Object, qemu_api_macros::Device)] pub struct DummyState { parent: ParentField, + #[property(rename =3D "migrate-clk", default =3D true)] migrate_clock: bool, } =20 @@ -44,17 +44,6 @@ pub fn class_init(self: &mut DummyClass) { } } =20 -declare_properties! { - DUMMY_PROPERTIES, - define_property!( - c"migrate-clk", - DummyState, - migrate_clock, - unsafe { &qdev_prop_bool }, - bool - ), -} - unsafe impl ObjectType for DummyState { type Class =3D DummyClass; const TYPE_NAME: &'static CStr =3D c"dummy"; @@ -69,16 +58,13 @@ impl ObjectImpl for DummyState { impl ResettablePhasesImpl for DummyState {} =20 impl DeviceImpl for DummyState { - fn properties() -> &'static [Property] { - &DUMMY_PROPERTIES - } fn vmsd() -> Option<&'static VMStateDescription> { Some(&VMSTATE) } } =20 #[repr(C)] -#[derive(qemu_api_macros::Object)] +#[derive(qemu_api_macros::Object, qemu_api_macros::Device)] pub struct DummyChildState { parent: ParentField, } --- base-commit: c77283dd5d79149f4e7e9edd00f65416c648ee59 change-id: 20250522-rust-qdev-properties-728e8f6a468e prerequisite-change-id: 20250703-rust_bindings_allow_unnecessary_transmutes= -d614db4517a4:v1 prerequisite-patch-id: 570fede8eee168ade58c7c7599bdc8b94c8c1a22 prerequisite-change-id: 20250704-rust_add_derive_macro_unit_tests-3e7daf905= d62:v1 prerequisite-patch-id: 08d7aa46ded5f33efaf4e9d450f1080854cb6b2d prerequisite-patch-id: 48db905333ffc7c9725cf72d646cc265a9d9ef36 prerequisite-change-id: 20250703-rust_macros-53d9e6a0b802:v1 prerequisite-patch-id: 985f50552aa858d14dcbc709d87e65d21538747d -- =CE=B3=CE=B1=E1=BF=96=CE=B1 =CF=80=CF=85=CF=81=CE=AF =CE=BC=CE=B9=CF=87=CE= =B8=CE=AE=CF=84=CF=89