Skip to contentSkip to conversation

rust: `overflow_assert!` macro

PATCH Superseded Antonio Hickey 4 participants 9 messages Jun 29, 2025 – Jul 21, 2025 Rust

v4 of 6 Superseded Latest is v6 →

lore
Share & tools
lore
#0 lore raw

v4 cover rust: `overflow_assert!` macro

This patch set introduces a macro for overflow assertions, the use of this macro will avoid local #ifdefs by encapsulating the conditional behavior to the macro. In addition this macro also allows us to document the intent of the assertion more clearly.

This patch set requires Alice's strncpy_from_user patch[1] linked below, because I use it as an example usecase for the overflow_assert! macro.

Dependent Patch [1]: https://lore.kernel.org/rust-for-linux/[email protected]/

Changes in v4:
- Added the ability for callers to supply a custom message to the
overflow assertion.
- Small change to verbage in documentation.
- Link to v3: https://lore.kernel.org/all/[email protected]/

Changes in v3:
- Made the overflow_assert! macro take in expressions instead of
values.
- Fixed path in macro to fully qualify.
- Refactor macro to make the conditional compilation as local as
possible.
- Refactor macro to utilize the cfg! macro like the standard library
does to reduce boilerplate.
- Added an example use case of the overflow_assert! macro
- Link to v2: https://lore.kernel.org/rust-for-linux/[email protected]/

Changes in v2:
- Fixed example doc comment so it doesn't panic.
- Link to v1: https://lore.kernel.org/rust-for-linux/[email protected]/

Antonio Hickey (2):
rust: kernel: create overflow_assert! macro
rust: uaccess: refactor to use overflow_assert!

 rust/kernel/lib.rs             |  1 +
 rust/kernel/overflow_assert.rs | 32 ++++++++++++++++++++++++++++++++
 rust/kernel/uaccess.rs         |  4 ++--
 3 files changed, 35 insertions(+), 2 deletions(-)
 create mode 100644 rust/kernel/overflow_assert.rs
Signature · 1 line
2.50.0
#1 lore raw

PATCH v4 1/2 rust: kernel: create `overflow_assert!` macro

This commit creates a macro for overflow assertions, the use of this macro will avoid local #ifdefs by encapsulating the conditional behavior (like #[cfg(CONFIG_RUST_OVERFLOW_CHECKS)]) to the macro.

In addition this macro allows us to document the intent of the assertion more clearly.

---
 rust/kernel/lib.rs             |  1 +
 rust/kernel/overflow_assert.rs | 32 ++++++++++++++++++++++++++++++++
 2 files changed, 33 insertions(+)
 create mode 100644 rust/kernel/overflow_assert.rs
rust/kernel/lib.rs +1 -0
index 6b4774b2b1c3..e395adb6b293 100644
@@ -92,6 +92,7 @@
 pub mod of;
 #[cfg(CONFIG_PM_OPP)]
 pub mod opp;
+pub mod overflow_assert;
 pub mod page;
 #[cfg(CONFIG_PCI)]
 pub mod pci;
rust/kernel/overflow_assert.rs new file +32 -0
new file mode 100644
index 000000000000..5164339813cb
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Overflow assertion.
+
+/// Verifies at runtime that an expression is within an expected bound.
+///
+/// This macro is only active when `CONFIG_RUST_OVERFLOW_CHECKS` is enabled.
+///
+/// # Examples
+///
+/// ```
+/// overflow_assert!(3 <= 10);
+/// overflow_assert!(5 <= 5);
+///
+/// const X: u8 = 5;
+/// overflow_assert!(X + 3 < 10);
+///
+/// const MAX: i32 = 42;
+/// const fn f(x: i32) -> i32 {
+///     x + 1
+/// }
+/// overflow_assert!(f(40) < MAX);
+/// overflow_assert!(f(40) < MAX, "f(x) must not overflow the max value.");
+/// ```
+#[macro_export]
+macro_rules! overflow_assert {
+    ($cond:expr $(,$arg:literal)?) => {
+        if cfg!(CONFIG_RUST_OVERFLOW_CHECKS) {
+            ::core::assert!($cond $(,$arg)?);
+        }
+    };
+}
Signature · 1 line
2.50.0
#2 lore raw

Re: [PATCH v4 1/2] rust: kernel: create `overflow_assert!` macro

Quoted 37 lines · Antonio Hickey

This commit creates a macro for overflow assertions, the use of this macro will avoid local #ifdefs by encapsulating the conditional behavior (like #[cfg(CONFIG_RUST_OVERFLOW_CHECKS)]) to the macro.

In addition this macro allows us to document the intent of the assertion more clearly.

---
 rust/kernel/lib.rs             |  1 +
 rust/kernel/overflow_assert.rs | 32 ++++++++++++++++++++++++++++++++
 2 files changed, 33 insertions(+)
 create mode 100644 rust/kernel/overflow_assert.rs
rust/kernel/lib.rs +1 -0
index 6b4774b2b1c3..e395adb6b293 100644
@@ -92,6 +92,7 @@
 pub mod of;
 #[cfg(CONFIG_PM_OPP)]
 pub mod opp;
+pub mod overflow_assert;
 pub mod page;
 #[cfg(CONFIG_PCI)]
 pub mod pci;
rust/kernel/overflow_assert.rs new file +0 -0
new file mode 100644
index 000000000000..5164339813cb

rust/kernel/overflow_assert.rs line 5

Quoted 5 lines
rust/kernel/overflow_assert.rs new file +5 -0
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Overflow assertion.
+
+/// Verifies at runtime that an expression is within an expected bound.

This is a strange comment, imo. The only thing special about this macro relative to a plain assert is that it disabled when CONFIG_RUST_OVERFLOW_CHECKS=n.

Quoted 32 lines
rust/kernel/overflow_assert.rs new file +27 -1
+///
+/// This macro is only active when `CONFIG_RUST_OVERFLOW_CHECKS` is enabled.
+///
+/// # Examples
+///
+/// ```
+/// overflow_assert!(3 <= 10);
+/// overflow_assert!(5 <= 5);
+///
+/// const X: u8 = 5;
+/// overflow_assert!(X + 3 < 10);
+///
+/// const MAX: i32 = 42;
+/// const fn f(x: i32) -> i32 {
+///     x + 1
+/// }
+/// overflow_assert!(f(40) < MAX);
+/// overflow_assert!(f(40) < MAX, "f(x) must not overflow the max value.");
+/// ```
+#[macro_export]
+macro_rules! overflow_assert {
+    ($cond:expr $(,$arg:literal)?) => {
+        if cfg!(CONFIG_RUST_OVERFLOW_CHECKS) {
+            ::core::assert!($cond $(,$arg)?);
+        }
+    };
+}
--

2.50.0

#3 lore raw

Re: [PATCH v4 1/2] rust: kernel: create `overflow_assert!` macro

Quoted 9 lines · Tamir Duberstein

rust/kernel/overflow_assert.rs line 5

Quoted 3 lines · Antonio Hickey
rust/kernel/overflow_assert.rs new file +3 -0
+//! Overflow assertion.
+
+/// Verifies at runtime that an expression is within an expected bound.

This is a strange comment, imo. The only thing special about this macro relative to a plain assert is that it disabled when CONFIG_RUST_OVERFLOW_CHECKS=n.

Special yes, but it also documents the intent of the assert. I did include a comment about the conditional behaviour with CONFIG_RUST_OVERFLOW_CHECKS being enabled/disabled.

I'm open to rewording this doc comment to be better though. I should also add information about the optional panic message like the static_assert does as well, what about something like:

```
/// Overflow assertion.
///
/// Runtime assertion that an expression is within an expected bounds.
///
/// This macro is only enabled when `CONFIG_RUST_OVERFLOW_CHECKS` is true.
///
/// An optional panic message can be supplied after the expression.
/// Currently only a string literal without formatting is supported
/// due to constness limitations of the [`assert!`] macro.
```

Thanks

Quoted 3 lines
Quoted 3 lines
rust/kernel/overflow_assert.rs new file +2 -0
+///
+/// This macro is only active when `CONFIG_RUST_OVERFLOW_CHECKS` is enabled.
#4 lore raw

Re: [PATCH v4 1/2] rust: kernel: create `overflow_assert!` macro

Quoted 16 lines · Antonio Hickey
Quoted 9 lines · Tamir Duberstein

rust/kernel/overflow_assert.rs line 5

Quoted 3 lines · Antonio Hickey
rust/kernel/overflow_assert.rs new file +3 -0
+//! Overflow assertion.
+
+/// Verifies at runtime that an expression is within an expected bound.

This is a strange comment, imo. The only thing special about this macro relative to a plain assert is that it disabled when CONFIG_RUST_OVERFLOW_CHECKS=n.

Special yes, but it also documents the intent of the assert. I did include a comment about the conditional behaviour with CONFIG_RUST_OVERFLOW_CHECKS being enabled/disabled.

Quoted 8 lines

I'm open to rewording this doc comment to be better though. I should also add information about the optional panic message like the static_assert does as well, what about something like:

```
/// Overflow assertion.
///
/// Runtime assertion that an expression is within an expected bounds.

I still disprefer this phrasing because there's nothing stopping someone from writing

overflow_assert!(sky_is_blue());

In other words the type of the expression is bool while the comment implies that the type of the expression is numeric.

Quoted 6 lines

///
/// This macro is only enabled when CONFIG_RUST_OVERFLOW_CHECKS is true. ///
/// An optional panic message can be supplied after the expression. /// Currently only a string literal without formatting is supported /// due to constness limitations of the [assert!] macro.

I don't think this is correct; in a non-const context you could use formatting with this macro, no? IMO the doc comment on debug_assert is good to use as a guide here.

https://doc.rust-lang.org/stable/std/macro.debug_assert.html

Consider also using the same implementation as that macro; there's no need to separate cond from the other arguments.

Quoted 8 lines

```

Thanks

Quoted 3 lines
Quoted 3 lines
rust/kernel/overflow_assert.rs new file +2 -0
+///
+/// This macro is only active when `CONFIG_RUST_OVERFLOW_CHECKS` is enabled.
#5 lore raw

Re: [PATCH v4 1/2] rust: kernel: create `overflow_assert!` macro

In reply to Antonio Hickey

Hi Antonio,

Since you are sending likely a new version, a couple quick comments...

Quoted 6 lines · Antonio Hickey

The usual order of the tags would be:

Quoted 1 line

/// This macro is only active when CONFIG_RUST_OVERFLOW_CHECKS is enabled.

I would probably add another paragraph to clarify/warn that, therefore, one can only use this macro to add extra checks for users that don't mind panics in such a case, but that it cannot be relied for things that need to be always tested for (to prevent UB, access checks, etc.), similar to what the standard library says for debug_assert! like Tamir mentions or the WARN*() docs in C.

Quoted 6 lines
rust/kernel/overflow_assert.rs new file +6 -0
+/// # Examples
+///
+/// ```
+/// overflow_assert!(3 <= 10);
+/// overflow_assert!(5 <= 5);
+///

rust/kernel/overflow_assert.rs line 24

Quoted 10 lines
rust/kernel/overflow_assert.rs new file +10 -0
+/// const X: u8 = 5;
+/// overflow_assert!(X + 3 < 10);
+///
+/// const MAX: i32 = 42;
+/// const fn f(x: i32) -> i32 {
+///     x + 1
+/// }
+/// overflow_assert!(f(40) < MAX);
+/// overflow_assert!(f(40) < MAX, "f(x) must not overflow the max value.");
+/// ```

Since now the macro takes just a bool, I would probably try to keep two or so of these, and I would add a couple comments and try to have a more "real life" example if possible.

Thanks!

Cheers,
Miguel

#6 lore raw

PATCH v4 2/2 rust: uaccess: refactor to use `overflow_assert!`

In reply to Antonio Hickey

Using the overflow_assert! macro here adds documentation to the intent of the assertion, and avoids local #ifdefss by encapsulating the conditional behavior to the macro itself.

---
 rust/kernel/uaccess.rs | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
rust/kernel/uaccess.rs +2 -2
index 635a03e0989f..452a5e0d76d2 100644
@@ -9,6 +9,7 @@
     bindings,
     error::Result,
     ffi::{c_char, c_void},
+    overflow_assert,
     prelude::*,
     transmute::{AsBytes, FromBytes},
 };
@@ -394,8 +395,7 @@ fn raw_strncpy_from_user(dst: &mut [MaybeUninit<u8>], src: UserPtr) -> Result<us
         return Err(Error::from_errno(res as i32));
     }
 
-    #[cfg(CONFIG_RUST_OVERFLOW_CHECKS)]
-    assert!(res <= len);
+    overflow_assert!(res <= len);
 
     // GUARANTEES: `strncpy_from_user` was successful, so `dst` has contents in accordance with the
     // guarantees of this function.
Signature · 1 line
2.50.0
Reviewed-by on v4 2/2
#7 lore raw

Re: [PATCH v4 2/2] rust: uaccess: refactor to use `overflow_assert!`

Quoted 11 lines · Antonio Hickey

Using the overflow_assert! macro here adds documentation to the intent of the assertion, and avoids local #ifdefss by encapsulating the conditional behavior to the macro itself.

---

Quoted 30 lines
 rust/kernel/uaccess.rs | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
rust/kernel/uaccess.rs +2 -3
index 635a03e0989f..452a5e0d76d2 100644
@@ -9,6 +9,7 @@
     bindings,
     error::Result,
     ffi::{c_char, c_void},
+    overflow_assert,
     prelude::*,
     transmute::{AsBytes, FromBytes},
 };
@@ -394,8 +395,7 @@ fn raw_strncpy_from_user(dst: &mut [MaybeUninit<u8>], src: UserPtr) -> Result<us
         return Err(Error::from_errno(res as i32));
     }
 
-    #[cfg(CONFIG_RUST_OVERFLOW_CHECKS)]
-    assert!(res <= len);
+    overflow_assert!(res <= len);
 
     // GUARANTEES: `strncpy_from_user` was successful, so `dst` has contents in accordance with the
     // guarantees of this function.
--

2.50.0

reviewer Reviewed-by on v4 2/2
#8 lore raw

Re: [PATCH v4 2/2] rust: uaccess: refactor to use `overflow_assert!`

In reply to Antonio Hickey
Quoted 9 lines · Antonio Hickey

Using the overflow_assert! macro here adds documentation to the intent of the assertion, and avoids local #ifdefss by encapsulating the conditional behavior to the macro itself.