Skip to contentSkip to conversation

rust: make unsafe_precondition_assert! const compatible

PATCH In review JX 2 participants 6 messages Sep 8 2 messages not in the archive

Subsystems (2)
lore
Share & tools
lore

JX

author
#1 lore raw

PATCH v2 1/2 rust: make unsafe_precondition_assert! const compatible

In reply to a message not in the archive

The no-message form of unsafe_precondition_assert! routes the stringified condition through the formatting machinery. This prevents the macro from being used in const unsafe functions.

Build its static diagnostic with concat! instead. This preserves the message while allowing the no-message form in const contexts. Keep the custom-message form unchanged since it intentionally supports runtime formatting.

---
 rust/kernel/safety.rs | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
rust/kernel/safety.rs +9 -1
index c1c6bd0fa2..a45a574709 100644
@@ -7,6 +7,8 @@
 /// The check is enabled at runtime if debug assertions (`CONFIG_RUST_DEBUG_ASSERTIONS`)
 /// are enabled. Otherwise, this macro is a no-op.
 ///
+/// The form without a custom message can be used in const contexts.
+///
 /// # Examples
 ///
 /// ```no_run
@@ -40,7 +42,13 @@
 #[macro_export]
 macro_rules! unsafe_precondition_assert {
     ($cond:expr $(,)?) => {
-        $crate::unsafe_precondition_assert!(@inner $cond, ::core::stringify!($cond))
+        ::core::debug_assert!(
+            $cond,
+            ::core::concat!(
+                "unsafe precondition violated: ",
+                ::core::stringify!($cond),
+            ),
+        )
     };
 
     ($cond:expr, $($arg:tt)+) => {
Signature · 1 line
2.54.0
author
#2 lore raw

PATCH v2 2/2 rust: alloc: use unsafe_precondition_assert! in Vec length helpers

In reply to a message not in the archive

Vec::inc_len and Vec::dec_len are unsafe functions whose debug assertions directly check their documented safety preconditions.

Use unsafe_precondition_assert! for these checks so violations are identified as unsafe precondition failures. The inc_len use also keeps the const-compatible macro path covered by kernel compilation.

---
 rust/kernel/alloc/kvec.rs | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
rust/kernel/alloc/kvec.rs +4 -3
index c7546b9da4..9216a4a304 100644
@@ -23,7 +23,8 @@
     page::{
         AsPageIter,
         PAGE_SIZE, //
-    }, //
+    },
+    unsafe_precondition_assert, //
 };
 
 use core::{
@@ -230,7 +231,7 @@ pub const fn len(&self) -> usize {
     #[inline]
     pub const unsafe fn inc_len(&mut self, additional: usize) {
         // Guaranteed by the type invariant to never underflow.
-        debug_assert!(additional <= self.capacity() - self.len());
+        unsafe_precondition_assert!(additional <= self.capacity() - self.len());
         // INVARIANT: By the safety requirements of this method this represents the exact number of
         // elements stored within `self`.
         self.len += additional;
@@ -245,7 +246,7 @@ pub const fn len(&self) -> usize {
     ///
     /// - `count` must be less than or equal to `self.len`.
     unsafe fn dec_len(&mut self, count: usize) -> &mut [T] {
-        debug_assert!(count <= self.len());
+        unsafe_precondition_assert!(count <= self.len());
         // INVARIANT: We relinquish ownership of the elements within the range `[self.len - count,
         // self.len)`, hence the updated value of `set.len` represents the exact number of elements
         // stored within `self`.
Signature · 1 line
2.54.0
author
#4 lore raw

PATCH v2 1/2 rust: make unsafe_precondition_assert! const compatible

In reply to a message not in the archive

The no-message form of unsafe_precondition_assert! routes the condition through the formatting machinery. This prevents the macro from being used in const unsafe functions.

Use a fixed diagnostic literal instead. This allows the no-message form in const contexts without interpreting tokens from the condition as format string syntax. Keep the custom-message form unchanged since it intentionally supports runtime formatting.

---
 rust/kernel/safety.rs | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
rust/kernel/safety.rs +10 -1
index c1c6bd0fa2..f3c498c242 100644
@@ -7,6 +7,15 @@
 /// The check is enabled at runtime if debug assertions (`CONFIG_RUST_DEBUG_ASSERTIONS`)
 /// are enabled. Otherwise, this macro is a no-op.
 ///
+/// The form without a custom message can be used in const contexts.
+///
+/// ```
+/// # use kernel::unsafe_precondition_assert;
+/// const fn check(value: usize) {
+///     unsafe_precondition_assert!({ value < 4 });
+/// }
+/// ```
+///
 /// # Examples
 ///
 /// ```no_run
@@ -40,7 +49,7 @@
 #[macro_export]
 macro_rules! unsafe_precondition_assert {
     ($cond:expr $(,)?) => {
-        $crate::unsafe_precondition_assert!(@inner $cond, ::core::stringify!($cond))
+        ::core::debug_assert!($cond, "unsafe precondition violated")
     };
 
     ($cond:expr, $($arg:tt)+) => {
Signature · 1 line
2.54.0
author
#7 lore raw

v2 cover rust: add unsafe precondition assertions to Vec length helpers

In reply to a message not in the archive

The safety requirements of Vec::inc_len and Vec::dec_len are currently checked with debug_assert!. Convert them to unsafe_precondition_assert! so violations are reported consistently with other unsafe precondition failures.

The first patch makes the no-message form of unsafe_precondition_assert! usable from const functions. This is needed by Vec::inc_len, which is const, and avoids runtime formatting.

The second patch converts both Vec length helpers.

The series has been checked with:

make rustfmtcheck
make CLIPPY=1 rust/kernel.o
make rusttest
make rustdoc

Changes in v2:
- Use a fixed diagnostic literal instead of concatenating the stringified condition into a format string, since conditions may contain braces.
- Add a const-context documentation example with a block expression.

JX (2):
rust: make unsafe_precondition_assert! const compatible
rust: alloc: use unsafe_precondition_assert! in Vec length helpers

 rust/kernel/alloc/kvec.rs |  7 ++++---
 rust/kernel/safety.rs     | 11 ++++++++++-
 2 files changed, 14 insertions(+), 4 deletions(-)

base-commit: cee9395acd8043be0644b25c34bfa86623f2b935

Signature · 1 line
2.54.0
author
#6 lore raw

PATCH v2 2/2 rust: alloc: use unsafe_precondition_assert! in Vec length helpers

In reply to a message not in the archive

Vec::inc_len and Vec::dec_len are unsafe functions whose debug assertions directly check their documented safety preconditions.

Use unsafe_precondition_assert! for these checks so violations are identified as unsafe precondition failures. The inc_len use also keeps the const-compatible macro path covered by kernel compilation.

---
 rust/kernel/alloc/kvec.rs | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
rust/kernel/alloc/kvec.rs +4 -3
index c7546b9da4..9216a4a304 100644
@@ -23,7 +23,8 @@
     page::{
         AsPageIter,
         PAGE_SIZE, //
-    }, //
+    },
+    unsafe_precondition_assert, //
 };
 
 use core::{
@@ -230,7 +231,7 @@ pub const fn len(&self) -> usize {
     #[inline]
     pub const unsafe fn inc_len(&mut self, additional: usize) {
         // Guaranteed by the type invariant to never underflow.
-        debug_assert!(additional <= self.capacity() - self.len());
+        unsafe_precondition_assert!(additional <= self.capacity() - self.len());
         // INVARIANT: By the safety requirements of this method this represents the exact number of
         // elements stored within `self`.
         self.len += additional;
@@ -245,7 +246,7 @@ pub const fn len(&self) -> usize {
     ///
     /// - `count` must be less than or equal to `self.len`.
     unsafe fn dec_len(&mut self, count: usize) -> &mut [T] {
-        debug_assert!(count <= self.len());
+        unsafe_precondition_assert!(count <= self.len());
         // INVARIANT: We relinquish ownership of the elements within the range `[self.len - count,
         // self.len)`, hence the updated value of `set.len` represents the exact number of elements
         // stored within `self`.
Signature · 1 line
2.54.0
#5 lore raw
In reply to JX
Quoted 2 lines · JX

Thanks for the patch!

The kernel requires a "known identity" for the Signed-off-by -- please see:

https://docs.kernel.org/process/submitting-patches.html#sign-your-work-the-developer-s-certificate-of-origin

(The thread in lore.kernel.org shows unknown messages and v1's cover letter was separate -- I would suggest sending the patches with git-send-email or b4 and using a new thread for each version -- I hope that helps!).

Cheers,
Miguel