Re: [PATCH v6] rust: kernel: introduce `unsafe_precondition_assert!` macro
From: Benno Lossin
Date: Mon Nov 03 2025 - 05:40:17 EST
On Tue Oct 7, 2025 at 11:50 PM CEST, Ritvik Gupta wrote:
> Introduce a new `safety` module containing `unsafe_precondition_assert!`
> macro. It is a wrapper around `debug_assert!`, intended for validating
> pre-conditions of unsafe function.
>
> When `CONFIG_RUST_DEBUG_ASSERTIONS` flag is enabled, this macro performs
> runtime checks to ensure that the preconditions for unsafe function hold.
> Otherwise, the macro is a no-op.
>
> Suggested-by: Miguel Ojeda <ojeda@xxxxxxxxxx>
> Link: https://github.com/Rust-for-Linux/linux/issues/1162
> Link: https://rust-for-linux.zulipchat.com/#narrow/channel/291566-Library/topic/.60unsafe_precondition_assert.60.20macro/with/528457452
> Signed-off-by: Ritvik Gupta <ritvikfoss@xxxxxxxxx>
I think it's a good idea to have something like this, not sure if we
have the final version here, but we should merge something.
Reviewed-by: Benno Lossin <lossin@xxxxxxxxxx>
One nit below (that Miguel can fix when picking the patch).
> +#[macro_export]
> +macro_rules! unsafe_precondition_assert {
> + ($cond:expr $(,)?) => {
> + $crate::unsafe_precondition_assert!(@inner $cond, ::core::stringify!($cond))
> + };
> +
> + ($cond:expr, $($arg:tt)+) => {
> + $crate::unsafe_precondition_assert!(@inner $cond, $crate::prelude::fmt!($($arg)+))
> + };
> +
> + (@inner $cond:expr, $msg:expr) => {
> + ::core::debug_assert!($cond, "unsafe precondition(s) violated: {}", $msg)
This should be singular, since the name of the macro also is singular.
Cheers,
Benno
> + };
> +}
>
> base-commit: c746c3b5169831d7fb032a1051d8b45592ae8d78