From nobody Sun Feb 8 00:26:35 2026 Received: from mail-pg1-f201.google.com (mail-pg1-f201.google.com [209.85.215.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 05FFB309EF1 for ; Fri, 26 Dec 2025 21:08:37 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.215.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1766783319; cv=none; b=tPZsg/R6a1KWvJGaw5KoV+zIVsp7jnnn7bA92L4TfLfo09FaEHoYaTr56LwJYdWJ2F1TCyCBABoNs9uyOUJrsyPFVgnVuwTv0rYoLBVgoMP4XvWr9vzauzZ3dGczrmdNQk6tS8nE85DodS8ptq47fJDdGaTIDKvoy2AOr3qTjpM= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1766783319; c=relaxed/simple; bh=yRqOM84UfhvlX1GusCxviw7NRGJEsBz5ywTKlFKiQrA=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=bNVnkMGRZw/tjoskQMnOic2Z2fsLl5Sywpqr6XWJBHaJubrK1zS6GtR3jdFTwJsg5wNRq7dFk3dqoYYlG878WkLPxkHQbkzRugjXoPYQPpe/ESx8HZ5tXYSIPPfKKjFrytKK1kOd7n4a+XfoNam5i/9eXGLQOn4uh14WKeW9UiU= 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=J1noZb4+; arc=none smtp.client-ip=209.85.215.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="J1noZb4+" Received: by mail-pg1-f201.google.com with SMTP id 41be03b00d2f7-c2bfb70bd53so3676186a12.2 for ; Fri, 26 Dec 2025 13:08:37 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1766783317; x=1767388117; 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=LJS1IhwhkUR4azPowta91Z/26RTynx20SFmLNTxsNmE=; b=J1noZb4+nTuFrst5Xbr7d4Hzk064DFVXsFgIg+Y/rm7pZw0PN4u2dK+Xr4kOUwLkp7 7N7HQTx90FCOH/Z7oYHD45Zm4XSjvuxahpsruKLoS36ZtchL9fmESkZRdOXUrzLjXf9J LAwmhKJkEQP5VIzbFUlZEZEEKBVe3HMGNgGAyTIqEY2X1XZPwXXjNr3gRmq2c96uDfpP sH9igTvmN8a/uTUqoO+cEWbgJc2ZHTF5uxsvs/n2iYFKhT+yVmNJHEhwwwfr434LQDM6 D+QkEeMAQCwjaKmbAJdnOskTXjAWtkj3n12c8Kdpg65zFB+qB8wNBmQP+nYwcevxdcRD /W/w== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1766783317; x=1767388117; 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=LJS1IhwhkUR4azPowta91Z/26RTynx20SFmLNTxsNmE=; b=wC8jIW8j/9hAAwVx/6XIN8EmkoV8R+MRfmUVOao0RwIyuri31J2cAg16MDt636dTrw 3WK6tcWlZTTMtAtpWM7D7N7XFTK+9KUwz9vx1HbdidwJpZtZi0EtJ5/Fjq0jvVoebvWh YIpnZIXIdP2gb4PXZlCOjm6D4j9Y5y96dXGa2kVuvuaA3H4vfJ51gvHMTlxVZx6C6VGO cd9TkHZAt2/QJu/yNDi3DljBpeQ3+fnuHOrX/EML0t57vQeniky4ufGfcAEIH/HsvdfK 0NYsqbddOqCR1VJ7dPxm97tsUx3PvAoG5khbaSOftrEmBFPMFkQm15G9yjpyvCYMnDMx RoUw== X-Forwarded-Encrypted: i=1; AJvYcCVfwv/OSLWPd3NH8DGUSp8aaGJVG7FQ7GJfYMgtHezCDKitA1T6kkG7cgnJRvKOOf7LegpHTVwXkiBClYA=@vger.kernel.org X-Gm-Message-State: AOJu0Yx6IOPPoBBG7DG+iZj/6nD+0dNSAx6+cm1D9t1nbFEn6VIRv3Xk oLs3chJCLOHhVxGJQzJwIzOeQmuxp5vlkqyFBwycNYJ27q0aKFcrO5i72mH5UGyA31T6woi3Q9t N5I3rrHVYvA== X-Google-Smtp-Source: AGHT+IGWQCOT7tRQme+xoXGfeNeSS8GhTj7F5/XJQT6DU4knJWlizMnSMdxXfuhPgU3KtaUGxrfM8QSewT+J X-Received: from dycc13.prod.google.com ([2002:a05:693c:60cd:b0:2ae:6000:3855]) (user=mmaurer job=prod-delivery.src-stubby-dispatcher) by 2002:a05:7301:3aa4:b0:2ac:1b11:bf98 with SMTP id 5a478bee46e88-2b05ec7425amr14867141eec.28.1766783317236; Fri, 26 Dec 2025 13:08:37 -0800 (PST) Date: Fri, 26 Dec 2025 21:08:20 +0000 In-Reply-To: <20251226-transmute-v3-0-c69a81bf8621@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20251226-transmute-v3-0-c69a81bf8621@google.com> X-Developer-Key: i=mmaurer@google.com; a=ed25519; pk=2Ezhl7+fEjTOMVFpplDeak2AdQ8cjJieLRVJdNzrW+E= X-Developer-Signature: v=1; a=ed25519-sha256; t=1766783314; l=3846; i=mmaurer@google.com; s=20250429; h=from:subject:message-id; bh=yRqOM84UfhvlX1GusCxviw7NRGJEsBz5ywTKlFKiQrA=; b=ko6Dp6YXYaL7fl8WCgXLr9N/+x0NSuA3igNCM4Fff6fIW6bFPFlQdUybmDtUJMTz/J70IZqI+ ZujSc34JfQlCL/5dq4RAhDY2nSJJmUeYYmn4ZT+hIlp/tRylR2JQgLV X-Mailer: b4 0.14.2 Message-ID: <20251226-transmute-v3-1-c69a81bf8621@google.com> Subject: [PATCH v3 1/4] 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 , Daniel Almeida 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. Reviewed-by: Daniel Almeida 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.351.gbe84eed79e-goog From nobody Sun Feb 8 00:26:35 2026 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 98E7530F52A for ; Fri, 26 Dec 2025 21:08:39 +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=1766783322; cv=none; b=NxGPq8aRoDeA62EeTkfYlSvI1vBB0ATVI7Msuk3m29KnToKU2Wo9oOULsMUvO1g7hHIgxO6DuJJd1AKPB4XjBiJVW538bUv3Bah+UbyYkWEq4seV26R//4ce9QvWm5evbjUdipT9cZ/RC90kaRxTBDqhSch4h56E1qEOVDuNmAQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1766783322; c=relaxed/simple; bh=G6nHU3/yePo+JOOiZrq3c4OKAHWoFHwwlQQ1jamejvw=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=cMerGzIDsbhPWQaH0Zg66SjfUlwTSPvTqcU1ZsrVXyNwHFq9Sk7fx3CzeVrR0dd4IOpH7hZwtVXHMdFqRn9ygnQeckD/Snq0POHh8N3/SKNcNHClDd6OAcC8xm4pANK7tdMhS49NAPufchAMC4yo6sXuJj0VpTuCHG5KL+N9DkI= 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=BDCdsmdr; 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="BDCdsmdr" Received: by mail-pg1-f202.google.com with SMTP id 41be03b00d2f7-b6097ca315bso13854290a12.3 for ; Fri, 26 Dec 2025 13:08:39 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1766783319; x=1767388119; 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=8OgOKhaobVd3bgzcF9yvMkUb5KrzfgIkJG6R5fDGIIs=; b=BDCdsmdreFrCcgpjAPAQ+nQVFBv1ZgAfzPyxa3X3Z8cahSi3Qnn5ReDjEvAs+BUxpm n8lMrA63h5t9fcKVDpy+t9zpmP+GJFHH9L2OI+An8pgyf1CIg2c+u4HcL8IaBLt+lKg5 5H6lh8quwWaIBvPUxVeE2lH/QdMVV6O9iUoPt2ZuOmqwFMW9HI/Eki/l3GU9XPgEKx4T xgaN1aU688/ZLHWeqaS78QBVb/2+ERoJkeJMOctKoPKlc9nEVpdffAjYwhW4CFWf93rk uZq17zMOsfrF9bF7t11jnhaAUz6mlXIeUX500sl5PD1P7eWIeVG7Grj63Hm1tz1HFa+p 0NXA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1766783319; x=1767388119; 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=8OgOKhaobVd3bgzcF9yvMkUb5KrzfgIkJG6R5fDGIIs=; b=m2wtZ4DpDQNNDdnKdwUGgP2Hdth2MsUi+nFa7450DblZ5wZOZAHYszYE0HP83RWoVF vt8lVYZIWLJH905sT540DILM/oE89JbTDyMiX76mFuLU4wYO65f4wOZGJWqpLyxzz3Gm rGAT0ZvCbMofNcJ7JpeXg+PJX37LCkCGVxRA9j7PLomy0+Js11TriKRmwW3U2wIrzoTr zbbx5ctKSJSwr67L/LliVeQtOnmYgH4W0+fmXyeaXV5VUwBids+2NUsYM7aHZH/lSyXm 8TAUJVMe/581RK7IBafTqVEKHBSI/Lz52wVk0RalqIjNwcoBny6QoM0TsFndD9bOOCOA OMDQ== X-Forwarded-Encrypted: i=1; AJvYcCX+tiFMcsLRHl7aoCeS8PjYGXEnd6HPyblbnOR3DFOmAW8eN4TIR2ogIWHlnyPyUGr5Gs7YrfFcYUFhGjs=@vger.kernel.org X-Gm-Message-State: AOJu0YzF33sEvTPl4EseVq+/o9Y1fHdEyVEjpulUseiU8hS875iVXdQl ND9jWnQLonsaStZwtPpzsvvFM9oyPlkqfR3JPTGW2DhkjrQPDJMPvAZuL68NqkpmaA/wZ60JoTF 8I2+noka5rA== X-Google-Smtp-Source: AGHT+IGkew6YLqhUIX2VJ9nQTbGmNt7bppNeO6lq11BM/7vT6IJSURxdGgymnf7pm+YOktaRIxwYGWCExitQ X-Received: from dyboo7.prod.google.com ([2002:a05:7301:1e87:b0:2ac:36d5:fc65]) (user=mmaurer job=prod-delivery.src-stubby-dispatcher) by 2002:a05:7300:ec89:b0:2ab:ca55:89c6 with SMTP id 5a478bee46e88-2b05ec6f3e8mr18308186eec.41.1766783318777; Fri, 26 Dec 2025 13:08:38 -0800 (PST) Date: Fri, 26 Dec 2025 21:08:21 +0000 In-Reply-To: <20251226-transmute-v3-0-c69a81bf8621@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20251226-transmute-v3-0-c69a81bf8621@google.com> X-Developer-Key: i=mmaurer@google.com; a=ed25519; pk=2Ezhl7+fEjTOMVFpplDeak2AdQ8cjJieLRVJdNzrW+E= X-Developer-Signature: v=1; a=ed25519-sha256; t=1766783314; l=6182; i=mmaurer@google.com; s=20250429; h=from:subject:message-id; bh=G6nHU3/yePo+JOOiZrq3c4OKAHWoFHwwlQQ1jamejvw=; b=HUyuTV7HlHiaYzr7nimpLqLAeO73ucVTZFW4agihqOukLqNCofoMDXTHBJISTkiQQgd3JmjyX 7PfM2eVowdlBPQZq8w1ZRfsgQ+f+c47+s7sLJ5PbFTc/fQB9ZbuuTp5 X-Mailer: b4 0.14.2 Message-ID: <20251226-transmute-v3-2-c69a81bf8621@google.com> Subject: [PATCH v3 2/4] rust: transmute: 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 | 65 ++++++++++++++++++++++++++++++++++++++++++++= ++++ 2 files changed, 128 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..56818880f8b5e3c1933a4e33617= 90d3c8be3238c --- /dev/null +++ b/rust/macros/transmute.rs @@ -0,0 +1,65 @@ +// 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); + // The `for<'a>` is a workaround for lacking `#![feature(trivial_bound= s)]` + // It allows us to add conditions which are trivially false to the whe= re clause, which means + // that we can write `impl`s that the compiler will determine to be ir= relevant for us. For + // example, it allows us to put a `*const c_void: FromBytes` restricti= on on an automatically + // generated `FromBytes` implementation for a struct that has `*const = c_void` as a member. The + // implementation will not actually provide `FromBytes` (since its req= uirements are not met), + // but it will not fail to compile. + 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.351.gbe84eed79e-goog From nobody Sun Feb 8 00:26:35 2026 Received: from mail-pj1-f74.google.com (mail-pj1-f74.google.com [209.85.216.74]) (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 2692830F544 for ; Fri, 26 Dec 2025 21:08:41 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1766783323; cv=none; b=jhXkH2T5slMHvRF3w2qVGtNQH9iHaVlmC/6ex7xJzLyor2UDM9AudjwxZ4dzCd1ozfW4zVOhXcokbAEe95a1AM8SA+r9VJ/IbKy2ridTotFW1U2ydj8HUP/vdXgovqizDab7jf4ZbNEQbhUgCzX0qxaioewlQsPfv0g+brFjAzs= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1766783323; c=relaxed/simple; bh=VccHLUjK3IRX9cFk0CQPTzdLOHNgkUDYIYBSB1eUnV8=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=W31Xh221yE/rIhnJZZ9jP+Y2kS7ScYW6KYZCuS85kSjmF4w62V1SrseSjIeAQmDha5KoJLNeszjTygwo7IwHOu2WfIMiXMFcYz5n7LhQ+KEA8MKqaX0oxZ3v30zKaHZqVgRou6qHnnWYBeifPY7ommROsw9r4Qc1izZNcfbwBNI= 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=zZsq3Slx; arc=none smtp.client-ip=209.85.216.74 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="zZsq3Slx" Received: by mail-pj1-f74.google.com with SMTP id 98e67ed59e1d1-34c387d3eb6so7248975a91.2 for ; Fri, 26 Dec 2025 13:08:41 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1766783320; x=1767388120; 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=D0vAmDPnKhZaxIMXmCiS6v0B3OVLZh4yL/KA0IE6TCw=; b=zZsq3SlxsasTH8BDtN8IlMXcYkAr9eqXMsctp8le2CMvshDppvzjZ8DRdctdIK+NzL 2Ue58zPU5HtueGw3AthWHnvDUwyD/02MENWRv6ArLxZOap6J6EVYXLHH8yRl6jS1sRUG RpP3BucnbnQQkEY8dQgRtcvypFRPKjPLMHC49AWOS26j+jq0uJI1+LLpCXJUStGzuEx+ wGFDyURMxDatDbpQPUgWc49X36rJDCjmly/aLHrxDTAXmLESSim2zy5tPezu/GPAHIfm kSKkwXTcjI6hPWuPNJDtGOUdmZKf0gMT6i5ONJ5zvL5PKxAEH/PvbpPpHYdcUFycPJCj jbBg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1766783320; x=1767388120; 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=D0vAmDPnKhZaxIMXmCiS6v0B3OVLZh4yL/KA0IE6TCw=; b=v6vyd1bbbEoX/FTSBuD2uJ8nvRt/RitbmqwWDEybwdLM3k/T+Ms5TUXgCIV77jOUF1 qE6FRnjkDcspgovGbJBeC+4zekhYdUIh5ISoRLVa9aCaZF4+vs6LjRFQWSGYJq121ZCa SKeIjmdqM79j4meBBwHzuI7oWxklXvPg6Q6LQ+b7Argh4nw+1ZI+5OjZr8oSwEeeGH1d iNXG9BATAOybOUKZH886veYlDMyQEAWl3wRnezxQYtzcFCOeiydsAI3Vs7UFT3c1jtzo /4dJB7qxCrhZiO1RWE+5CF8NQzSXAgyDIrXovQuHtjB0aTI/kndlrmfLYLFm8JJkYxD8 7kdg== X-Forwarded-Encrypted: i=1; AJvYcCXeReeTMriFJk4uK36WPKZFnFBC5zRdDnYB+2/HRCn/xZiz1GTl920G23lexaWOGcMSKmSaBS1zijGQiWM=@vger.kernel.org X-Gm-Message-State: AOJu0YyNR4QZNAPu7ASvinm7rK3PMHVL8ynoCZlstZIgn27pwRrCXXni xvc3TodzXrav44wU9Ey75hrCsOuSLrEXWWAw+g1nNalDHLLHgnZonztBT+s9J0FcaejlaqvEhK9 sOaBUTpqAgQ== X-Google-Smtp-Source: AGHT+IHuYGZ+YiX9+snBG0lqZczrBSGybXzxG3SALPhqNUd/Pdi32QMIZF7otLmy1sbSZNOxCTBK3ptP7N9p X-Received: from dlc13.prod.google.com ([2002:a05:7022:38d:b0:11f:457b:a457]) (user=mmaurer job=prod-delivery.src-stubby-dispatcher) by 2002:a05:7022:6ab:b0:11b:c0db:a5ea with SMTP id a92af1059eb24-121722d3a98mr25104281c88.26.1766783320464; Fri, 26 Dec 2025 13:08:40 -0800 (PST) Date: Fri, 26 Dec 2025 21:08:22 +0000 In-Reply-To: <20251226-transmute-v3-0-c69a81bf8621@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20251226-transmute-v3-0-c69a81bf8621@google.com> X-Developer-Key: i=mmaurer@google.com; a=ed25519; pk=2Ezhl7+fEjTOMVFpplDeak2AdQ8cjJieLRVJdNzrW+E= X-Developer-Signature: v=1; a=ed25519-sha256; t=1766783314; l=4016; i=mmaurer@google.com; s=20250429; h=from:subject:message-id; bh=VccHLUjK3IRX9cFk0CQPTzdLOHNgkUDYIYBSB1eUnV8=; b=2cVKLnh9slEA2V7MhxuCXwqIXLL+815nLADLq62pkWp6fObgrGyBo4eHeQA20HIRQaWIsZ2tb SYaRsAHRnDeAkjhnp4M/m+2yCl46FXV8m5CLFdQYf2jpV2dHG/Wsx20 X-Mailer: b4 0.14.2 Message-ID: <20251226-transmute-v3-3-c69a81bf8621@google.com> Subject: [PATCH v3 3/4] rust: transmute: Migrate AsBytes/FromBytes to ffi crate for bindgen 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 When referencing a trait from inside the `uapi` or `bindings` crates, the `kernel` crate is not available as the it depends on them. To break this cycle, move the `transmute` module containing the two traits to the `ffi` crate which is already used to export similar traits to `uapi` and `bindings`. Re-export `transmute` in its original position in the kernel to avoid any breakage. Normal users are expected to continue using it from `kernel::transmute`. Signed-off-by: Matthew Maurer --- rust/Makefile | 6 +++--- rust/{ffi.rs =3D> ffi/lib.rs} | 5 +++++ rust/{kernel =3D> ffi}/transmute.rs | 0 rust/kernel/lib.rs | 2 +- scripts/generate_rust_analyzer.py | 2 +- 5 files changed, 10 insertions(+), 5 deletions(-) diff --git a/rust/Makefile b/rust/Makefile index 5d357dce1704d15e43effc528be8f5a4d74d3d8d..5c2cb78f7c258aa87d812859315= 9be1f5945252f 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,7 +657,7 @@ $(obj)/build_error.o: $(src)/build_error.rs $(obj)/comp= iler_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 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/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.351.gbe84eed79e-goog From nobody Sun Feb 8 00:26:35 2026 Received: from mail-pf1-f201.google.com (mail-pf1-f201.google.com [209.85.210.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 2B09F30F555 for ; Fri, 26 Dec 2025 21:08:42 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1766783325; cv=none; b=LI3JARhTuaGyExhz8mq0ghjvVUL+71iohgrDOkQmoooBOJgG+A4W5MxmNld5c+OTv7+dj7OuTjFbtPIkWoyU+ijqvPOJCMOt9LciLlJ0C7qqYj2nWKHWKmLfIdZrq0H5dECZctIfBePuR+rhNz+INMZ1jWikcOX3PrjJ4bf4vBI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1766783325; c=relaxed/simple; bh=qHhaP61mOajwYz1JwneBoVLmywYgSBLmUzjXBnzFvV8=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=QWigpmvTPMMQe3riA1/fz3CKF6Aqu8Ik7ZOrbmjvVlAa2tILywM8tAlnuQfu9XJjRQazSdUFwTfge8Fvm2Rl3jzb1fXkSj3pcIVdiRGTDVgqyLOG6pDLQG1bOT0JdSriUUwfIB5+sqriC79sn1CNZB5oqbJjJg0B1tqT+A6YfuQ= 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=QZMCrx9h; arc=none smtp.client-ip=209.85.210.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="QZMCrx9h" Received: by mail-pf1-f201.google.com with SMTP id d2e1a72fcca58-7bf5cdef41dso13191728b3a.0 for ; Fri, 26 Dec 2025 13:08:42 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1766783322; x=1767388122; 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=d7mTBTyMaS+wDpWH5NUbweun10KVW7XKOhqDwPXW//Q=; b=QZMCrx9h+KxCWk/tCdd/zJzoi2kIqgmS0lXse65pTaLMdDAeuBgXYD7qhn9/hE9C9m RdYKESAY6BXV3hb5iYkqgPH0LkKRtzN2SSD1aCvrEKFFoCqn12d0Sg/xcR7fxy6Uc7xC USgh2OGcuSrkypZ6Tw6ftZI+u3teo6FQF72CUkZcYhAI/BKd2OVKIa4SonY8xW0eCV7z MfAky2miWF5V/3aWLnBDrM9gfv0985LdCgEgnrAEh83gjU0yfcaikrg/+34BAJeKX7Ek 0N3NAIASSTskfo/5c/KZINy6QQg9+kNTJ1wJ2FJk+Io8D37oXrTYSTsJ5+39UE194son DeRA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1766783322; x=1767388122; 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=d7mTBTyMaS+wDpWH5NUbweun10KVW7XKOhqDwPXW//Q=; b=ffizOOMBaj4xzbsctX8enULCvY4a66T5n3Ezke5RVYRP5EIVvsgnVCjB7f8y0fPeP1 uTc5mf1qm1nxS7beIqlSrBGfKW3PR4I+XGbnmyLTmKxoU7m7FkbkkR5glkEupOG2vVHC hNjBlY19xkX3xoWhCUiSdUGnIRpZUI4EBUEy2fN3OLqgIDGDKq0nUJ2n5Ole9xkym/v8 bIVA0MQoRkzWxCt1tZkH8GYdadAEZPCQkSUbS/h7UylsVmTfogCvYluZaHOs9ENb0+jT Z5V9n7LWiVTDYhq4DH8UiU4MArjHyMIHORf0xhdToz0+hYzBakw5qI9bGXYq0eh7ujHd mGlw== X-Forwarded-Encrypted: i=1; AJvYcCUftYJiML3MIbfBV7mDWpgJ+f4pDNxl1YmNoX3EVIzyrJYGc9uwTejv6ddXieZatN2rXfmIBaMG28B1aWU=@vger.kernel.org X-Gm-Message-State: AOJu0YyJ0T9QNaMvUVziYsaWgx+y1c3vmPx0nZpwcGmAfOifJsQRg2rx kRQyQsuS2hZ0mn3myWQ+if23yaC3jj08l5K60FvXEgn+K1/Rg00cx23Pw0ZqnBsUxTMxe4NNfgY /EWJD3yT7nw== X-Google-Smtp-Source: AGHT+IGvGXpfjBwZ/r6mO5fSFGZHXr9hj2BRGllitYl1BOk6ELJoP+vvvf04ARqEjIkV1Vb4FuiYpGjACIe0 X-Received: from dlbdx18.prod.google.com ([2002:a05:7022:e12:b0:11a:44f1:daa3]) (user=mmaurer job=prod-delivery.src-stubby-dispatcher) by 2002:a05:701b:220f:b0:11a:3a1c:6c5c with SMTP id a92af1059eb24-121721ad442mr22259846c88.3.1766783322103; Fri, 26 Dec 2025 13:08:42 -0800 (PST) Date: Fri, 26 Dec 2025 21:08:23 +0000 In-Reply-To: <20251226-transmute-v3-0-c69a81bf8621@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20251226-transmute-v3-0-c69a81bf8621@google.com> X-Developer-Key: i=mmaurer@google.com; a=ed25519; pk=2Ezhl7+fEjTOMVFpplDeak2AdQ8cjJieLRVJdNzrW+E= X-Developer-Signature: v=1; a=ed25519-sha256; t=1766783314; l=8180; i=mmaurer@google.com; s=20250429; h=from:subject:message-id; bh=qHhaP61mOajwYz1JwneBoVLmywYgSBLmUzjXBnzFvV8=; b=NRmsJpRDFsVW4ZJALmYPzoGckv/9UAZVtWT9VyjGNFdHigQnABZfSYQjOAKrKPv664fJYhJ6e nauyPoDA387CAY2pWPbD8AOw6RYDi5TsJwbsvGqo2I5GLMd5blGsA6x X-Mailer: b4 0.14.2 Message-ID: <20251226-transmute-v3-4-c69a81bf8621@google.com> Subject: [PATCH v3 4/4] rust: transmute: 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 Provide an internal macro pair, hidden from documentation, `FromBytesFfi` and `AsBytesFfi` which target the `ffi` crate as the definition site of the trait rather than the `kernel` crate. Use `FromBytesFfi` automatically on everything that might support it in bindings/uapi output. Use `AsBytesFfi` on one sample struct that supports it in bindings/uapi output. While it is safe to add this to any type, adding it to a type with padding will result in a compilation failure, so for now only add it to a single sample type. Signed-off-by: Matthew Maurer --- rust/Makefile | 8 ++++++-- rust/bindgen_parameters | 8 ++++++++ rust/bindings/lib.rs | 4 ++++ rust/macros/lib.rs | 24 ++++++++++++++++++++++-- rust/macros/transmute.rs | 12 +++++++----- rust/uapi/lib.rs | 4 ++++ 6 files changed, 51 insertions(+), 9 deletions(-) diff --git a/rust/Makefile b/rust/Makefile index 5c2cb78f7c258aa87d8128593159be1f5945252f..178aa3036c4acba1c4c26619691= 2da2d60fe0d5f 100644 --- a/rust/Makefile +++ b/rust/Makefile @@ -660,19 +660,23 @@ $(obj)/ffi.o: private skip_gendwarfksyms =3D 1 $(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/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 56818880f8b5e3c1933a4e3361790d3c8be3238c..a62c9cb581e2fc1b4b141fc4bc7= 5550bda0618ba 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 { @@ -26,7 +26,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") }; } @@ -34,7 +35,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! { @@ -44,13 +45,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")); --=20 2.52.0.351.gbe84eed79e-goog