rust: pin-init: internal: init: document load-bearing fact of field accessors
Subsystems (2)
Benno Lossin
reviewerPATCH 1/2 rust: pin-init: internal: init: document load-bearing fact of field accessors
[ Upstream commit 580cc37b1de4fcd9997c48d7080e744533f09f36 ]
The functions [Pin]Init::__[pinned_]init and ptr::write called from the init! macro require the passed pointer to be aligned. This fact is ensured by the creation of field accessors to previously initialized fields.
Since we missed this very important fact from the beginning [1], document it in the code.
[ Moved changes to the declarative macro, because 6.19.y and earlier do not
have syn. Also duplicated the comment for all field accessor creations.
- Benno ]
--- rust/pin-init/src/macros.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+)
rust/pin-init/src/macros.rs +16 -0
@@ -1312,6 +1312,10 @@ fn assert_zeroable<T: $crate::Zeroable>(_: *mut T) {}// return when an error/panic occurs. // We also use the `data` to require the correct trait (`Init` or `PinInit`) for `$field`. unsafe { $data.$field(::core::ptr::addr_of_mut!((*$slot).$field), init)? }; +// NOTE: the field accessor ensures that the initialized field is properly aligned. +// Unaligned fields will cause the compiler to emit E0793. We do not support +// unaligned fields since `Init::__init` requires an aligned pointer; the call to +// `ptr::write` below has the same requirement. // SAFETY: // - the project function does the correct field projection, // - the field has been initialized,
@@ -1351,6 +1355,10 @@ fn assert_zeroable<T: $crate::Zeroable>(_: *mut T) {}// return when an error/panic occurs. unsafe { $crate::Init ::__init (init, ::core::ptr::addr_of_mut!((*$slot).$field))? }; +// NOTE: the field accessor ensures that the initialized field is properly aligned. +// Unaligned fields will cause the compiler to emit E0793. We do not support +// unaligned fields since `Init::__init` requires an aligned pointer; the call to +// `ptr::write` below has the same requirement. // SAFETY: // - the field is not structurally pinned, since the line above must compile, // - the field has been initialized,
@@ -1391,6 +1399,10 @@ fn assert_zeroable<T: $crate::Zeroable>(_: *mut T) {}unsafe { ::core::ptr::write (::core::ptr::addr_of_mut!((*$slot).$field), $field) }; } +// NOTE: the field accessor ensures that the initialized field is properly aligned. +// Unaligned fields will cause the compiler to emit E0793. We do not support +// unaligned fields since `Init::__init` requires an aligned pointer; the call to +// `ptr::write` below has the same requirement. #[allow(unused_variables)] // SAFETY: // - the field is not structurally pinned, since no `use_data` was required to create this
@@ -1431,6 +1443,10 @@ fn assert_zeroable<T: $crate::Zeroable>(_: *mut T) {}// SAFETY: The memory at `slot` is uninitialized. unsafe { ::core::ptr::write (::core::ptr::addr_of_mut!((*$slot).$field), $field) }; } +// NOTE: the field accessor ensures that the initialized field is properly aligned. +// Unaligned fields will cause the compiler to emit E0793. We do not support +// unaligned fields since `Init::__init` requires an aligned pointer; the call to +// `ptr::write` below has the same requirement. // SAFETY: // - the project function does the correct field projection, // - the field has been initialized,
base-commit: 4a2b0ed2ac7abe9743e1559d212075a0ebac96b3
Signature · 1 line
2.53.0
Benno Lossin
reviewerPATCH 2/2 rust: pin-init: replace shadowed return token by `unsafe`-to-create token
[ Upstream commit fdbaa9d2b78e0da9e1aeb303bbdc3adfe6d8e749 ]
We use a unit struct __InitOk in the closure generated by the initializer macros as the return value. We shadow it by creating a struct with the same name again inside of the closure, preventing early returns of Ok in the initializer (before all fields have been initialized).
In the face of Type Alias Impl Trait (TAIT) and the next trait solver, this solution no longer works [1]. The shadowed struct can be named through type inference. In addition, there is an RFC proposing to add the feature of path inference to Rust, which would similarly allow [2].
Thus remove the shadowed token and replace it with an unsafe to create token.
The reason we initially used the shadowing solution was because an alternative solution used a builder pattern. Gary writes [3]:
In the early builder-pattern based InitOk, having a single InitOk type for token is unsound because one can launder an InitOk token used for one place to another initializer. I used a branded lifetime solution, and then you figured out that using a shadowed type would work better because nobody could construct it at all.
The laundering issue does not apply to the approach we ended up with today.
With this change, the example by Tim Chirananthavat in [1] no longer compiles and results in this error:
error: cannot construct `pin_init::__internal::InitOk` with struct literal syntax due to private fields
--> src/main.rs:26:17
|
26 | InferredType {}
| ^^^^^^^^^^^^
|
= note: private field `0` that was not provided
help: you might have meant to use the `new` associated function
|
26 - InferredType {}
26 + InferredType::new()
|Applying the suggestion of using the ::new() function, results in another expected error:
error[E0133]: call to unsafe function `pin_init::__internal::InitOk::new` is unsafe and requires unsafe block
--> src/main.rs:26:17
|
26 | InferredType::new()
| ^^^^^^^^^^^^^^^^^^^ call to unsafe function
|
= note: consult the function's documentation for information on how to avoid undefined behavior[ Moved to declarative macro, because 6.19.y and earlier do not have
syn. - Benno ]
--- rust/pin-init/src/__internal.rs | 28 +++++++++++-- rust/pin-init/src/macros.rs | 73 +++++++++++++++------------------ 2 files changed, 57 insertions(+), 44 deletions(-)
rust/pin-init/src/__internal.rs +24 -4
@@ -46,6 +46,24 @@ unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> { } } +/// Token type to signify successful initialization. +/// +/// Can only be constructed via the unsafe [`Self::new`] function. The initializer macros use this +/// token type to prevent returning `Ok` from an initializer without initializing all fields. +pub struct InitOk (()); + +impl InitOk { +/// Creates a new token. +/// +/// # Safety +/// +/// This function may only be called from the `__init_internal!` macro in `./macros.rs`. +#[inline(always)] +pub unsafe fn new () ->Self { +Self (()) + } +} +/// This trait is only implemented via the `#[pin_data]` proc-macro. It is used to facilitate /// the pin projections within the initializers. ///
@@ -68,9 +86,10 @@ pub unsafe trait PinData: Copy {type Datee : ?Sized +HasPinData ;/// Type inference helper function. -fn make_closure <F ,O ,E >(self, f:F ) ->F +#[inline(always)] +fn make_closure <F ,E >(self, f:F ) ->F where -F :FnOnce (*mut Self ::Datee ) ->Result <O ,E >, +F :FnOnce (*mut Self ::Datee ) ->Result <InitOk ,E >, { f }
@@ -98,9 +117,10 @@ pub unsafe trait InitData: Copy {type Datee : ?Sized +HasInitData ;/// Type inference helper function. -fn make_closure <F ,O ,E >(self, f:F ) ->F +#[inline(always)] +fn make_closure <F ,E >(self, f:F ) ->F where -F :FnOnce (*mut Self ::Datee ) ->Result <O ,E >, +F :FnOnce (*mut Self ::Datee ) ->Result <InitOk ,E >, { f }
rust/pin-init/src/macros.rs +33 -40
90 lines not on this page · raw message
Signature · 1 line
2.53.0
Greg KH
maintainerRe: [PATCH 6.19.y 2/2] rust: pin-init: replace shadowed return token by `unsafe`-to-create token
Quoted 67 lines · Benno Lossin
[ Upstream commit
fdbaa9d2b78e0da9e1aeb303bbdc3adfe6d8e749]We use a unit struct
__InitOkin the closure generated by the initializer macros as the return value. We shadow it by creating a struct with the same name again inside of the closure, preventing early returns ofOkin the initializer (before all fields have been initialized).In the face of Type Alias Impl Trait (TAIT) and the next trait solver, this solution no longer works [1]. The shadowed struct can be named through type inference. In addition, there is an RFC proposing to add the feature of path inference to Rust, which would similarly allow [2].
Thus remove the shadowed token and replace it with an
unsafeto create token.The reason we initially used the shadowing solution was because an alternative solution used a builder pattern. Gary writes [3]:
In the early builder-pattern based InitOk, having a single InitOk type for token is unsound because one can launder an InitOk token used for one place to another initializer. I used a branded lifetime solution, and then you figured out that using a shadowed type would work better because nobody could construct it at all.
The laundering issue does not apply to the approach we ended up with today.
With this change, the example by Tim Chirananthavat in [1] no longer compiles and results in this error:
error: cannot construct `pin_init::__internal::InitOk` with struct literal syntax due to private fields --> src/main.rs:26:17 | 26 | InferredType {} | ^^^^^^^^^^^^ | = note: private field `0` that was not provided help: you might have meant to use the `new` associated function | 26 - InferredType {} 26 + InferredType::new() |Applying the suggestion of using the
::new()function, results in another expected error:error[E0133]: call to unsafe function `pin_init::__internal::InitOk::new` is unsafe and requires unsafe block --> src/main.rs:26:17 | 26 | InferredType::new() | ^^^^^^^^^^^^^^^^^^^ call to unsafe function | = note: consult the function's documentation for information on how to avoid undefined behaviorReported-by Tim Chirananthavat <[email protected]>Fixes fc6c6baa1f40 ("rust: init: add initialization macros")Signed-off-by Benno Lossin <[email protected]>Reviewed-by Alice Ryhl <[email protected]>Reviewed-by Gary Guo <[email protected]>[ Added period as mentioned. - Miguel ]Signed-off-by Miguel Ojeda <[email protected]>
Quoted 3 lines
[ Moved to declarative macro, because 6.19.y and earlier do not have
syn. - Benno ]Signed-off-by Benno Lossin <[email protected]>
This commit blows up the build for me with lots of errors like:
error[E0433]: failed to resolve: could not find init in $crate
--> rust/kernel/maple_tree.rs:393:20
|
393 | let tree = pin_init!(MapleTree {
| ____________________^
394 | | // SAFETY: This initializes a maple tree into a pinned slot. The maple tree will be
395 | | // destroyed in Drop before the memory location becomes invalid.
396 | | tree <- Opaque::ffi_init(|slot| unsafe {
... |
399 | | _p: PhantomData,
400 | | });
| |__________^ could not find `init` in `$crate` |
= note: this error originates in the macro $crate::__init_internal which comes from the expansion of the macro pin_init (in Nightly builds, run with -Z macro-backtrace for more info)
So I'll take patch 1 here, but not this one :(
thanks,
greg k-h
Gary Guo
reviewerRe: [PATCH 6.19.y 2/2] rust: pin-init: replace shadowed return token by `unsafe`-to-create token
Quoted 86 lines · Greg KH
Quoted 67 lines · Benno Lossin
[ Upstream commit
fdbaa9d2b78e0da9e1aeb303bbdc3adfe6d8e749]We use a unit struct
__InitOkin the closure generated by the initializer macros as the return value. We shadow it by creating a struct with the same name again inside of the closure, preventing early returns ofOkin the initializer (before all fields have been initialized).In the face of Type Alias Impl Trait (TAIT) and the next trait solver, this solution no longer works [1]. The shadowed struct can be named through type inference. In addition, there is an RFC proposing to add the feature of path inference to Rust, which would similarly allow [2].
Thus remove the shadowed token and replace it with an
unsafeto create token.The reason we initially used the shadowing solution was because an alternative solution used a builder pattern. Gary writes [3]:
In the early builder-pattern based InitOk, having a single InitOk type for token is unsound because one can launder an InitOk token used for one place to another initializer. I used a branded lifetime solution, and then you figured out that using a shadowed type would work better because nobody could construct it at all.
The laundering issue does not apply to the approach we ended up with today.
With this change, the example by Tim Chirananthavat in [1] no longer compiles and results in this error:
error: cannot construct `pin_init::__internal::InitOk` with struct literal syntax due to private fields --> src/main.rs:26:17 | 26 | InferredType {} | ^^^^^^^^^^^^ | = note: private field `0` that was not provided help: you might have meant to use the `new` associated function | 26 - InferredType {} 26 + InferredType::new() |Applying the suggestion of using the
::new()function, results in another expected error:error[E0133]: call to unsafe function `pin_init::__internal::InitOk::new` is unsafe and requires unsafe block --> src/main.rs:26:17 | 26 | InferredType::new() | ^^^^^^^^^^^^^^^^^^^ call to unsafe function | = note: consult the function's documentation for information on how to avoid undefined behaviorReported-by Tim Chirananthavat <[email protected]>Fixes fc6c6baa1f40 ("rust: init: add initialization macros")Signed-off-by Benno Lossin <[email protected]>Reviewed-by Alice Ryhl <[email protected]>Reviewed-by Gary Guo <[email protected]>[ Added period as mentioned. - Miguel ]Signed-off-by Miguel Ojeda <[email protected]>Quoted 3 lines
[ Moved to declarative macro, because 6.19.y and earlier do not have
syn. - Benno ]Signed-off-by Benno Lossin <[email protected]>This commit blows up the build for me with lots of errors like:
error[E0433]: failed to resolve: could not find
initin$crate
-->rust/kernel/maple_tree.rs:393:20| 393 | let tree = pin_init!(MapleTree { | ____________________^ 394 | | // SAFETY: This initializes a maple tree into a pinned slot. The maple tree will be 395 | | // destroyed in Drop before the memory location becomes invalid. 396 | | tree <- Opaque::ffi_init(|slot| unsafe { ... | 399 | | _p: PhantomData, 400 | | }); | |__________^ could not find `init` in `$crate`
Quoted 6 lines
|
= note: this error originates in the macro$crate::__init_internalwhich comes from the expansion of the macropin_init(in Nightly builds, run with -Z macro-backtrace for more info)So I'll take patch 1 here, but not this one :(
This was dicussed in a RfL call, and we think it's fine to not backport this specific patch.
The soundness issue that this patch is fixing relies on code deliberately triggering this, a future Rust compiler that enables path inference without feature gates, and people using that compiler to build an old LTS/stable kernel.
On the other hand, the other two (or 1 for recent enough stable versions) patches have known broken out-of-tree users. So it's good that they're backported as code could have relied on them by accident.
Best,
Gary
Quoted 4 lines
thanks,
greg k-h
Greg KH
maintainerRe: [PATCH 6.19.y 2/2] rust: pin-init: replace shadowed return token by `unsafe`-to-create token
Quoted 97 lines · Gary Guo
Quoted 86 lines · Greg KH
Quoted 67 lines · Benno Lossin
[ Upstream commit
fdbaa9d2b78e0da9e1aeb303bbdc3adfe6d8e749]We use a unit struct
__InitOkin the closure generated by the initializer macros as the return value. We shadow it by creating a struct with the same name again inside of the closure, preventing early returns ofOkin the initializer (before all fields have been initialized).In the face of Type Alias Impl Trait (TAIT) and the next trait solver, this solution no longer works [1]. The shadowed struct can be named through type inference. In addition, there is an RFC proposing to add the feature of path inference to Rust, which would similarly allow [2].
Thus remove the shadowed token and replace it with an
unsafeto create token.The reason we initially used the shadowing solution was because an alternative solution used a builder pattern. Gary writes [3]:
In the early builder-pattern based InitOk, having a single InitOk type for token is unsound because one can launder an InitOk token used for one place to another initializer. I used a branded lifetime solution, and then you figured out that using a shadowed type would work better because nobody could construct it at all.
The laundering issue does not apply to the approach we ended up with today.
With this change, the example by Tim Chirananthavat in [1] no longer compiles and results in this error:
error: cannot construct `pin_init::__internal::InitOk` with struct literal syntax due to private fields --> src/main.rs:26:17 | 26 | InferredType {} | ^^^^^^^^^^^^ | = note: private field `0` that was not provided help: you might have meant to use the `new` associated function | 26 - InferredType {} 26 + InferredType::new() |Applying the suggestion of using the
::new()function, results in another expected error:error[E0133]: call to unsafe function `pin_init::__internal::InitOk::new` is unsafe and requires unsafe block --> src/main.rs:26:17 | 26 | InferredType::new() | ^^^^^^^^^^^^^^^^^^^ call to unsafe function | = note: consult the function's documentation for information on how to avoid undefined behaviorReported-by Tim Chirananthavat <[email protected]>Fixes fc6c6baa1f40 ("rust: init: add initialization macros")Signed-off-by Benno Lossin <[email protected]>Reviewed-by Alice Ryhl <[email protected]>Reviewed-by Gary Guo <[email protected]>[ Added period as mentioned. - Miguel ]Signed-off-by Miguel Ojeda <[email protected]>Quoted 3 lines
[ Moved to declarative macro, because 6.19.y and earlier do not have
syn. - Benno ]Signed-off-by Benno Lossin <[email protected]>This commit blows up the build for me with lots of errors like:
error[E0433]: failed to resolve: could not find
initin$crate
-->rust/kernel/maple_tree.rs:393:20| 393 | let tree = pin_init!(MapleTree { | ____________________^ 394 | | // SAFETY: This initializes a maple tree into a pinned slot. The maple tree will be 395 | | // destroyed in Drop before the memory location becomes invalid. 396 | | tree <- Opaque::ffi_init(|slot| unsafe { ... | 399 | | _p: PhantomData, 400 | | }); | |__________^ could not find `init` in `$crate`Quoted 6 lines
|
= note: this error originates in the macro$crate::__init_internalwhich comes from the expansion of the macropin_init(in Nightly builds, run with -Z macro-backtrace for more info)So I'll take patch 1 here, but not this one :(
This was dicussed in a RfL call, and we think it's fine to not backport this specific patch.
Quoted 7 lines
The soundness issue that this patch is fixing relies on code deliberately triggering this, a future Rust compiler that enables path inference without feature gates, and people using that compiler to build an old LTS/stable kernel.
On the other hand, the other two (or 1 for recent enough stable versions) patches have known broken out-of-tree users. So it's good that they're backported as code could have relied on them by accident.
Ok, then we are all set, thanks for the backports.
greg k-h