public inbox for linux-kernel@vger.kernel.org
 help / color / mirror / Atom feed
* [PATCH v3 0/4] Support more safe `AsBytes`/`FromBytes` usage
@ 2025-12-26 21:08 Matthew Maurer
  2025-12-26 21:08 ` [PATCH v3 1/4] rust: transmute: Support transmuting slices of AsBytes/FromBytes types Matthew Maurer
                   ` (4 more replies)
  0 siblings, 5 replies; 9+ messages in thread
From: Matthew Maurer @ 2025-12-26 21:08 UTC (permalink / raw)
  To: Miguel Ojeda, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	Danilo Krummrich
  Cc: rust-for-linux, linux-kernel, Matthew Maurer, Daniel Almeida

Currently:
* Slices of `AsBytes`/`FromBytes` types cannot be synthesized from
  bytes slices (without unsafe).
* Users must use `unsafe impl` to assert that structs are `AsBytes` or
  `FromBytes` and write appropriate justifications.
* Bindgen-generated types cannot implement `AsBytes` or `FromBytes`,
  meaning that casting them to or from bytes involves assumptions in the
  `unsafe impl` that could easily go out of sync if the underlying
  header is edited or an assumption is invalid on a platform the author
  did not consider.

This series seeks to address all there of these by:
1. Adding slice cast functions to `FromBytes`
2. Adding a derive for `AsBytes` and `FromBytes`, for now restricted to
   the simple case of structs.
3. Refactoring the crate structure to move `AsBytes` and `FromBytes` to
   `ffi` to allow `bindings` and `uapi` to reference them.
4. Enabling bindgen derivation in `bindings`/`uapi` through `AsBytesFfi`
   and `FromBytesFfi`.

1+2 can be landed separately if needed, 3 has no purpose without 4, and
3+4 need 1+2.

Signed-off-by: Matthew Maurer <mmaurer@google.com>
---
Changes in v3:
- Explained the `for<'a>` usage in the where clauses generated by macro.
- Split bindgen support into two commits, one which does the crate
  migration and one which enables it.
- Link to v2: https://lore.kernel.org/r/20251216-transmute-v2-0-b23e5277ad02@google.com

Changes in v2:
- Reworked to put `transmute` in `ffi` rather than creating a new crate,
  per Alice's comment on Zulip.
- Switched to new kernel import style.
- Link to v1: https://lore.kernel.org/r/20251212-transmute-v1-0-9b28e06c6508@google.com

---
Matthew Maurer (4):
      rust: transmute: Support transmuting slices of AsBytes/FromBytes types
      rust: transmute: Add support for deriving `AsBytes` and `FromBytes`
      rust: transmute: Migrate AsBytes/FromBytes to ffi crate for bindgen
      rust: transmute: Support deriving AsBytes/FromBytes on bindgen types

 rust/Makefile                     | 14 ++++---
 rust/bindgen_parameters           |  8 ++++
 rust/bindings/lib.rs              |  4 ++
 rust/{ffi.rs => ffi/lib.rs}       |  5 +++
 rust/{kernel => ffi}/transmute.rs | 72 +++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs                |  2 +-
 rust/macros/lib.rs                | 83 +++++++++++++++++++++++++++++++++++++++
 rust/macros/transmute.rs          | 67 +++++++++++++++++++++++++++++++
 rust/uapi/lib.rs                  |  4 ++
 scripts/generate_rust_analyzer.py |  2 +-
 10 files changed, 254 insertions(+), 7 deletions(-)
---
base-commit: 008d3547aae5bc86fac3eda317489169c3fda112
change-id: 20251212-transmute-8ab6076700a8

Best regards,
-- 
Matthew Maurer <mmaurer@google.com>


^ permalink raw reply	[flat|nested] 9+ messages in thread

* [PATCH v3 1/4] rust: transmute: Support transmuting slices of AsBytes/FromBytes types
  2025-12-26 21:08 [PATCH v3 0/4] Support more safe `AsBytes`/`FromBytes` usage Matthew Maurer
@ 2025-12-26 21:08 ` Matthew Maurer
  2025-12-26 21:08 ` [PATCH v3 2/4] rust: transmute: Add support for deriving `AsBytes` and `FromBytes` Matthew Maurer
                   ` (3 subsequent siblings)
  4 siblings, 0 replies; 9+ messages in thread
From: Matthew Maurer @ 2025-12-26 21:08 UTC (permalink / raw)
  To: Miguel Ojeda, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	Danilo Krummrich
  Cc: rust-for-linux, linux-kernel, Matthew Maurer, Daniel Almeida

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 <daniel.almeida@collabora.com>
Signed-off-by: Matthew Maurer <mmaurer@google.com>
---
 rust/kernel/transmute.rs | 72 ++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 72 insertions(+)

diff --git a/rust/kernel/transmute.rs b/rust/kernel/transmute.rs
index be5dbf3829e25c92f85083cc0f4940f35bb7baec..5cc5f4fde4c31cea3c51ab078b4d68f3a0a2caa1 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])>
         }
     }
 
+    /// Converts a slice of bytes to a slice of `Self`.
+    ///
+    /// Succeeds if the reference is properly aligned, and the size of `bytes` is a multiple of that
+    /// of `Self`.
+    ///
+    /// Otherwise, returns [`None`].
+    fn from_bytes_to_slice(bytes: &[u8]) -> Option<&[Self]>
+    where
+        Self: Sized,
+    {
+        let size = size_of::<Self>();
+        if size == 0 {
+            return None;
+        }
+        if bytes.len() % size != 0 {
+            return None;
+        }
+        let len = bytes.len() / size;
+        let ptr = bytes.as_ptr().cast::<Self>();
+
+        #[allow(clippy::incompatible_msrv)]
+        if ptr.is_aligned() {
+            // SAFETY:
+            // - `ptr` is valid for reads of `bytes.len()` bytes, which is
+            //   `len * size_of::<Self>()`.
+            // - `ptr` is aligned for `Self`.
+            // - `ptr` points to `len` consecutive properly initialized values 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 `bytes` 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 = size_of::<Self>();
+        if size == 0 {
+            return None;
+        }
+        if bytes.len() % size != 0 {
+            return None;
+        }
+        let len = bytes.len() / size;
+        let ptr = bytes.as_mut_ptr().cast::<Self>();
+
+        #[allow(clippy::incompatible_msrv)]
+        if ptr.is_aligned() {
+            // SAFETY:
+            // - `ptr` is valid for reads and writes of `bytes.len()` bytes, which is
+            //   `len * size_of::<Self>()`.
+            // - `ptr` is aligned for `Self`.
+            // - `ptr` points to `len` consecutive properly initialized values of type `Self`
+            //   because `Self` implements `FromBytes`.
+            // - `AsBytes` guarantees that writing a new `Self` to the resulting 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, this method can be used on

-- 
2.52.0.351.gbe84eed79e-goog


^ permalink raw reply related	[flat|nested] 9+ messages in thread

* [PATCH v3 2/4] rust: transmute: Add support for deriving `AsBytes` and `FromBytes`
  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 ` Matthew Maurer
  2025-12-26 21:08 ` [PATCH v3 3/4] rust: transmute: Migrate AsBytes/FromBytes to ffi crate for bindgen Matthew Maurer
                   ` (2 subsequent siblings)
  4 siblings, 0 replies; 9+ messages in thread
From: Matthew Maurer @ 2025-12-26 21:08 UTC (permalink / raw)
  To: Miguel Ojeda, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	Danilo Krummrich
  Cc: rust-for-linux, linux-kernel, Matthew Maurer

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 <mmaurer@google.com>
---
 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..d66397942529f67697f74a908e257cacc4201d84 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;
 
 use proc_macro::TokenStream;
+use syn::{
+    parse_macro_input,
+    DeriveInput, //
+};
 
 /// 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 determined to implement
+/// `FromBytes` safely. It may still fail for some types which would be safe to implement
+/// `FromBytes` for, 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 `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 = 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 determined 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 = 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..56818880f8b5e3c1933a4e3361790d3c8be3238c
--- /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, WhereClause};
+
+fn all_fields_impl(fields: &Fields, trait_: &Path) -> WhereClause {
+    let tys = fields.iter().map(|field| &field.ty);
+    // The `for<'a>` is a workaround for lacking `#![feature(trivial_bounds)]`
+    // It allows us to add conditions which are trivially false to the where clause, which means
+    // that we can write `impl`s that the compiler will determine to be irrelevant for us. For
+    // example, it allows us to put a `*const c_void: FromBytes` restriction 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 requirements 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 = fields.iter().map(|field| &field.ty);
+    parse_quote! {
+        const _: () = {
+            assert!(#(core::mem::size_of::<#tys>())+* == core::mem::size_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) = &input.data else {
+        return quote::quote! { compile_error!("#[derive(AsBytes)] only supports structs") };
+    };
+    let name = input.ident;
+    let trait_ = parse_quote! { ::kernel::transmute::AsBytes };
+    let where_clause = all_fields_impl(&ds.fields, &trait_);
+    let padding_check = struct_padding_check(&ds.fields, &name);
+    quote::quote! {
+        #padding_check
+        // SAFETY: #name has no padding and all of its fields implement `AsBytes`
+        unsafe impl #trait_ for #name #where_clause {}
+    }
+}
+
+pub(crate) fn from_bytes(input: DeriveInput) -> TokenStream {
+    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 mut where_clause = all_fields_impl(&ds.fields, &trait_);
+    if let Some(base_clause) = base_where_clause {
+        where_clause
+            .predicates
+            .extend(base_clause.predicates.clone())
+    };
+    quote::quote! {
+        // SAFETY: All fields of #name implement `FromBytes` and it is a struct, so there is no
+        // implicit discriminator.
+        unsafe impl #impl_generics #trait_ for #name #ty_generics #where_clause {}
+    }
+}

-- 
2.52.0.351.gbe84eed79e-goog


^ permalink raw reply related	[flat|nested] 9+ messages in thread

* [PATCH v3 3/4] rust: transmute: Migrate AsBytes/FromBytes to ffi crate for bindgen
  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 ` Matthew Maurer
  2025-12-26 21:08 ` [PATCH v3 4/4] rust: transmute: Support deriving AsBytes/FromBytes on bindgen types Matthew Maurer
  2026-04-30  0:27 ` [PATCH v3 0/4] Support more safe `AsBytes`/`FromBytes` usage Alexandre Courbot
  4 siblings, 0 replies; 9+ messages in thread
From: Matthew Maurer @ 2025-12-26 21:08 UTC (permalink / raw)
  To: Miguel Ojeda, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	Danilo Krummrich
  Cc: rust-for-linux, linux-kernel, Matthew Maurer

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 <mmaurer@google.com>
---
 rust/Makefile                     | 6 +++---
 rust/{ffi.rs => ffi/lib.rs}       | 5 +++++
 rust/{kernel => 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..5c2cb78f7c258aa87d8128593159be1f5945252f 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)
 
 rustdoc-ffi: private is-kernel-object := y
-rustdoc-ffi: $(src)/ffi.rs rustdoc-core FORCE
+rustdoc-ffi: $(src)/ffi/lib.rs rustdoc-core FORCE
 	+$(call if_changed,rustdoc)
 
 rustdoc-pin_init_internal: private rustdoc_host = yes
@@ -249,7 +249,7 @@ quiet_cmd_rustc_test_library = $(RUSTC_OR_CLIPPY_QUIET) TL $<
 rusttestlib-build_error: $(src)/build_error.rs FORCE
 	+$(call if_changed,rustc_test_library)
 
-rusttestlib-ffi: $(src)/ffi.rs FORCE
+rusttestlib-ffi: $(src)/ffi/lib.rs FORCE
 	+$(call if_changed,rustc_test_library)
 
 rusttestlib-proc_macro2: private rustc_target_flags = $(proc_macro2-flags)
@@ -657,7 +657,7 @@ $(obj)/build_error.o: $(src)/build_error.rs $(obj)/compiler_builtins.o FORCE
 	+$(call if_changed_rule,rustc_library)
 
 $(obj)/ffi.o: private skip_gendwarfksyms = 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)
 
 $(obj)/bindings.o: private rustc_target_flags = --extern ffi --extern pin_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..14052362f091a609bc505fe6eca77fe998fe2321 100644
--- a/rust/ffi.rs
+++ b/rust/ffi/lib.rs
@@ -10,6 +10,11 @@
 
 #![no_std]
 
+#[doc(hidden)]
+// This lives here to make it accessible to `bindings`, similar to the other `ffi` types.
+// User code should access it through `kernel::transmute`.
+pub mod transmute;
+
 macro_rules! alias {
     ($($name:ident = $ty:ty;)*) => {$(
         #[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..4aa54dd83319ef16bd4baa1964114f1e6549942b 100644
--- a/rust/kernel/lib.rs
+++ b/rust/kernel/lib.rs
@@ -63,6 +63,7 @@
 extern crate self as kernel;
 
 pub use ffi;
+pub use ffi::transmute;
 
 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 = "y")]
diff --git a/scripts/generate_rust_analyzer.py b/scripts/generate_rust_analyzer.py
index 147d0cc940681426771db865bc2462e7029a6d7d..843d081eacaca8edeeac5978bd8107a498008186 100755
--- a/scripts/generate_rust_analyzer.py
+++ b/scripts/generate_rust_analyzer.py
@@ -137,7 +137,7 @@ def generate_crates(srctree, objtree, sysroot_src, external_src, cfgs, core_edit
 
     append_crate(
         "ffi",
-        srctree / "rust" / "ffi.rs",
+        srctree / "rust" / "ffi" / "lib.rs",
         ["core", "compiler_builtins"],
     )
 

-- 
2.52.0.351.gbe84eed79e-goog


^ permalink raw reply related	[flat|nested] 9+ messages in thread

* [PATCH v3 4/4] rust: transmute: Support deriving AsBytes/FromBytes on bindgen types
  2025-12-26 21:08 [PATCH v3 0/4] Support more safe `AsBytes`/`FromBytes` usage Matthew Maurer
                   ` (2 preceding siblings ...)
  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
  2026-04-30  0:27 ` [PATCH v3 0/4] Support more safe `AsBytes`/`FromBytes` usage Alexandre Courbot
  4 siblings, 0 replies; 9+ messages in thread
From: Matthew Maurer @ 2025-12-26 21:08 UTC (permalink / raw)
  To: Miguel Ojeda, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	Danilo Krummrich
  Cc: rust-for-linux, linux-kernel, Matthew Maurer

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


^ permalink raw reply related	[flat|nested] 9+ messages in thread

* Re: [PATCH v3 0/4] Support more safe `AsBytes`/`FromBytes` usage
  2025-12-26 21:08 [PATCH v3 0/4] Support more safe `AsBytes`/`FromBytes` usage Matthew Maurer
                   ` (3 preceding siblings ...)
  2025-12-26 21:08 ` [PATCH v3 4/4] rust: transmute: Support deriving AsBytes/FromBytes on bindgen types Matthew Maurer
@ 2026-04-30  0:27 ` Alexandre Courbot
  2026-04-30  3:22   ` Matthew Maurer
  4 siblings, 1 reply; 9+ messages in thread
From: Alexandre Courbot @ 2026-04-30  0:27 UTC (permalink / raw)
  To: Matthew Maurer
  Cc: Miguel Ojeda, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	Danilo Krummrich, rust-for-linux, linux-kernel, Daniel Almeida

Hi Matthew,

On Sat Dec 27, 2025 at 6:08 AM JST, Matthew Maurer wrote:
> Currently:
> * Slices of `AsBytes`/`FromBytes` types cannot be synthesized from
>   bytes slices (without unsafe).
> * Users must use `unsafe impl` to assert that structs are `AsBytes` or
>   `FromBytes` and write appropriate justifications.
> * Bindgen-generated types cannot implement `AsBytes` or `FromBytes`,
>   meaning that casting them to or from bytes involves assumptions in the
>   `unsafe impl` that could easily go out of sync if the underlying
>   header is edited or an assumption is invalid on a platform the author
>   did not consider.
>
> This series seeks to address all there of these by:
> 1. Adding slice cast functions to `FromBytes`
> 2. Adding a derive for `AsBytes` and `FromBytes`, for now restricted to
>    the simple case of structs.
> 3. Refactoring the crate structure to move `AsBytes` and `FromBytes` to
>    `ffi` to allow `bindings` and `uapi` to reference them.
> 4. Enabling bindgen derivation in `bindings`/`uapi` through `AsBytesFfi`
>    and `FromBytesFfi`.
>
> 1+2 can be landed separately if needed, 3 has no purpose without 4, and
> 3+4 need 1+2.
>
> Signed-off-by: Matthew Maurer <mmaurer@google.com>

Do you have plans to carry this series on? If not I would be willing to
try and drive it until it can be merged, as it would be very handy to
use in nova-core.

^ permalink raw reply	[flat|nested] 9+ messages in thread

* Re: [PATCH v3 0/4] Support more safe `AsBytes`/`FromBytes` usage
  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
  0 siblings, 1 reply; 9+ messages in thread
From: Matthew Maurer @ 2026-04-30  3:22 UTC (permalink / raw)
  To: Alexandre Courbot
  Cc: Miguel Ojeda, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	Danilo Krummrich, rust-for-linux, linux-kernel, Daniel Almeida

>
> Do you have plans to carry this series on? If not I would be willing to
> try and drive it until it can be merged, as it would be very handy to
> use in nova-core.

If you want to drive it you can, I was not pushing on this because:
1. I received no feedback on v3, so I figured it was in a state of
"good enough but in need of a user"
2. I heard there was work going on to introduce `zerocopy` as an
additional vendored crate. If that were done, this patchset would be
mostly not necessary (we'd need some of the bindgen tweaks).

If you are aware of something I should be fixing about this patchset,
let me know, I'd still be happy to update it if there's something I'm
missing.

^ permalink raw reply	[flat|nested] 9+ messages in thread

* Re: [PATCH v3 0/4] Support more safe `AsBytes`/`FromBytes` usage
  2026-04-30  3:22   ` Matthew Maurer
@ 2026-04-30  8:09     ` Miguel Ojeda
  2026-04-30  8:24       ` Alexandre Courbot
  0 siblings, 1 reply; 9+ messages in thread
From: Miguel Ojeda @ 2026-04-30  8:09 UTC (permalink / raw)
  To: Matthew Maurer
  Cc: Alexandre Courbot, Miguel Ojeda, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, Danilo Krummrich, rust-for-linux, linux-kernel,
	Daniel Almeida

On Thu, Apr 30, 2026 at 5:22 AM Matthew Maurer <mmaurer@google.com> wrote:
>
> 2. I heard there was work going on to introduce `zerocopy` as an
> additional vendored crate.

Yeah, that is my plan for this cycle.

Cheers,
Miguel

^ permalink raw reply	[flat|nested] 9+ messages in thread

* Re: [PATCH v3 0/4] Support more safe `AsBytes`/`FromBytes` usage
  2026-04-30  8:09     ` Miguel Ojeda
@ 2026-04-30  8:24       ` Alexandre Courbot
  0 siblings, 0 replies; 9+ messages in thread
From: Alexandre Courbot @ 2026-04-30  8:24 UTC (permalink / raw)
  To: Miguel Ojeda
  Cc: Matthew Maurer, Miguel Ojeda, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, Danilo Krummrich, rust-for-linux, linux-kernel,
	Daniel Almeida

On Thu Apr 30, 2026 at 5:09 PM JST, Miguel Ojeda wrote:
> On Thu, Apr 30, 2026 at 5:22 AM Matthew Maurer <mmaurer@google.com> wrote:
>>
>> 2. I heard there was work going on to introduce `zerocopy` as an
>> additional vendored crate.
>
> Yeah, that is my plan for this cycle.

Great news - holding on then.

^ permalink raw reply	[flat|nested] 9+ messages in thread

end of thread, other threads:[~2026-04-30  8:25 UTC | newest]

Thread overview: 9+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
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 ` [PATCH v3 4/4] rust: transmute: Support deriving AsBytes/FromBytes on bindgen types Matthew Maurer
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

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox