[PATCH v2] rust: init: remove impl Zeroable for Infallible
From: Laine Taffin Altman
Date: Mon Apr 01 2024 - 21:53:55 EST
A type is inhabited if at least one valid value of that type exists; a type is uninhabited if no valid values of that type exist. The terms "inhabited" and "uninhabited" in this sense originate in type theory, a branch of mathematics.
In Rust, producing an invalid value of any type is immediate undefined behavior (UB); this includes via zeroing memory. Therefore, since an uninhabited type has no valid values, producing any values at all for it is UB.
The Rust standard library type `core::convert::Infallible` is uninhabited, by virtue of having been declared as an enum with no cases, which always produces uninhabited types in Rust.
The current kernel code allows this UB to be triggered, for example by code like:
`pr_info!("{}”, Box::<core::convert::Infallible>::init(kernel::init::zeroed())?);`
Thus, remove the implementation of `Zeroable` for `Infallible`, thereby avoiding the UB.
Cc: stable@xxxxxxxxxxxxxxx
Fixes: 38cde0bd7b67 ("rust: init: add `Zeroable` trait and `init::zeroed` function")
Closes: https://github.com/Rust-for-Linux/pinned-init/pull/13
Signed-off-by: Laine Taffin Altman <alexanderaltman@xxxxxx>
Reviewed-by: Alice Ryhl <aliceryhl@xxxxxxxxxx>
Reviewed-by: Boqun Feng <boqun.feng@xxxxxxxxx>
—
V1 -> V2: Added more documentation to the comment, with links; also added more details to the commit message.
rust/kernel/init.rs | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs
index 424257284d16..9353c9919fd4 100644
--- a/rust/kernel/init.rs
+++ b/rust/kernel/init.rs
@@ -1292,8 +1292,11 @@ macro_rules! impl_zeroable {
i8, i16, i32, i64, i128, isize,
f32, f64,
- // SAFETY: These are ZSTs, there is nothing to zero.
- {<T: ?Sized>} PhantomData<T>, core::marker::PhantomPinned, Infallible, (),
+ // SAFETY: These are inhabited ZSTs; there is nothing to zero and a valid value exists.
+ // Note: do not add uninhabited types (such as ! or Infallible) to this list; creating an instance of an uninhabited type is immediate undefined behavior.
+ // For more on uninhabited/empty types, consult The Rustonomicon: https://doc.rust-lang.org/stable/nomicon/exotic-sizes.html#empty-types
+ // The Rust Reference also has information on undefined behavior: https://doc.rust-lang.org/stable/reference/behavior-considered-undefined.html
+ {<T: ?Sized>} PhantomData<T>, core::marker::PhantomPinned, (),
// SAFETY: Type is allowed to take any value, including all zeros.
{<T>} MaybeUninit<T>,
--
2.44.0