From patchwork Thu Dec 19 12:12:07 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Paolo Bonzini X-Patchwork-Id: 13915275 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 6B1DCE77184 for ; Thu, 19 Dec 2024 16:41:34 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tOJFR-0001mV-7b; Thu, 19 Dec 2024 11:19:37 -0500 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 1tOFOI-00065h-OS for qemu-devel@nongnu.org; Thu, 19 Dec 2024 07:12:30 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.133.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tOFOG-00087N-Uk for qemu-devel@nongnu.org; Thu, 19 Dec 2024 07:12:30 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1734610348; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=0vGbxeyUby2e1YBpFsrxSiWFR5XYA6Df2008LzEqLo4=; b=fCESzMEqCcFHLHvGeAHwxvY0l+2jjuXHM4EWYqdPxngMANvpCrFwLE1ZDP98ruL5MpUmRG 2xADaeCJSxcif/z+L2Oc3zYBj/jFnOu74RkUnyt5L1pIIvwlMRS6zPq50ibaX6meziO3Oq uQ3/Qnh8wJ3VxTVVrveHDH8fTg3Or2U= Received: from mail-wm1-f72.google.com (mail-wm1-f72.google.com [209.85.128.72]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-78-mH16JKLzO-6V2X5QTeH-ew-1; Thu, 19 Dec 2024 07:12:23 -0500 X-MC-Unique: mH16JKLzO-6V2X5QTeH-ew-1 X-Mimecast-MFC-AGG-ID: mH16JKLzO-6V2X5QTeH-ew Received: by mail-wm1-f72.google.com with SMTP id 5b1f17b1804b1-43623bf2a83so6107775e9.0 for ; Thu, 19 Dec 2024 04:12:23 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1734610340; x=1735215140; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=0vGbxeyUby2e1YBpFsrxSiWFR5XYA6Df2008LzEqLo4=; b=LO2oWHIZC0zvpOpb8W0gwjhgZLkQkTV3rKv6d4f8aD56yePd15KGy9uv6HwRnthcNa nFWW/rRhUJoLQo2p+YKYUVXQJPcD5SLaisDkkuJ6a/kRBsnGfnF2rydL+Kg/oGk4Y/mw v0FwpDwmq5tXUqJ5PrR7asVQhWKBsUdSEf8iUvwo2NfNkxuKsLVWrHvuw83pBFvISF73 Lt6G1N0/irQP1qQncZ6AYwoXsreZekKoLUW2RVwV1n+Kw2Uau7StAFTPtAFm+kSpo/Z9 vWvxyiXKDhYdZziJ3iVfQtPiiu+12rDaory9RWxQHcfsOfluz1aX3I7iH59T8WzplpeY R9eQ== X-Gm-Message-State: AOJu0YzJ2dHqYyCyvQe7jMMsw9wQ0rTKEY7Pf7CKcBXqkkMF8gWCkIAQ k+oZ72nDVwQ81A5cl+xf2xiLA7+OL5v5kDlvBtSrirm/LpGK0/jbTM1MtJox1YuOUMai54vl5uI kguk58fxqXojVWZJJ7p8KsIJ0Tua8KDMxKzA8Am3bmAfSpdARaRHeiUvG+mzQpdfTrP1xWz24+K 5zGpcbRTHV5SShlygjRyScX1kEv96LS3iP5rzi X-Gm-Gg: ASbGncu+OW3JlWkhc+t0nbhPhzE/ra0RcbKu9Z9TFBtN0+C/3w2sJGD6lsECo8Niofk 4S81/zArAmKMxKXjjNrO91J5fVBwO/HSIDb593kctUfpIm3nZq1K6b9OJwCmmUg/g0JA9o/RPP4 oOGR5TZQaMZcmr/dY3CF5FV0QdSwAyIAvHWNDKs17FsIyY/ult/jmE8gQFhEKKZvk35RctWNu59 Z6hIu58ibuEDvVon0eWbYcUtgfcfA4aic0Wdnu9gP3984atxW6t4b0KcoOO X-Received: by 2002:a5d:64a7:0:b0:385:f560:7924 with SMTP id ffacd0b85a97d-388e4d30f16mr5206554f8f.4.1734610340519; Thu, 19 Dec 2024 04:12:20 -0800 (PST) X-Google-Smtp-Source: AGHT+IEGLDLy1I/JHySafW0VHoWat3oVlESM2h61+AfUoumbqC+QQB+VnBHfnXAlca1gz+Z/1uGPsg== X-Received: by 2002:a5d:64a7:0:b0:385:f560:7924 with SMTP id ffacd0b85a97d-388e4d30f16mr5206518f8f.4.1734610339983; Thu, 19 Dec 2024 04:12:19 -0800 (PST) Received: from [192.168.10.47] ([151.81.118.45]) by smtp.gmail.com with ESMTPSA id 5b1f17b1804b1-4366121955fsm16756355e9.21.2024.12.19.04.12.18 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 19 Dec 2024 04:12:18 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: zhao1.liu@intel.com Subject: [PATCH 01/10] rust: qom: add ParentField Date: Thu, 19 Dec 2024 13:12:07 +0100 Message-ID: <20241219121216.416905-2-pbonzini@redhat.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241219121216.416905-1-pbonzini@redhat.com> References: <20241219121216.416905-1-pbonzini@redhat.com> MIME-Version: 1.0 Received-SPF: pass client-ip=170.10.133.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -31 X-Spam_score: -3.2 X-Spam_bar: --- X-Spam_report: (-3.2 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.001, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H2=-1.116, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=ham 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+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Add a type that, together with the C function object_deinit, ensures the correct drop order for QOM objects relative to their superclasses. Right now it is not possible to implement the Drop trait for QOM classes that are defined in Rust, as the drop() function would not be called when the object goes away; instead what is called is ObjectImpl::INSTANCE_FINALIZE. It would be nice for INSTANCE_FINALIZE to just drop the object, but this has a problem: suppose you have pub struct MySuperclass { parent: DeviceState, field: Box, ... } impl Drop for MySuperclass { ... } pub struct MySubclass { parent: MySuperclass, ... } and an instance_finalize implementation that is like unsafe extern "C" fn drop_object(obj: *mut Object) { unsafe { std::ptr::drop_in_place(obj.cast::()) } } When instance_finalize is called for MySubclass, it will walk the struct's list of fields and call the drop method for MySuperclass. Then, object_deinit recurses to the superclass and calls the same drop method again. This will cause double-freeing of the Box. What's happening here is that QOM wants to control the drop order of MySuperclass and MySubclass's fields. To do so, the parent field must be marked ManuallyDrop<>, which is quite ugly. Instead, add a wrapper type ParentField<> that is specific to QOM. This hides the implementation detail of *what* is special about the ParentField, and will also be easy to check in the #[derive(Object)] macro. Signed-off-by: Paolo Bonzini --- rust/hw/char/pl011/src/device.rs | 6 ++-- rust/qemu-api/src/qom.rs | 56 +++++++++++++++++++++++++++++--- rust/qemu-api/tests/tests.rs | 4 +-- 3 files changed, 57 insertions(+), 9 deletions(-) diff --git a/rust/hw/char/pl011/src/device.rs b/rust/hw/char/pl011/src/device.rs index 18cc122951d..689202f4550 100644 --- a/rust/hw/char/pl011/src/device.rs +++ b/rust/hw/char/pl011/src/device.rs @@ -14,7 +14,7 @@ irq::InterruptSource, prelude::*, qdev::DeviceImpl, - qom::ObjectImpl, + qom::{ObjectImpl, ParentField}, }; use crate::{ @@ -86,7 +86,7 @@ fn index(&self, idx: u32) -> &Self::Output { #[derive(Debug, qemu_api_macros::Object, qemu_api_macros::offsets)] /// PL011 Device Model in QEMU pub struct PL011State { - pub parent_obj: SysBusDevice, + pub parent_obj: ParentField, pub iomem: MemoryRegion, #[doc(alias = "fr")] pub flags: registers::Flags, @@ -645,7 +645,7 @@ pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> { #[derive(Debug, qemu_api_macros::Object)] /// PL011 Luminary device model. pub struct PL011Luminary { - parent_obj: PL011State, + parent_obj: ParentField, } impl PL011Luminary { diff --git a/rust/qemu-api/src/qom.rs b/rust/qemu-api/src/qom.rs index 7d5fbef1e17..1341a173893 100644 --- a/rust/qemu-api/src/qom.rs +++ b/rust/qemu-api/src/qom.rs @@ -55,6 +55,7 @@ use std::{ ffi::CStr, + fmt, ops::{Deref, DerefMut}, os::raw::c_void, }; @@ -105,6 +106,52 @@ fn as_ref(&self) -> &$parent { }; } +/// This is the same as [`ManuallyDrop`](std::mem::ManuallyDrop), though +/// it hides the standard methods of `ManuallyDrop`. +/// +/// The first field of an `ObjectType` must be of type `ParentField`. +/// (Technically, this is only necessary if there is at least one Rust +/// superclass in the hierarchy). This is to ensure that the parent field is +/// dropped after the subclass; this drop order is enforced by the C +/// `object_deinit` function. +/// +/// # Examples +/// +/// ```ignore +/// #[repr(C)] +/// #[derive(qemu_api_macros::Object)] +/// pub struct MyDevice { +/// parent: ParentField, +/// ... +/// } +/// ``` +#[derive(Debug)] +#[repr(transparent)] +pub struct ParentField(std::mem::ManuallyDrop); + +impl Deref for ParentField { + type Target = T; + + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for ParentField { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl fmt::Display for ParentField { + #[inline(always)] + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + self.0.fmt(f) + } +} + unsafe extern "C" fn rust_instance_init(obj: *mut Object) { // SAFETY: obj is an instance of T, since rust_instance_init // is called from QOM core as the instance_init function @@ -151,8 +198,9 @@ fn as_ref(&self) -> &$parent { /// /// - the struct must be `#[repr(C)]`; /// -/// - the first field of the struct must be of the instance struct corresponding -/// to the superclass, which is `ObjectImpl::ParentType` +/// - the first field of the struct must be of type +/// [`ParentField`](ParentField), where `T` is the parent type +/// [`ObjectImpl::ParentType`] /// /// - likewise, the first field of the `Class` must be of the class struct /// corresponding to the superclass, which is `ObjectImpl::ParentType::Class`. @@ -384,8 +432,8 @@ impl ObjectCastMut for &mut T {} /// Trait a type must implement to be registered with QEMU. pub trait ObjectImpl: ObjectType + ClassInitImpl { - /// The parent of the type. This should match the first field of - /// the struct that implements `ObjectImpl`: + /// The parent of the type. This should match the first field of the + /// struct that implements `ObjectImpl`, minus the `ParentField<_>` wrapper. type ParentType: ObjectType; /// Whether the object can be instantiated diff --git a/rust/qemu-api/tests/tests.rs b/rust/qemu-api/tests/tests.rs index 41ea4026b83..3b3cf793ae3 100644 --- a/rust/qemu-api/tests/tests.rs +++ b/rust/qemu-api/tests/tests.rs @@ -15,7 +15,7 @@ c_str, declare_properties, define_property, prelude::*, qdev::{DeviceImpl, DeviceState, Property}, - qom::ObjectImpl, + qom::{ObjectImpl, ParentField}, vmstate::VMStateDescription, zeroable::Zeroable, }; @@ -31,7 +31,7 @@ #[repr(C)] #[derive(qemu_api_macros::Object)] pub struct DummyState { - parent: DeviceState, + parent: ParentField, migrate_clock: bool, } From patchwork Thu Dec 19 12:12:08 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Paolo Bonzini X-Patchwork-Id: 13915236 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id D99CBE77184 for ; Thu, 19 Dec 2024 16:26:55 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tOJIc-00010M-NN; Thu, 19 Dec 2024 11:22:55 -0500 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 1tOFOG-00065E-A6 for qemu-devel@nongnu.org; Thu, 19 Dec 2024 07:12:28 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.129.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tOFOE-000868-Ha for qemu-devel@nongnu.org; Thu, 19 Dec 2024 07:12:28 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1734610345; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=a1QIUW+QMqWVmHcaXDZQKBZwBUp/d4OJo6fmKpU6JGs=; b=OSJyNE7IL+LJbN9x8/1A7BccOFFsF5XvcsHzsx+XTDqtbUDObb6YBA0EWj7QDFhJM+J/yc RnFLRrkaOlAGjWNm+xvAVpnZGnLk55GDq8E7URXw7lj5atNOXbCAQfgrfbbJhBqeBiexZf nc4/C9WyU8U3uNqj9vh3Tw7XmjJl5rY= Received: from mail-wm1-f70.google.com (mail-wm1-f70.google.com [209.85.128.70]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-637-J4jy_740NEexWbWrfoxVzw-1; Thu, 19 Dec 2024 07:12:24 -0500 X-MC-Unique: J4jy_740NEexWbWrfoxVzw-1 X-Mimecast-MFC-AGG-ID: J4jy_740NEexWbWrfoxVzw Received: by mail-wm1-f70.google.com with SMTP id 5b1f17b1804b1-4361ac8b25fso4268415e9.2 for ; Thu, 19 Dec 2024 04:12:24 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1734610342; x=1735215142; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=a1QIUW+QMqWVmHcaXDZQKBZwBUp/d4OJo6fmKpU6JGs=; b=YCl/gqO85c4lZ8dvBlGIqetk5wpOm18wAi1qwB5CkZjA/q6DTJYdQU5HCkGB5VuKnF DkMAf/oiS9pwmfdhzu9AdhSYE/lcEsIDwuQoYbstWaUjqmkMYk7Rf9ulLFnrWXf1K3qw 3ETiCoVFvPtqdvCOnKqQmKRkvkArfGHZrMNlAMXawgrBPmY3V0qhsSMvQ+1RbVMm3v3y mR+hmyGGeHkBPH6KzHOmx8nqdowt1Rv1dB6fadVBGNi2x0tCOgjCEeNXHtiadP/Gz7Md cETTDJzv1N0WJWoMe+eCPmpYLc8qCakjG43ek5A7QQdUku08MPklhXpSdx5eqQccrI0T yYaA== X-Gm-Message-State: AOJu0YyoRMVBEkX3kYvFbrHwQ43Z9D8MnzgQiJxGN+fcHpcBoMJ34w5v XUook+XQW+xMOuFjzDQXmOzkjph+D64DEvp4RRoqTHjJWdR3gw6uwE/aNmL+5s8h57FVQS8Ixa6 v1FlV7u0lVEj6p+dmh8jB4opup81cweaRur2I5kXM+Xiz3B7xRFC1QRo5ctV6HRK6srKz6z+5ri yilBRVmoR2/ZvQW51SaFA4KnrOZIRt5PBQculH X-Gm-Gg: ASbGnctUTkLyrDP/JbiJG6U+qB4xcSjaiY4KkJJaDRIS6c8PdfBhfGigbSTLN8TdR/a nOUKh9WcjbI8S3OZywFndzQdvzofcZV59iEov3Uk1cp1DWP0phxzAblpRhc8t6xyqS+i71s+0/G Ui+2kYbZxoV6oPk3hNBr6ruZEXHcJjlK8Nf6AEunck5NgzOG01oMqAXSheyuhWprWDKXOIxCvhX /qRUqIFe3ttwgnKfIgUJGSqPb9Xn+9hVzH/LrhF26k4nU6JAo/0uMl9A/tg X-Received: by 2002:a05:600c:4587:b0:434:fbd5:2f0a with SMTP id 5b1f17b1804b1-4365535bb16mr63670305e9.9.1734610341690; Thu, 19 Dec 2024 04:12:21 -0800 (PST) X-Google-Smtp-Source: AGHT+IGlxnMhNVSuRZhbDqNK8VxR6LB6C2XxexG7+EKTiKcgRwBoOLjTHxckGDlqMNqTcOUasS08AA== X-Received: by 2002:a05:600c:4587:b0:434:fbd5:2f0a with SMTP id 5b1f17b1804b1-4365535bb16mr63669945e9.9.1734610341177; Thu, 19 Dec 2024 04:12:21 -0800 (PST) Received: from [192.168.10.47] ([151.81.118.45]) by smtp.gmail.com with ESMTPSA id ffacd0b85a97d-38a1c8a6e19sm1410520f8f.100.2024.12.19.04.12.20 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 19 Dec 2024 04:12:20 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: zhao1.liu@intel.com Subject: [PATCH 02/10] rust: add a utility module for compile-time type checks Date: Thu, 19 Dec 2024 13:12:08 +0100 Message-ID: <20241219121216.416905-3-pbonzini@redhat.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241219121216.416905-1-pbonzini@redhat.com> References: <20241219121216.416905-1-pbonzini@redhat.com> MIME-Version: 1.0 Received-SPF: pass client-ip=170.10.129.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -31 X-Spam_score: -3.2 X-Spam_bar: --- X-Spam_report: (-3.2 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.001, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H2=-1.116, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=ham 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+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org It is relatively common in the low-level qemu_api code to assert that a field of a struct has a specific type; for example, it can be used to ensure that the fields match what the qemu_api and C code expects for safety. Signed-off-by: Paolo Bonzini --- rust/qemu-api/meson.build | 1 + rust/qemu-api/src/assertions.rs | 90 +++++++++++++++++++++++++++++++++ rust/qemu-api/src/lib.rs | 1 + 3 files changed, 92 insertions(+) create mode 100644 rust/qemu-api/src/assertions.rs diff --git a/rust/qemu-api/meson.build b/rust/qemu-api/meson.build index 8c82c5e96c2..321c025354c 100644 --- a/rust/qemu-api/meson.build +++ b/rust/qemu-api/meson.build @@ -15,6 +15,7 @@ _qemu_api_rs = static_library( structured_sources( [ 'src/lib.rs', + 'src/assertions.rs', 'src/bindings.rs', 'src/bitops.rs', 'src/callbacks.rs', diff --git a/rust/qemu-api/src/assertions.rs b/rust/qemu-api/src/assertions.rs new file mode 100644 index 00000000000..8371cf8f66b --- /dev/null +++ b/rust/qemu-api/src/assertions.rs @@ -0,0 +1,90 @@ +// Copyright 2024, Red Hat Inc. +// Author(s): Paolo Bonzini +// SPDX-License-Identifier: GPL-2.0-or-later + +//! This module provides macros to check the equality of types and +//! the type of `struct` fields. This can be useful to ensure that +//! types match the expectations of C code. + +// Based on https://stackoverflow.com/questions/64251852/x/70978292#70978292 +// (stackoverflow answers are released under MIT license). + +#[doc(hidden)] +pub trait EqType { + type Itself; +} + +impl EqType for T { + type Itself = T; +} + +/// Assert that two types are the same. +/// +/// # Examples +/// +/// ``` +/// # use assertions::*; +/// # use std::ops::Deref; +/// assert_same_type!(u32, u32); +/// assert_same_type!( as Deref>::Target, u32); +/// ``` +/// +/// Different types will cause a compile failure +/// +/// ```compile_fail +/// # use assertions::*; +/// assert_same_type!(&Box, &u32); +/// ``` +#[macro_export] +macro_rules! assert_same_type { + ($t1:ty, $t2:ty) => { + const _: () = { + #[allow(unused)] + fn assert_same_type(v: $t1) { + fn types_must_be_equal(_: T) + where + T: $crate::assertions::EqType, + { + } + types_must_be_equal::<_, $t2>(v); + } + }; + }; +} + +/// Assert that a field of a struct has the given type. +/// +/// # Examples +/// +/// ``` +/// # use assertions::*; +/// pub struct A { +/// field1: u32, +/// } +/// +/// assert_field_type!(A, field1, u32); +/// ``` +/// +/// Different types will cause a compile failure +/// +/// ```compile_fail +/// # use assertions::*; +/// # pub struct A { field1: u32 } +/// assert_field_type!(A, field1, i32); +/// ``` +#[macro_export] +macro_rules! assert_field_type { + ($t:ty, $i:ident, $ti:ty) => { + const _: () = { + #[allow(unused)] + fn assert_field_type(v: $t) { + fn types_must_be_equal(_: T) + where + T: $crate::assertions::EqType, + { + } + types_must_be_equal::<_, $ti>(v.$i); + } + }; + }; +} diff --git a/rust/qemu-api/src/lib.rs b/rust/qemu-api/src/lib.rs index 4b43e02c0f9..83c6a987c05 100644 --- a/rust/qemu-api/src/lib.rs +++ b/rust/qemu-api/src/lib.rs @@ -12,6 +12,7 @@ #[rustfmt::skip] pub mod prelude; +pub mod assertions; pub mod bitops; pub mod c_str; pub mod callbacks; From patchwork Thu Dec 19 12:12:09 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Paolo Bonzini X-Patchwork-Id: 13915255 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 9C878E7718B for ; Thu, 19 Dec 2024 16:33:37 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tOJFV-0001nd-SH; Thu, 19 Dec 2024 11:19:42 -0500 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 1tOFOI-00065m-TW for qemu-devel@nongnu.org; Thu, 19 Dec 2024 07:12:30 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.129.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tOFOH-000887-BA for qemu-devel@nongnu.org; Thu, 19 Dec 2024 07:12:30 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1734610348; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=IqbmpoLQyfb2UAoXyBV1EOkxQeun0T/cCIXmsB4p+Sw=; b=LeL45Zt3hBuL0W6Y4EXPzwFFEFpTgBkS9knwJtZNzmB5hS3fAFxYl10CB4KDqT/WPRIhm1 LIU1vu26T+lhlkK4weMELGG+SiPbJzwV/b+t823MPj4qBqY0zgqkbhEDSz6E4NZ2epm+Kp LpkuWtEaWjOpHwaWht0OghY584HDnGo= Received: from mail-wr1-f72.google.com (mail-wr1-f72.google.com [209.85.221.72]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-677-cjgOhLUvMWC5uv65QPs9Yw-1; Thu, 19 Dec 2024 07:12:27 -0500 X-MC-Unique: cjgOhLUvMWC5uv65QPs9Yw-1 X-Mimecast-MFC-AGG-ID: cjgOhLUvMWC5uv65QPs9Yw Received: by mail-wr1-f72.google.com with SMTP id ffacd0b85a97d-385e3cbf308so332600f8f.2 for ; Thu, 19 Dec 2024 04:12:27 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1734610345; x=1735215145; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=IqbmpoLQyfb2UAoXyBV1EOkxQeun0T/cCIXmsB4p+Sw=; b=iLmb4CCLoc6DfhJ94oQFxo/K/RAk/JNP44Bo3IO59tusVZdgvU/UkOYP2W4uSZm6d9 SrBxFCwqXbsnslt71UipeTCRkMA6Vb71TL6PjCSsY78DwNPWtGqcFn0rjVaYDKA1ijOG LGQG/KvPSIpNNkkiFKKmnVqdhJYFdBMBSZnM6cFlSOGHiMla1ZN/Pfbp34pXoPdqXj43 wQApFJA8102BwFf2mAIRC1hcAeDHiE5dN9HD0gOoN/wDnOQe3HQ3PT7KwFU6YCSZqWF0 RHee0htY5gyGdOtEhP2jLZTapjb0aaIeI34GL33PKV/kdEaTSPQ45EAdwMTOcUHxB+SI A2Zw== X-Gm-Message-State: AOJu0YwV92FYg/0Zzk7VEPqEt+wpOD+RdaePK0/ylOmgG2V0LvqMj6mJ Vf4D9Y6bMU43vy6eV+AodT/5l4pgU87j/E254Z2RfbdgPyOlvY3rUVyU4gfyh3TelGDF39HXym1 2g3sfR63+Tj5v8Qz/SsUjzRZSErKm73rl0i5kdYz1sFu7jzvDFRTDUSBvCTQreK6ccHzBFEHsk+ F4uEhhHCKlmQYIt/kOZ8giwtQt6wAdzUWnXsjT X-Gm-Gg: ASbGncvKMatVfzpntLqA1vSbJM8MxKunYF2ar2UJElh6juu3j/ucZ5xhtVqNuCs8sOj 96ZcsH3GKXabCYYtJfehztqf6nWuu2Sm0fuN6+pw2sTzdvNPfKPa4OR0Sj+dmqYaXDuSdx1yOji af69njh+/Oy8h9tLXTU8TMEozILT8/9sIfqcFgLLGzbDBIVdphNyqArCCAs1BwxVF+YqQDa2uWL 8DpN4H3MPmMXisjVIq6wN1Euq0fKthVkG1SL2Vk9x1+AncOhet925eTDiga X-Received: by 2002:a05:6000:4b0e:b0:386:3db6:2775 with SMTP id ffacd0b85a97d-388e4d8a6d1mr6487621f8f.25.1734610345114; Thu, 19 Dec 2024 04:12:25 -0800 (PST) X-Google-Smtp-Source: AGHT+IFmhl4axdIZriMSkZ7wACfJo+CMThnd4qeBvW38nmBDRihMD+to10bkB0vMJsDp0g+d+vzJsg== X-Received: by 2002:a05:6000:4b0e:b0:386:3db6:2775 with SMTP id ffacd0b85a97d-388e4d8a6d1mr6487584f8f.25.1734610344669; Thu, 19 Dec 2024 04:12:24 -0800 (PST) Received: from [192.168.10.47] ([151.81.118.45]) by smtp.gmail.com with ESMTPSA id 5b1f17b1804b1-43656b015absm50490235e9.13.2024.12.19.04.12.21 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 19 Dec 2024 04:12:21 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: zhao1.liu@intel.com Subject: [PATCH 03/10] rust: macros: check that the first field of a #[derive(Object)] struct is a ParentField Date: Thu, 19 Dec 2024 13:12:09 +0100 Message-ID: <20241219121216.416905-4-pbonzini@redhat.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241219121216.416905-1-pbonzini@redhat.com> References: <20241219121216.416905-1-pbonzini@redhat.com> MIME-Version: 1.0 Received-SPF: pass client-ip=170.10.129.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -31 X-Spam_score: -3.2 X-Spam_bar: --- X-Spam_report: (-3.2 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.001, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H2=-1.116, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=ham 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+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Signed-off-by: Paolo Bonzini --- rust/qemu-api-macros/src/lib.rs | 61 +++++++++++++++++++-------------- 1 file changed, 36 insertions(+), 25 deletions(-) diff --git a/rust/qemu-api-macros/src/lib.rs b/rust/qemu-api-macros/src/lib.rs index 74a8bc7503e..778b698be45 100644 --- a/rust/qemu-api-macros/src/lib.rs +++ b/rust/qemu-api-macros/src/lib.rs @@ -19,6 +19,27 @@ fn from(err: CompileError) -> Self { } } +fn get_fields<'a>( + input: &'a DeriveInput, + msg: &str, +) -> Result<&'a Punctuated, CompileError> { + if let Data::Struct(s) = &input.data { + if let Fields::Named(fs) = &s.fields { + Ok(&fs.named) + } else { + Err(CompileError( + format!("Named fields required for {}", msg), + input.ident.span(), + )) + } + } else { + Err(CompileError( + format!("Struct required for {}", msg), + input.ident.span(), + )) + } +} + fn is_c_repr(input: &DeriveInput, msg: &str) -> Result<(), CompileError> { let expected = parse_quote! { #[repr(C)] }; @@ -32,38 +53,28 @@ fn is_c_repr(input: &DeriveInput, msg: &str) -> Result<(), CompileError> { } } -#[proc_macro_derive(Object)] -pub fn derive_object(input: TokenStream) -> TokenStream { - let input = parse_macro_input!(input as DeriveInput); - let name = input.ident; +fn derive_object_or_error(input: DeriveInput) -> Result { + let name = &input.ident; + let parent = &get_fields(&input, "#[derive(Object)]")?[0].ident; + + Ok(quote! { + ::qemu_api::assert_field_type!(#name, #parent, + ::qemu_api::qom::ParentField<<#name as ::qemu_api::qom::ObjectImpl>::ParentType>); - let expanded = quote! { ::qemu_api::module_init! { MODULE_INIT_QOM => unsafe { ::qemu_api::bindings::type_register_static(&<#name as ::qemu_api::qom::ObjectImpl>::TYPE_INFO); } } - }; - - TokenStream::from(expanded) + }) } -fn get_fields(input: &DeriveInput) -> Result<&Punctuated, CompileError> { - if let Data::Struct(s) = &input.data { - if let Fields::Named(fs) = &s.fields { - Ok(&fs.named) - } else { - Err(CompileError( - "Cannot generate offsets for unnamed fields.".to_string(), - input.ident.span(), - )) - } - } else { - Err(CompileError( - "Cannot generate offsets for union or enum.".to_string(), - input.ident.span(), - )) - } +#[proc_macro_derive(Object)] +pub fn derive_object(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as DeriveInput); + let expanded = derive_object_or_error(input).unwrap_or_else(Into::into); + + TokenStream::from(expanded) } #[rustfmt::skip::macros(quote)] @@ -71,7 +82,7 @@ fn derive_offsets_or_error(input: DeriveInput) -> Result = fields.iter().map(|f| f.ident.as_ref().unwrap()).collect(); let field_types: Vec<&Type> = fields.iter().map(|f| &f.ty).collect(); let field_vis: Vec<&Visibility> = fields.iter().map(|f| &f.vis).collect(); From patchwork Thu Dec 19 12:12:10 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Paolo Bonzini X-Patchwork-Id: 13915226 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 8AF9AE77184 for ; Thu, 19 Dec 2024 16:22:36 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tOJFV-0001na-5p; Thu, 19 Dec 2024 11:19:41 -0500 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 1tOFOL-000660-4l for qemu-devel@nongnu.org; Thu, 19 Dec 2024 07:12:33 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.133.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tOFOJ-00088O-Jt for qemu-devel@nongnu.org; Thu, 19 Dec 2024 07:12:32 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1734610351; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=01O/MAUKR9Ox+siVKoWDUrcgLu5PuJZFTnesxu9l5+0=; b=D8XlhHomxaaRw+d+SlPiTlOmCJLEBBwx+GMMyK/3EwPFptCfXWbR/DcU64q1BeHVGwVDCO ACUZe3YxM70Q8fWwfX3RafecgNPJmGykfonchIi2xA+Ujg4Wr85dXvRvFpi6eYSMKh9u3R LIAkZx39qY6k85PGnkjDIlcwa7T5Xmo= Received: from mail-wm1-f71.google.com (mail-wm1-f71.google.com [209.85.128.71]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-112-TRCa2_BjOPS-jUWHaryMSw-1; Thu, 19 Dec 2024 07:12:29 -0500 X-MC-Unique: TRCa2_BjOPS-jUWHaryMSw-1 X-Mimecast-MFC-AGG-ID: TRCa2_BjOPS-jUWHaryMSw Received: by mail-wm1-f71.google.com with SMTP id 5b1f17b1804b1-43582d49dacso5929375e9.2 for ; Thu, 19 Dec 2024 04:12:29 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1734610348; x=1735215148; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=01O/MAUKR9Ox+siVKoWDUrcgLu5PuJZFTnesxu9l5+0=; b=Lgm1e2sGGU5aorUMMncCSTJwGgdnieBTXvSHnKGQHJRuyDaPL2yH64xbX2BnQocfah FsiLEARvOEjRZsfjspja5Y/vCuE6wFtCOtGLAIOREzZ5a9Ji/GzbF/of98fFsNgroNMw t2vSeY9JD0xRpkERo8QR3OxIPuN7XXKQGP69gd1Wuc1TOFJ8bMFuRl0fkuFDI+zVQViM 0JU4PO16daXaJKUz5ZCleiTGsoowOAOI+EdSHSNeFHqDiQbse0w5y/yRQwQD/qOus9Q8 x4CmOkpRZABtmk3nRZRCw0G/xo0QplmaI8k8/mIodELvmqTaRvx1ttdfAzKxvS6poHeW BjRg== X-Gm-Message-State: AOJu0Yy88w5IZw/GBsHqDFfWcZsatcap9/C7g3/RPYFostu1jmrbnY8J PW572xS0VSBKQAXO132G8Wr/0m4ogJFw3QizylKvWRR6wv7DxOcVMjD37QUokb3X2/cctgN5Cwg Q+/qNyJLB7g3w1ApjKTGEKl4vUSGcMQyfvhipIXh1GnSARSRfmOobifrGPGrjxP3/KSYFHVObu5 WF6aou7b3s64CQDdkp+Ktdg+lwFA+urjMG7wX9 X-Gm-Gg: ASbGnctRHMaj/oHOv96+KDTqbyJimHe6tDjSF8f901HBRL1z0kqjPya6JjKpsUi0RdH /Uct7JHpB2FZnG/vju80XjdCBeGdkFqTWQZn/PDXHkFd0AUmg1JPA6zF9AOC1XPh+NYkyA/xcUE p6x9s5+5xvjmPGFGq4gMNQ4iISCeObFssDELw5xpS6BSiveKhE1vwuvQoMih3pHaY6H8xIlzPNG r1NVAf40P0AQTSCo4/SOUUQpWJVezCcyf3V5fdnrzG3+RNcGuYNVGpaJyyH X-Received: by 2002:a05:600c:3106:b0:434:fa61:fdfb with SMTP id 5b1f17b1804b1-436553685ecmr62042035e9.18.1734610348028; Thu, 19 Dec 2024 04:12:28 -0800 (PST) X-Google-Smtp-Source: AGHT+IFOoS7R67l/AhDZ0Ln78MMOHmR5MZkCb7FKxO8UAmuS44IcqYxGRbmWRC178Qgk4rNyEPsgBQ== X-Received: by 2002:a05:600c:3106:b0:434:fa61:fdfb with SMTP id 5b1f17b1804b1-436553685ecmr62041625e9.18.1734610347581; Thu, 19 Dec 2024 04:12:27 -0800 (PST) Received: from [192.168.10.47] ([151.81.118.45]) by smtp.gmail.com with ESMTPSA id 5b1f17b1804b1-436611ea3d5sm16996935e9.5.2024.12.19.04.12.25 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 19 Dec 2024 04:12:25 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: zhao1.liu@intel.com Subject: [PATCH 04/10] rust: macros: check that #[derive(Object)] requires #[repr(C)] Date: Thu, 19 Dec 2024 13:12:10 +0100 Message-ID: <20241219121216.416905-5-pbonzini@redhat.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241219121216.416905-1-pbonzini@redhat.com> References: <20241219121216.416905-1-pbonzini@redhat.com> MIME-Version: 1.0 Received-SPF: pass client-ip=170.10.133.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -31 X-Spam_score: -3.2 X-Spam_bar: --- X-Spam_report: (-3.2 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.001, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H2=-1.116, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=ham 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+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Signed-off-by: Paolo Bonzini --- rust/qemu-api-macros/src/lib.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/rust/qemu-api-macros/src/lib.rs b/rust/qemu-api-macros/src/lib.rs index 778b698be45..0f04cca3841 100644 --- a/rust/qemu-api-macros/src/lib.rs +++ b/rust/qemu-api-macros/src/lib.rs @@ -54,6 +54,8 @@ fn is_c_repr(input: &DeriveInput, msg: &str) -> Result<(), CompileError> { } fn derive_object_or_error(input: DeriveInput) -> Result { + is_c_repr(&input, "#[derive(Object)]")?; + let name = &input.ident; let parent = &get_fields(&input, "#[derive(Object)]")?[0].ident; From patchwork Thu Dec 19 12:12:11 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Paolo Bonzini X-Patchwork-Id: 13915227 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id CC58DE7718A for ; Thu, 19 Dec 2024 16:23:16 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tOJGy-0004oL-EA; Thu, 19 Dec 2024 11:21:12 -0500 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 1tOFOP-00066L-3A for qemu-devel@nongnu.org; Thu, 19 Dec 2024 07:12:38 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.129.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tOFOM-000899-DY for qemu-devel@nongnu.org; Thu, 19 Dec 2024 07:12:36 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1734610352; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=MFM1GOCm15L/cPIdOg468IxeTeTqWnTkcNuwrJVlvEk=; b=eJ76o8+IAa1ACvFyaYt7Fy4koZidTho5lhScALrt1YwMyBM4qBfd4q6THgDNkID4FFjV+q vMXSm7U7OL91TM/cSbS6wEGf3fCKi5PiMDgH4d8kdqzDuiEuNEXOL8wfiPMTD8APlKjVls 2mUY+9gLc+VgD0mdWHNHxiX+3TpUaIo= Received: from mail-wm1-f69.google.com (mail-wm1-f69.google.com [209.85.128.69]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-365-eFX-leFHO8GeYyZkCN4oJQ-1; Thu, 19 Dec 2024 07:12:31 -0500 X-MC-Unique: eFX-leFHO8GeYyZkCN4oJQ-1 X-Mimecast-MFC-AGG-ID: eFX-leFHO8GeYyZkCN4oJQ Received: by mail-wm1-f69.google.com with SMTP id 5b1f17b1804b1-4362f893bfaso4300335e9.1 for ; Thu, 19 Dec 2024 04:12:31 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1734610349; x=1735215149; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=MFM1GOCm15L/cPIdOg468IxeTeTqWnTkcNuwrJVlvEk=; b=UJhnTsUeW5Ax5p4KeW5TY5P/iG7Z6WAsC3K4bmDiD23YNLyBKfL+t2fgf3/OGuEMMT sf3WL9KhAlQEYrw2MHT9/n27hvhnzGegCP4NtBS05WWzggGK4PI+0JLODuAsaUMskQ9N kPH2dcv9+K8yI9+Vcet0mxPzeomMh2SWO3DhTotw8IOrkBMUfZmEeuvEqkeZF64GIfUq ybdJ9MHoXae8DTsEU4Nenrz+pQMHv06lKW7m1EwiMawL47Jk8IRV3tvH8CRJjCSUA2ia CobqZrokowE2WynzciNCcPFf3otrtrEo0lhG0FYrFdui/0S8jvu5nqwilN07nJUoj8us FoqA== X-Gm-Message-State: AOJu0YzIEVg/RLKpzwl6C9kwgeyG1xsDT1Tum2s6miXpsEoephFtQlZn n8MPYF1limpb+sqcCneyG8QtuPRU2Gns2e903lbWy0vbG2/fsXiZN7psBJnay5I/Hvcds0ZY3D4 KmIA4vPaaWK29STQI3efGQjtKoLHAdKgyc1+cYfzXKAlg3Ddf8pcw8sWv0HHRZmc+q7SLWoJd6H U1boMc3oBGtLEi5ZNptCmMYYGo/c6aU1TjPxqd X-Gm-Gg: ASbGnct+Xoex8MKIPi8tfXua3TNIcX1Cmj89kjVscmZ+EriN+/d472j9t0YfVfxHaFr wv5aeqbX84VXSmObvOGl+lUH8mKirk0PITL9Lb7gcfpZx8P+aAyUzCb56/CXXHMzE/v/cOelWHx F0XSRHSHcCM5mrkLniI6d2Cn8vRZhnBqCDf2wFYqsbjYDLxs0hNPGJCeowBFKeIB5CS2U53fHPB Vqgz+bIrFAQwwEB9xJB7WHQKMk+zJwLcqmMkRi2KBwwkxNc3yZNHNTIKGkX X-Received: by 2002:a05:600c:4e8d:b0:434:a59c:43c6 with SMTP id 5b1f17b1804b1-436553fe252mr49982355e9.26.1734610349669; Thu, 19 Dec 2024 04:12:29 -0800 (PST) X-Google-Smtp-Source: AGHT+IGqqjoeSmDmnBsO3Xk+9gkFZGZo+5L/bZKpFkIrRTdwIgTgSfw5+ohJf2luSFozGEh4bD2WAw== X-Received: by 2002:a05:600c:4e8d:b0:434:a59c:43c6 with SMTP id 5b1f17b1804b1-436553fe252mr49982175e9.26.1734610349230; Thu, 19 Dec 2024 04:12:29 -0800 (PST) Received: from [192.168.10.47] ([151.81.118.45]) by smtp.gmail.com with ESMTPSA id 5b1f17b1804b1-436611ea387sm16221995e9.6.2024.12.19.04.12.28 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 19 Dec 2024 04:12:28 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: zhao1.liu@intel.com Subject: [PATCH 05/10] rust: qom: automatically use Drop trait to implement instance_finalize Date: Thu, 19 Dec 2024 13:12:11 +0100 Message-ID: <20241219121216.416905-6-pbonzini@redhat.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241219121216.416905-1-pbonzini@redhat.com> References: <20241219121216.416905-1-pbonzini@redhat.com> MIME-Version: 1.0 Received-SPF: pass client-ip=170.10.129.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -31 X-Spam_score: -3.2 X-Spam_bar: --- X-Spam_report: (-3.2 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.001, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H2=-1.116, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=ham 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+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Replace the customizable INSTANCE_FINALIZE with a generic function that drops the Rust object. Reviewed-by: Zhao Liu Signed-off-by: Paolo Bonzini --- rust/qemu-api/src/qom.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/rust/qemu-api/src/qom.rs b/rust/qemu-api/src/qom.rs index 1341a173893..861f1e50ac4 100644 --- a/rust/qemu-api/src/qom.rs +++ b/rust/qemu-api/src/qom.rs @@ -180,6 +180,16 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { T::class_init(unsafe { &mut *klass.cast::() }) } +unsafe extern "C" fn drop_object(obj: *mut Object) { + // SAFETY: obj is an instance of T, since drop_object is called + // from the QOM core function object_deinit() as the instance_finalize + // function for class T. Note that while object_deinit() will drop the + // superclass field separately after this function returns, `T` must + // implement the unsafe trait ObjectType; the safety rules for the + // trait mandate that the parent field is manually dropped. + unsafe { std::ptr::drop_in_place(obj.cast::()) } +} + /// Trait exposed by all structs corresponding to QOM objects. /// /// # Safety @@ -438,7 +448,6 @@ pub trait ObjectImpl: ObjectType + ClassInitImpl { /// Whether the object can be instantiated const ABSTRACT: bool = false; - const INSTANCE_FINALIZE: Option = None; /// Function that is called to initialize an object. The parent class will /// have already been initialized so the type is only responsible for @@ -474,7 +483,7 @@ pub trait ObjectImpl: ObjectType + ClassInitImpl { None => None, Some(_) => Some(rust_instance_post_init::), }, - instance_finalize: Self::INSTANCE_FINALIZE, + instance_finalize: Some(drop_object::), abstract_: Self::ABSTRACT, class_size: core::mem::size_of::(), class_init: Some(rust_class_init::), From patchwork Thu Dec 19 12:12:12 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Paolo Bonzini X-Patchwork-Id: 13915222 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 793B9E77184 for ; Thu, 19 Dec 2024 16:20:26 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tOJFQ-0001mI-0M; Thu, 19 Dec 2024 11:19:36 -0500 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 1tOFOP-00066M-MW for qemu-devel@nongnu.org; Thu, 19 Dec 2024 07:12:38 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.133.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tOFON-00089d-Vg for qemu-devel@nongnu.org; Thu, 19 Dec 2024 07:12:37 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1734610355; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=s6nygS97dluqx/BeGp3uSmNclmtr8ycVi93iMqAtirw=; b=ZY/IY5mHC74yyMzxsyHsm2szV1iMhebsxpz2DjHLMtDBdkDPjWGTmRLHa6i8Vj/X1a5n0W CJYssrnHfyvhWhNGfnLiaPLcaiC8RF/nZxrkJLchnJ3EQ3Jm5lSQrU7BGDzRF4TB7rFFtw ZEN76AUDE3NyKfBEhWPgcsVHFJ0Lpa4= Received: from mail-wm1-f70.google.com (mail-wm1-f70.google.com [209.85.128.70]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-688-LX4o54gSPBaM84RnFei4Qw-1; Thu, 19 Dec 2024 07:12:34 -0500 X-MC-Unique: LX4o54gSPBaM84RnFei4Qw-1 X-Mimecast-MFC-AGG-ID: LX4o54gSPBaM84RnFei4Qw Received: by mail-wm1-f70.google.com with SMTP id 5b1f17b1804b1-43625ceae52so4351855e9.0 for ; Thu, 19 Dec 2024 04:12:33 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1734610352; x=1735215152; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=s6nygS97dluqx/BeGp3uSmNclmtr8ycVi93iMqAtirw=; b=e8LXmcg6aYsM2M54fszjkVOSlTWgrrDBwkWhT+gPf6ltHicPxLg49n1MxYnIaO8dm+ /IV63oouP4Fd7OKtVm8yA/idkhalpJNa4tX1rQNnDdDxdlQALcsHusNFEWe7YTDQWHWv v1dXi/tSC++IxSx63krLX5UjtP6UixnSPkxW/GKE+GiP3R9n/6fEsi9EbLgWSxtwoZdY TE0Zb9mmbaTv+LIFG6q1jq9p2CHapQWh/vf61xKk5y69Lu4YmQ3hD+McsUxt+DbEfAtW GP3QrGfiCzYu6PTONghurJ/TyTISPjqSy/iCjLECQt7XAEqmVFak0Od+SBzON67+l6T/ lBJg== X-Gm-Message-State: AOJu0Yyu+MvvHZEjI7E8hT5Gc6GBbmIprgSJ8PgLwcZT03RGUH0IICiO l7lEMI5Nj1XeWYCvtfcaPZFu9BdqMRkz3fxXSBNJWseDz0zcJF+UHLmX2BiCjNbQjLMFsWYkpXz ShHTLpVKg+bEwE3TTuKLYrLOW5XGcH6QYN16Xi2b4QiHMxNioOo0X5nLFAgX7LSyJsXS7fgc4zw lxgz2FI5WY2qCWflCsklCBuIrjfo5YGyJmREv+ X-Gm-Gg: ASbGncs8S7jbHZz7SFSbVxlb4QEezOn1Po5nD9JCOosrq5X3isnCRbJeQN+8vlnxyhw f8D0jf/YGJ+6aNq64JI1RLFRMtuT40prfkgAVsYxacXwWtjH7EZx4ipC4XXZrqA++tIgQEbXiF7 4lwj5kAtzlhT01zqNePBHlnigV9ihDRmNCydRmXTJdSMLwAZghB/ByQPZjVXz9gm6TVQ7MztFHK tLyBXgoozA7lyrVYl8p1GeoCvWcQFe4xmPEhtXEXE3R+p5LSB+QeCBFKkZL X-Received: by 2002:a05:6000:156c:b0:385:f220:f788 with SMTP id ffacd0b85a97d-388e4dad7b7mr6318064f8f.48.1734610351694; Thu, 19 Dec 2024 04:12:31 -0800 (PST) X-Google-Smtp-Source: AGHT+IGXLEWpbID6WJom2RkjUcAVDjCHTbt5/SVlufliM1MucKhzTOpUxdcYhp/FoZZdM13qfJFoaw== X-Received: by 2002:a05:6000:156c:b0:385:f220:f788 with SMTP id ffacd0b85a97d-388e4dad7b7mr6318033f8f.48.1734610351240; Thu, 19 Dec 2024 04:12:31 -0800 (PST) Received: from [192.168.10.47] ([151.81.118.45]) by smtp.gmail.com with ESMTPSA id ffacd0b85a97d-38a1c832e1bsm1427795f8f.31.2024.12.19.04.12.29 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 19 Dec 2024 04:12:29 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: zhao1.liu@intel.com Subject: [PATCH 06/10] rust: qom: move device_id to PL011 class side Date: Thu, 19 Dec 2024 13:12:12 +0100 Message-ID: <20241219121216.416905-7-pbonzini@redhat.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241219121216.416905-1-pbonzini@redhat.com> References: <20241219121216.416905-1-pbonzini@redhat.com> MIME-Version: 1.0 Received-SPF: pass client-ip=170.10.133.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -31 X-Spam_score: -3.2 X-Spam_bar: --- X-Spam_report: (-3.2 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.001, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H2=-1.116, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=ham 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+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org There is no need to monkeypatch DeviceId::Luminary into the already-initialized PL011State. Instead, now that we can define a class hierarchy, we can define PL011Class and make device_id a field in there. There is also no need anymore to have "Arm" as zero, so change DeviceId into a wrapper for the array; all it does is provide an Index implementation because arrays can only be indexed by usize. Signed-off-by: Paolo Bonzini --- rust/hw/char/pl011/src/device.rs | 59 +++++++++++++++----------------- 1 file changed, 28 insertions(+), 31 deletions(-) diff --git a/rust/hw/char/pl011/src/device.rs b/rust/hw/char/pl011/src/device.rs index 689202f4550..215f94a6e4a 100644 --- a/rust/hw/char/pl011/src/device.rs +++ b/rust/hw/char/pl011/src/device.rs @@ -5,7 +5,7 @@ use core::ptr::{addr_of_mut, NonNull}; use std::{ ffi::CStr, - os::raw::{c_int, c_uchar, c_uint, c_void}, + os::raw::{c_int, c_uint, c_void}, }; use qemu_api::{ @@ -14,7 +14,7 @@ irq::InterruptSource, prelude::*, qdev::DeviceImpl, - qom::{ObjectImpl, ParentField}, + qom::{ClassInitImpl, ObjectImpl, ParentField}, }; use crate::{ @@ -33,27 +33,20 @@ /// QEMU sourced constant. pub const PL011_FIFO_DEPTH: u32 = 16; -#[derive(Clone, Copy, Debug)] -enum DeviceId { - #[allow(dead_code)] - Arm = 0, - Luminary, -} +#[derive(Clone, Copy)] +struct DeviceId(&'static [u8; 8]); impl std::ops::Index for DeviceId { - type Output = c_uchar; + type Output = u8; fn index(&self, idx: hwaddr) -> &Self::Output { - match self { - Self::Arm => &Self::PL011_ID_ARM[idx as usize], - Self::Luminary => &Self::PL011_ID_LUMINARY[idx as usize], - } + &self.0[idx as usize] } } impl DeviceId { - const PL011_ID_ARM: [c_uchar; 8] = [0x11, 0x10, 0x14, 0x00, 0x0d, 0xf0, 0x05, 0xb1]; - const PL011_ID_LUMINARY: [c_uchar; 8] = [0x11, 0x00, 0x18, 0x01, 0x0d, 0xf0, 0x05, 0xb1]; + const ARM: Self = Self(&[0x11, 0x10, 0x14, 0x00, 0x0d, 0xf0, 0x05, 0xb1]); + const LUMINARY: Self = Self(&[0x11, 0x00, 0x18, 0x01, 0x0d, 0xf0, 0x05, 0xb1]); } // FIFOs use 32-bit indices instead of usize, for compatibility with @@ -126,17 +119,28 @@ pub struct PL011State { pub clock: NonNull, #[doc(alias = "migrate_clk")] pub migrate_clock: bool, - /// The byte string that identifies the device. - device_id: DeviceId, } qom_isa!(PL011State : SysBusDevice, DeviceState, Object); +pub struct PL011Class { + parent_class: ::Class, + /// The byte string that identifies the device. + device_id: DeviceId, +} + unsafe impl ObjectType for PL011State { - type Class = ::Class; + type Class = PL011Class; const TYPE_NAME: &'static CStr = crate::TYPE_PL011; } +impl ClassInitImpl for PL011State { + fn class_init(klass: &mut PL011Class) { + klass.device_id = DeviceId::ARM; + >::class_init(&mut klass.parent_class); + } +} + impl ObjectImpl for PL011State { type ParentType = SysBusDevice; @@ -214,7 +218,8 @@ pub fn read(&mut self, offset: hwaddr, _size: c_uint) -> std::ops::ControlFlow> 2)) => { - u32::from(self.device_id[(offset - 0xfe0) >> 2]) + let device_id = self.get_class().device_id; + u32::from(device_id[(offset - 0xfe0) >> 2]) } Err(_) => { // qemu_log_mask(LOG_GUEST_ERROR, "pl011_read: Bad offset 0x%x\n", (int)offset); @@ -648,16 +653,10 @@ pub struct PL011Luminary { parent_obj: ParentField, } -impl PL011Luminary { - /// Initializes a pre-allocated, unitialized instance of `PL011Luminary`. - /// - /// # Safety - /// - /// We expect the FFI user of this function to pass a valid pointer, that - /// has the same size as [`PL011Luminary`]. We also expect the device is - /// readable/writeable from one thread at any time. - unsafe fn init(&mut self) { - self.parent_obj.device_id = DeviceId::Luminary; +impl ClassInitImpl for PL011Luminary { + fn class_init(klass: &mut PL011Class) { + klass.device_id = DeviceId::LUMINARY; + >::class_init(&mut klass.parent_class); } } @@ -670,8 +669,6 @@ unsafe impl ObjectType for PL011Luminary { impl ObjectImpl for PL011Luminary { type ParentType = PL011State; - - const INSTANCE_INIT: Option = Some(Self::init); } impl DeviceImpl for PL011Luminary {} From patchwork Thu Dec 19 12:12:13 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Paolo Bonzini X-Patchwork-Id: 13915247 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 4FE44E77184 for ; Thu, 19 Dec 2024 16:30:13 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tOJFX-0001nu-EL; Thu, 19 Dec 2024 11:19:43 -0500 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 1tOFPW-0006Hr-3S for qemu-devel@nongnu.org; Thu, 19 Dec 2024 07:13:46 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.129.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tOFPU-0008LE-En for qemu-devel@nongnu.org; Thu, 19 Dec 2024 07:13:45 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1734610423; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=MBnoMQiocVwxb195C5dPLUMqfWHTI2r8yktVChDs01k=; b=FTEpGmb4Is5jezR053KsUydt2hDTuPl8SNY4HR7rslIVX30g1lLnnU5V1p1GAu4w5bdUmC O8PWdhYx7Aa4VoC9izFW9yty5sGDFA1katkq6TRvvPy2WvNkg1fOcPytG4Ehc+RODQhtdX UxvUw4tGTld48v6aqlhVezMOeNakuko= Received: from mail-wr1-f72.google.com (mail-wr1-f72.google.com [209.85.221.72]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-101-3NbD55LEPbaRRZu_03e4rw-1; Thu, 19 Dec 2024 07:12:35 -0500 X-MC-Unique: 3NbD55LEPbaRRZu_03e4rw-1 X-Mimecast-MFC-AGG-ID: 3NbD55LEPbaRRZu_03e4rw Received: by mail-wr1-f72.google.com with SMTP id ffacd0b85a97d-385d52591d6so397470f8f.1 for ; Thu, 19 Dec 2024 04:12:35 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1734610353; x=1735215153; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=MBnoMQiocVwxb195C5dPLUMqfWHTI2r8yktVChDs01k=; b=Gwb6VoNve8i05fhclpsg60Rts1yFbXWG8qCId4gOyy6cEgr+J1/NIDwlvTo3VaPgjL p/vYxcGaWL/wxazzKE1HoPLYl95hO7qu+1Mh2jBJcQJaw9boq5QUf/l93YtZyTsSYrn7 qx+mLB9x+8tasJ22iPOANXUFtaOVmkSTIobujByRRP6js830Yp/i1/UWq/YAteMh68T1 39QrgDZy4J1ibVvd2RrCd+eRDNgelmWG4p/cwZyPIJSD/YZ4W5YoLB6rQK5hbjRHPUGY cbfgweALbQay3E2TdKWaFC9Ws7KrkdUliFSa1xhQcuxOCtAEelMK/j3W4N1ftaJsWMEB ulUw== X-Gm-Message-State: AOJu0YxnJ4pS8MaCGCiEMHtHQPvDxIoYidTI8HzdFTc43bRUUPIlp24g 57jnTMFIGIulxGvVfjYjQitCsgrDbZZTAcnhTDrrxjsbGpEEFycUHnPugDtDJs3y9dPqFDoYL37 QrItKXSrqoOOp3LwW8RGYdjHI+shpe+7TQMgFNFXwDTSAP6CAFXuqZw6eHLOii6AV7QdKAYyh3z ElcwM20fuXInNuWmzMG8+cwpniFGPLxgaE0MKe X-Gm-Gg: ASbGncvvKMkaT2auovBv6U0MO+tFZUAWzBdASKt6DWXeKl4BSQ2/wG99aL6majXT5j9 tuUGava3d19MVCvBSEaATPuJNKAee21bDLZWa5dW6OjMjz43v2FXnJ4a3okDstVcOQlQmingqxE Wyn35KWMoTwbWTaE1JJmw+DNzu5dpp7qYySM1mU5uGEDid40/sUkb+EUZA/bMBqtT+PJZ1c3Kr0 H1q+WpcbvkqrbhL7vM4ISCZVaZo+zoYPD6mDqY9fL//262eZhN72kbvAafQ X-Received: by 2002:a5d:6485:0:b0:386:3711:ffa9 with SMTP id ffacd0b85a97d-38a1a233376mr2455803f8f.16.1734610352716; Thu, 19 Dec 2024 04:12:32 -0800 (PST) X-Google-Smtp-Source: AGHT+IFn/X+VXeH/+Y5BjvHR60r7gdL4D1WUB5BT0zlWbiCN6CfHyBEuRhAAwI+7HuyMC6fkQ/mttg== X-Received: by 2002:a5d:6485:0:b0:386:3711:ffa9 with SMTP id ffacd0b85a97d-38a1a233376mr2455779f8f.16.1734610352291; Thu, 19 Dec 2024 04:12:32 -0800 (PST) Received: from [192.168.10.47] ([151.81.118.45]) by smtp.gmail.com with ESMTPSA id 5b1f17b1804b1-436604e9c2csm18193875e9.43.2024.12.19.04.12.31 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 19 Dec 2024 04:12:31 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: zhao1.liu@intel.com Subject: [PATCH 07/10] rust: pl011: only leave embedded object initialization in instance_init Date: Thu, 19 Dec 2024 13:12:13 +0100 Message-ID: <20241219121216.416905-8-pbonzini@redhat.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241219121216.416905-1-pbonzini@redhat.com> References: <20241219121216.416905-1-pbonzini@redhat.com> MIME-Version: 1.0 Received-SPF: pass client-ip=170.10.129.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -31 X-Spam_score: -3.2 X-Spam_bar: --- X-Spam_report: (-3.2 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.001, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H2=-1.116, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=ham 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+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Leave IRQ and MMIO initialization to instance_post_init. In Rust the two callbacks are more distinct, because only instance_post_init has a fully initialized object available. While at it, add a wrapper for sysbus_init_mmio so that accesses to the SysBusDevice correctly use shared references. Signed-off-by: Paolo Bonzini --- rust/hw/char/pl011/src/device.rs | 18 ++++++++++-------- rust/qemu-api/src/sysbus.rs | 12 ++++++++++++ 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/rust/hw/char/pl011/src/device.rs b/rust/hw/char/pl011/src/device.rs index 215f94a6e4a..72a4cea042c 100644 --- a/rust/hw/char/pl011/src/device.rs +++ b/rust/hw/char/pl011/src/device.rs @@ -145,6 +145,7 @@ impl ObjectImpl for PL011State { type ParentType = SysBusDevice; const INSTANCE_INIT: Option = Some(Self::init); + const INSTANCE_POST_INIT: Option = Some(Self::post_init); } impl DeviceImpl for PL011State { @@ -183,14 +184,6 @@ unsafe fn init(&mut self) { Self::TYPE_NAME.as_ptr(), 0x1000, ); - - let sbd: &mut SysBusDevice = self.upcast_mut(); - sysbus_init_mmio(sbd, addr_of_mut!(self.iomem)); - } - - for irq in self.interrupts.iter() { - let sbd: &SysBusDevice = self.upcast(); - sbd.init_irq(irq); } // SAFETY: @@ -213,6 +206,15 @@ unsafe fn init(&mut self) { } } + fn post_init(&mut self) { + let sbd: &SysBusDevice = self.upcast(); + + sbd.init_mmio(&self.iomem); + for irq in self.interrupts.iter() { + sbd.init_irq(irq); + } + } + pub fn read(&mut self, offset: hwaddr, _size: c_uint) -> std::ops::ControlFlow { use RegisterOffset::*; diff --git a/rust/qemu-api/src/sysbus.rs b/rust/qemu-api/src/sysbus.rs index 8193734bde4..b96eaaf25f2 100644 --- a/rust/qemu-api/src/sysbus.rs +++ b/rust/qemu-api/src/sysbus.rs @@ -38,6 +38,18 @@ const fn as_mut_ptr(&self) -> *mut SysBusDevice { addr_of!(*self) as *mut _ } + /// Expose a memory region to the board so that it can give it an address + /// in guest memory. Note that the ordering of calls to `init_mmio` is + /// important, since whoever creates the sysbus device will refer to the + /// region with a number that corresponds to the order of calls to + /// `init_mmio`. + pub fn init_mmio(&self, iomem: &bindings::MemoryRegion) { + assert!(bql_locked()); + unsafe { + bindings::sysbus_init_mmio(self.as_mut_ptr(), addr_of!(*iomem) as *mut _); + } + } + /// Expose an interrupt source outside the device as a qdev GPIO output. /// Note that the ordering of calls to `init_irq` is important, since /// whoever creates the sysbus device will refer to the interrupts with From patchwork Thu Dec 19 12:12:14 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Paolo Bonzini X-Patchwork-Id: 13915245 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 1D797E77184 for ; Thu, 19 Dec 2024 16:29:05 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tOJIc-0000zZ-3e; Thu, 19 Dec 2024 11:22:54 -0500 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 1tOFOX-0006DT-KM for qemu-devel@nongnu.org; Thu, 19 Dec 2024 07:12:45 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.133.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tOFOW-0008AI-03 for qemu-devel@nongnu.org; Thu, 19 Dec 2024 07:12:45 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1734610360; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=u9nMTxyosvlBNmWHbdS3uU97thxBhf1W17a5325xukk=; b=I0X8XtTksjAg5r9WDZkXE95XIzqLSXCESAbmPct8zwhYc8oxqJLCyIPiG+BFFTpbYP457i DcN+E7yc/DX5ZYS+mAbv1mGdZHH+ZBdefAsAFYWsE/vukYs/hBvbYpCyjHXT7VkoiXEwbK X7oSnBF7T/rbK71V4eWdyV3Cge1TAjI= Received: from mail-wr1-f69.google.com (mail-wr1-f69.google.com [209.85.221.69]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-392-80rFSyrUNfylHPk1a0ExHw-1; Thu, 19 Dec 2024 07:12:38 -0500 X-MC-Unique: 80rFSyrUNfylHPk1a0ExHw-1 X-Mimecast-MFC-AGG-ID: 80rFSyrUNfylHPk1a0ExHw Received: by mail-wr1-f69.google.com with SMTP id ffacd0b85a97d-386321c8f4bso437059f8f.0 for ; Thu, 19 Dec 2024 04:12:38 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1734610356; x=1735215156; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=u9nMTxyosvlBNmWHbdS3uU97thxBhf1W17a5325xukk=; b=gbl973onmp5OGaCLU7wkcnd40uZCHJN1QGUHKYvXsq+h4llISD9QX58AkmJT3ldZZI 0idAF7XRkW27snWTjkcgxGjrKtFs1T2ql1XOGC48uRI5uI4pCMbDCfOl4+CDBJaac9Mv OgL3n+rJiSQrNaImCVAaOpOy5A2k+7uR561fRygTUKJtHV5haLp9Y+zgaV8QucJFW1aP 70H4NvRKZwQgqRxoGeUWDiWnJ22oedO/UFX4JLC9vGuEpkiExeqJ0pXnj/oQnPWn3bPy KYAMP6retaoT4NPWopnEI6w2aWEG1xJc0p/hFdOK1iqcA19M6tYyiZFjjKmKHyYmydkH GSvA== X-Gm-Message-State: AOJu0Yx0JNORx/1Mop6glHWt0E58dX3ymw46XgcRnZy8O91ONOTRHjxF +BX9XGY1d04/HpAjNQ2S93iFp3LqmJAnk8PLITlHZS329rkcyWa+o8OOqxvJIECrjNZrIpZOv1l bder6RECgxbtwA5e5TCjFORhUCkEQ0ZKJm5q5P61eRyed3XsSy9b41btljC0/QBwjnUx6/iS2V7 oSf6rM82RSJd/i+CHGjL9UKKCR9pUL4CCNNJby X-Gm-Gg: ASbGncvnn/YazxB/ylKseL/A1VhuGAf99cCIMpFJKauBJg/PQcJuNS30ITZvVrgTKW0 4gtnGBZjbMpJSlObXqW3DDyeQyA6zexplEYpvQ4GquuDzTHWf4qmkkU3NniZa6FBruyRMgf1p1x bnr8KAqlfLIUwGfI+oE5Q5Wc1UF7z+iPHuikltBZdNwu7+BBs5nmGlnPNXX2W2ET/MBAJorczWl 2MC6rZgD0uAhwgQEZM+7nahLqEpxyIZ7JBKIWUq2UYisnPHi1DAaY3V9UmF X-Received: by 2002:a05:6000:184b:b0:385:df4e:3645 with SMTP id ffacd0b85a97d-388e4d9c528mr5233242f8f.50.1734610356160; Thu, 19 Dec 2024 04:12:36 -0800 (PST) X-Google-Smtp-Source: AGHT+IEUh2M9/mnSogeQ773STUYnJzJNd5S5eWvf3oRcRQezB6U0AwDcAXGbiOpHZ9UUI+vGCXK0XQ== X-Received: by 2002:a05:6000:184b:b0:385:df4e:3645 with SMTP id ffacd0b85a97d-388e4d9c528mr5233203f8f.50.1734610355678; Thu, 19 Dec 2024 04:12:35 -0800 (PST) Received: from [192.168.10.47] ([151.81.118.45]) by smtp.gmail.com with ESMTPSA id 5b1f17b1804b1-4366127c4fcsm16696415e9.29.2024.12.19.04.12.32 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 19 Dec 2024 04:12:32 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: zhao1.liu@intel.com Subject: [PATCH 08/10] rust: qom: make INSTANCE_POST_INIT take a shared reference Date: Thu, 19 Dec 2024 13:12:14 +0100 Message-ID: <20241219121216.416905-9-pbonzini@redhat.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241219121216.416905-1-pbonzini@redhat.com> References: <20241219121216.416905-1-pbonzini@redhat.com> MIME-Version: 1.0 Received-SPF: pass client-ip=170.10.133.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -31 X-Spam_score: -3.2 X-Spam_bar: --- X-Spam_report: (-3.2 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.001, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H2=-1.116, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=ham 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+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Signed-off-by: Paolo Bonzini --- rust/hw/char/pl011/src/device.rs | 4 ++-- rust/qemu-api/src/qom.rs | 8 ++------ 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/rust/hw/char/pl011/src/device.rs b/rust/hw/char/pl011/src/device.rs index 72a4cea042c..6792d13fb77 100644 --- a/rust/hw/char/pl011/src/device.rs +++ b/rust/hw/char/pl011/src/device.rs @@ -145,7 +145,7 @@ impl ObjectImpl for PL011State { type ParentType = SysBusDevice; const INSTANCE_INIT: Option = Some(Self::init); - const INSTANCE_POST_INIT: Option = Some(Self::post_init); + const INSTANCE_POST_INIT: Option = Some(Self::post_init); } impl DeviceImpl for PL011State { @@ -206,7 +206,7 @@ unsafe fn init(&mut self) { } } - fn post_init(&mut self) { + fn post_init(&self) { let sbd: &SysBusDevice = self.upcast(); sbd.init_mmio(&self.iomem); diff --git a/rust/qemu-api/src/qom.rs b/rust/qemu-api/src/qom.rs index 861f1e50ac4..5934eb0cc50 100644 --- a/rust/qemu-api/src/qom.rs +++ b/rust/qemu-api/src/qom.rs @@ -163,11 +163,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { // SAFETY: obj is an instance of T, since rust_instance_post_init // is called from QOM core as the instance_post_init function // for class T - // - // FIXME: it's not really guaranteed that there are no backpointers to - // obj; it's quite possible that they have been created by instance_init(). - // The receiver should be &self, not &mut self. - T::INSTANCE_POST_INIT.unwrap()(unsafe { &mut *obj.cast::() }) + T::INSTANCE_POST_INIT.unwrap()(unsafe { &*obj.cast::() }) } unsafe extern "C" fn rust_class_init>( @@ -459,7 +455,7 @@ pub trait ObjectImpl: ObjectType + ClassInitImpl { /// Function that is called to finish initialization of an object, once /// `INSTANCE_INIT` functions have been called. - const INSTANCE_POST_INIT: Option = None; + const INSTANCE_POST_INIT: Option = None; /// Called on descendent classes after all parent class initialization /// has occurred, but before the class itself is initialized. This From patchwork Thu Dec 19 12:12:15 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Paolo Bonzini X-Patchwork-Id: 13915266 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 76EC4E77184 for ; Thu, 19 Dec 2024 16:37:03 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tOJGI-0002Rn-At; Thu, 19 Dec 2024 11:20:30 -0500 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 1tOFsX-0002KC-Si for qemu-devel@nongnu.org; Thu, 19 Dec 2024 07:43:45 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.129.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tOFsW-0006R5-Cg for qemu-devel@nongnu.org; Thu, 19 Dec 2024 07:43:45 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1734612222; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=Szoag27KIkqUli3n0xSrTUcaxn0aravcRGL/6Nt+Rm8=; b=BB6HSiZPiNwrHDpP0Y/io6IihDGxJoF+jkQiEI+PSG4ho+qxUoRcVVG7bDOL3xpTVDNYaW 4DdQ3+d1Vi7pBF+JPt4aI1Wq3MGAa24yPC1imdRTLQAZscf/3nV7MnCsHA9l2qQAz85LKW 4ngMOGXOVsRQVffdHU/UyK2S4WoHvJk= Received: from mail-lj1-f198.google.com (mail-lj1-f198.google.com [209.85.208.198]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-341-zWV4_998OiWkrToLU5q9kg-1; Thu, 19 Dec 2024 07:43:41 -0500 X-MC-Unique: zWV4_998OiWkrToLU5q9kg-1 X-Mimecast-MFC-AGG-ID: zWV4_998OiWkrToLU5q9kg Received: by mail-lj1-f198.google.com with SMTP id 38308e7fff4ca-3023f0f1852so4072261fa.1 for ; Thu, 19 Dec 2024 04:43:41 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1734612219; x=1735217019; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=Szoag27KIkqUli3n0xSrTUcaxn0aravcRGL/6Nt+Rm8=; b=prfouKt2IxEwhiL/deMFH7+MXAEh2dRWefA/Cch9C0IJAoDQBRtsxdKfY/JGCCtxBC A+jkpDzlYPkiRKH31e9CG+hP/zmq92GxiTCkkR53r5KgCU4qiKc3K7LHnX8zPH/M8qQC FiWEoDatj2czGRDVNE0wLVeRG+5dPQyyHUQXDX0H7HN3Q8kOx1hXzD4sRlGsNlFcx4ub TspBgeSKxuiHMFf/a03dggzD+PA11TOo7YXR395r+I3RHjoS8cTWBR1+yp8xehYYNOPd XkRLSEiv9HqGw6NSMVFNQfczlMzg+j9icQSVsf0DXNeoVe1ScNLK4zPOEE9vPy9UGLYy j77g== X-Gm-Message-State: AOJu0YzOH8ZEkwepmgtdPLxmGMXVUJxnbuZBBTta34dzu28Mh6F2xdcG VDjT1oPdXfInVq35N2xR9pS74qtyXMP6woTn7S3u5PBUzxQGn6JpO0vqSOVA+05wTvkQiNWhq1T ccnxVqlYVqrhcC32CB1vP7YbC8eRLEDuvHwkbrzd/7pk2t+eGIci9e11eAH47Liq7Okr6rEGtZK vm4Tdf0qeBIergaS82XXxNpYee8ottqMsPIcNG X-Gm-Gg: ASbGncuqRvMjgCMHrRV1ZNugjEyv2jyLwnLxZe+NZISG5Si4+BLDkuksZAsNEN6W86O yVJguMiGHIPTodbqN4tK0JeE+MQ9JVfnAgfxMS1j01FlhGGyhSavl/ZsFCteFt7loLlb4etNtCc v5+HWE+vQttPubuqnQvgUR/ZMjojEmboYPsvtC5wdiBT6iHrRaO1ha8kTTHm4QlFKDhc3pbGRQ1 ufejjtAbctchFe6NWAVp9Bc4z/si8LytwQjkdrruBz3+T3kcdMx5OB1+SDG X-Received: by 2002:a05:600c:2303:b0:434:f335:83b with SMTP id 5b1f17b1804b1-4365c77e441mr26215515e9.5.1734610359393; Thu, 19 Dec 2024 04:12:39 -0800 (PST) X-Google-Smtp-Source: AGHT+IFp8w+yg9TiVsrWbDzZp13nv15+EZCExns15U2PsP9opFPSacpvlxA3rOl0ZzAZrcvWhUDiFg== X-Received: by 2002:a05:600c:2303:b0:434:f335:83b with SMTP id 5b1f17b1804b1-4365c77e441mr26215205e9.5.1734610358873; Thu, 19 Dec 2024 04:12:38 -0800 (PST) Received: from [192.168.10.47] ([151.81.118.45]) by smtp.gmail.com with ESMTPSA id ffacd0b85a97d-38a1c828897sm1416417f8f.20.2024.12.19.04.12.36 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 19 Dec 2024 04:12:36 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: zhao1.liu@intel.com Subject: [PATCH 09/10] rust: qemu-api-macros: extend error reporting facility to parse errors Date: Thu, 19 Dec 2024 13:12:15 +0100 Message-ID: <20241219121216.416905-10-pbonzini@redhat.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241219121216.416905-1-pbonzini@redhat.com> References: <20241219121216.416905-1-pbonzini@redhat.com> MIME-Version: 1.0 Received-SPF: pass client-ip=170.10.129.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -31 X-Spam_score: -3.2 X-Spam_bar: --- X-Spam_report: (-3.2 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.001, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H2=-1.116, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=ham 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+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Generalize the CompileError tuple to an enum, that can be either an error message or a parse error from syn. Signed-off-by: Paolo Bonzini --- rust/qemu-api-macros/src/lib.rs | 27 ++++++++++----------------- rust/qemu-api-macros/src/utils.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 17 deletions(-) create mode 100644 rust/qemu-api-macros/src/utils.rs diff --git a/rust/qemu-api-macros/src/lib.rs b/rust/qemu-api-macros/src/lib.rs index 0f04cca3841..539c48df298 100644 --- a/rust/qemu-api-macros/src/lib.rs +++ b/rust/qemu-api-macros/src/lib.rs @@ -3,57 +3,50 @@ // SPDX-License-Identifier: GPL-2.0-or-later use proc_macro::TokenStream; -use proc_macro2::Span; -use quote::{quote, quote_spanned}; +use quote::quote; use syn::{ parse_macro_input, parse_quote, punctuated::Punctuated, token::Comma, Data, DeriveInput, Field, Fields, Ident, Type, Visibility, }; -struct CompileError(String, Span); - -impl From for proc_macro2::TokenStream { - fn from(err: CompileError) -> Self { - let CompileError(msg, span) = err; - quote_spanned! { span => compile_error!(#msg); } - } -} +mod utils; +use utils::MacroError; fn get_fields<'a>( input: &'a DeriveInput, msg: &str, -) -> Result<&'a Punctuated, CompileError> { +) -> Result<&'a Punctuated, MacroError> { if let Data::Struct(s) = &input.data { if let Fields::Named(fs) = &s.fields { Ok(&fs.named) } else { - Err(CompileError( + Err(MacroError::Message( format!("Named fields required for {}", msg), input.ident.span(), )) } } else { - Err(CompileError( + Err(MacroError::Message( format!("Struct required for {}", msg), input.ident.span(), )) } } -fn is_c_repr(input: &DeriveInput, msg: &str) -> Result<(), CompileError> { +fn is_c_repr(input: &DeriveInput, msg: &str) -> Result<(), MacroError> { let expected = parse_quote! { #[repr(C)] }; if input.attrs.iter().any(|attr| attr == &expected) { Ok(()) } else { - Err(CompileError( + Err(MacroError::Message( format!("#[repr(C)] required for {}", msg), input.ident.span(), )) } } -fn derive_object_or_error(input: DeriveInput) -> Result { +fn derive_object_or_error(input: DeriveInput) -> Result { is_c_repr(&input, "#[derive(Object)]")?; let name = &input.ident; @@ -80,7 +73,7 @@ pub fn derive_object(input: TokenStream) -> TokenStream { } #[rustfmt::skip::macros(quote)] -fn derive_offsets_or_error(input: DeriveInput) -> Result { +fn derive_offsets_or_error(input: DeriveInput) -> Result { is_c_repr(&input, "#[derive(offsets)]")?; let name = &input.ident; diff --git a/rust/qemu-api-macros/src/utils.rs b/rust/qemu-api-macros/src/utils.rs new file mode 100644 index 00000000000..02c91aed7f6 --- /dev/null +++ b/rust/qemu-api-macros/src/utils.rs @@ -0,0 +1,26 @@ +// Procedural macro utilities. +// Author(s): Paolo Bonzini +// SPDX-License-Identifier: GPL-2.0-or-later + +use proc_macro2::Span; +use quote::quote_spanned; + +pub enum MacroError { + Message(String, Span), + ParseError(syn::Error), +} + +impl From for MacroError { + fn from(err: syn::Error) -> Self { + MacroError::ParseError(err) + } +} + +impl From for proc_macro2::TokenStream { + fn from(err: MacroError) -> Self { + match err { + MacroError::Message(msg, span) => quote_spanned! { span => compile_error!(#msg); }, + MacroError::ParseError(err) => err.into_compile_error(), + } + } +} From patchwork Thu Dec 19 12:12:16 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Paolo Bonzini X-Patchwork-Id: 13915263 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 38903E77184 for ; Thu, 19 Dec 2024 16:36:28 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tOJIq-0002IU-Q9; Thu, 19 Dec 2024 11:23:09 -0500 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 1tOFOb-0006F8-Qn for qemu-devel@nongnu.org; Thu, 19 Dec 2024 07:12:49 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.133.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tOFOa-0008Ig-1E for qemu-devel@nongnu.org; Thu, 19 Dec 2024 07:12:49 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1734610367; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=5CE9shW3ftWbl1V1SBQeRNzap/cYi489BVwR842VWpQ=; b=RAuV5t8jrKb+CdzFcJ2QhSgHE8z2tOojpORD3sFEG0QVWfRUFpfc4/bDt5msqkCg3xPDEZ /zdAVxtjFhJXvduHC839ZebRklmX5lgo0vqCi52kqVFLgoNT0WUnuNOWCa5KKWkcIzW3G3 dpOPm2QGlTXv3U32DqrCDPp+YGr5wdg= Received: from mail-wm1-f71.google.com (mail-wm1-f71.google.com [209.85.128.71]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-474-RoehPfcONdid58Ylk8sDRw-1; Thu, 19 Dec 2024 07:12:43 -0500 X-MC-Unique: RoehPfcONdid58Ylk8sDRw-1 X-Mimecast-MFC-AGG-ID: RoehPfcONdid58Ylk8sDRw Received: by mail-wm1-f71.google.com with SMTP id 5b1f17b1804b1-43623bf2a83so6110855e9.0 for ; Thu, 19 Dec 2024 04:12:42 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1734610361; x=1735215161; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=5CE9shW3ftWbl1V1SBQeRNzap/cYi489BVwR842VWpQ=; b=Z20wXL1gmDRFHs2mH1i0SuLoXmr2pljddTmZO3CgrDPYKRggvnrNmLusGnbRMNiVIx y10ZLqD6yLMdM1LFZ3KNTzkcjB3rpUuilHyAM6J1YvZg+TqLjGyzS+c6JiBZz46mK1iK ze5iXzZo88Vz+5J30yInP+L9isA85WUMNzPO1UTd5pG1v4NUx9vp6OsrsSWSHgetS3LY RVd3NsuHfFKfdkY8ofQWcM4jcLam7e9nFu9FPJ2Kzy3GyNCU7/51Q69cGYEHnL1w0wpV JfNx6s9WyTaMKKE+Go9XoJz8Lm9wDwIiicDOPQfxH0/VNw893cLDrN5f4xWK3yK5EzVp Iiqw== X-Gm-Message-State: AOJu0YxAGThBvkVvwziKvFwRlc4qR9b939/SaoJLdlHt6Lknjsrg+jZp SbjADor3cfb+xODzq/r84+vIH7LfRiyoWi03YjG/lUhGnwm1m3oyMWmFiopDd4VHJxFlF9zm8DS kqVpcgosj3SSAuw4Ip/a6C4Tt17YG7+qDlWl+YGiYELyHFXRxbrDZ5t4jiTOudbo4vRwUyVLGYZ BNb/Y8jGsAF5fzqM+VDTH7YX8HDJHNb3wXnL2i X-Gm-Gg: ASbGncts4/dWTEGCPoUs2MdLx6M2uTv6NH6XexrWDqyU6d17qHujJBdtERO72KvewxP VPAFYdJsX/pY9fNwWv2BTYXIZG6yF8NPE++oIl2ASW4cSVTHRs6NjUPqgcFvbDcB47XyCbk5/Rw thzjSqec7tbIQ0m5RmbjCqeuT4X4x9Kme+jGM3JGq1wKTVdVlKebWIdFf0L5uXq5j7dwYSQVi6Y VeEG/qRKdYesfFKo5JPaB/bDKnKIlMO0/1jGr4GWXDZlcS1daKaorAnFgSf X-Received: by 2002:a05:600c:3ca1:b0:434:fd77:5436 with SMTP id 5b1f17b1804b1-4365536f8eemr73738815e9.15.1734610360565; Thu, 19 Dec 2024 04:12:40 -0800 (PST) X-Google-Smtp-Source: AGHT+IFkPkv1lZx0+WC10VUGiiF9xcKhQWsT7rQcdcJRSaghwVuOXGOEhUoIP4n7wShv7b5j9hzDWQ== X-Received: by 2002:a05:600c:3ca1:b0:434:fd77:5436 with SMTP id 5b1f17b1804b1-4365536f8eemr73738435e9.15.1734610360083; Thu, 19 Dec 2024 04:12:40 -0800 (PST) Received: from [192.168.10.47] ([151.81.118.45]) by smtp.gmail.com with ESMTPSA id 5b1f17b1804b1-43661218f43sm16579525e9.19.2024.12.19.04.12.39 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 19 Dec 2024 04:12:39 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: zhao1.liu@intel.com Subject: [PATCH 10/10] rust: qemu-api-macros: add automatic TryFrom/TryInto derivation Date: Thu, 19 Dec 2024 13:12:16 +0100 Message-ID: <20241219121216.416905-11-pbonzini@redhat.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241219121216.416905-1-pbonzini@redhat.com> References: <20241219121216.416905-1-pbonzini@redhat.com> MIME-Version: 1.0 Received-SPF: pass client-ip=170.10.133.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -31 X-Spam_score: -3.2 X-Spam_bar: --- X-Spam_report: (-3.2 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.001, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H2=-1.116, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=ham 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+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org This is going to be fairly common. Using a custom procedural macro provides better error messages and automatically finds the right type. Note that this is different from the same-named macro in the derive_more crate. That one provides conversion from e.g. tuples to enums with tuple variants, not from integers to enums. Signed-off-by: Paolo Bonzini --- rust/hw/char/pl011/src/lib.rs | 28 +------------ rust/qemu-api-macros/src/lib.rs | 74 ++++++++++++++++++++++++++++++++- 2 files changed, 73 insertions(+), 29 deletions(-) diff --git a/rust/hw/char/pl011/src/lib.rs b/rust/hw/char/pl011/src/lib.rs index 69064d6929b..0a89d393e0f 100644 --- a/rust/hw/char/pl011/src/lib.rs +++ b/rust/hw/char/pl011/src/lib.rs @@ -45,7 +45,7 @@ #[doc(alias = "offset")] #[allow(non_camel_case_types)] #[repr(u64)] -#[derive(Debug)] +#[derive(Debug, qemu_api_macros::TryInto)] pub enum RegisterOffset { /// Data Register /// @@ -102,32 +102,6 @@ pub enum RegisterOffset { //Reserved = 0x04C, } -impl core::convert::TryFrom for RegisterOffset { - type Error = u64; - - fn try_from(value: u64) -> Result { - macro_rules! case { - ($($discriminant:ident),*$(,)*) => { - /* check that matching on all macro arguments compiles, which means we are not - * missing any enum value; if the type definition ever changes this will stop - * compiling. - */ - const fn _assert_exhaustive(val: RegisterOffset) { - match val { - $(RegisterOffset::$discriminant => (),)* - } - } - - match value { - $(x if x == Self::$discriminant as u64 => Ok(Self::$discriminant),)* - _ => Err(value), - } - } - } - case! { DR, RSR, FR, FBRD, ILPR, IBRD, LCR_H, CR, FLS, IMSC, RIS, MIS, ICR, DMACR } - } -} - pub mod registers { //! Device registers exposed as typed structs which are backed by arbitrary //! integer bitmaps. [`Data`], [`Control`], [`LineControl`], etc. diff --git a/rust/qemu-api-macros/src/lib.rs b/rust/qemu-api-macros/src/lib.rs index 539c48df298..7ec218202f4 100644 --- a/rust/qemu-api-macros/src/lib.rs +++ b/rust/qemu-api-macros/src/lib.rs @@ -5,8 +5,8 @@ use proc_macro::TokenStream; use quote::quote; use syn::{ - parse_macro_input, parse_quote, punctuated::Punctuated, token::Comma, Data, DeriveInput, Field, - Fields, Ident, Type, Visibility, + parse_macro_input, parse_quote, punctuated::Punctuated, spanned::Spanned, token::Comma, Data, + DeriveInput, Field, Fields, Ident, Meta, Path, Token, Type, Variant, Visibility, }; mod utils; @@ -98,3 +98,73 @@ pub fn derive_offsets(input: TokenStream) -> TokenStream { TokenStream::from(expanded) } + +#[allow(non_snake_case)] +fn get_repr_uN(input: &DeriveInput, msg: &str) -> Result { + let repr = input.attrs.iter().find(|attr| attr.path().is_ident("repr")); + if let Some(repr) = repr { + let nested = repr.parse_args_with(Punctuated::::parse_terminated)?; + for meta in nested { + match meta { + Meta::Path(path) if path.is_ident("u8") => return Ok(path), + Meta::Path(path) if path.is_ident("u16") => return Ok(path), + Meta::Path(path) if path.is_ident("u32") => return Ok(path), + Meta::Path(path) if path.is_ident("u64") => return Ok(path), + _ => {} + } + } + } + + Err(MacroError::Message( + format!("#[repr(u8/u16/u32/u64) required for {}", msg), + input.ident.span(), + )) +} + +fn get_variants(input: &DeriveInput) -> Result<&Punctuated, MacroError> { + if let Data::Enum(e) = &input.data { + if let Some(v) = e.variants.iter().find(|v| v.fields != Fields::Unit) { + return Err(MacroError::Message( + "Cannot derive TryInto for enum with non-unit variants.".to_string(), + v.fields.span(), + )); + } + Ok(&e.variants) + } else { + Err(MacroError::Message( + "Cannot derive TryInto for union or struct.".to_string(), + input.ident.span(), + )) + } +} + +#[rustfmt::skip::macros(quote)] +fn derive_tryinto_or_error(input: DeriveInput) -> Result { + let repr = get_repr_uN(&input, "#[derive(TryInto)]")?; + + let name = &input.ident; + let variants = get_variants(&input)?; + let discriminants: Vec<&Ident> = variants.iter().map(|f| &f.ident).collect(); + + Ok(quote! { + impl core::convert::TryFrom<#repr> for #name { + type Error = #repr; + + fn try_from(value: #repr) -> Result { + #(const #discriminants: #repr = #name::#discriminants as #repr;)*; + match value { + #(#discriminants => Ok(Self::#discriminants),)* + _ => Err(value), + } + } + } + }) +} + +#[proc_macro_derive(TryInto)] +pub fn derive_tryinto(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as DeriveInput); + let expanded = derive_tryinto_or_error(input).unwrap_or_else(Into::into); + + TokenStream::from(expanded) +}