lock_hierarchy/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
//! This crate offers debug assertions for violations of lock hierarchies. No runtime overhead or
//! protection occurs for release builds.

#[cfg(debug_assertions)]
use std::{cell::RefCell, thread_local};
use std::{ops::{Deref, DerefMut}, sync::PoisonError};

#[cfg(debug_assertions)]
thread_local! {
    pub static LOCK_LEVELS: RefCell<Vec<u32>> = RefCell::new(Vec::new());
}

/// Wrapper around a [`std::sync::Mutex`] which uses a thread local variable in order to check for
/// lock hierachy violations.
///
/// Each Mutex is assigned a level. Mutecies with higher levels must be acquired before mutices with
/// lower levels.
pub struct Mutex<T> {
    #[cfg(debug_assertions)]
    level: u32,
    inner: std::sync::Mutex<T>,
}

impl<T> Mutex<T> {
    /// Creates Mutex with level 0 (innermost Mutex)
    pub fn new(t: T) -> Self {
        Self::with_level(t, 0)
    }

    pub fn with_level(t: T, level: u32) -> Self {
        // Explicitly ignore level in release builds
        #[cfg(not(debug_assertions))]
        let _ = level;
        Mutex {
            #[cfg(debug_assertions)]
            level,
            inner: std::sync::Mutex::new(t),
        }
    }

    pub fn lock(&self) -> Result<MutexGuard<T>, PoisonError<std::sync::MutexGuard<'_, T>>> {
        #[cfg(debug_assertions)]
        LOCK_LEVELS.with(|levels| {
            let mut levels = levels.borrow_mut();
            if let Some(&lowest) = levels.last() {
                assert!(lowest > self.level)
            }
            levels.push(self.level);
        });
        self.inner.lock().map(|guard| MutexGuard {
            #[cfg(debug_assertions)]
            level: self.level,
            inner: guard,
        })
    }
}

pub struct MutexGuard<'a, T> {
    #[cfg(debug_assertions)]
    level: u32,
    inner: std::sync::MutexGuard<'a, T>,
}

impl<T> Drop for MutexGuard<'_, T> {
    fn drop(&mut self) {
        #[cfg(debug_assertions)]
        LOCK_LEVELS.with(|levels| {
            let mut levels = levels.borrow_mut();
            let index = levels
                .iter()
                .rposition(|&level| level == self.level)
                .expect("Position must exist, because we inserted it during lock!");
            levels.remove(index);
        });
    }
}

impl<'a, T> Deref for MutexGuard<'a, T> {
    type Target = T;

    fn deref(&self) -> &T {
        self.inner.deref()
    }
}

impl<'a, T> DerefMut for MutexGuard<'a, T> {

    fn deref_mut(&mut self) -> &mut Self::Target {
        self.inner.deref_mut()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn acquire_resource() {
        let mutex = Mutex::new(42);
        let guard = mutex.lock().unwrap();

        assert_eq!(42, *guard)
    }

    #[test]
    fn should_allow_mutation() {
        let mutex = Mutex::new(42);
        let mut guard = mutex.lock().unwrap();

        *guard = 43;

        assert_eq!(43, *guard)
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic]
    fn should_panic_if_two_mutices_with_level_0_are_acquired() {
        let mutex_a = Mutex::new(()); // Level 0
        let mutex_b = Mutex::new(()); // also level 0
        // Fine, first mutex in thread
        let _guard_a = mutex_a.lock().unwrap();
        // Must panic, lock hierarchy violation
        let _guard_b = mutex_b.lock().unwrap();
    }

    #[test]
    #[cfg(not(debug_assertions))]
    fn should_not_check_in_release_build() {
        let mutex_a = Mutex::new(5); // Level 0
        let mutex_b = Mutex::new(42); // also level 0
                                      // Fine, first mutex in thread
        let _guard_a = mutex_a.lock().unwrap();
        // Lock hierarchy violation, but we do not panic, since debug assertions are not active
        let _guard_b = mutex_b.lock().unwrap();
    }

    #[test]
    fn should_allow_for_two_level_0_in_succession() {
        let mutex_a = Mutex::new(5); // Level 0
        let mutex_b = Mutex::new(42); // also level 0
                                      // Fine, first mutex in thread
        let guard_a = mutex_a.lock().unwrap();
        drop(guard_a);
        // Fine, first mutext has already been dropped
        let _guard_b = mutex_b.lock().unwrap();
    }

    #[test]
    fn should_allow_for_simultanous_lock_if_higher_is_acquired_first() {
        let mutex_a = Mutex::with_level(5, 1); // Level 1
        let mutex_b = Mutex::new(42); // also level 0
        // Fine, first mutex in thread
        let _guard_a = mutex_a.lock().unwrap();
        // Fine: 0 is lower level than 1
        let _guard_b = mutex_b.lock().unwrap();
    }

    #[test]
    fn should_allow_for_any_order_of_release() {
        let mutex_a = Mutex::with_level((), 2);
        let mutex_b = Mutex::with_level((), 1);
        let mutex_c = Mutex::new(());
        // Fine, first mutex in thread
        let _guard_a = mutex_a.lock().unwrap();
        // Fine: 0 is lower level than 1
        let guard_b = mutex_b.lock().unwrap();
        let _guard_c = mutex_c.lock().unwrap();
        drop(guard_b)
    }
}