From nobody Sun Dec 14 06:40:54 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 0C7F930EF63 for ; Fri, 12 Dec 2025 23:42:32 +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=1765582954; cv=none; b=jYq/0iBLsaIdx00rDc/jbFvMWJjVPJS0iI3sLls4deXvGguiBkzCji7Q74OELGnuj/SwgDykJi8+Ok+KrJstt1m4EhAo5RkSJ6XuIYXaBjtY6MLzmwlaRS864cP0lHFq198KlVO+OyE/8Uj1ZMcXrNy+mYxhhQJ6rX9vpaPaAxk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1765582954; c=relaxed/simple; bh=zWmWPrNOhUkM882JMpbDBfEGQcxG/fITkb9z+Trg0V8=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=EHrGSXolpsWLhvLiijp08qkHTkjxxlDLBlq2WzXgaRjBDnYpb4Fcdt+E7hb9HWcgf2P5ybEBBcHvWinriN4RCOenjPrARHqXhN6sSluN9teb2x2QB0lf5rQvfn0tdKazHjeqZVnXG8r1bkO06xkI/czwE7Ta9JzqMza5ryGGWSY= 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=q+1zyVJI; 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="q+1zyVJI" Received: by mail-pg1-f202.google.com with SMTP id 41be03b00d2f7-b6097ca315bso2747375a12.3 for ; Fri, 12 Dec 2025 15:42:32 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1765582952; x=1766187752; 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=q+1zyVJINRXqdnaXxIC3VK9Bwr1UiVPUX3bbI7P7MOchvc8rgQbwUKyTIdmKPErRRb 4ZzSb7DvmdHlzN337iXjyatKgBHqUDqyb8mQAsOZEPkvH+x+DOl2LOl3vFpuE40hOCW/ UwukFfZsmovpVfnf1e7Vb1OjjtBaDeI55MgrA8TYn3Wd+1aFBJH8za1Sv833YNzVmDUh srfG/idFd2lzD+3XVYxftI0isw9KrEiD15mC6jqBlpYmd13rkQWBXVNd/CBVC2yc5eoJ 29nPHgqrcl9KPEeZUZAn7ynBxI86rsBg217FemesmlY+DY7Ph8ZE7OhudDKO/kXxsT9X rhVQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1765582952; x=1766187752; 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=NNl3wNhECHnDho1dMiT+M6XxvGTYsqSYPGUV0FqnrXTL3LnzjW/oO4tvBoqQ6Sk4Gi dlMK7+R/Rd4iysP1+QdiOzOTuudhSLuz81sIeXgRB/3rID/ccFLMRMaN6TQq2HP60h03 TXt4v+DpE8Wbf6qDWrC6jNMTnM7xybDuks57jEJXSV0SdeoJy6S29XvtqINj5n1BDr+w UVcwOqjqG7NjSHOG7W7yw9kPuhdfHjykl0+m3NP7y3jLFKSwqb0/jo2FX1xLT99SSk5T TcQh8cSaKmYF0gFtCziPtoatTW43k1oLzTfv2DbOHR4h2Tfnkgw1lOwyoRMA2ZsDOEOz OO4A== X-Forwarded-Encrypted: i=1; AJvYcCW1JO8M+UiJqSb2rFxhR7UU84R8baRQjh6GRSEIW2VfLUXujoBSD2Kondo8V2HHJdZyZT24MwB/n6dv0MI=@vger.kernel.org X-Gm-Message-State: AOJu0YwCeMOoSla7Y0wHNFc2k2+ukDszMyIwI4vSzMckk4K+YX+GAPJs 6VRTFlybln1BVhDutGAB0qPSsoUBCwz/F6J/oJ7WRTrolfSh3UPwKf9DGXXs5W21k7KGzVmhlMU Z5FaaWKA6Gg== X-Google-Smtp-Source: AGHT+IGjrlVj6t2VMO6pNuEY3FLrlWBfPb8VdKSXQTdk2nAip8yza2Lg/t5wuRdSBSs7QnkzuXNi9H3EA4j3 X-Received: from dycmv2.prod.google.com ([2002:a05:693c:2802:b0:2a2:318c:8559]) (user=mmaurer job=prod-delivery.src-stubby-dispatcher) by 2002:a05:7301:53c3:b0:2ac:4db:9481 with SMTP id 5a478bee46e88-2ac2f8d1712mr2421622eec.19.1765582952141; Fri, 12 Dec 2025 15:42:32 -0800 (PST) Date: Fri, 12 Dec 2025 23:42:19 +0000 In-Reply-To: <20251212-transmute-v1-0-9b28e06c6508@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20251212-transmute-v1-0-9b28e06c6508@google.com> X-Developer-Key: i=mmaurer@google.com; a=ed25519; pk=2Ezhl7+fEjTOMVFpplDeak2AdQ8cjJieLRVJdNzrW+E= X-Developer-Signature: v=1; a=ed25519-sha256; t=1765582949; l=3786; i=mmaurer@google.com; s=20250429; h=from:subject:message-id; bh=zWmWPrNOhUkM882JMpbDBfEGQcxG/fITkb9z+Trg0V8=; b=7VRIUHwRNnlmURhG35fKZRQowcBdjQWcur0LUck1p6YJhaARGI8bUve3O5kQ/GvSfzFB+Mr8O RRYKuB7fqcHAk+oX25ohbK2kyKme8TsaEVGbY0GVLmrcvFk+TUWoa5A X-Mailer: b4 0.14.2 Message-ID: <20251212-transmute-v1-1-9b28e06c6508@google.com> Subject: [PATCH 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 --- 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 Sun Dec 14 06:40:54 2025 Received: from mail-pl1-f201.google.com (mail-pl1-f201.google.com [209.85.214.201]) (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 D7905310625 for ; Fri, 12 Dec 2025 23:42:34 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1765582959; cv=none; b=iCs0jvwOnoqvypl0hu6NXtFV/UbV4bLlJzRLSNmqtIV+GxHiZySsenc9mieIWooZk1gcDi6iwdKBuCm45NCLGEXtUdsYD2rZLDAt0IGgWsSJJlh9aiE0YrbBzAbyJ/QMZYr1CnvPCkHD9Ge7WlYRdxvfh4P9jJu+Nb4xr9Oj9BY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1765582959; c=relaxed/simple; bh=5KnwVG3yDzu2d+NIcIUYmz9FUTmRn7r0evtR1ztUoak=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=UDWdTMGT9MKEujYZc6X3Qzk4VKlhc+4EaDhTzeZ1HPJ6hFODUm6bYlqK/Yuy755P8qEGeLPKzkp6QIqHyPjivbuEg3ftSrfaqG3RNOOJP8rW7CUgRX9XDGH065yqJ/oUwBaUaRx5w3S1cjh97eSaV98YrrT+Zm+yVIkE8Vb+tC4= 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=dNxlS0Kw; arc=none smtp.client-ip=209.85.214.201 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="dNxlS0Kw" Received: by mail-pl1-f201.google.com with SMTP id d9443c01a7336-29be4d2ef78so32945175ad.2 for ; Fri, 12 Dec 2025 15:42:34 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1765582954; x=1766187754; 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=IdhN8tl/FUHqLxDThvV9fKvIGwQC9dcDXu1W6Fov51Y=; b=dNxlS0KwApZ0LiBJ0BqbUde4cY52m7Nt7InzFHjFwxAx7XzmNPphVjEN9NWluVU7C+ Kjiq4TiZd7Hc8g9gl3mPBxfqpbt3lZacYmLkcntrrsPKTcWbyOAab0eC5EU0i8+MapzG wbhiJpyXvU6mXUEbLsWF9eVREy1cOyZRpsMa0Gk3NBrGcXULtE54IXx/FpL2s7HqJBoU Vpatt/POmYjY3H5IutDIBnAvsRYRbqO65b1ED0ssf58V8kEvxs4bo4ZwoHyiJXKtXgmg F7YRRfWn/l6iWehXI+vl89F5ad0/9R+2pZkZjQcjzk+H3AvhEcLAmF8yuB687HFGsqJN cMOg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1765582954; x=1766187754; 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=IdhN8tl/FUHqLxDThvV9fKvIGwQC9dcDXu1W6Fov51Y=; b=m/K9ct/M2mcSMkLnpcGyKxh7eA8RimV7KFEWARNqGLyA24u+o5pg3kgpviD9aEcFe8 GKgxH36IZNgdJnoMj38eojVsM44rOFF3j+BjyP7vJMZWzWi7gkj5jXQt5rlGbSRSzZLl PoyHVgG2VpsabPY6eo8o3LpCMChFuRkd+dUkzkh42Vf1F4fR6b3rYpiKE9D8Pn2Rzwiu HCarjuV+sgDU/M/Dur7Bx4INRjddonTA6l3fPArYSNGqicgtIo/9gAXtZQeWEXJAIaH/ ncc2Yvo82ceLX5+SV8a9WhZI/Fho8pF5BnnbU0HphyRRGtsXsXGzlaoRRpVNHoeQvMlx fKMg== X-Forwarded-Encrypted: i=1; AJvYcCUx79W8lX/NEel8McmuGCJ0Hek8AlK6A4lufdw+WdFp8choA0kUs8yIazMqjXa0r0PjbuySvu9dM0QEQJk=@vger.kernel.org X-Gm-Message-State: AOJu0Yx9frN6BA9J8/zS4IEZ4GZacK+caA/k6mYf/FFn2q+leHCOtu8I dZ7NeAK6c9kRsbVGx+lUAPOyZInYh4wiAcceCcztpqCoCl271kMyXBhcCLWTEgW4cz9xTV2g193 /nl7AF8F2Ag== X-Google-Smtp-Source: AGHT+IGmQdUDYkGnRhcpp7ks0v//jFQLLsh2PFEFgAg5ntuOCNFgOHrmVuMP4ABSFQHvEGG0zZE0dtj5wijX X-Received: from dlf36.prod.google.com ([2002:a05:7022:424:b0:119:9f33:34ae]) (user=mmaurer job=prod-delivery.src-stubby-dispatcher) by 2002:a05:701b:2808:b0:11c:b3ae:c9f1 with SMTP id a92af1059eb24-11f349a1911mr3039236c88.1.1765582953981; Fri, 12 Dec 2025 15:42:33 -0800 (PST) Date: Fri, 12 Dec 2025 23:42:20 +0000 In-Reply-To: <20251212-transmute-v1-0-9b28e06c6508@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20251212-transmute-v1-0-9b28e06c6508@google.com> X-Developer-Key: i=mmaurer@google.com; a=ed25519; pk=2Ezhl7+fEjTOMVFpplDeak2AdQ8cjJieLRVJdNzrW+E= X-Developer-Signature: v=1; a=ed25519-sha256; t=1765582949; l=5543; i=mmaurer@google.com; s=20250429; h=from:subject:message-id; bh=5KnwVG3yDzu2d+NIcIUYmz9FUTmRn7r0evtR1ztUoak=; b=zSqHsL8ItXbCK6J8BJfPfwJkDbLsqOLUfuQVpUjl2Wrdoc+74dBO/mvC3dwtdkm3qOzRo0Tyq 4qdyczQvWzlAksk3URu8bLZ6rKmBZCkZlrHKxkMs/OazzZcuRCSWHWc X-Mailer: b4 0.14.2 Message-ID: <20251212-transmute-v1-2-9b28e06c6508@google.com> Subject: [PATCH 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 | 60 ++++++++++++++++++++++++++++++++++++++++++++= ++++ rust/macros/transmute.rs | 58 ++++++++++++++++++++++++++++++++++++++++++++= ++ 2 files changed, 118 insertions(+) diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index b38002151871a33f6b4efea70be2deb6ddad38e2..cec8bd3a742b3f6b3680c4286f7= 3c8fa550a58a0 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -20,9 +20,11 @@ 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 +477,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 Sun Dec 14 06:40:54 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 ECE243101A5 for ; Fri, 12 Dec 2025 23:42:37 +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=1765582960; cv=none; b=lLz2gCtVocmxdlL3oqXsoy8zP9E9aYHW957e3ZnafcW+Jbh1X3OgJelpbe75EDO7amYc+O3nFdZjo6A2aw951xSdTKXBMlYrR/Orvj+PONl9yzwPa4s7lHQPYDImkNxdJWu0t+iHdBvPEZXHdZ0826LL11VpV7IHI+8IKfXPolA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1765582960; c=relaxed/simple; bh=a4fBIhT9OP8XBv90Ul5+2iSakBnB35GLRJBkUmDan0Y=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=geh/2t3FQvvjKmV+20tMM6kTKf/l3Eeag50FVGeKetH0v5vyThGzbIiq8cB4Po+VrlqgXb7WVvTaKCR0f5PzOiRwO/im5YQ7WxF4IYa6UJouJr27dRqFrLU1Kmkbex91dBlj2NwVU+YWxuAgxtcGGIhhZO197CA76D6qQ29iXk8= 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=nc6wc1Ki; 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="nc6wc1Ki" Received: by mail-pg1-f202.google.com with SMTP id 41be03b00d2f7-b6097ca315bso2747441a12.3 for ; Fri, 12 Dec 2025 15:42:37 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1765582957; x=1766187757; 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=W5rKFlQEdv6mp3b6khBfhqQ83uqWy1wmdv/8dcXGXm0=; b=nc6wc1KijsK5fAi3izxF8Tlu6pn0RnoxVUHeTPoaPdl4wZx+IJi1tVcKRJiyKE8fU9 qN5hzOinEDTn2gTnUksWQVWbBjx6yrkeGA2a309YmqTWMadSKCU0stKfvcm8W7DQCNmG tFKNJU9wgQW3yZX3rPfuGtouLt8ZDT3Pl18h9I4bgxE8BS8b0NVDgKwkYFuFwyQhQKh9 Nebvk5nVL9v/HmT7trGDzDPATBR/x7EpY73WXel1utlqPFY+tWt9qNXUOyLPYFnOOD5n t013tACGopWNU0rZMv9q3jieH4Uw3rwUh1SsN0Xk1tShF8jWVTF51djzOLqP/8oJWKYw sC0w== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1765582957; x=1766187757; 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=W5rKFlQEdv6mp3b6khBfhqQ83uqWy1wmdv/8dcXGXm0=; b=sV8AkVr13wu6FT6fqcjrCHc24v8O3uNyv/Y0yupgmNsStZSTgsP6wMy5CboKobJgmL A/+LlnYkqSwFWQHfTsdahi8gFUNTOc77EGWihFncOKtAyR6W1HKT+3ig3qAWLjv/nL7X zg506vPuipdx+7Cnwszo+2CkDEVfB6GKBsAGPcqZTMQOlsNugJPDNDzPwzPj9lijFkt2 vPQ1EgcHbXppHjvuW0fD+/753M3tc9X3+LlLN1K8vJY0eoZDrugDYnK1+98sHJztu5Ie Vq3mwTI8kEjnt4cQsqGmdfDr3B7U8mJxsVj+c85MqrCxJXX8jAR/+tNWyoMuz7/7oFCr yCUw== X-Forwarded-Encrypted: i=1; AJvYcCUumUAwRSrPN5dxFLH62pANjUgVMHQu2jqKkb2Cktsi/r/dhMuzQ8WQz7DxQor8xUQMPNz4IhKXFFSdIYA=@vger.kernel.org X-Gm-Message-State: AOJu0YzqUreugO1c3NeND/LXml+zKdOk+x2PDCykq8ah6vVfHrdhlchG 6CI/eW7TeRoUClv9z9qEmkBG7fvCynPbCpUsOzj8OVI2Sp+FehibeNJ/AnT6kkRk+dxvTh99DEB mBBnv5hmcug== X-Google-Smtp-Source: AGHT+IG/OBFVGzp+B1Pwr4c/sK8EobUryFxZ1KPilfpcUcukaoOJ8RaVG9RFQoYdwPP1hPN/HvRZipgnWceZ X-Received: from dycrr5.prod.google.com ([2002:a05:693c:2c85:b0:2a4:6f9d:b3cb]) (user=mmaurer job=prod-delivery.src-stubby-dispatcher) by 2002:a05:7301:df44:b0:2a4:7fb3:7a96 with SMTP id 5a478bee46e88-2ac3014694emr2149620eec.36.1765582957189; Fri, 12 Dec 2025 15:42:37 -0800 (PST) Date: Fri, 12 Dec 2025 23:42:21 +0000 In-Reply-To: <20251212-transmute-v1-0-9b28e06c6508@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20251212-transmute-v1-0-9b28e06c6508@google.com> X-Developer-Key: i=mmaurer@google.com; a=ed25519; pk=2Ezhl7+fEjTOMVFpplDeak2AdQ8cjJieLRVJdNzrW+E= X-Developer-Signature: v=1; a=ed25519-sha256; t=1765582949; l=10140; i=mmaurer@google.com; s=20250429; h=from:subject:message-id; bh=a4fBIhT9OP8XBv90Ul5+2iSakBnB35GLRJBkUmDan0Y=; b=1Ai9maUqqxpxnEwLMeD1d0XkSSB/GvIl2h0lOXy6cvA6mbwIKWmAV/jdQpctWKFdRSeFtNWav Mi7n3QiU4nhAmKL121HCNxeK6P7pdRZphq9de+Z2VGMYufYC3Ijj6v8 X-Mailer: b4 0.14.2 Message-ID: <20251212-transmute-v1-3-9b28e06c6508@google.com> Subject: [PATCH 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. `traits::transmute` is now available for use in `bindings`. Signed-off-by: Matthew Maurer --- rust/Makefile | 19 +++++++++++++++---- rust/bindgen_parameters | 8 ++++++++ rust/bindings/lib.rs | 1 + rust/kernel/lib.rs | 3 ++- rust/macros/lib.rs | 24 ++++++++++++++++++++++-- rust/macros/transmute.rs | 12 +++++++----- rust/traits/lib.rs | 6 ++++++ rust/{kernel =3D> traits}/transmute.rs | 0 rust/uapi/lib.rs | 1 + 9 files changed, 62 insertions(+), 12 deletions(-) diff --git a/rust/Makefile b/rust/Makefile index 5d357dce1704d15e43effc528be8f5a4d74d3d8d..bbede4b5b4faa5edeb1d33bdce3= 38a7b76915d07 100644 --- a/rust/Makefile +++ b/rust/Makefile @@ -660,26 +660,37 @@ $(obj)/ffi.o: private skip_gendwarfksyms =3D 1 $(obj)/ffi.o: $(src)/ffi.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 traits --extern macros $(obj)/bindings.o: $(src)/bindings/lib.rs \ $(obj)/ffi.o \ $(obj)/pin_init.o \ + $(obj)/traits.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)/traits.o: private skip_gendwarfksyms =3D 1 +$(obj)/traits.o: $(src)/traits/lib.rs FORCE + +$(call if_changed_rule,rustc_library) + + +$(obj)/uapi.o: private rustc_target_flags =3D --extern ffi --extern pin_in= it \ + --extern traits --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)/traits.o \ + $(obj)/$(libmacros_name) \ $(obj)/uapi/uapi_generated.rs FORCE +$(call if_changed_rule,rustc_library) =20 $(obj)/kernel.o: private rustc_target_flags =3D --extern ffi --extern pin_= init \ - --extern build_error --extern macros --extern bindings --extern uapi + --extern build_error --extern macros --extern bindings --extern uapi -= -extern traits $(obj)/kernel.o: $(src)/kernel/lib.rs $(obj)/build_error.o $(obj)/pin_init= .o \ - $(obj)/$(libmacros_name) $(obj)/bindings.o $(obj)/uapi.o FORCE + $(obj)/$(libmacros_name) $(obj)/bindings.o $(obj)/uapi.o $(obj)/traits= .o FORCE +$(call if_changed_rule,rustc_library) =20 ifdef CONFIG_JUMP_LABEL diff --git a/rust/bindgen_parameters b/rust/bindgen_parameters index fd2fd1c3cb9a51ea46fcd721907783b457aa1378..60910ba8731180516b4980b9e0d= c5fb0c297da55 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 .*=3DFromBytesTrait + +# 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=3DAsBytesTrait diff --git a/rust/bindings/lib.rs b/rust/bindings/lib.rs index 0c57cf9b4004f176997c59ecc58a9a9ac76163d9..07932ab130c0a8e56e35d49ace7= 7ae1becc09ae6 100644 --- a/rust/bindings/lib.rs +++ b/rust/bindings/lib.rs @@ -31,6 +31,7 @@ #[allow(clippy::undocumented_unsafe_blocks)] #[cfg_attr(CONFIG_RUSTC_HAS_UNNECESSARY_TRANSMUTES, allow(unnecessary_tran= smutes))] mod bindings_raw { + use macros::{AsBytesTrait, FromBytesTrait}; use pin_init::{MaybeZeroable, Zeroable}; =20 // Manual definition for blocklisted types. diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index f812cf12004286962985a068665443dc22c389a2..8c605f4905223077f5d824f2722= 0c4c24e71d5f4 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -146,7 +146,6 @@ pub mod task; pub mod time; pub mod tracepoint; -pub mod transmute; pub mod types; pub mod uaccess; #[cfg(CONFIG_USB =3D "y")] @@ -159,6 +158,8 @@ pub use macros; pub use uapi; =20 +pub use traits::*; + /// Prefix to appear before log messages printed from within the `kernel` = crate. const __LOG_PREFIX: &[u8] =3D b"rust_kernel\0"; =20 diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index cec8bd3a742b3f6b3680c4286f73c8fa550a58a0..862de56339bbb18cd30a260444d= c19f24b13a0d0 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -503,7 +503,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. @@ -533,5 +533,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(FromBytesTrait)] +/// This is equivalent to `FromBytes`, but uses the `trait` crate as the t= rait 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("traits", input).into() +} + +#[doc(hidden)] +#[proc_macro_derive(AsBytesTrait)] +/// This is equivalent to `AsBytes`, but uses the `trait` 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_as_bytes_trait(tokens: TokenStream) -> TokenStream { + let input =3D parse_macro_input!(tokens as DeriveInput); + transmute::as_bytes("traits", 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/traits/lib.rs b/rust/traits/lib.rs new file mode 100644 index 0000000000000000000000000000000000000000..33020a17333521b3bee71bd3d00= 3a759ac97fedd --- /dev/null +++ b/rust/traits/lib.rs @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Support crate containing traits and other definitions that need to be = available without the +//! kernel crate. The usual case for this is code that needs to be availab= le in the bindings crate. +#![no_std] +pub mod transmute; diff --git a/rust/kernel/transmute.rs b/rust/traits/transmute.rs similarity index 100% rename from rust/kernel/transmute.rs rename to rust/traits/transmute.rs diff --git a/rust/uapi/lib.rs b/rust/uapi/lib.rs index 1d5fd9efb93e9db97fec84fca2bae37b500c20c5..928b4b2eb035250399e3150f20b= 638edbf04dac1 100644 --- a/rust/uapi/lib.rs +++ b/rust/uapi/lib.rs @@ -34,6 +34,7 @@ type __kernel_ssize_t =3D isize; type __kernel_ptrdiff_t =3D isize; =20 +use macros::{AsBytesTrait, FromBytesTrait}; use pin_init::MaybeZeroable; =20 include!(concat!(env!("OBJTREE"), "/rust/uapi/uapi_generated.rs")); --=20 2.52.0.305.g3fc767764a-goog