From nobody Thu Dec 18 08:53:03 2025 Received: from mail-pg1-f202.google.com (mail-pg1-f202.google.com [209.85.215.202]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id F2258263F52 for ; Tue, 16 Dec 2025 00:44:53 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.215.202 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1765845896; cv=none; b=DQIzGBTHhjwYsm/4x4GpaUNNkHyccC27tTW1ZwK6flvxuA9kv2HvSPA05KzpSB4VXG99g0CfEsAoK0SunSwAi/NQc/bgP9e4QWeX3cBMapQGMUF5Kvy73nGdxZhbEkwDhf6/uW977pjeW+srcWzQcJ6pDsbXF0Bxe/Ek5QOf6Cc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1765845896; c=relaxed/simple; bh=zWmWPrNOhUkM882JMpbDBfEGQcxG/fITkb9z+Trg0V8=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=Wo8Md37RQOUDfJrceaQwx3gs2DbE7QETXgsDEWvRC9ZQ8TBlzJK/Ed+iaZsaFZ327dM9M+m1qDN5lUwSlilcUmqfTJOliAaTxvvPd0tNdiiOvTjUMD721Itppp5TUvPdapm6feUr22aBiMG6LYaw3ctPzqChLLrzuCjBPqZyseA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--mmaurer.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=irvSTSY0; arc=none smtp.client-ip=209.85.215.202 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--mmaurer.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="irvSTSY0" Received: by mail-pg1-f202.google.com with SMTP id 41be03b00d2f7-b9b9e8b0812so6695454a12.0 for ; Mon, 15 Dec 2025 16:44:53 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1765845893; x=1766450693; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=cEnDmHEq/pjEOk2KbWPaIkOgwqje/3X84mpIIYgLImI=; b=irvSTSY0F9l89sut/Y3Rx4BbbLpj4feEMCN8G+IkECTrg4a1kdzYbxKZdKh4d1n1x7 uFUKKWj+8KxvIjeyP1d6/zr37o7u/HY0DZCimmd7y6oRLSUcQCGJ+HWtJNvP1uOJq68d jtlh54nb+fgkI/Y3vL+CHu01fouGs6WjYSHY9U98836BOOq+ZDzHwVuYh53R5xMpmWa8 Wj2gVg5DnYnfzENSVWGwPtn1xZGFvFCU4Tmx7QS+NznWzIfCumu43ew1t0JZSCwhiFS2 j+xqGiFMAereyVH5W3N1sWFvS9v7z5Z/Og2sFN2sHko/Lw1qQWPFRDM7++DFZbdthxWO ypmA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1765845893; x=1766450693; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=cEnDmHEq/pjEOk2KbWPaIkOgwqje/3X84mpIIYgLImI=; b=TsECQm01FCHhgXbNA/6vkATfoMaNz70G0shWTBk4EwfB6MsWoDtyF4Jqw2+55/4kuL 1jyQg+ADeHW5/V0LNpDv8dGbzbnhwOGS1JgB0oK66nhxqQnqFwQhpYvx+DUHp5lR+Qcv fHrfqQ4QxfWHJ8pNotYxpEQxj7VMyEZImtuz4+nSw5E3l55sjmvYfU9DF8PAaHKa8ePY ywnLl0tPo4FwHKuFqfukeohkiSzUzoEmVAGPJjikZTVQc+R/HN7ipiD9cqzgQFHzr/+n Jsship70h5/eW35DKUZqH8AEWXLUnzhxJfiYDJlA+sTN0sauDTcH+oe5AricawphU7Uw Qsuw== X-Forwarded-Encrypted: i=1; AJvYcCXtaHTXuTOkAwPx7IP1NfDo/5lHDZTbjLQGTe/TK+bT++PrNMj1y0yRRqsJU3K37rpYPnCxzAHXvwn0Guo=@vger.kernel.org X-Gm-Message-State: AOJu0YyarGfiLr3wia0/YNoF1bcihMLnz10U6eQjGy/O2HZPBv0bcHrK g0oly8JLEBHmxRoltjRIH1q2lCZc43ODOtWn6chbSbwIGlDM5HpShi9A6z6tqPiF07vbDlXT2xy CxKboeDQ0Jw== X-Google-Smtp-Source: AGHT+IGRZPMQ2yBe0NhIvb5hOnB2DN4D4G61oVHxl7WF0Mdjz4pPXx29w9FfD3xZ46WBgKt50LDhqF9T4TV7 X-Received: from dyki18.prod.google.com ([2002:a05:7300:7c12:b0:2ac:1eee:fdb4]) (user=mmaurer job=prod-delivery.src-stubby-dispatcher) by 2002:a05:7301:df44:b0:2a4:7fb3:7a96 with SMTP id 5a478bee46e88-2ac3014694emr7291095eec.36.1765845893134; Mon, 15 Dec 2025 16:44:53 -0800 (PST) Date: Tue, 16 Dec 2025 00:44:41 +0000 In-Reply-To: <20251216-transmute-v2-0-b23e5277ad02@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20251216-transmute-v2-0-b23e5277ad02@google.com> X-Developer-Key: i=mmaurer@google.com; a=ed25519; pk=2Ezhl7+fEjTOMVFpplDeak2AdQ8cjJieLRVJdNzrW+E= X-Developer-Signature: v=1; a=ed25519-sha256; t=1765845890; l=3786; i=mmaurer@google.com; s=20250429; h=from:subject:message-id; bh=zWmWPrNOhUkM882JMpbDBfEGQcxG/fITkb9z+Trg0V8=; b=gi00nijuT2TpF/lR3rXX31OTfUtcwxGU0aW4+os2xhsYPx12A8zt05wJ2d5wQPaQFFxPyYnAT Ws6J/pxRM1vAe6a2m82ebV7KlIBKOmy5JfQtFfWVgt065/ITyEPrYC1 X-Mailer: b4 0.14.2 Message-ID: <20251216-transmute-v2-1-b23e5277ad02@google.com> Subject: [PATCH v2 1/3] rust: transmute: Support transmuting slices of AsBytes/FromBytes types From: Matthew Maurer To: Miguel Ojeda , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Matthew Maurer Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Currently, we support either transmuting a byte slice of the exact size of the target type or a single element from a prefix of a byte slice. This adds support for transmuting from a byte slice to a slice of elements, assuming appropriate traits are implemented. Signed-off-by: Matthew Maurer Reviewed-by: Daniel Almeida --- rust/kernel/transmute.rs | 72 ++++++++++++++++++++++++++++++++++++++++++++= ++++ 1 file changed, 72 insertions(+) diff --git a/rust/kernel/transmute.rs b/rust/kernel/transmute.rs index be5dbf3829e25c92f85083cc0f4940f35bb7baec..5cc5f4fde4c31cea3c51ab078b4= d68f3a0a2caa1 100644 --- a/rust/kernel/transmute.rs +++ b/rust/kernel/transmute.rs @@ -122,6 +122,78 @@ fn from_bytes_mut_prefix(bytes: &mut [u8]) -> Option<(= &mut Self, &mut [u8])> } } =20 + /// Converts a slice of bytes to a slice of `Self`. + /// + /// Succeeds if the reference is properly aligned, and the size of `by= tes` is a multiple of that + /// of `Self`. + /// + /// Otherwise, returns [`None`]. + fn from_bytes_to_slice(bytes: &[u8]) -> Option<&[Self]> + where + Self: Sized, + { + let size =3D size_of::(); + if size =3D=3D 0 { + return None; + } + if bytes.len() % size !=3D 0 { + return None; + } + let len =3D bytes.len() / size; + let ptr =3D bytes.as_ptr().cast::(); + + #[allow(clippy::incompatible_msrv)] + if ptr.is_aligned() { + // SAFETY: + // - `ptr` is valid for reads of `bytes.len()` bytes, which is + // `len * size_of::()`. + // - `ptr` is aligned for `Self`. + // - `ptr` points to `len` consecutive properly initialized va= lues of type `Self` + // because `Self` implements `FromBytes` (any bit pattern is= valid). + // - The lifetime of the returned slice is bound to the input = `bytes`. + unsafe { Some(core::slice::from_raw_parts(ptr, len)) } + } else { + None + } + } + + /// Converts a mutable slice of bytes to a mutable slice of `Self`. + /// + /// Succeeds if the reference is properly aligned, and the size of `by= tes` is a multiple of that + /// of `Self`. + /// + /// Otherwise, returns [`None`]. + fn from_bytes_to_mut_slice(bytes: &mut [u8]) -> Option<&mut [Self]> + where + Self: AsBytes + Sized, + { + let size =3D size_of::(); + if size =3D=3D 0 { + return None; + } + if bytes.len() % size !=3D 0 { + return None; + } + let len =3D bytes.len() / size; + let ptr =3D bytes.as_mut_ptr().cast::(); + + #[allow(clippy::incompatible_msrv)] + if ptr.is_aligned() { + // SAFETY: + // - `ptr` is valid for reads and writes of `bytes.len()` byte= s, which is + // `len * size_of::()`. + // - `ptr` is aligned for `Self`. + // - `ptr` points to `len` consecutive properly initialized va= lues of type `Self` + // because `Self` implements `FromBytes`. + // - `AsBytes` guarantees that writing a new `Self` to the res= ulting slice can safely + // be reflected as bytes in the original slice. + // - The lifetime of the returned slice is bound to the input = `bytes`. + unsafe { Some(core::slice::from_raw_parts_mut(ptr, len)) } + } else { + None + } + } + /// Creates an owned instance of `Self` by copying `bytes`. /// /// Unlike [`FromBytes::from_bytes`], which requires aligned input, th= is method can be used on --=20 2.52.0.305.g3fc767764a-goog From nobody Thu Dec 18 08:53:03 2025 Received: from mail-pg1-f202.google.com (mail-pg1-f202.google.com [209.85.215.202]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 8A56226E708 for ; Tue, 16 Dec 2025 00:44:55 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.215.202 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1765845897; cv=none; b=qbOWUOKFiXRM4p+DripXW0bVwEc1FTkY11qVGJ2W+mojx+xuEtqTpqQtj53A6DLkYiMNnnAuqEjXicAPzQ7UsmZTDPWG18DGJS9i0S6ggbsTapFh1jYWv8T7m38AqZfY6V2/AXKqC11ewSSL7Nz8q0Ov4F1X5PZfIXlaBr0h97Q= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1765845897; c=relaxed/simple; bh=6wygOt1D76qaraHZDNszRyQ5DIBdZPIQXleSdYwh9us=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=F6LLyPDsO9xkImgfLRl5wxu8J/6tvYp3P/KpuBhWZ6/qcGQ58p6IyaMv84w2ie6GPZH7NmTbMPzSaNXgq0GhhRyx5DkgWzZE/28efjRRGHEIyDb9PU6MXg6zJ6OL5mjFyEyiloYJvfARmW7mZp63dRSi0/ewKioSALPqkfFjNpM= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--mmaurer.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=r/8spQtu; arc=none smtp.client-ip=209.85.215.202 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--mmaurer.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="r/8spQtu" Received: by mail-pg1-f202.google.com with SMTP id 41be03b00d2f7-b993eb2701bso3945712a12.0 for ; Mon, 15 Dec 2025 16:44:55 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1765845895; x=1766450695; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=ZfIR7uowxPfrBGm0h5/0Sac13z+XC1w8PXgcnbB/c+4=; b=r/8spQtu5LkJZaTKq9IiDotDFMPuUvucKRBk4/uHhAgJKknNNP3egqIQtU9ekCE4yo aQMiBR0m2y2FjkiCaP5w8lVv6eIC+l50+miNYv32zZmU5ku/Ai2R4UR8qmSCTZftJbxV KtxNX6flzbtOINHwfBL4GReHquZJxSQJbwngdGDFoZdWxNln/Z3HfG4OwPq9n/CoC5zv 9coBS5p2wp20gYNjc6qjZb+MxgPZ18DILNVn9dJAoEYeOS+LOGYHZYHBesDs8HmRa2fM 5kDLxQu1zgKubqi+xhNg8ajbgQ2B1f3wq/NCX1q7ELERYBiLnAWE4ZSAjDnyb2/QEy0t y35A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1765845895; x=1766450695; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=ZfIR7uowxPfrBGm0h5/0Sac13z+XC1w8PXgcnbB/c+4=; b=obPDPMheMstOWz5luzqE9EjRe9oz3yV+1Qgr6GWwIi0BGfNUm1B740x5hx3FJaq/Fp 7AFcpUxmA1f1Sx6Oyy6ztjwaQhUEpUeCZ+bC5e5PCl3j4aJMEED7IyYqzjQZ8yO/OfVH b7ZvKON3VrhvdQIn+/cbQmVpsWj6GkMW/Jrfi6388ptUHKvTL3p0EFLB1foYTGSrWk4c gg1mMJGqJ8zgu5EwDJB5rPJcXkza4IH2QejfHtaI2f6NVAgC3qo8gOrmMlaBM/IA0RNN XonPXhhAVUkH2efZdx1Qeg9Ter8gD7nq+A62WOqf0fsflvTrdsMCQlakY50ziRfrbg9h lXhA== X-Forwarded-Encrypted: i=1; AJvYcCUjvrYJNVERbtZRv+xnB052CDgbbyWgNYIS+sXCw9yeXtLWmhhF8A0IZi3wHzz9a+UNjGlwKD1wu0AFruE=@vger.kernel.org X-Gm-Message-State: AOJu0Yy0AdY01jc46jmjZN6MzgF/c0Oo1QuZobaxAgH2t73rnoY2NQ2p lxg1982Bhw8ZOjprYnNn2g1rJcHn8FBrpgGe8+N3oE9zJyYB740J9BNjENjmC0BPfKMJHaS6nux YcAn7DhLSMw== X-Google-Smtp-Source: AGHT+IFqSf3q193P4LBHoVV6viSmK6DVC79Cs1RUnidxl/IY+cL+SDg3bXJP2FIPBC25IfMmPtxP8JpuNH8b X-Received: from dlkk32.prod.google.com ([2002:a05:7022:60a0:b0:11d:cf7a:5407]) (user=mmaurer job=prod-delivery.src-stubby-dispatcher) by 2002:a05:7022:6982:b0:11f:2c69:2d with SMTP id a92af1059eb24-11f34c2f2fbmr9887359c88.45.1765845894728; Mon, 15 Dec 2025 16:44:54 -0800 (PST) Date: Tue, 16 Dec 2025 00:44:42 +0000 In-Reply-To: <20251216-transmute-v2-0-b23e5277ad02@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20251216-transmute-v2-0-b23e5277ad02@google.com> X-Developer-Key: i=mmaurer@google.com; a=ed25519; pk=2Ezhl7+fEjTOMVFpplDeak2AdQ8cjJieLRVJdNzrW+E= X-Developer-Signature: v=1; a=ed25519-sha256; t=1765845890; l=5561; i=mmaurer@google.com; s=20250429; h=from:subject:message-id; bh=6wygOt1D76qaraHZDNszRyQ5DIBdZPIQXleSdYwh9us=; b=pIydZKX38osjwrZhA1nMfCFpTpxKPqd2SJF4SsLsdCdGf3IjsXuXYhZOzPebrFIKjn/FzJmv+ AlLs3q9lkpVA8is9WxX2c98oCDi8+ct34SbR7c3BDTkBL8cyUk1WoUy X-Mailer: b4 0.14.2 Message-ID: <20251216-transmute-v2-2-b23e5277ad02@google.com> Subject: [PATCH v2 2/3] rust: Add support for deriving `AsBytes` and `FromBytes` From: Matthew Maurer To: Miguel Ojeda , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Matthew Maurer Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable This provides a derive macro for `AsBytes` and `FromBytes` for structs only. For both, it checks the respective trait on every underlying field. For `AsBytes`, it emits a const-time padding check that will fail the compilation if derived on a type with padding. Signed-off-by: Matthew Maurer --- rust/macros/lib.rs | 63 ++++++++++++++++++++++++++++++++++++++++++++= ++++ rust/macros/transmute.rs | 58 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 121 insertions(+) diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index b38002151871a33f6b4efea70be2deb6ddad38e2..d66397942529f67697f74a908e2= 57cacc4201d84 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -20,9 +20,14 @@ mod kunit; mod module; mod paste; +mod transmute; mod vtable; =20 use proc_macro::TokenStream; +use syn::{ + parse_macro_input, + DeriveInput, // +}; =20 /// Declares a kernel module. /// @@ -475,3 +480,61 @@ pub fn paste(input: TokenStream) -> TokenStream { pub fn kunit_tests(attr: TokenStream, ts: TokenStream) -> TokenStream { kunit::kunit_tests(attr, ts) } + +/// Implements `FromBytes` for a struct. +/// +/// It will fail compilation if the struct you are deriving on cannot be d= etermined to implement +/// `FromBytes` safely. It may still fail for some types which would be sa= fe to implement +/// `FromBytes` for, in which case you will need to write the implementati= on and justification +/// yourself. +/// +/// Main reasons your type may be rejected: +/// * Not a `struct` +/// * One of the fields is not `FromBytes` +/// +/// # Examples +/// +/// ``` +/// #[derive(FromBytes)] +/// #[repr(C)] +/// struct Foo { +/// x: u32, +/// y: u16, +/// z: u16, +/// } +/// ``` +#[proc_macro_derive(FromBytes)] +pub fn derive_from_bytes(tokens: TokenStream) -> TokenStream { + let input =3D parse_macro_input!(tokens as DeriveInput); + transmute::from_bytes(input).into() +} + +/// Implements `AsBytes` for a struct. +/// +/// It will fail compilation if the struct you are deriving on cannot be d= etermined to implement +/// `AsBytes` safely. It may still fail for some structures which would be= safe to implement +/// `AsBytes`, in which case you will need to write the implementation and= justification +/// yourself. +/// +/// Main reasons your type may be rejected: +/// * Not a `struct` +/// * One of the fields is not `AsBytes` +/// * Your struct has generic parameters +/// * There is padding somewhere in your struct +/// +/// # Examples +/// +/// ``` +/// #[derive(AsBytes)] +/// #[repr(C)] +/// struct Foo { +/// x: u32, +/// y: u16, +/// z: u16, +/// } +/// ``` +#[proc_macro_derive(AsBytes)] +pub fn derive_as_bytes(tokens: TokenStream) -> TokenStream { + let input =3D parse_macro_input!(tokens as DeriveInput); + transmute::as_bytes(input).into() +} diff --git a/rust/macros/transmute.rs b/rust/macros/transmute.rs new file mode 100644 index 0000000000000000000000000000000000000000..43cf36a1334f1fed23c0e777026= 392f987f78d8d --- /dev/null +++ b/rust/macros/transmute.rs @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: GPL-2.0 + +use proc_macro2::TokenStream; +use syn::{parse_quote, DeriveInput, Fields, Ident, ItemConst, Path, WhereC= lause}; + +fn all_fields_impl(fields: &Fields, trait_: &Path) -> WhereClause { + let tys =3D fields.iter().map(|field| &field.ty); + parse_quote! { + where #(for<'a> #tys: #trait_),* + } +} + +fn struct_padding_check(fields: &Fields, name: &Ident) -> ItemConst { + let tys =3D fields.iter().map(|field| &field.ty); + parse_quote! { + const _: () =3D { + assert!(#(core::mem::size_of::<#tys>())+* =3D=3D core::mem::si= ze_of::<#name>()); + }; + } +} + +pub(crate) fn as_bytes(input: DeriveInput) -> TokenStream { + if !input.generics.params.is_empty() { + return quote::quote! { compile_error!("#[derive(AsBytes)] does not= support generics") }; + } + let syn::Data::Struct(ref ds) =3D &input.data else { + return quote::quote! { compile_error!("#[derive(AsBytes)] only sup= ports structs") }; + }; + let name =3D input.ident; + let trait_ =3D parse_quote! { ::kernel::transmute::AsBytes }; + let where_clause =3D all_fields_impl(&ds.fields, &trait_); + let padding_check =3D struct_padding_check(&ds.fields, &name); + quote::quote! { + #padding_check + // SAFETY: #name has no padding and all of its fields implement `A= sBytes` + unsafe impl #trait_ for #name #where_clause {} + } +} + +pub(crate) fn from_bytes(input: DeriveInput) -> TokenStream { + let syn::Data::Struct(ref ds) =3D &input.data else { + return quote::quote! { compile_error!("#[derive(FromBytes)] only s= upports structs") }; + }; + let (impl_generics, ty_generics, base_where_clause) =3D input.generics= .split_for_impl(); + let name =3D input.ident; + let trait_ =3D parse_quote! { ::kernel::transmute::FromBytes }; + let mut where_clause =3D all_fields_impl(&ds.fields, &trait_); + if let Some(base_clause) =3D base_where_clause { + where_clause + .predicates + .extend(base_clause.predicates.clone()) + }; + quote::quote! { + // SAFETY: All fields of #name implement `FromBytes` and it is a s= truct, so there is no + // implicit discriminator. + unsafe impl #impl_generics #trait_ for #name #ty_generics #where_c= lause {} + } +} --=20 2.52.0.305.g3fc767764a-goog From nobody Thu Dec 18 08:53:03 2025 Received: from mail-pg1-f202.google.com (mail-pg1-f202.google.com [209.85.215.202]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 73B1026B2DA for ; Tue, 16 Dec 2025 00:44:57 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.215.202 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1765845899; cv=none; b=cVfk9Js1OCNX3oU4pIGVsqo8kBYYkEtMigF6qir4l/7yZWY+nguFfkIu60CcNfAxVFOGqQiyKzUXSIhKASpIh7+x8Vc0XIQ7w17NB7aQ/0aV1la/UV+pjKlCaPqKK5xxbSyGab54zIonoaBvRWGXw8swDvaQ5bMxgOTaNOA6Q7M= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1765845899; c=relaxed/simple; bh=eJzzXyTehyDOrkdA4s2sZqkwAreYcpT1LVD5yuHGCEg=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=mcEDwERtkUccIvxMrE7dqIzlslpfDHLrGhCkZSSOTw2Pwrx25AnelObNpGXkdXSCXFVQy4gulCqU6mB+5VFGnxO7nxj3lrk3YuvEEt/MXnmsdTL/8pihw4+rS7ZLmeJ9v36HJqWSSwi9n4stlDghqlWBoFabGgCkJUtzP1zmjmc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--mmaurer.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=PLx3t8+F; arc=none smtp.client-ip=209.85.215.202 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--mmaurer.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="PLx3t8+F" Received: by mail-pg1-f202.google.com with SMTP id 41be03b00d2f7-b99763210e5so7810986a12.3 for ; Mon, 15 Dec 2025 16:44:57 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1765845897; x=1766450697; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=KesyPju459Z9i93tKmGW4+cYM/ROQPbIUqpeFkvB4f4=; b=PLx3t8+FbeQpm64MFqzsR9DM+MYXAPSuDO+xXaJrWLgVVrujI87TsGlra48uZqMjEF hLh21j+YT1HbiC00bDMRLDrYMRmv7SKxyHPJYH+B5k1uHX4n94FLBkGVHZWLilSxuiPp P3I1G6CoBB2/xwSYj2HyUYJCu41Z+70ne8ij5KsQ6q29Tby1qXns6yLYJpUGB4/HsBMF Ct791J1L8HGEaSnzq28a3374yiQODYBQLP+oX9Ofr8Mnoecs3PhR5wyNepTzCngJ56eW F8ahnjJW9KZMLrvQKVge+ZBDUmF1JElRlVjU/HBVZZcz/ToZjmSiYh1/ccN0v2mS9Nc8 WrnQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1765845897; x=1766450697; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=KesyPju459Z9i93tKmGW4+cYM/ROQPbIUqpeFkvB4f4=; b=Z//z/5JiL4B4FGLUXRi8sTWtHhzFpI2EecdbbIVkdFKsMa8F84aomX1BJWGCteY/wU d9tqXtfc0tbIyK2rJIOX3KhcFr16M2B7z64welg4MlRIgbkYt4uuyRvt3MOrQdy0SA+z vTEonmfr14DW19oemk6ymF7izv0aDMLEJO6EZW8L4jJwiL+K1Lf7fyM/mynoeY+w0vLy L37rzU0nrXfXpsja054HfimFKVyh9/xlx2H4MvLSipR5qlPNTHMZiV2rqmzVPjSNjJ2e R0Mwf9rhECbE1WrS7XJK5hjwqbs/N8VB58xJ5ZDagY0hsAxEFeJ+T9nu8iroNK50SIIZ jW7A== X-Forwarded-Encrypted: i=1; AJvYcCW92STrG10Sku0Zuw94ik4ExZwAMQDnIsavoXKLRFy0/5Jh/jyWHgE0KBRjyrftF4IZ2f0uvjlWeULj09U=@vger.kernel.org X-Gm-Message-State: AOJu0Yz1vTd6VM2Cclvwu8KehTg5mEwWn57XoCv+g5KAkbagCKTkstHZ qs8Fpxpjj1O1+oM71JZZNyu4feW81RtZowyiFQ5Gz+evnVYSzkLa33xBoXSBCntiHl5gSMuMk3u 3J82P3ouIRw== X-Google-Smtp-Source: AGHT+IEQ5wxKL6gYrutG2VXGN+zazB4TwDak9ykhby/gvEC3VGcHSiTMhK8WLTx5Vhbjtidy0p3BqhJLi54F X-Received: from dycns7.prod.google.com ([2002:a05:7300:f787:b0:2ac:2c66:7180]) (user=mmaurer job=prod-delivery.src-stubby-dispatcher) by 2002:a05:7300:50e4:b0:2a4:3593:6452 with SMTP id 5a478bee46e88-2ac2f85e8a0mr8360771eec.2.1765845896521; Mon, 15 Dec 2025 16:44:56 -0800 (PST) Date: Tue, 16 Dec 2025 00:44:43 +0000 In-Reply-To: <20251216-transmute-v2-0-b23e5277ad02@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20251216-transmute-v2-0-b23e5277ad02@google.com> X-Developer-Key: i=mmaurer@google.com; a=ed25519; pk=2Ezhl7+fEjTOMVFpplDeak2AdQ8cjJieLRVJdNzrW+E= X-Developer-Signature: v=1; a=ed25519-sha256; t=1765845890; l=10908; i=mmaurer@google.com; s=20250429; h=from:subject:message-id; bh=eJzzXyTehyDOrkdA4s2sZqkwAreYcpT1LVD5yuHGCEg=; b=9udXk9G1Dt7+BmcMMAc+ksdY1kYgvCDrvn2/pYGVJNNN24pKAJAmnOVsaftEkpz6lfgfYo9fx GhEmAzrI3tGCqrxK1FPXWRJpUApNy7EOA3hKdERdIscJ2MwWvPB8w+i X-Mailer: b4 0.14.2 Message-ID: <20251216-transmute-v2-3-b23e5277ad02@google.com> Subject: [PATCH v2 3/3] rust: Support deriving `AsBytes`/`FromBytes` on bindgen types From: Matthew Maurer To: Miguel Ojeda , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Matthew Maurer Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable To support this, we need to move the `transmute` module into a separate crate to allow the `bindings` crate to depend on it. Most user code is still expected to address the module as `kernel::transmute`, which is a re-export. `ffi::transmute` is now available for use in `bindings`. Signed-off-by: Matthew Maurer --- rust/Makefile | 14 +++++++++----- rust/bindgen_parameters | 8 ++++++++ rust/bindings/lib.rs | 4 ++++ rust/{ffi.rs =3D> ffi/lib.rs} | 5 +++++ rust/{kernel =3D> ffi}/transmute.rs | 0 rust/kernel/lib.rs | 2 +- rust/macros/lib.rs | 24 ++++++++++++++++++++++-- rust/macros/transmute.rs | 12 +++++++----- rust/uapi/lib.rs | 4 ++++ scripts/generate_rust_analyzer.py | 2 +- 10 files changed, 61 insertions(+), 14 deletions(-) diff --git a/rust/Makefile b/rust/Makefile index 5d357dce1704d15e43effc528be8f5a4d74d3d8d..178aa3036c4acba1c4c26619691= 2da2d60fe0d5f 100644 --- a/rust/Makefile +++ b/rust/Makefile @@ -207,7 +207,7 @@ rustdoc-compiler_builtins: $(src)/compiler_builtins.rs = rustdoc-core FORCE +$(call if_changed,rustdoc) =20 rustdoc-ffi: private is-kernel-object :=3D y -rustdoc-ffi: $(src)/ffi.rs rustdoc-core FORCE +rustdoc-ffi: $(src)/ffi/lib.rs rustdoc-core FORCE +$(call if_changed,rustdoc) =20 rustdoc-pin_init_internal: private rustdoc_host =3D yes @@ -249,7 +249,7 @@ quiet_cmd_rustc_test_library =3D $(RUSTC_OR_CLIPPY_QUIE= T) TL $< rusttestlib-build_error: $(src)/build_error.rs FORCE +$(call if_changed,rustc_test_library) =20 -rusttestlib-ffi: $(src)/ffi.rs FORCE +rusttestlib-ffi: $(src)/ffi/lib.rs FORCE +$(call if_changed,rustc_test_library) =20 rusttestlib-proc_macro2: private rustc_target_flags =3D $(proc_macro2-flag= s) @@ -657,22 +657,26 @@ $(obj)/build_error.o: $(src)/build_error.rs $(obj)/co= mpiler_builtins.o FORCE +$(call if_changed_rule,rustc_library) =20 $(obj)/ffi.o: private skip_gendwarfksyms =3D 1 -$(obj)/ffi.o: $(src)/ffi.rs $(obj)/compiler_builtins.o FORCE +$(obj)/ffi.o: $(src)/ffi/lib.rs $(obj)/compiler_builtins.o FORCE +$(call if_changed_rule,rustc_library) =20 -$(obj)/bindings.o: private rustc_target_flags =3D --extern ffi --extern pi= n_init +$(obj)/bindings.o: private rustc_target_flags =3D --extern ffi --extern pi= n_init \ + --extern macros $(obj)/bindings.o: $(src)/bindings/lib.rs \ $(obj)/ffi.o \ $(obj)/pin_init.o \ + $(obj)/$(libmacros_name) \ $(obj)/bindings/bindings_generated.rs \ $(obj)/bindings/bindings_helpers_generated.rs FORCE +$(call if_changed_rule,rustc_library) =20 -$(obj)/uapi.o: private rustc_target_flags =3D --extern ffi --extern pin_in= it +$(obj)/uapi.o: private rustc_target_flags =3D --extern ffi --extern pin_in= it \ + --extern macros $(obj)/uapi.o: private skip_gendwarfksyms =3D 1 $(obj)/uapi.o: $(src)/uapi/lib.rs \ $(obj)/ffi.o \ $(obj)/pin_init.o \ + $(obj)/$(libmacros_name) \ $(obj)/uapi/uapi_generated.rs FORCE +$(call if_changed_rule,rustc_library) =20 diff --git a/rust/bindgen_parameters b/rust/bindgen_parameters index fd2fd1c3cb9a51ea46fcd721907783b457aa1378..d56343ca03979e345f8adb7eb8f= d7f2b9d4be6ee 100644 --- a/rust/bindgen_parameters +++ b/rust/bindgen_parameters @@ -64,3 +64,11 @@ # Structs should implement `Zeroable` when all of their fields do. --with-derive-custom-struct .*=3DMaybeZeroable --with-derive-custom-union .*=3DMaybeZeroable + +# Every C struct can try to derive FromBytes. If they have unmet requireme= nts, +# the impl will just be a no-op due to the where clause. +--with-derive-custom-struct .*=3DFromBytesFfi + +# We can't auto-derive AsBytes, as we need a const-time check to see if th= ere +# is padding involved. Add it explicitly when you expect no padding. +--with-derive-custom-struct cpumask=3DAsBytesFfi diff --git a/rust/bindings/lib.rs b/rust/bindings/lib.rs index 0c57cf9b4004f176997c59ecc58a9a9ac76163d9..c29312fca1b01b707bb11b05d44= 6d44480a4b81f 100644 --- a/rust/bindings/lib.rs +++ b/rust/bindings/lib.rs @@ -31,6 +31,10 @@ #[allow(clippy::undocumented_unsafe_blocks)] #[cfg_attr(CONFIG_RUSTC_HAS_UNNECESSARY_TRANSMUTES, allow(unnecessary_tran= smutes))] mod bindings_raw { + use macros::{ + AsBytesFfi, + FromBytesFfi, // + }; use pin_init::{MaybeZeroable, Zeroable}; =20 // Manual definition for blocklisted types. diff --git a/rust/ffi.rs b/rust/ffi/lib.rs similarity index 87% rename from rust/ffi.rs rename to rust/ffi/lib.rs index f961e9728f590fd2c52d4c03a1f715d654051d04..14052362f091a609bc505fe6eca= 77fe998fe2321 100644 --- a/rust/ffi.rs +++ b/rust/ffi/lib.rs @@ -10,6 +10,11 @@ =20 #![no_std] =20 +#[doc(hidden)] +// This lives here to make it accessible to `bindings`, similar to the oth= er `ffi` types. +// User code should access it through `kernel::transmute`. +pub mod transmute; + macro_rules! alias { ($($name:ident =3D $ty:ty;)*) =3D> {$( #[allow(non_camel_case_types, missing_docs)] diff --git a/rust/kernel/transmute.rs b/rust/ffi/transmute.rs similarity index 100% rename from rust/kernel/transmute.rs rename to rust/ffi/transmute.rs diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index f812cf12004286962985a068665443dc22c389a2..4aa54dd83319ef16bd4baa19641= 14f1e6549942b 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -63,6 +63,7 @@ extern crate self as kernel; =20 pub use ffi; +pub use ffi::transmute; =20 pub mod acpi; pub mod alloc; @@ -146,7 +147,6 @@ pub mod task; pub mod time; pub mod tracepoint; -pub mod transmute; pub mod types; pub mod uaccess; #[cfg(CONFIG_USB =3D "y")] diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index d66397942529f67697f74a908e257cacc4201d84..bde94c2a8ddf708872bcd56a471= 3784b5ccdf04e 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -506,7 +506,7 @@ pub fn kunit_tests(attr: TokenStream, ts: TokenStream) = -> TokenStream { #[proc_macro_derive(FromBytes)] pub fn derive_from_bytes(tokens: TokenStream) -> TokenStream { let input =3D parse_macro_input!(tokens as DeriveInput); - transmute::from_bytes(input).into() + transmute::from_bytes("kernel", input).into() } =20 /// Implements `AsBytes` for a struct. @@ -536,5 +536,25 @@ pub fn derive_from_bytes(tokens: TokenStream) -> Token= Stream { #[proc_macro_derive(AsBytes)] pub fn derive_as_bytes(tokens: TokenStream) -> TokenStream { let input =3D parse_macro_input!(tokens as DeriveInput); - transmute::as_bytes(input).into() + transmute::as_bytes("kernel", input).into() +} + +#[doc(hidden)] +#[proc_macro_derive(FromBytesFfi)] +/// This is equivalent to `FromBytes`, but uses the `ffi` crate as the tra= it definition site +/// instead of `kernel`. This is intended for use inside `bindings`. Every= one else can refer to the +/// trait through `kernel`. +pub fn derive_from_bytes_trait(tokens: TokenStream) -> TokenStream { + let input =3D parse_macro_input!(tokens as DeriveInput); + transmute::from_bytes("ffi", input).into() +} + +#[doc(hidden)] +#[proc_macro_derive(AsBytesFfi)] +/// This is equivalent to `AsBytes`, but uses the `ffi` crate as the trait= definition site +/// instead of `kernel`. This is intended for use inside `bindings`. Every= one else can refer to the +/// trait through `kernel`. +pub fn derive_as_bytes_trait(tokens: TokenStream) -> TokenStream { + let input =3D parse_macro_input!(tokens as DeriveInput); + transmute::as_bytes("ffi", input).into() } diff --git a/rust/macros/transmute.rs b/rust/macros/transmute.rs index 43cf36a1334f1fed23c0e777026392f987f78d8d..9bd6d279675fb1d58cdceff1f4d= de0dcf33fbf99 100644 --- a/rust/macros/transmute.rs +++ b/rust/macros/transmute.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: GPL-2.0 =20 -use proc_macro2::TokenStream; +use proc_macro2::{Span, TokenStream}; use syn::{parse_quote, DeriveInput, Fields, Ident, ItemConst, Path, WhereC= lause}; =20 fn all_fields_impl(fields: &Fields, trait_: &Path) -> WhereClause { @@ -19,7 +19,8 @@ fn struct_padding_check(fields: &Fields, name: &Ident) ->= ItemConst { } } =20 -pub(crate) fn as_bytes(input: DeriveInput) -> TokenStream { +pub(crate) fn as_bytes(crate_: &str, input: DeriveInput) -> TokenStream { + let crate_ =3D Ident::new(crate_, Span::call_site()); if !input.generics.params.is_empty() { return quote::quote! { compile_error!("#[derive(AsBytes)] does not= support generics") }; } @@ -27,7 +28,7 @@ pub(crate) fn as_bytes(input: DeriveInput) -> TokenStream= { return quote::quote! { compile_error!("#[derive(AsBytes)] only sup= ports structs") }; }; let name =3D input.ident; - let trait_ =3D parse_quote! { ::kernel::transmute::AsBytes }; + let trait_ =3D parse_quote! { ::#crate_::transmute::AsBytes }; let where_clause =3D all_fields_impl(&ds.fields, &trait_); let padding_check =3D struct_padding_check(&ds.fields, &name); quote::quote! { @@ -37,13 +38,14 @@ unsafe impl #trait_ for #name #where_clause {} } } =20 -pub(crate) fn from_bytes(input: DeriveInput) -> TokenStream { +pub(crate) fn from_bytes(crate_: &str, input: DeriveInput) -> TokenStream { + let crate_ =3D Ident::new(crate_, Span::call_site()); let syn::Data::Struct(ref ds) =3D &input.data else { return quote::quote! { compile_error!("#[derive(FromBytes)] only s= upports structs") }; }; let (impl_generics, ty_generics, base_where_clause) =3D input.generics= .split_for_impl(); let name =3D input.ident; - let trait_ =3D parse_quote! { ::kernel::transmute::FromBytes }; + let trait_ =3D parse_quote! { ::#crate_::transmute::FromBytes }; let mut where_clause =3D all_fields_impl(&ds.fields, &trait_); if let Some(base_clause) =3D base_where_clause { where_clause diff --git a/rust/uapi/lib.rs b/rust/uapi/lib.rs index 1d5fd9efb93e9db97fec84fca2bae37b500c20c5..2033b7125558d7ccfae67b94777= f5ce59593a528 100644 --- a/rust/uapi/lib.rs +++ b/rust/uapi/lib.rs @@ -34,6 +34,10 @@ type __kernel_ssize_t =3D isize; type __kernel_ptrdiff_t =3D isize; =20 +use macros::{ + AsBytesFfi, + FromBytesFfi, // +}; use pin_init::MaybeZeroable; =20 include!(concat!(env!("OBJTREE"), "/rust/uapi/uapi_generated.rs")); diff --git a/scripts/generate_rust_analyzer.py b/scripts/generate_rust_anal= yzer.py index 147d0cc940681426771db865bc2462e7029a6d7d..843d081eacaca8edeeac5978bd8= 107a498008186 100755 --- a/scripts/generate_rust_analyzer.py +++ b/scripts/generate_rust_analyzer.py @@ -137,7 +137,7 @@ def generate_crates(srctree, objtree, sysroot_src, exte= rnal_src, cfgs, core_edit =20 append_crate( "ffi", - srctree / "rust" / "ffi.rs", + srctree / "rust" / "ffi" / "lib.rs", ["core", "compiler_builtins"], ) =20 --=20 2.52.0.305.g3fc767764a-goog