[PATCH 2/3] rust: sync: Assert Lock::is_locked in Guard::new for debug builds

From: Lyude Paul
Date: Wed Nov 20 2024 - 17:35:46 EST


Since we're allowing code to unsafely claim that it's acquired a lock
let's use the new Lock::is_locked() function so that when debug assertions
are enabled, we can verify that the lock has actually been acquired.

Signed-off-by: Lyude Paul <lyude@xxxxxxxxxx>
---
rust/kernel/sync/lock.rs | 7 +++++++
1 file changed, 7 insertions(+)

diff --git a/rust/kernel/sync/lock.rs b/rust/kernel/sync/lock.rs
index 542f846ac02b2..0a7f2ed767423 100644
--- a/rust/kernel/sync/lock.rs
+++ b/rust/kernel/sync/lock.rs
@@ -244,10 +244,17 @@ fn drop(&mut self) {
impl<'a, T: ?Sized, B: Backend> Guard<'a, T, B> {
/// Constructs a new immutable lock guard.
///
+ /// # Panics
+ ///
+ /// This function will panic if debug assertions are enabled and `lock` is not actually
+ /// acquired.
+ ///
/// # Safety
///
/// The caller must ensure that it owns the lock.
pub unsafe fn new(lock: &'a Lock<T, B>, state: B::GuardState) -> Self {
+ debug_assert!(lock.is_locked());
+
Self {
lock,
state,
--
2.47.0