From: Matthew Maurer <mmaurer@google.com>
To: "Miguel Ojeda" <ojeda@kernel.org>,
"Boqun Feng" <boqun.feng@gmail.com>,
"Gary Guo" <gary@garyguo.net>,
"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
"Benno Lossin" <lossin@kernel.org>,
"Andreas Hindborg" <a.hindborg@kernel.org>,
"Alice Ryhl" <aliceryhl@google.com>,
"Trevor Gross" <tmgross@umich.edu>,
"Danilo Krummrich" <dakr@kernel.org>
Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org,
Matthew Maurer <mmaurer@google.com>
Subject: [PATCH v3 4/4] rust: transmute: Support deriving AsBytes/FromBytes on bindgen types
Date: Fri, 26 Dec 2025 21:08:23 +0000 [thread overview]
Message-ID: <20251226-transmute-v3-4-c69a81bf8621@google.com> (raw)
In-Reply-To: <20251226-transmute-v3-0-c69a81bf8621@google.com>
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 <mmaurer@google.com>
---
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..178aa3036c4acba1c4c266196912da2d60fe0d5f 100644
--- a/rust/Makefile
+++ b/rust/Makefile
@@ -660,19 +660,23 @@ $(obj)/ffi.o: private skip_gendwarfksyms = 1
$(obj)/ffi.o: $(src)/ffi/lib.rs $(obj)/compiler_builtins.o FORCE
+$(call if_changed_rule,rustc_library)
-$(obj)/bindings.o: private rustc_target_flags = --extern ffi --extern pin_init
+$(obj)/bindings.o: private rustc_target_flags = --extern ffi --extern pin_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)
-$(obj)/uapi.o: private rustc_target_flags = --extern ffi --extern pin_init
+$(obj)/uapi.o: private rustc_target_flags = --extern ffi --extern pin_init \
+ --extern macros
$(obj)/uapi.o: private skip_gendwarfksyms = 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)
diff --git a/rust/bindgen_parameters b/rust/bindgen_parameters
index fd2fd1c3cb9a51ea46fcd721907783b457aa1378..d56343ca03979e345f8adb7eb8fd7f2b9d4be6ee 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 .*=MaybeZeroable
--with-derive-custom-union .*=MaybeZeroable
+
+# Every C struct can try to derive FromBytes. If they have unmet requirements,
+# the impl will just be a no-op due to the where clause.
+--with-derive-custom-struct .*=FromBytesFfi
+
+# We can't auto-derive AsBytes, as we need a const-time check to see if there
+# is padding involved. Add it explicitly when you expect no padding.
+--with-derive-custom-struct cpumask=AsBytesFfi
diff --git a/rust/bindings/lib.rs b/rust/bindings/lib.rs
index 0c57cf9b4004f176997c59ecc58a9a9ac76163d9..c29312fca1b01b707bb11b05d446d44480a4b81f 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_transmutes))]
mod bindings_raw {
+ use macros::{
+ AsBytesFfi,
+ FromBytesFfi, //
+ };
use pin_init::{MaybeZeroable, Zeroable};
// Manual definition for blocklisted types.
diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs
index d66397942529f67697f74a908e257cacc4201d84..bde94c2a8ddf708872bcd56a4713784b5ccdf04e 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 = parse_macro_input!(tokens as DeriveInput);
- transmute::from_bytes(input).into()
+ transmute::from_bytes("kernel", input).into()
}
/// Implements `AsBytes` for a struct.
@@ -536,5 +536,25 @@ pub fn derive_from_bytes(tokens: TokenStream) -> TokenStream {
#[proc_macro_derive(AsBytes)]
pub fn derive_as_bytes(tokens: TokenStream) -> TokenStream {
let input = 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 trait definition site
+/// instead of `kernel`. This is intended for use inside `bindings`. Everyone else can refer to the
+/// trait through `kernel`.
+pub fn derive_from_bytes_trait(tokens: TokenStream) -> TokenStream {
+ let input = 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`. Everyone else can refer to the
+/// trait through `kernel`.
+pub fn derive_as_bytes_trait(tokens: TokenStream) -> TokenStream {
+ let input = 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..a62c9cb581e2fc1b4b141fc4bc75550bda0618ba 100644
--- a/rust/macros/transmute.rs
+++ b/rust/macros/transmute.rs
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: GPL-2.0
-use proc_macro2::TokenStream;
+use proc_macro2::{Span, TokenStream};
use syn::{parse_quote, DeriveInput, Fields, Ident, ItemConst, Path, WhereClause};
fn all_fields_impl(fields: &Fields, trait_: &Path) -> WhereClause {
@@ -26,7 +26,8 @@ fn struct_padding_check(fields: &Fields, name: &Ident) -> ItemConst {
}
}
-pub(crate) fn as_bytes(input: DeriveInput) -> TokenStream {
+pub(crate) fn as_bytes(crate_: &str, input: DeriveInput) -> TokenStream {
+ let crate_ = 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 supports structs") };
};
let name = input.ident;
- let trait_ = parse_quote! { ::kernel::transmute::AsBytes };
+ let trait_ = parse_quote! { ::#crate_::transmute::AsBytes };
let where_clause = all_fields_impl(&ds.fields, &trait_);
let padding_check = struct_padding_check(&ds.fields, &name);
quote::quote! {
@@ -44,13 +45,14 @@ unsafe impl #trait_ for #name #where_clause {}
}
}
-pub(crate) fn from_bytes(input: DeriveInput) -> TokenStream {
+pub(crate) fn from_bytes(crate_: &str, input: DeriveInput) -> TokenStream {
+ let crate_ = Ident::new(crate_, Span::call_site());
let syn::Data::Struct(ref ds) = &input.data else {
return quote::quote! { compile_error!("#[derive(FromBytes)] only supports structs") };
};
let (impl_generics, ty_generics, base_where_clause) = input.generics.split_for_impl();
let name = input.ident;
- let trait_ = parse_quote! { ::kernel::transmute::FromBytes };
+ let trait_ = parse_quote! { ::#crate_::transmute::FromBytes };
let mut where_clause = all_fields_impl(&ds.fields, &trait_);
if let Some(base_clause) = base_where_clause {
where_clause
diff --git a/rust/uapi/lib.rs b/rust/uapi/lib.rs
index 1d5fd9efb93e9db97fec84fca2bae37b500c20c5..2033b7125558d7ccfae67b94777f5ce59593a528 100644
--- a/rust/uapi/lib.rs
+++ b/rust/uapi/lib.rs
@@ -34,6 +34,10 @@
type __kernel_ssize_t = isize;
type __kernel_ptrdiff_t = isize;
+use macros::{
+ AsBytesFfi,
+ FromBytesFfi, //
+};
use pin_init::MaybeZeroable;
include!(concat!(env!("OBJTREE"), "/rust/uapi/uapi_generated.rs"));
--
2.52.0.351.gbe84eed79e-goog
next prev parent reply other threads:[~2025-12-26 21:08 UTC|newest]
Thread overview: 9+ messages / expand[flat|nested] mbox.gz Atom feed top
2025-12-26 21:08 [PATCH v3 0/4] Support more safe `AsBytes`/`FromBytes` usage Matthew Maurer
2025-12-26 21:08 ` [PATCH v3 1/4] rust: transmute: Support transmuting slices of AsBytes/FromBytes types Matthew Maurer
2025-12-26 21:08 ` [PATCH v3 2/4] rust: transmute: Add support for deriving `AsBytes` and `FromBytes` Matthew Maurer
2025-12-26 21:08 ` [PATCH v3 3/4] rust: transmute: Migrate AsBytes/FromBytes to ffi crate for bindgen Matthew Maurer
2025-12-26 21:08 ` Matthew Maurer [this message]
2026-04-30 0:27 ` [PATCH v3 0/4] Support more safe `AsBytes`/`FromBytes` usage Alexandre Courbot
2026-04-30 3:22 ` Matthew Maurer
2026-04-30 8:09 ` Miguel Ojeda
2026-04-30 8:24 ` Alexandre Courbot
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20251226-transmute-v3-4-c69a81bf8621@google.com \
--to=mmaurer@google.com \
--cc=a.hindborg@kernel.org \
--cc=aliceryhl@google.com \
--cc=bjorn3_gh@protonmail.com \
--cc=boqun.feng@gmail.com \
--cc=dakr@kernel.org \
--cc=gary@garyguo.net \
--cc=linux-kernel@vger.kernel.org \
--cc=lossin@kernel.org \
--cc=ojeda@kernel.org \
--cc=rust-for-linux@vger.kernel.org \
--cc=tmgross@umich.edu \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox