Support more safe `AsBytes`/`FromBytes` usage
Subsystems (2)
v2 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 allow the derives added in 2 to be used on bindgen definitions.
1 or 2 can be taken independently, 3 requires 2.
---
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 (3):
rust: transmute: Support transmuting slices of AsBytes/FromBytes types
rust: Add support for deriving AsBytes and FromBytes
rust: 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 | 60 ++++++++++++++++++++++++++++
rust/uapi/lib.rs | 4 ++
scripts/generate_rust_analyzer.py | 2 +-
10 files changed, 247 insertions(+), 7 deletions(-)---
base-commit: 008d3547aae5bc86fac3eda317489169c3fda112
change-id: 20251212-transmute-8ab6076700a8
Best regards,
Signature · 1 line
Matthew Maurer <[email protected]>
PATCH v2 1/3 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.305.g3fc767764a-goog
Re: [PATCH v2 1/3] rust: transmute: Support transmuting slices of AsBytes/FromBytes types
Hi Matthew,
Quoted 44 lines · Matthew Maurer
Currently, we support either transmuting a byte slice of the exact size of the target type or a single element from a prefix of a byte slice.
This adds support for transmuting from a byte slice to a slice of elements, assuming appropriate traits are implemented.
Signed-off-by Matthew Maurer <[email protected]>---
rust/kernel/transmute.rs| 72 ++++++++++++++++++++++++++++++++++++++++++++++++1 file changed, 72 insertions(+)rust/kernel/transmute.rs +23
-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:
rust/kernel/transmute.rs fn from_bytes_mut_prefix(bytes: &mut [u8]) -> Option<(&mut Self, &mut [u8])> · line 157
Quoted 10 lines
rust/kernel/transmute.rs +10
-0+// - `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 + }
Nit: I’d rewrite this as
if !ptr.is_aligned() {
return None;
}
unsafe { Some(core::slice::from_raw_parts(ptr, len)) }
This saves one indentation level.
Quoted 27 lines
rust/kernel/transmute.rs +27
-0+ } + +/// 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>()`.
rust/kernel/transmute.rs fn from_bytes_mut_prefix(bytes: &mut [u8]) -> Option<(&mut Self, &mut [u8])> · line 194
Quoted 10 lines
rust/kernel/transmute.rs +10
-0+// - `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 + }
Same here.
Quoted 10 lines
rust/kernel/transmute.rs +2
-0+ } +/// Creates an owned instance of `Self` by copying `bytes`. /// /// Unlike [`FromBytes::from_bytes`], which requires aligned input, this method can be used on Signature · 2 lines
-- 2.52.0.305.g3fc767764a-goog
Re: [PATCH v2 1/3] rust: transmute: Support transmuting slices of AsBytes/FromBytes types
Quoted 60 lines · Daniel Almeida
Hi Matthew,
Quoted 44 lines · Matthew Maurer
Currently, we support either transmuting a byte slice of the exact size of the target type or a single element from a prefix of a byte slice.
This adds support for transmuting from a byte slice to a slice of elements, assuming appropriate traits are implemented.
Signed-off-by Matthew Maurer <[email protected]>---
rust/kernel/transmute.rs| 72 ++++++++++++++++++++++++++++++++++++++++++++++++1 file changed, 72 insertions(+)rust/kernel/transmute.rs +23
-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: rust/kernel/transmute.rs fn from_bytes_mut_prefix(bytes: &mut [u8]) -> Option<(&mut Self, &mut [u8])> · line 157
Quoted 10 lines
rust/kernel/transmute.rs +10
-0+// - `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 + }Nit: I’d rewrite this as
Quoted 8 lines
if !ptr.is_aligned() {
return None;
}unsafe {
Some(core::slice::from_raw_parts(ptr, len))}This saves one indentation level.
If this code were sizable, or if there were no unsafe, I'd agree with you. However:
1. It makes the path condition for the unsafe block clearer - the if condition directly guards the unsafe block, which makes it locally obvious why it can assume "ptr is aligned for Self." With the "check error and early return" strategy, you need to reason less locally about the reachability of the statement.
2. The guarded code is one line long. If it were significant, then I can see the point of using an early-return style in order to avoid indentation, especially if the block *itself* had indentation. This is one line.
3. This is coherent with from_bytes_mut and from_bytes in this file, which also use this style.
Quoted 31 lines
Quoted 31 lines
rust/kernel/transmute.rs +31
-0+ } + +/// 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
Quoted 8 lines
rust/kernel/transmute.rs fn from_bytes_mut_prefix(bytes: &mut [u8]) -> Option<(&mut Self, &mut [u8])> · line 194
Quoted 6 lines
rust/kernel/transmute.rs +6
-0+// 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 + }Same here.
Same here :)
Quoted 14 lines
Quoted 11 lines
rust/kernel/transmute.rs +2
-1+ } +/// 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.305.g3fc767764a-goog
Reviewed-by Daniel Almeida <[email protected]>
PATCH v2 2/3 rust: 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 | 58 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 121 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 +58 -0
58 lines not on this page · raw message
Signature · 1 line
2.52.0.305.g3fc767764a-goog
Alexandre Courbot
reviewerRe: [PATCH v2 2/3] rust: Add support for deriving `AsBytes` and `FromBytes`
Quoted 6 lines · Matthew Maurer
This provides a derive macro for
AsBytesandFromBytesfor structs only. For both, it checks the respective trait on every underlying field. ForAsBytes, it emits a const-time padding check that will fail the compilation if derived on a type with padding.Signed-off-by Matthew Maurer <[email protected]>
I like this a lot. We have a bunch of unsafe impls in Nova that this could help us get rid of.
Amazed that this even seems to work on tuple structs!
Quoted 41 lines
--- rust/macros/lib.rs | 63 ++++++++++++++++++++++++++++++++++++++++++++++++ rust/macros/transmute.rs | 58 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 121 insertions(+)rust/macros/lib.rs +18
-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
rust/macros/lib.rs pub fn paste(input: TokenStream) -> TokenStream { · line 505
Quoted 10 lines
rust/macros/lib.rs +10
-0+/// +/// ``` +/// #[derive(FromBytes)] +/// #[repr(C)] +/// struct Foo { +/// x: u32, +/// y: u16, +/// z: u16, +/// } +/// ```
One thing I have noticed is that I could sucessfully derive FromBytes on a struct that is not repr(C)... Is that something we want to disallow?
Re: [PATCH v2 2/3] rust: Add support for deriving `AsBytes` and `FromBytes`
Quoted 61 lines · Alexandre Courbot
Quoted 6 lines · Matthew Maurer
This provides a derive macro for
AsBytesandFromBytesfor structs only. For both, it checks the respective trait on every underlying field. ForAsBytes, it emits a const-time padding check that will fail the compilation if derived on a type with padding.Signed-off-by Matthew Maurer <[email protected]>I like this a lot. We have a bunch of unsafe impls in Nova that this could help us get rid of.
Amazed that this even seems to work on tuple structs!
Quoted 47 lines
--- rust/macros/lib.rs | 63 ++++++++++++++++++++++++++++++++++++++++++++++++ rust/macros/transmute.rs | 58 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 121 insertions(+)rust/macros/lib.rs +24
-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,
Quoted 9 lines
rust/macros/lib.rs pub fn paste(input: TokenStream) -> TokenStream { · line 505
Quoted 4 lines
rust/macros/lib.rs +4
-0+/// y: u16, +/// z: u16, +/// } +/// ``` One thing I have noticed is that I could sucessfully derive
FromByteson a struct that is notrepr(C)... Is that something we want to disallow?
Why should we disallow this? I can enforce it very easily if we want it, but the only difference between #[repr(C)] and #[repr(Rust)] is whether we can statically predict their layout. In theory you can use this to elide the padding check for #[repr(C)] structs (and zerocopy does this), but it's significantly more complicated.
The only argument I see in favor of disallowing #[repr(Rust)] here is that if it's not a struct that also supports AsBytes, there's a question about where you're getting the bytes to load from.
I will point out that we probably don't *just* want to restrict to #[repr(C)] because #[repr(transparent)] and #[repr(packed)] are also great use cases.
Daniel Almeida
reviewerRe: [PATCH v2 2/3] rust: Add support for deriving `AsBytes` and `FromBytes`
Quoted 82 lines · Matthew Maurer
Quoted 61 lines · Alexandre Courbot
Quoted 6 lines · Matthew Maurer
This provides a derive macro for
AsBytesandFromBytesfor structs only. For both, it checks the respective trait on every underlying field. ForAsBytes, it emits a const-time padding check that will fail the compilation if derived on a type with padding.Signed-off-by Matthew Maurer <[email protected]>I like this a lot. We have a bunch of unsafe impls in Nova that this could help us get rid of.
Amazed that this even seems to work on tuple structs!
Quoted 47 lines
---
rust/macros/lib.rs| 63 ++++++++++++++++++++++++++++++++++++++++++++++++rust/macros/transmute.rs| 58 ++++++++++++++++++++++++++++++++++++++++++++2 files changed, 121 insertions(+)rust/macros/lib.rs +24
-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, Quoted 9 lines
rust/macros/lib.rs pub fn paste(input: TokenStream) -> TokenStream { · line 505
Quoted 4 lines
rust/macros/lib.rs +4
-0+/// y: u16, +/// z: u16, +/// } +/// ``` One thing I have noticed is that I could sucessfully derive
FromByteson a struct that is notrepr(C)... Is that something we want to disallow?Why should we disallow this? I can enforce it very easily if we want it, but the only difference between
#[repr(C)]and#[repr(Rust)]is whether we can statically predict their layout. In theory you can use this to elide the padding check for#[repr(C)]structs (andzerocopydoes this), but it's significantly more complicated.
Quoted 8 lines
The only argument I see in favor of disallowing
#[repr(Rust)]here is that if it's not a struct that also supportsAsBytes, there's a question about where you're getting the bytes to load from.I will point out that we probably don't *just* want to restrict to
#[repr(C)]because#[repr(transparent)]and#[repr(packed)]are also great use cases.
I don’t see the point of disallowing other reprs. You can currently derive FromBytes/AsBytes for any repr anyways. It’s up to the caller to make sure that deriving these traits make sense.
Alexandre Courbot
reviewerRe: [PATCH v2 2/3] rust: Add support for deriving `AsBytes` and `FromBytes`
In reply to Matthew MaurerQuoted 78 lines · Matthew Maurer
Quoted 61 lines · Alexandre Courbot
Quoted 6 lines · Matthew Maurer
This provides a derive macro for
AsBytesandFromBytesfor structs only. For both, it checks the respective trait on every underlying field. ForAsBytes, it emits a const-time padding check that will fail the compilation if derived on a type with padding.Signed-off-by Matthew Maurer <[email protected]>I like this a lot. We have a bunch of unsafe impls in Nova that this could help us get rid of.
Amazed that this even seems to work on tuple structs!
Quoted 47 lines
--- rust/macros/lib.rs | 63 ++++++++++++++++++++++++++++++++++++++++++++++++ rust/macros/transmute.rs | 58 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 121 insertions(+)rust/macros/lib.rs +24
-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, Quoted 9 lines
rust/macros/lib.rs pub fn paste(input: TokenStream) -> TokenStream { · line 505
Quoted 4 lines
rust/macros/lib.rs +4
-0+/// y: u16, +/// z: u16, +/// } +/// ``` One thing I have noticed is that I could sucessfully derive
FromByteson a struct that is notrepr(C)... Is that something we want to disallow?Why should we disallow this? I can enforce it very easily if we want it, but the only difference between
#[repr(C)]and#[repr(Rust)]is whether we can statically predict their layout. In theory you can use this to elide the padding check for#[repr(C)]structs (andzerocopydoes this), but it's significantly more complicated.
Quoted 7 lines
The only argument I see in favor of disallowing
#[repr(Rust)]here is that if it's not a struct that also supportsAsBytes, there's a question about where you're getting the bytes to load from.I will point out that we probably don't *just* want to restrict to
#[repr(C)]because#[repr(transparent)]and#[repr(packed)]are also great use cases.
Yeah it's probably correct as it is. I am not sure why we would want to use it on types without a predictable layout, but also cannot say this is fundamentally broken.
Alice Ryhl
reviewerRe: [PATCH v2 2/3] rust: Add support for deriving `AsBytes` and `FromBytes`
Quoted 40 lines · Alexandre Courbot
Quoted 39 lines · Matthew Maurer
Quoted 18 lines · Alexandre Courbot
Quoted 18 lines
rust/macros/lib.rs +18
-0+/// 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, Quoted 9 lines
rust/macros/lib.rs pub fn paste(input: TokenStream) -> TokenStream { · line 505
Quoted 4 lines
rust/macros/lib.rs +4
-0+/// y: u16, +/// z: u16, +/// } +/// ``` One thing I have noticed is that I could sucessfully derive
FromByteson a struct that is notrepr(C)... Is that something we want to disallow?Why should we disallow this? I can enforce it very easily if we want it, but the only difference between
#[repr(C)]and#[repr(Rust)]is whether we can statically predict their layout. In theory you can use this to elide the padding check for#[repr(C)]structs (andzerocopydoes this), but it's significantly more complicated.The only argument I see in favor of disallowing
#[repr(Rust)]here is that if it's not a struct that also supportsAsBytes, there's a question about where you're getting the bytes to load from.
Quoted 7 lines
Quoted 3 lines
I will point out that we probably don't *just* want to restrict to
#[repr(C)]because#[repr(transparent)]and#[repr(packed)]are also great use cases.Yeah it's probably correct as it is. I am not sure why we would want to use it on types without a predictable layout, but also cannot say this is fundamentally broken.
At the very least such types can roundtrip to/from byte arrays. Or you could pass them to the randomness pool:
https://lore.kernel.org/all/[email protected]/
Alice
Daniel Almeida
reviewerRe: [PATCH v2 2/3] rust: Add support for deriving `AsBytes` and `FromBytes`
In reply to Matthew MaurerMatthew,
Quoted 67 lines · Matthew Maurer
This provides a derive macro for
AsBytesandFromBytesfor structs only. For both, it checks the respective trait on every underlying field. ForAsBytes, it emits a const-time padding check that will fail the compilation if derived on a type with padding.Signed-off-by Matthew Maurer <[email protected]>---
rust/macros/lib.rs| 63 ++++++++++++++++++++++++++++++++++++++++++++++++rust/macros/transmute.rs| 58 ++++++++++++++++++++++++++++++++++++++++++++2 files changed, 121 insertions(+)rust/macros/lib.rs +36
-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. +///
rust/macros/lib.rs pub fn paste(input: TokenStream) -> TokenStream { · line 523
Quoted 10 lines
rust/macros/lib.rs +10
-0+/// 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
Why is padding relevant here but not in FromBytes?
Quoted 23 lines
rust/macros/lib.rs +17
-0+/// +/// # 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 +0
-0
rust/macros/transmute.rs line 9
Quoted 9 lines
rust/macros/transmute.rs new file +9
-0@@ -0,0 +1,58 @@ +// 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); +parse_quote! { +where #(for <'a> #tys : #trait_),*
Why do we need this hrtb here?
Quoted 18 lines
rust/macros/transmute.rs new file +18
-0+ } +} + +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.dataelse { +return quote::quote! {compile_error! ("#[derive(AsBytes)] only supports structs" ) };
rust/macros/transmute.rs line 37
Quoted 10 lines
rust/macros/transmute.rs new file +10
-0+ }; +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 {} + }
In general I’d add blanks.
Quoted 26 lines
rust/macros/transmute.rs new file +21
-0+} + +pub (crate )fn from_bytes (input:DeriveInput ) ->TokenStream { +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 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 {} + } +}Signature · 2 lines
-- 2.52.0.305.g3fc767764a-goog
Overall looks good. Please chime in on the two questions above.
— Daniel
Re: [PATCH v2 2/3] rust: Add support for deriving `AsBytes` and `FromBytes`
Quoted 74 lines · Daniel Almeida
Matthew,
Quoted 71 lines · Matthew Maurer
This provides a derive macro for
AsBytesandFromBytesfor structs only. For both, it checks the respective trait on every underlying field. ForAsBytes, it emits a const-time padding check that will fail the compilation if derived on a type with padding.Signed-off-by Matthew Maurer <[email protected]>---
rust/macros/lib.rs| 63 ++++++++++++++++++++++++++++++++++++++++++++++++rust/macros/transmute.rs| 58 ++++++++++++++++++++++++++++++++++++++++++++2 files changed, 121 insertions(+)rust/macros/lib.rs +40
-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.
Quoted 8 lines
rust/macros/lib.rs pub fn paste(input: TokenStream) -> TokenStream { · line 523
Quoted 6 lines
rust/macros/lib.rs +6
-0+/// +/// 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 Why is padding relevant here but not in FromBytes?
Padding bytes can be initialized to any value, but it is UB to observe their contents because they may be implicitly uninitialized[1]. This also matches the approach of zerocopy[2], which is the standard for these sorts of transmutations outside the kernel - any byte can go into the padding, but you cannot *read* any byte out of the padding.
[1]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html#r-undefined.validity.undef
[2]: https://docs.rs/zerocopy/latest/zerocopy/trait.FromBytes.html#warning-padding-bytes
Quoted 27 lines
Quoted 27 lines
rust/macros/lib.rs +17
-0+/// +/// # 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 +3
-0@@ -0,0 +1,58 @@ +// SPDX-License-Identifier: GPL-2.0 + +use proc_macro2::TokenStream ;
Quoted 8 lines
rust/macros/transmute.rs line 9
Quoted 6 lines
rust/macros/transmute.rs new file +6
-0+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); +parse_quote! { +where #(for <'a> #tys : #trait_),*Why do we need this hrtb here?
It's a workaround to avoid needing #![feature(trivial_bounds)]. Without it, generated code for, say, where *const T: FromBytes will immediately cause a compilation error. With it, it will simply cause the trait's requirements to be unfulfilled.
Quoted 23 lines
Quoted 23 lines
rust/macros/transmute.rs new file +22
-0+ } +} + +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.dataelse { +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_);
Quoted 8 lines
rust/macros/transmute.rs line 37
Quoted 6 lines
rust/macros/transmute.rs new file +6
-0+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 {} + }In general I’d add blanks.
I'm not sure what you're suggesting here.
Quoted 32 lines
Quoted 24 lines
rust/macros/transmute.rs new file +21
-1+} + +pub (crate )fn from_bytes (input:DeriveInput ) ->TokenStream { +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 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 {} + } +} --Quoted 3 lines
2.52.0.305.g3fc767764a-goog
Overall looks good. Please chime in on the two questions above.
— Daniel
Daniel Almeida
reviewerRe: [PATCH v2 2/3] rust: Add support for deriving `AsBytes` and `FromBytes`
Quoted 89 lines · Matthew Maurer
Quoted 74 lines · Daniel Almeida
Matthew,
Quoted 71 lines · Matthew Maurer
This provides a derive macro for
AsBytesandFromBytesfor structs only. For both, it checks the respective trait on every underlying field. ForAsBytes, it emits a const-time padding check that will fail the compilation if derived on a type with padding.Signed-off-by Matthew Maurer <[email protected]>---
rust/macros/lib.rs| 63 ++++++++++++++++++++++++++++++++++++++++++++++++rust/macros/transmute.rs| 58 ++++++++++++++++++++++++++++++++++++++++++++2 files changed, 121 insertions(+)rust/macros/lib.rs +40
-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. Quoted 8 lines
rust/macros/lib.rs pub fn paste(input: TokenStream) -> TokenStream { · line 523
Quoted 6 lines
rust/macros/lib.rs +6
-0+/// +/// 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 Why is padding relevant here but not in FromBytes?
Quoted 8 lines
Padding bytes can be initialized to any value, but it is UB to observe their contents because they may be implicitly uninitialized[1]. This also matches the approach of
zerocopy[2], which is the standard for these sorts of transmutations outside the kernel - any byte can go into the padding, but you cannot *read* any byte out of the padding.[1]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html#r-undefined.validity.undef
[2]: https://docs.rs/zerocopy/latest/zerocopy/trait.FromBytes.html#warning-padding-bytes
Ack
Quoted 37 lines
Quoted 28 lines
Quoted 28 lines
rust/macros/lib.rs +17
-0+/// +/// # 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 +3
-0@@ -0,0 +1,58 @@ +// SPDX-License-Identifier: GPL-2.0 + +use proc_macro2::TokenStream ;Quoted 8 lines
rust/macros/transmute.rs line 9
Quoted 6 lines
rust/macros/transmute.rs new file +6
-0+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); +parse_quote! { +where #(for <'a> #tys : #trait_),*Why do we need this hrtb here?
Quoted 4 lines
It's a workaround to avoid needing
#![feature(trivial_bounds)]. Without it, generated code for, say,where *const T: FromByteswill immediately cause a compilation error. With it, it will simply cause the trait's requirements to be unfulfilled.
Perhaps add this as a comment. It’s not clear at all that this is a workaround at first.
Quoted 33 lines
Quoted 24 lines
Quoted 24 lines
rust/macros/transmute.rs new file +22
-0+ } +} + +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.dataelse { +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_);Quoted 8 lines
rust/macros/transmute.rs line 37
Quoted 6 lines
rust/macros/transmute.rs new file +6
-0+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 {} + }In general I’d add blanks.
Quoted 1 line
I'm not sure what you're suggesting here.
Add blank lines to break this thing up for readability. This entire function has 0 blank lines, it’s a bit hard to read. Anyways, this is just a nit.
Quoted 32 lines
Quoted 32 lines
Quoted 25 lines
rust/macros/transmute.rs new file +21
-1+} + +pub (crate )fn from_bytes (input:DeriveInput ) ->TokenStream { +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 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 {} + } +} --Quoted 3 lines
2.52.0.305.g3fc767764a-goog
Overall looks good. Please chime in on the two questions above.
— Daniel
PATCH v2 3/3 rust: Support deriving `AsBytes`/`FromBytes` on bindgen types
In reply to Matthew MaurerTo support this, we need to move the transmute module into a separate crate to allow the bindings crate to depend on it. Most user code is still expected to address the module as kernel::transmute, which is a re-export. ffi::transmute is now available for use in bindings.
---
rust/Makefile | 14 +++++++++-----
rust/bindgen_parameters | 8 ++++++++
rust/bindings/lib.rs | 4 ++++
rust/{ffi.rs => ffi/lib.rs} | 5 +++++
rust/{kernel => ffi}/transmute.rs | 0
rust/kernel/lib.rs | 2 +-
rust/macros/lib.rs | 24 ++++++++++++++++++++++--
rust/macros/transmute.rs | 12 +++++++-----
rust/uapi/lib.rs | 4 ++++
scripts/generate_rust_analyzer.py | 2 +-
10 files changed, 61 insertions(+), 14 deletions(-)rust/Makefile +9 -5
@@ -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,22 +657,26 @@ $(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 +$(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/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" )]
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 {
@@ -19,7 +19,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" ) }; }
@@ -27,7 +28,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! {
@@ -37,13 +38,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" ));
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.305.g3fc767764a-goog
Alexandre Courbot
reviewerRe: [PATCH v2 3/3] rust: Support deriving `AsBytes`/`FromBytes` on bindgen types
Quoted 6 lines · Matthew Maurer
To support this, we need to move the
transmutemodule into a separate crate to allow thebindingscrate to depend on it. Most user code is still expected to address the module askernel::transmute, which is a re-export.ffi::transmuteis now available for use inbindings.Signed-off-by Matthew Maurer <[email protected]>
Maybe this should be two commits, one for the new crate, another one to introduce the ability to use on bindgen types.
I have tried this with the Nova bindings, and somehow could not get past this error:
error[E0433]: failed to resolve: could not find ffi in the list of imported crates
--> ../drivers/gpu/nova-core/gsp/fw/r570_144/bindings.rs:321:54
|
321 | #[derive(Debug, Default, Copy, Clone, MaybeZeroable, FromBytesFfi)]
| ^^^^^^^^^^^^ could not find ffi in the list of imported crates
|
= note: this error originates in the derive macro FromBytesFfi (in Nightly builds, run with -Z macro-backtrace for more info)
I do have kernel::ffi imported in the bindings module though, so I am not quite sure what this is about. Any idea?
Re: [PATCH v2 3/3] rust: Support deriving `AsBytes`/`FromBytes` on bindgen types
Quoted 11 lines · Alexandre Courbot
Quoted 6 lines · Matthew Maurer
To support this, we need to move the
transmutemodule into a separate crate to allow thebindingscrate to depend on it. Most user code is still expected to address the module askernel::transmute, which is a re-export.ffi::transmuteis now available for use inbindings.Signed-off-by Matthew Maurer <[email protected]>Maybe this should be two commits, one for the new crate, another one to introduce the ability to use on bindgen types.
I could do this if people think it'd be helpful, but moving it into the ffi crate has no point without using on the main set of bindgen types.
Quoted 12 lines
I have tried this with the Nova bindings, and somehow could not get past this error:
error[E0433]: failed to resolve: could not find
ffiin the list of imported crates
-->../drivers/gpu/nova-core/gsp/fw/r570_144/bindings.rs:321:54
|
321 | #[derive(Debug, Default, Copy, Clone, MaybeZeroable, FromBytesFfi)]
| ^^^^^^^^^^^^ could not findffiin the list of imported crates
|
= note: this error originates in the derive macroFromBytesFfi(in Nightly builds, run with -Z macro-backtrace for more info)
Quoted 2 lines
I do have
kernel::ffiimported in the bindings module though, so I am not quite sure what this is about. Any idea?
If you have the kernel module available, please set the bindgen flag to apply FromBytes and AsBytes rather than FromBytesFfi and AsBytesFfi. Those are only for the crates that are used by the kernel crate, and so do not have access to the kernel crate.
The macro itself will generate ::kernel::transmute::FromBytes when you use FromBytes and ::ffi::transmute::FromBytes when you use FromBytesFfi, specifically to avoid weirdness around namespaces and imports.
If for some reason you really wanted to use FromBytesFfi (you shouldn't, but just so you understand the mechanism), you'd need to add a direct dependency edge on the ffi crate, i.e. --extern crate ffi
Daniel Almeida
reviewerRe: [PATCH v2 3/3] rust: Support deriving `AsBytes`/`FromBytes` on bindgen types
In reply to Matthew MaurerMatthew,
Quoted 6 lines · Matthew Maurer
To support this, we need to move the
transmutemodule into a separate crate to allow thebindingscrate to depend on it. Most user code is still expected to address the module askernel::transmute, which is a re-export.ffi::transmuteis now available for use inbindings.
Thanks, that’s really useful for Tyr.
Quoted 60 lines
Signed-off-by Matthew Maurer <[email protected]>---
rust/Makefile | 14 +++++++++----- rust/bindgen_parameters | 8 ++++++++ rust/bindings/lib.rs | 4 ++++ rust/{ffi.rs => ffi/lib.rs} | 5 +++++ rust/{kernel => ffi}/transmute.rs | 0 rust/kernel/lib.rs | 2 +- rust/macros/lib.rs | 24 ++++++++++++++++++++++-- rust/macros/transmute.rs | 12 +++++++----- rust/uapi/lib.rs | 4 ++++ scripts/generate_rust_analyzer.py | 2 +- 10 files changed, 61 insertions(+), 14 deletions(-)rust/Makefile +1
-0@@ -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
rust/Makefile +2
-1-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= yesrust/Makefile +0
-0@@ -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)
rust/Makefile +2
-1-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)rust/Makefile +1
-0@@ -657,22 +657,26 @@ $(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 --externpin_init+$(obj)/bindings.o: privaterustc_target_flags= --extern ffi --externpin_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 --externpin_init+$(obj)/uapi.o: privaterustc_target_flags= --extern ffi --externpin_init\
+ --extern macros
$(obj)/uapi.o: privateskip_gendwarfksyms= 1
Quoted 6 lines
$(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)
+1 on splitting the above into a separate commit
Quoted 89 lines
rust/bindgen_parameters +8
-2@@ -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=AsBytesFfirust/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/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
-0rust/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" )] rust/macros/lib.rs +1
-1@@ -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.
rust/macros/lib.rs pub fn derive_from_bytes(tokens: TokenStream) -> TokenStream { · line 543
Quoted 9 lines
rust/macros/lib.rs +5
-1@@ -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 )]
Let’s perhaps capitalize this as FromBytesFFI?
rust/macros/lib.rs pub fn derive_from_bytes(tokens: TokenStream) -> TokenStream { · line 553
Quoted 10 lines
rust/macros/lib.rs +10
-0+/// 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 )]
Same here?
Quoted 60 lines
rust/macros/lib.rs +6
-0+/// 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 {@@ -19,7 +19,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" ) }; }@@ -27,7 +28,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! {@@ -37,13 +38,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_clauserust/uapi/lib.rs +0
-0
rust/uapi/lib.rs line 39
Quoted 6 lines
rust/uapi/lib.rs +3
-0@@ -34,6 +34,10 @@type __kernel_ssize_t =isize ;type __kernel_ptrdiff_t =isize ; +use macros::{ +AsBytesFfi , +FromBytesFfi ,//
Why is this “//" here? Is this related to the import style change that took place recently?
Quoted 22 lines
rust/uapi/lib.rs +1
-0+};use pin_init::MaybeZeroable ;include! (concat! (env! ("OBJTREE" ),"/rust/uapi/uapi_generated.rs" ));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 · 2 lines
-- 2.52.0.305.g3fc767764a-goog
^ IMHO, this should also be in separate commit.
Looks good to me overall.
— Daniel
Re: [PATCH v2 3/3] rust: Support deriving `AsBytes`/`FromBytes` on bindgen types
Quoted 68 lines · Daniel Almeida
Matthew,
Quoted 6 lines · Matthew Maurer
To support this, we need to move the
transmutemodule into a separate crate to allow thebindingscrate to depend on it. Most user code is still expected to address the module askernel::transmute, which is a re-export.ffi::transmuteis now available for use inbindings.Thanks, that’s really useful for Tyr.
Quoted 56 lines
Signed-off-by Matthew Maurer <[email protected]>---
rust/Makefile | 14 +++++++++----- rust/bindgen_parameters | 8 ++++++++ rust/bindings/lib.rs | 4 ++++ rust/{ffi.rs => ffi/lib.rs} | 5 +++++ rust/{kernel => ffi}/transmute.rs | 0 rust/kernel/lib.rs | 2 +- rust/macros/lib.rs | 24 ++++++++++++++++++++++-- rust/macros/transmute.rs | 12 +++++++----- rust/uapi/lib.rs | 4 ++++ scripts/generate_rust_analyzer.py | 2 +- 10 files changed, 61 insertions(+), 14 deletions(-)rust/Makefile +1
-0@@ -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
rust/Makefile +2
-1-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= yesrust/Makefile +0
-0@@ -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)
rust/Makefile +2
-1-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)rust/Makefile +1
-0@@ -657,22 +657,26 @@ $(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 --externpin_init+$(obj)/bindings.o: privaterustc_target_flags= --extern ffi --externpin_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)
Quoted 12 lines
Quoted 10 lines
-$(obj)/uapi.o: private
rustc_target_flags= --extern ffi --externpin_init+$(obj)/uapi.o: privaterustc_target_flags= --extern ffi --externpin_init\
+ --extern macros
$(obj)/uapi.o: privateskip_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)
+1 on splitting the above into a separate commit
Sure, I'll do that in the next rev. Two people seems like enough of a signal :)
Quoted 88 lines
Quoted 88 lines
rust/bindgen_parameters +8
-2@@ -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=AsBytesFfirust/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/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
-0rust/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" )] rust/macros/lib.rs +1
-1@@ -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 () }
Quoted 13 lines
rust/macros/lib.rs pub fn derive_from_bytes(tokens: TokenStream) -> TokenStream { · line 543
Quoted 11 lines
rust/macros/lib.rs +5
-1/// 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 )] Let’s perhaps capitalize this as FromBytesFFI?
Our Rust coding guidelines[1] do not specify a kernel-specific practice here, and say to defer to standard ecosystem guidance[2]. Derive macros take the position of traits, which should be in UpperCamelCase. There is an explicit section which reads: "In UpperCamelCase, acronyms and contractions of compound words count as one word: use Uuid rather than UUID". While we are free to define our own naming standards in the kernel, I do not see anything in the current Rust coding guidelines[2] to overrule standard guidance here.
[1]: https://docs.kernel.org/rust/coding-guidelines.html
[2]: https://rust-lang.github.io/api-guidelines/naming.html
Quoted 112 lines
rust/macros/lib.rs pub fn derive_from_bytes(tokens: TokenStream) -> TokenStream { · line 553
Quoted 11 lines
rust/macros/lib.rs +10
-0+/// 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 )] Same here?
Quoted 60 lines
rust/macros/lib.rs +6
-0+/// 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 {@@ -19,7 +19,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" ) }; }@@ -27,7 +28,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! {@@ -37,13 +38,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_clauserust/uapi/lib.rs +0
-0rust/uapi/lib.rs line 39
Quoted 6 lines
rust/uapi/lib.rs +3
-0@@ -34,6 +34,10 @@type __kernel_ssize_t =isize ;type __kernel_ptrdiff_t =isize ; +use macros::{ +AsBytesFfi , +FromBytesFfi ,// Why is this “//" here? Is this related to the import style change that took place recently?
Quoted 19 lines
rust/uapi/lib.rs +1
-0+};use pin_init::MaybeZeroable ;include! (concat! (env! ("OBJTREE" ),"/rust/uapi/uapi_generated.rs" ));scripts/generate_rust_analyzer.py +1
-2@@ -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"], ) --Quoted 3 lines
2.52.0.305.g3fc767764a-goog
^ IMHO, this should also be in separate commit.
Looks good to me overall.
— Daniel