Support more safe `AsBytes`/`FromBytes` usage
Subsystems (2)
v3 cover Support more safe `AsBytes`/`FromBytes` usage
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.
---
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/[email protected]
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/[email protected]
---
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,
Signature · 1 line
Matthew Maurer <[email protected]>
PATCH v3 1/4 rust: transmute: Support transmuting slices of AsBytes/FromBytes types
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.
--- rust/kernel/transmute.rs | 72 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+)
rust/kernel/transmute.rs +72 -0
@@ -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
Signature · 1 line
2.52.0.351.gbe84eed79e-goog
PATCH v3 2/4 rust: transmute: Add support for deriving `AsBytes` and `FromBytes`
In reply to Matthew MaurerThis 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.
--- rust/macros/lib.rs | 63 ++++++++++++++++++++++++++++++++++++++++++++++ rust/macros/transmute.rs | 65 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 128 insertions(+)
rust/macros/lib.rs +63 -0
@@ -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! (tokensas 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! (tokensas DeriveInput ); + transmute::as_bytes (input).into () +}
rust/macros/transmute.rs new file +65 -0
65 lines not on this page · raw message
Signature · 1 line
2.52.0.351.gbe84eed79e-goog
PATCH v3 3/4 rust: transmute: Migrate AsBytes/FromBytes to ffi crate for bindgen
In reply to Matthew MaurerWhen 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.
---
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(-)rust/Makefile +3 -3
@@ -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
rust/ffi/lib.rs renamed from rust/ffi.rs +5 -0
@@ -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)]
rust/ffi/transmute.rs renamed from rust/kernel/transmute.rs +0 -0
rust/kernel/lib.rs +1 -1
@@ -63,6 +63,7 @@extern crate selfas 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" )]
scripts/generate_rust_analyzer.py +1 -1
@@ -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"], )
Signature · 1 line
2.52.0.351.gbe84eed79e-goog
PATCH v3 4/4 rust: transmute: Support deriving AsBytes/FromBytes on bindgen types
In reply to Matthew MaurerProvide 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.
--- 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(-)
rust/Makefile +6 -2
@@ -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)
rust/bindgen_parameters +8 -0
@@ -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
rust/bindings/lib.rs +4 -0
@@ -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.
rust/macros/lib.rs +22 -2
@@ -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! (tokensas 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! (tokensas 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! (tokensas 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! (tokensas DeriveInput ); + transmute::as_bytes ("ffi" , input).into () }
rust/macros/transmute.rs +7 -5
@@ -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.dataelse {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
rust/uapi/lib.rs +4 -0
@@ -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" ));
Signature · 1 line
2.52.0.351.gbe84eed79e-goog
Alexandre Courbot
reviewerHi Matthew,
Quoted 20 lines · Matthew Maurer
Currently:
* Slices ofAsBytes/FromBytestypes cannot be synthesized from bytes slices (without unsafe).
* Users must useunsafe implto assert that structs areAsBytesorFromBytesand write appropriate justifications.
* Bindgen-generated types cannot implementAsBytesorFromBytes, meaning that casting them to or from bytes involves assumptions in theunsafe implthat 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 toFromBytes
2. Adding a derive forAsBytesandFromBytes, for now restricted to the simple case of structs.
3. Refactoring the crate structure to moveAsBytesandFromBytestoffito allowbindingsanduapito reference them.
4. Enabling bindgen derivation inbindings/uapithroughAsBytesFfiandFromBytesFfi.
Quoted 4 lines
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 <[email protected]>
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.
Quoted 4 lines
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.
Quoted 3 lines · Matthew Maurer
2. I heard there was work going on to introduce
zerocopyas an additional vendored crate.
Yeah, that is my plan for this cycle.
Cheers,
Miguel
Alexandre Courbot
reviewerQuoted 6 lines · Miguel Ojeda
Quoted 3 lines · Matthew Maurer
2. I heard there was work going on to introduce
zerocopyas an additional vendored crate.Yeah, that is my plan for this cycle.
Great news - holding on then.