From nobody Sat Nov 23 23:53:40 2024 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=redhat.com ARC-Seal: i=1; a=rsa-sha256; t=1728666972; cv=none; d=zohomail.com; s=zohoarc; b=Kq1KckTShdKWBmKHiO1iKgn5aJeknTx0v7uEH9UzvvmpCoUfDG5ybLqzaJ3jIXQ96VA2b+Y70qrsoeODDo6zN+qWowd8Pal0ZQU+fskixlMtoNLYWDA51/csK37Gj3DvtC2jbvjbNLe72xUDzWIGR9E880+kXZ1LKKmH7XVGw1g= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1728666972; h=Content-Transfer-Encoding:Cc:Cc:Date:Date:From:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:References:Sender:Subject:Subject:To:To:Message-Id:Reply-To; bh=kinzzcRWIY7fW3uY+q28/NRurKEz7TGCPrvgzsbL4iM=; b=V0bAUk4/Zrc0wCjC4ip04HqGFDjCQsimSF/wmiELA0Xn3fAEl0fCUNVjkU0v8j6AWIjr76wK1z7OZWWXqwYPy3PMqTHK7tLrttQDydzUosc8kyG+t/Wh155DREeHWTm2nqIeD+14GZ2NJrjRcRp85W8jT7dmq2UBb9UamdKYSwA= 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 172866697238999.8671270579714; Fri, 11 Oct 2024 10:16:12 -0700 (PDT) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1szJ4c-0001J9-Lf; Fri, 11 Oct 2024 13:05:06 -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 1szJ4T-0000wP-QC for qemu-devel@nongnu.org; Fri, 11 Oct 2024 13:04:57 -0400 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 1szHdf-0007E1-2z for qemu-devel@nongnu.org; Fri, 11 Oct 2024 11:33:15 -0400 Received: from mail-lf1-f72.google.com (mail-lf1-f72.google.com [209.85.167.72]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-3-QvrLBDIdOP2u5dXXB0eeDQ-1; Fri, 11 Oct 2024 11:33:06 -0400 Received: by mail-lf1-f72.google.com with SMTP id 2adb3069b0e04-5398ecc2a0cso2240650e87.3 for ; Fri, 11 Oct 2024 08:33:06 -0700 (PDT) Received: from avogadro.local ([151.81.124.37]) by smtp.gmail.com with ESMTPSA id a640c23a62f3a-a99a80dc638sm223354766b.169.2024.10.11.08.33.00 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 11 Oct 2024 08:33:01 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1728660788; 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=kinzzcRWIY7fW3uY+q28/NRurKEz7TGCPrvgzsbL4iM=; b=EGTyTCig203pHqdWs2YF7ftfMF2AcZxCwaLkB336fmu4bmgCwu1ViMqSBOgm9+YTQpUpu6 TpRvLbc7UGTarg5Y/pFliCTIWzMV55mCTSuTMKaWlH9PraJfDE8ZG0TtsKITmgcYiUvekU ZoffBoegv3EKbksQoBruSg9+Fy0ROIs= X-MC-Unique: QvrLBDIdOP2u5dXXB0eeDQ-1 X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1728660784; x=1729265584; 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=kinzzcRWIY7fW3uY+q28/NRurKEz7TGCPrvgzsbL4iM=; b=XiF1HTqHoxHkRgEdhFjDNM0dRl6BpBq9T0Ikj2dcDPb3VZJaBq2immhpBi6eY0pXj3 YxVcCXlVGT2KTvyngE8ce2WuCyeoNn4A4nV7Ess2hIsEyBKN2pHrKjD1hVww4CiYByEf VkXE/vgdCeOxSayWbr6OnZOTRYZU4uJ2z/oX/QNFGwX8HMsukBnQyt2KRdWu1d2AYLiI 4w8Hjj0MvxcZq5c79NJmL1jcNvW9HNxkcP6CvspJf+6QQv3kTbAWxv2UFjwvMb1RD62l qjIH2uRf5OT0yTFv9h39NjzyRUJxCru4UVln/iCPaj9lgyHsHiU/IRE9KZT8ZaGzZlDD gJ1g== X-Gm-Message-State: AOJu0YzE9EAAUTNbDhOPayefCUlCZOrmk5XQWTzoSEnDzW/sDZyG3/UA MncVtaxls2ITRDqwu2IyLKnKwMEi2W09VlSbRn/of2/tOBfKpTWh/RiARZwjus31Mk9Z93t398I x4OchPQS9HTgZv0kFrPGVCC+9xwYlf7qTD4vHtyghCLt/iD7Hb+QvKQlehuTI/EAfNuYtpWGJXn jb8e1qOUGqWvlqqQcF/MSVPvk4vW4VTaOF92frr8I= X-Received: by 2002:ac2:4f03:0:b0:539:905c:15c5 with SMTP id 2adb3069b0e04-539da4e2e26mr2636241e87.35.1728660784058; Fri, 11 Oct 2024 08:33:04 -0700 (PDT) X-Google-Smtp-Source: AGHT+IH8pW8tXNVnat6lGdX3UIB/J8vwevE0Ox2ojz7uYx0TuCsYbTLRQdW+YLoWX1v3ZvqJtJWWVQ== X-Received: by 2002:ac2:4f03:0:b0:539:905c:15c5 with SMTP id 2adb3069b0e04-539da4e2e26mr2636206e87.35.1728660783336; Fri, 11 Oct 2024 08:33:03 -0700 (PDT) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: Manos Pitsidianakis , Junjie Mao Subject: [PULL v3 07/18] rust: add crate to expose bindings and interfaces Date: Fri, 11 Oct 2024 17:32:15 +0200 Message-ID: <20241011153227.81770-8-pbonzini@redhat.com> X-Mailer: git-send-email 2.46.2 In-Reply-To: <20241011153227.81770-1-pbonzini@redhat.com> References: <20241011153227.81770-1-pbonzini@redhat.com> MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable 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=170.10.129.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -21 X-Spam_score: -2.2 X-Spam_bar: -- X-Spam_report: (-2.2 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.15, 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_H3=0.001, RCVD_IN_MSPIKE_WL=0.001, 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+importer=patchew.org@nongnu.org Sender: qemu-devel-bounces+importer=patchew.org@nongnu.org X-ZohoMail-DKIM: pass (identity @redhat.com) X-ZM-MESSAGEID: 1728666972905116600 Content-Type: text/plain; charset="utf-8" From: Manos Pitsidianakis Add rust/qemu-api, which exposes rust-bindgen generated FFI bindings and provides some declaration macros for symbols visible to the rest of QEMU. Co-authored-by: Junjie Mao Co-authored-by: Paolo Bonzini Signed-off-by: Junjie Mao Signed-off-by: Paolo Bonzini Signed-off-by: Manos Pitsidianakis Link: https://lore.kernel.org/r/0fb23fbe211761b263aacec03deaf85c0cc39995.17= 27961605.git.manos.pitsidianakis@linaro.org Signed-off-by: Paolo Bonzini --- MAINTAINERS | 6 ++ rust/meson.build | 1 + rust/qemu-api/.gitignore | 2 + rust/qemu-api/Cargo.lock | 7 ++ rust/qemu-api/Cargo.toml | 26 +++++ rust/qemu-api/README.md | 17 +++ rust/qemu-api/build.rs | 14 +++ rust/qemu-api/meson.build | 21 ++++ rust/qemu-api/src/definitions.rs | 97 +++++++++++++++++ rust/qemu-api/src/device_class.rs | 128 +++++++++++++++++++++++ rust/qemu-api/src/lib.rs | 166 ++++++++++++++++++++++++++++++ rust/qemu-api/src/tests.rs | 49 +++++++++ rust/rustfmt.toml | 7 ++ 13 files changed, 541 insertions(+) create mode 100644 rust/qemu-api/.gitignore create mode 100644 rust/qemu-api/Cargo.lock create mode 100644 rust/qemu-api/Cargo.toml create mode 100644 rust/qemu-api/README.md create mode 100644 rust/qemu-api/build.rs create mode 100644 rust/qemu-api/meson.build create mode 100644 rust/qemu-api/src/definitions.rs create mode 100644 rust/qemu-api/src/device_class.rs create mode 100644 rust/qemu-api/src/lib.rs create mode 100644 rust/qemu-api/src/tests.rs create mode 100644 rust/rustfmt.toml diff --git a/MAINTAINERS b/MAINTAINERS index f09029560b6..de583a16914 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -3291,6 +3291,12 @@ F: hw/core/register.c F: include/hw/register.h F: include/hw/registerfields.h =20 +Rust +M: Manos Pitsidianakis +S: Maintained +F: rust/qemu-api +F: rust/rustfmt.toml + SLIRP M: Samuel Thibault S: Maintained diff --git a/rust/meson.build b/rust/meson.build index e69de29bb2d..4a58d106b1d 100644 --- a/rust/meson.build +++ b/rust/meson.build @@ -0,0 +1 @@ +subdir('qemu-api') diff --git a/rust/qemu-api/.gitignore b/rust/qemu-api/.gitignore new file mode 100644 index 00000000000..b9e7e004c86 --- /dev/null +++ b/rust/qemu-api/.gitignore @@ -0,0 +1,2 @@ +# Ignore generated bindings file overrides. +src/bindings.rs diff --git a/rust/qemu-api/Cargo.lock b/rust/qemu-api/Cargo.lock new file mode 100644 index 00000000000..e9c51a243a8 --- /dev/null +++ b/rust/qemu-api/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version =3D 3 + +[[package]] +name =3D "qemu_api" +version =3D "0.1.0" diff --git a/rust/qemu-api/Cargo.toml b/rust/qemu-api/Cargo.toml new file mode 100644 index 00000000000..3677def3fe2 --- /dev/null +++ b/rust/qemu-api/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name =3D "qemu_api" +version =3D "0.1.0" +edition =3D "2021" +authors =3D ["Manos Pitsidianakis "] +license =3D "GPL-2.0-or-later" +readme =3D "README.md" +homepage =3D "https://www.qemu.org" +description =3D "Rust bindings for QEMU" +repository =3D "https://gitlab.com/qemu-project/qemu/" +resolver =3D "2" +publish =3D false +keywords =3D [] +categories =3D [] + +[dependencies] + +[features] +default =3D [] +allocator =3D [] + +# Do not include in any global workspace +[workspace] + +[lints.rust] +unexpected_cfgs =3D { level =3D "warn", check-cfg =3D ['cfg(MESON)', 'cfg(= HAVE_GLIB_WITH_ALIGNED_ALLOC)'] } diff --git a/rust/qemu-api/README.md b/rust/qemu-api/README.md new file mode 100644 index 00000000000..7588fa29ef3 --- /dev/null +++ b/rust/qemu-api/README.md @@ -0,0 +1,17 @@ +# QEMU bindings and API wrappers + +This library exports helper Rust types, Rust macros and C FFI bindings for= internal QEMU APIs. + +The C bindings can be generated with `bindgen`, using this build target: + +```console +$ ninja bindings.rs +``` + +## Generate Rust documentation + +To generate docs for this crate, including private items: + +```sh +cargo doc --no-deps --document-private-items +``` diff --git a/rust/qemu-api/build.rs b/rust/qemu-api/build.rs new file mode 100644 index 00000000000..419b154c2d2 --- /dev/null +++ b/rust/qemu-api/build.rs @@ -0,0 +1,14 @@ +// Copyright 2024, Linaro Limited +// Author(s): Manos Pitsidianakis +// SPDX-License-Identifier: GPL-2.0-or-later + +use std::path::Path; + +fn main() { + if !Path::new("src/bindings.rs").exists() { + panic!( + "No generated C bindings found! Either build them manually wit= h bindgen or with meson \ + (`ninja bindings.rs`) and copy them to src/bindings.rs, or bu= ild through meson." + ); + } +} diff --git a/rust/qemu-api/meson.build b/rust/qemu-api/meson.build new file mode 100644 index 00000000000..439ef73c29e --- /dev/null +++ b/rust/qemu-api/meson.build @@ -0,0 +1,21 @@ +_qemu_api_rs =3D static_library( + 'qemu_api', + structured_sources( + [ + 'src/lib.rs', + 'src/definitions.rs', + 'src/device_class.rs', + ], + {'.' : bindings_rs}, + ), + override_options: ['rust_std=3D2021', 'build.rust_std=3D2021'], + rust_abi: 'rust', + rust_args: rustc_args + [ + '--cfg', 'MESON', + # '--cfg', 'feature=3D"allocator"', + ], +) + +qemu_api =3D declare_dependency( + link_with: _qemu_api_rs, +) diff --git a/rust/qemu-api/src/definitions.rs b/rust/qemu-api/src/definitio= ns.rs new file mode 100644 index 00000000000..60bd3f8aaa6 --- /dev/null +++ b/rust/qemu-api/src/definitions.rs @@ -0,0 +1,97 @@ +// Copyright 2024, Linaro Limited +// Author(s): Manos Pitsidianakis +// SPDX-License-Identifier: GPL-2.0-or-later + +//! Definitions required by QEMU when registering a device. + +use ::core::ffi::{c_void, CStr}; + +use crate::bindings::{Object, ObjectClass, TypeInfo}; + +/// Trait a type must implement to be registered with QEMU. +pub trait ObjectImpl { + type Class; + const TYPE_INFO: TypeInfo; + const TYPE_NAME: &'static CStr; + const PARENT_TYPE_NAME: Option<&'static CStr>; + const ABSTRACT: bool; + const INSTANCE_INIT: Option; + const INSTANCE_POST_INIT: Option; + const INSTANCE_FINALIZE: Option; +} + +pub trait Class { + const CLASS_INIT: Option; + const CLASS_BASE_INIT: Option< + unsafe extern "C" fn(klass: *mut ObjectClass, data: *mut c_void), + >; +} + +#[macro_export] +macro_rules! module_init { + ($func:expr, $type:expr) =3D> { + #[used] + #[cfg_attr(target_os =3D "linux", link_section =3D ".ctors")] + #[cfg_attr(target_os =3D "macos", link_section =3D "__DATA,__mod_i= nit_func")] + #[cfg_attr(target_os =3D "windows", link_section =3D ".CRT$XCU")] + pub static LOAD_MODULE: extern "C" fn() =3D { + extern "C" fn __load() { + unsafe { + $crate::bindings::register_module_init(Some($func), $t= ype); + } + } + + __load + }; + }; + (qom: $func:ident =3D> $body:block) =3D> { + // NOTE: To have custom identifiers for the ctor func we need to e= ither supply + // them directly as a macro argument or create them with a proc ma= cro. + #[used] + #[cfg_attr(target_os =3D "linux", link_section =3D ".ctors")] + #[cfg_attr(target_os =3D "macos", link_section =3D "__DATA,__mod_i= nit_func")] + #[cfg_attr(target_os =3D "windows", link_section =3D ".CRT$XCU")] + pub static LOAD_MODULE: extern "C" fn() =3D { + extern "C" fn __load() { + #[no_mangle] + unsafe extern "C" fn $func() { + $body + } + + unsafe { + $crate::bindings::register_module_init( + Some($func), + $crate::bindings::module_init_type::MODULE_INIT_QO= M, + ); + } + } + + __load + }; + }; +} + +#[macro_export] +macro_rules! type_info { + ($t:ty) =3D> { + $crate::bindings::TypeInfo { + name: <$t as $crate::definitions::ObjectImpl>::TYPE_NAME.as_pt= r(), + parent: if let Some(pname) =3D <$t as $crate::definitions::Obj= ectImpl>::PARENT_TYPE_NAME { + pname.as_ptr() + } else { + ::core::ptr::null_mut() + }, + instance_size: ::core::mem::size_of::<$t>() as $crate::binding= s::size_t, + instance_align: ::core::mem::align_of::<$t>() as $crate::bindi= ngs::size_t, + instance_init: <$t as $crate::definitions::ObjectImpl>::INSTAN= CE_INIT, + instance_post_init: <$t as $crate::definitions::ObjectImpl>::I= NSTANCE_POST_INIT, + instance_finalize: <$t as $crate::definitions::ObjectImpl>::IN= STANCE_FINALIZE, + abstract_: <$t as $crate::definitions::ObjectImpl>::ABSTRACT, + class_size: ::core::mem::size_of::<<$t as $crate::definitions= ::ObjectImpl>::Class>() as $crate::bindings::size_t, + class_init: <<$t as $crate::definitions::ObjectImpl>::Class as= $crate::definitions::Class>::CLASS_INIT, + class_base_init: <<$t as $crate::definitions::ObjectImpl>::Cla= ss as $crate::definitions::Class>::CLASS_BASE_INIT, + class_data: ::core::ptr::null_mut(), + interfaces: ::core::ptr::null_mut(), + }; + } +} diff --git a/rust/qemu-api/src/device_class.rs b/rust/qemu-api/src/device_c= lass.rs new file mode 100644 index 00000000000..1ea95beb78d --- /dev/null +++ b/rust/qemu-api/src/device_class.rs @@ -0,0 +1,128 @@ +// Copyright 2024, Linaro Limited +// Author(s): Manos Pitsidianakis +// SPDX-License-Identifier: GPL-2.0-or-later + +use std::sync::OnceLock; + +use crate::bindings::Property; + +#[macro_export] +macro_rules! device_class_init { + ($func:ident, props =3D> $props:ident, realize_fn =3D> $realize_fn:exp= r, legacy_reset_fn =3D> $legacy_reset_fn:expr, vmsd =3D> $vmsd:ident$(,)*) = =3D> { + #[no_mangle] + pub unsafe extern "C" fn $func( + klass: *mut $crate::bindings::ObjectClass, + _: *mut ::core::ffi::c_void, + ) { + let mut dc =3D + ::core::ptr::NonNull::new(klass.cast::<$crate::bindings::D= eviceClass>()).unwrap(); + dc.as_mut().realize =3D $realize_fn; + dc.as_mut().vmsd =3D &$vmsd; + $crate::bindings::device_class_set_legacy_reset(dc.as_mut(), $= legacy_reset_fn); + $crate::bindings::device_class_set_props(dc.as_mut(), $props.a= s_mut_ptr()); + } + }; +} + +#[macro_export] +macro_rules! define_property { + ($name:expr, $state:ty, $field:expr, $prop:expr, $type:expr, default = =3D $defval:expr$(,)*) =3D> { + $crate::bindings::Property { + name: { + #[used] + static _TEMP: &::core::ffi::CStr =3D $name; + _TEMP.as_ptr() + }, + info: $prop, + offset: ::core::mem::offset_of!($state, $field) + .try_into() + .expect("Could not fit offset value to type"), + bitnr: 0, + bitmask: 0, + set_default: true, + defval: $crate::bindings::Property__bindgen_ty_1 { u: $defval.= into() }, + arrayoffset: 0, + arrayinfo: ::core::ptr::null(), + arrayfieldsize: 0, + link_type: ::core::ptr::null(), + } + }; + ($name:expr, $state:ty, $field:expr, $prop:expr, $type:expr$(,)*) =3D>= { + $crate::bindings::Property { + name: { + #[used] + static _TEMP: &::core::ffi::CStr =3D $name; + _TEMP.as_ptr() + }, + info: $prop, + offset: ::core::mem::offset_of!($state, $field) + .try_into() + .expect("Could not fit offset value to type"), + bitnr: 0, + bitmask: 0, + set_default: false, + defval: $crate::bindings::Property__bindgen_ty_1 { i: 0 }, + arrayoffset: 0, + arrayinfo: ::core::ptr::null(), + arrayfieldsize: 0, + link_type: ::core::ptr::null(), + } + }; +} + +#[repr(C)] +pub struct Properties(pub OnceLock<[Property; N]>, pub fn(= ) -> [Property; N]); + +impl Properties { + pub fn as_mut_ptr(&mut self) -> *mut Property { + _ =3D self.0.get_or_init(self.1); + self.0.get_mut().unwrap().as_mut_ptr() + } +} + +#[macro_export] +macro_rules! declare_properties { + ($ident:ident, $($prop:expr),*$(,)*) =3D> { + + const fn _calc_prop_len() -> usize { + let mut len =3D 1; + $({ + _ =3D stringify!($prop); + len +=3D 1; + })* + len + } + const PROP_LEN: usize =3D _calc_prop_len(); + + fn _make_properties() -> [$crate::bindings::Property; PROP_LEN] { + [ + $($prop),*, + unsafe { ::core::mem::MaybeUninit::<$crate::bindings::= Property>::zeroed().assume_init() }, + ] + } + + #[no_mangle] + pub static mut $ident: $crate::device_class::Properties = =3D $crate::device_class::Properties(::std::sync::OnceLock::new(), _make_pr= operties); + }; +} + +#[macro_export] +macro_rules! vm_state_description { + ($(#[$outer:meta])* + $name:ident, + $(name: $vname:expr,)* + $(unmigratable: $um_val:expr,)* + ) =3D> { + #[used] + $(#[$outer])* + pub static $name: $crate::bindings::VMStateDescription =3D $crate:= :bindings::VMStateDescription { + $(name: { + #[used] + static VMSTATE_NAME: &::core::ffi::CStr =3D $vname; + $vname.as_ptr() + },)* + unmigratable: true, + ..unsafe { ::core::mem::MaybeUninit::<$crate::bindings::VMStat= eDescription>::zeroed().assume_init() } + }; + } +} diff --git a/rust/qemu-api/src/lib.rs b/rust/qemu-api/src/lib.rs new file mode 100644 index 00000000000..e72fb4b4bb1 --- /dev/null +++ b/rust/qemu-api/src/lib.rs @@ -0,0 +1,166 @@ +// Copyright 2024, Linaro Limited +// Author(s): Manos Pitsidianakis +// SPDX-License-Identifier: GPL-2.0-or-later + +#![cfg_attr(not(MESON), doc =3D include_str!("../README.md"))] + +#[allow( + dead_code, + improper_ctypes_definitions, + improper_ctypes, + non_camel_case_types, + non_snake_case, + non_upper_case_globals, + unsafe_op_in_unsafe_fn, + clippy::missing_const_for_fn, + clippy::too_many_arguments, + clippy::approx_constant, + clippy::use_self, + clippy::useless_transmute, + clippy::missing_safety_doc, +)] +#[rustfmt::skip] +pub mod bindings; + +unsafe impl Send for bindings::Property {} +unsafe impl Sync for bindings::Property {} +unsafe impl Sync for bindings::TypeInfo {} +unsafe impl Sync for bindings::VMStateDescription {} + +pub mod definitions; +pub mod device_class; + +#[cfg(test)] +mod tests; + +use std::alloc::{GlobalAlloc, Layout}; + +#[cfg(HAVE_GLIB_WITH_ALIGNED_ALLOC)] +extern "C" { + fn g_aligned_alloc0( + n_blocks: bindings::gsize, + n_block_bytes: bindings::gsize, + alignment: bindings::gsize, + ) -> bindings::gpointer; + fn g_aligned_free(mem: bindings::gpointer); +} + +#[cfg(not(HAVE_GLIB_WITH_ALIGNED_ALLOC))] +extern "C" { + fn qemu_memalign(alignment: usize, size: usize) -> *mut ::core::ffi::c= _void; + fn qemu_vfree(ptr: *mut ::core::ffi::c_void); +} + +extern "C" { + fn g_malloc0(n_bytes: bindings::gsize) -> bindings::gpointer; + fn g_free(mem: bindings::gpointer); +} + +/// An allocator that uses the same allocator as QEMU in C. +/// +/// It is enabled by default with the `allocator` feature. +/// +/// To set it up manually as a global allocator in your crate: +/// +/// ```ignore +/// use qemu_api::QemuAllocator; +/// +/// #[global_allocator] +/// static GLOBAL: QemuAllocator =3D QemuAllocator::new(); +/// ``` +#[derive(Clone, Copy, Debug)] +#[repr(C)] +pub struct QemuAllocator { + _unused: [u8; 0], +} + +#[cfg_attr(all(feature =3D "allocator", not(test)), global_allocator)] +pub static GLOBAL: QemuAllocator =3D QemuAllocator::new(); + +impl QemuAllocator { + // From the glibc documentation, on GNU systems, malloc guarantees 16-= byte + // alignment on 64-bit systems and 8-byte alignment on 32-bit systems.= See + // https://www.gnu.org/software/libc/manual/html_node/Malloc-Examples.= html. + // This alignment guarantee also applies to Windows and Android. On Da= rwin + // and OpenBSD, the alignment is 16 bytes on both 64-bit and 32-bit sy= stems. + #[cfg(all( + target_pointer_width =3D "32", + not(any(target_os =3D "macos", target_os =3D "openbsd")) + ))] + pub const DEFAULT_ALIGNMENT_BYTES: Option =3D Some(8); + #[cfg(all( + target_pointer_width =3D "64", + not(any(target_os =3D "macos", target_os =3D "openbsd")) + ))] + pub const DEFAULT_ALIGNMENT_BYTES: Option =3D Some(16); + #[cfg(all( + any(target_pointer_width =3D "32", target_pointer_width =3D "64"), + any(target_os =3D "macos", target_os =3D "openbsd") + ))] + pub const DEFAULT_ALIGNMENT_BYTES: Option =3D Some(16); + #[cfg(not(any(target_pointer_width =3D "32", target_pointer_width =3D = "64")))] + pub const DEFAULT_ALIGNMENT_BYTES: Option =3D None; + + pub const fn new() -> Self { + Self { _unused: [] } + } +} + +impl Default for QemuAllocator { + fn default() -> Self { + Self::new() + } +} + +// Sanity check. +const _: [(); 8] =3D [(); ::core::mem::size_of::<*mut ::core::ffi::c_void>= ()]; + +unsafe impl GlobalAlloc for QemuAllocator { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + if matches!(Self::DEFAULT_ALIGNMENT_BYTES, Some(default) if defaul= t.checked_rem(layout.align()) =3D=3D Some(0)) + { + // SAFETY: g_malloc0() is safe to call. + unsafe { g_malloc0(layout.size().try_into().unwrap()).cast::() } + } else { + #[cfg(HAVE_GLIB_WITH_ALIGNED_ALLOC)] + { + // SAFETY: g_aligned_alloc0() is safe to call. + unsafe { + g_aligned_alloc0( + layout.size().try_into().unwrap(), + 1, + layout.align().try_into().unwrap(), + ) + .cast::() + } + } + #[cfg(not(HAVE_GLIB_WITH_ALIGNED_ALLOC))] + { + // SAFETY: qemu_memalign() is safe to call. + unsafe { qemu_memalign(layout.align(), layout.size()).cast= ::() } + } + } + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + if matches!(Self::DEFAULT_ALIGNMENT_BYTES, Some(default) if defaul= t.checked_rem(layout.align()) =3D=3D Some(0)) + { + // SAFETY: `ptr` must have been allocated by Self::alloc thus = a valid + // glib-allocated pointer, so `g_free`ing is safe. + unsafe { g_free(ptr.cast::<_>()) } + } else { + #[cfg(HAVE_GLIB_WITH_ALIGNED_ALLOC)] + { + // SAFETY: `ptr` must have been allocated by Self::alloc t= hus a valid aligned + // glib-allocated pointer, so `g_aligned_free`ing is safe. + unsafe { g_aligned_free(ptr.cast::<_>()) } + } + #[cfg(not(HAVE_GLIB_WITH_ALIGNED_ALLOC))] + { + // SAFETY: `ptr` must have been allocated by Self::alloc t= hus a valid aligned + // glib-allocated pointer, so `qemu_vfree`ing is safe. + unsafe { qemu_vfree(ptr.cast::<_>()) } + } + } + } +} diff --git a/rust/qemu-api/src/tests.rs b/rust/qemu-api/src/tests.rs new file mode 100644 index 00000000000..df54edbd4e2 --- /dev/null +++ b/rust/qemu-api/src/tests.rs @@ -0,0 +1,49 @@ +// Copyright 2024, Linaro Limited +// Author(s): Manos Pitsidianakis +// SPDX-License-Identifier: GPL-2.0-or-later + +use crate::{ + bindings::*, declare_properties, define_property, device_class_init, v= m_state_description, +}; + +#[test] +fn test_device_decl_macros() { + // Test that macros can compile. + vm_state_description! { + VMSTATE, + name: c"name", + unmigratable: true, + } + + #[repr(C)] + pub struct DummyState { + pub char_backend: CharBackend, + pub migrate_clock: bool, + } + + declare_properties! { + DUMMY_PROPERTIES, + define_property!( + c"chardev", + DummyState, + char_backend, + unsafe { &qdev_prop_chr }, + CharBackend + ), + define_property!( + c"migrate-clk", + DummyState, + migrate_clock, + unsafe { &qdev_prop_bool }, + bool + ), + } + + device_class_init! { + dummy_class_init, + props =3D> DUMMY_PROPERTIES, + realize_fn =3D> None, + reset_fn =3D> None, + vmsd =3D> VMSTATE, + } +} diff --git a/rust/rustfmt.toml b/rust/rustfmt.toml new file mode 100644 index 00000000000..ebecb99fe09 --- /dev/null +++ b/rust/rustfmt.toml @@ -0,0 +1,7 @@ +edition =3D "2021" +format_generated_files =3D false +format_code_in_doc_comments =3D true +format_strings =3D true +imports_granularity =3D "Crate" +group_imports =3D "StdExternalCrate" +wrap_comments =3D true --=20 2.46.2