1 pub use ::alloc::sync::Arc;
2 use core::ops::{Deref, DerefMut};
3 use core::time::Duration;
5 use std::cell::RefCell;
7 use std::sync::atomic::{AtomicUsize, Ordering};
8 use std::sync::Mutex as StdMutex;
9 use std::sync::MutexGuard as StdMutexGuard;
10 use std::sync::RwLock as StdRwLock;
11 use std::sync::RwLockReadGuard as StdRwLockReadGuard;
12 use std::sync::RwLockWriteGuard as StdRwLockWriteGuard;
13 use std::sync::Condvar as StdCondvar;
17 #[cfg(feature = "backtrace")]
18 use {prelude::hash_map, backtrace::Backtrace, std::sync::Once};
20 #[cfg(not(feature = "backtrace"))]
22 #[cfg(not(feature = "backtrace"))]
23 impl Backtrace { fn new() -> Backtrace { Backtrace {} } }
25 pub type LockResult<Guard> = Result<Guard, ()>;
32 pub fn new() -> Condvar {
33 Condvar { inner: StdCondvar::new() }
36 pub fn wait<'a, T>(&'a self, guard: MutexGuard<'a, T>) -> LockResult<MutexGuard<'a, T>> {
37 let mutex: &'a Mutex<T> = guard.mutex;
38 self.inner.wait(guard.into_inner()).map(|lock| MutexGuard { mutex, lock }).map_err(|_| ())
42 pub fn wait_timeout<'a, T>(&'a self, guard: MutexGuard<'a, T>, dur: Duration) -> LockResult<(MutexGuard<'a, T>, ())> {
43 let mutex = guard.mutex;
44 self.inner.wait_timeout(guard.into_inner(), dur).map(|(lock, _)| (MutexGuard { mutex, lock }, ())).map_err(|_| ())
47 pub fn notify_all(&self) { self.inner.notify_all(); }
51 /// We track the set of locks currently held by a reference to their `LockMetadata`
52 static LOCKS_HELD: RefCell<HashMap<u64, Arc<LockMetadata>>> = RefCell::new(HashMap::new());
54 static LOCK_IDX: AtomicUsize = AtomicUsize::new(0);
56 #[cfg(feature = "backtrace")]
57 static mut LOCKS: Option<StdMutex<HashMap<String, Arc<LockMetadata>>>> = None;
58 #[cfg(feature = "backtrace")]
59 static LOCKS_INIT: Once = Once::new();
61 /// Metadata about a single lock, by id, the set of things locked-before it, and the backtrace of
62 /// when the Mutex itself was constructed.
65 locked_before: StdMutex<HashMap<u64, LockDep>>,
66 _lock_construction_bt: Backtrace,
70 lock: Arc<LockMetadata>,
71 lockdep_trace: Backtrace,
74 #[cfg(feature = "backtrace")]
75 fn get_construction_location(backtrace: &Backtrace) -> String {
76 // Find the first frame that is after `debug_sync` (or that is in our tests) and use
77 // that as the mutex construction site. Note that the first few frames may be in
78 // the `backtrace` crate, so we have to ignore those.
79 let sync_mutex_constr_regex = regex::Regex::new(r"lightning.*debug_sync.*new").unwrap();
80 let mut found_debug_sync = false;
81 for frame in backtrace.frames() {
82 for symbol in frame.symbols() {
83 let symbol_name = symbol.name().unwrap().as_str().unwrap();
84 if !sync_mutex_constr_regex.is_match(symbol_name) {
86 if let Some(col) = symbol.colno() {
87 return format!("{}:{}:{}", symbol.filename().unwrap().display(), symbol.lineno().unwrap(), col);
89 // Windows debug symbols don't support column numbers, so fall back to
90 // line numbers only if no `colno` is available
91 return format!("{}:{}", symbol.filename().unwrap().display(), symbol.lineno().unwrap());
94 } else { found_debug_sync = true; }
97 panic!("Couldn't find mutex construction callsite");
101 fn new() -> Arc<LockMetadata> {
102 let backtrace = Backtrace::new();
103 let lock_idx = LOCK_IDX.fetch_add(1, Ordering::Relaxed) as u64;
105 let res = Arc::new(LockMetadata {
106 locked_before: StdMutex::new(HashMap::new()),
108 _lock_construction_bt: backtrace,
111 #[cfg(feature = "backtrace")]
113 let lock_constr_location = get_construction_location(&res._lock_construction_bt);
114 LOCKS_INIT.call_once(|| { unsafe { LOCKS = Some(StdMutex::new(HashMap::new())); } });
115 let mut locks = unsafe { LOCKS.as_ref() }.unwrap().lock().unwrap();
116 match locks.entry(lock_constr_location) {
117 hash_map::Entry::Occupied(e) => return Arc::clone(e.get()),
118 hash_map::Entry::Vacant(e) => { e.insert(Arc::clone(&res)); },
124 // Returns whether we were a recursive lock (only relevant for read)
125 fn _pre_lock(this: &Arc<LockMetadata>, read: bool) -> bool {
126 let mut inserted = false;
127 LOCKS_HELD.with(|held| {
128 // For each lock which is currently locked, check that no lock's locked-before
129 // set includes the lock we're about to lock, which would imply a lockorder
131 for (locked_idx, _locked) in held.borrow().iter() {
132 if read && *locked_idx == this.lock_idx {
133 // Recursive read locks are explicitly allowed
137 for (locked_idx, locked) in held.borrow().iter() {
138 if !read && *locked_idx == this.lock_idx {
139 // With `feature = "backtrace"` set, we may be looking at different instances
141 debug_assert!(cfg!(feature = "backtrace"), "Tried to acquire a lock while it was held!");
143 for (locked_dep_idx, locked_dep) in locked.locked_before.lock().unwrap().iter() {
144 if *locked_dep_idx == this.lock_idx && *locked_dep_idx != locked.lock_idx {
145 #[cfg(feature = "backtrace")]
146 panic!("Tried to violate existing lockorder.\nMutex that should be locked after the current lock was created at the following backtrace.\nNote that to get a backtrace for the lockorder violation, you should set RUST_BACKTRACE=1\nLock being taken constructed at: {} ({}):\n{:?}\nLock constructed at: {} ({})\n{:?}\n\nLock dep created at:\n{:?}\n\n",
147 get_construction_location(&this._lock_construction_bt), this.lock_idx, this._lock_construction_bt,
148 get_construction_location(&locked._lock_construction_bt), locked.lock_idx, locked._lock_construction_bt,
149 locked_dep.lockdep_trace);
150 #[cfg(not(feature = "backtrace"))]
151 panic!("Tried to violate existing lockorder. Build with the backtrace feature for more info.");
154 // Insert any already-held locks in our locked-before set.
155 let mut locked_before = this.locked_before.lock().unwrap();
156 if !locked_before.contains_key(&locked.lock_idx) {
157 let lockdep = LockDep { lock: Arc::clone(locked), lockdep_trace: Backtrace::new() };
158 locked_before.insert(lockdep.lock.lock_idx, lockdep);
161 held.borrow_mut().insert(this.lock_idx, Arc::clone(this));
167 fn pre_lock(this: &Arc<LockMetadata>) { Self::_pre_lock(this, false); }
168 fn pre_read_lock(this: &Arc<LockMetadata>) -> bool { Self::_pre_lock(this, true) }
170 fn try_locked(this: &Arc<LockMetadata>) {
171 LOCKS_HELD.with(|held| {
172 // Since a try-lock will simply fail if the lock is held already, we do not
173 // consider try-locks to ever generate lockorder inversions. However, if a try-lock
174 // succeeds, we do consider it to have created lockorder dependencies.
175 let mut locked_before = this.locked_before.lock().unwrap();
176 for (locked_idx, locked) in held.borrow().iter() {
177 if !locked_before.contains_key(locked_idx) {
178 let lockdep = LockDep { lock: Arc::clone(locked), lockdep_trace: Backtrace::new() };
179 locked_before.insert(*locked_idx, lockdep);
182 held.borrow_mut().insert(this.lock_idx, Arc::clone(this));
187 pub struct Mutex<T: Sized> {
189 deps: Arc<LockMetadata>,
192 #[must_use = "if unused the Mutex will immediately unlock"]
193 pub struct MutexGuard<'a, T: Sized + 'a> {
195 lock: StdMutexGuard<'a, T>,
198 impl<'a, T: Sized> MutexGuard<'a, T> {
199 fn into_inner(self) -> StdMutexGuard<'a, T> {
200 // Somewhat unclear why we cannot move out of self.lock, but doing so gets E0509.
202 let v: StdMutexGuard<'a, T> = std::ptr::read(&self.lock);
203 std::mem::forget(self);
209 impl<T: Sized> Drop for MutexGuard<'_, T> {
211 LOCKS_HELD.with(|held| {
212 held.borrow_mut().remove(&self.mutex.deps.lock_idx);
217 impl<T: Sized> Deref for MutexGuard<'_, T> {
220 fn deref(&self) -> &T {
225 impl<T: Sized> DerefMut for MutexGuard<'_, T> {
226 fn deref_mut(&mut self) -> &mut T {
227 self.lock.deref_mut()
232 pub fn new(inner: T) -> Mutex<T> {
233 Mutex { inner: StdMutex::new(inner), deps: LockMetadata::new() }
236 pub fn lock<'a>(&'a self) -> LockResult<MutexGuard<'a, T>> {
237 LockMetadata::pre_lock(&self.deps);
238 self.inner.lock().map(|lock| MutexGuard { mutex: self, lock }).map_err(|_| ())
241 pub fn try_lock<'a>(&'a self) -> LockResult<MutexGuard<'a, T>> {
242 let res = self.inner.try_lock().map(|lock| MutexGuard { mutex: self, lock }).map_err(|_| ());
244 LockMetadata::try_locked(&self.deps);
250 pub struct RwLock<T: Sized> {
252 deps: Arc<LockMetadata>,
255 pub struct RwLockReadGuard<'a, T: Sized + 'a> {
258 guard: StdRwLockReadGuard<'a, T>,
261 pub struct RwLockWriteGuard<'a, T: Sized + 'a> {
263 guard: StdRwLockWriteGuard<'a, T>,
266 impl<T: Sized> Deref for RwLockReadGuard<'_, T> {
269 fn deref(&self) -> &T {
274 impl<T: Sized> Drop for RwLockReadGuard<'_, T> {
276 if !self.first_lock {
277 // Note that its not strictly true that the first taken read lock will get unlocked
278 // last, but in practice our locks are always taken as RAII, so it should basically
282 LOCKS_HELD.with(|held| {
283 held.borrow_mut().remove(&self.lock.deps.lock_idx);
288 impl<T: Sized> Deref for RwLockWriteGuard<'_, T> {
291 fn deref(&self) -> &T {
296 impl<T: Sized> Drop for RwLockWriteGuard<'_, T> {
298 LOCKS_HELD.with(|held| {
299 held.borrow_mut().remove(&self.lock.deps.lock_idx);
304 impl<T: Sized> DerefMut for RwLockWriteGuard<'_, T> {
305 fn deref_mut(&mut self) -> &mut T {
306 self.guard.deref_mut()
311 pub fn new(inner: T) -> RwLock<T> {
312 RwLock { inner: StdRwLock::new(inner), deps: LockMetadata::new() }
315 pub fn read<'a>(&'a self) -> LockResult<RwLockReadGuard<'a, T>> {
316 let first_lock = LockMetadata::pre_read_lock(&self.deps);
317 self.inner.read().map(|guard| RwLockReadGuard { lock: self, guard, first_lock }).map_err(|_| ())
320 pub fn write<'a>(&'a self) -> LockResult<RwLockWriteGuard<'a, T>> {
321 LockMetadata::pre_lock(&self.deps);
322 self.inner.write().map(|guard| RwLockWriteGuard { lock: self, guard }).map_err(|_| ())
325 pub fn try_write<'a>(&'a self) -> LockResult<RwLockWriteGuard<'a, T>> {
326 let res = self.inner.try_write().map(|guard| RwLockWriteGuard { lock: self, guard }).map_err(|_| ());
328 LockMetadata::try_locked(&self.deps);
334 pub type FairRwLock<T> = RwLock<T>;
337 use super::{RwLock, Mutex};
341 #[cfg(not(feature = "backtrace"))]
342 fn recursive_lock_fail() {
343 let mutex = Mutex::new(());
344 let _a = mutex.lock().unwrap();
345 let _b = mutex.lock().unwrap();
349 fn recursive_read() {
350 let lock = RwLock::new(());
351 let _a = lock.read().unwrap();
352 let _b = lock.read().unwrap();
357 fn lockorder_fail() {
358 let a = Mutex::new(());
359 let b = Mutex::new(());
361 let _a = a.lock().unwrap();
362 let _b = b.lock().unwrap();
365 let _b = b.lock().unwrap();
366 let _a = a.lock().unwrap();
372 fn write_lockorder_fail() {
373 let a = RwLock::new(());
374 let b = RwLock::new(());
376 let _a = a.write().unwrap();
377 let _b = b.write().unwrap();
380 let _b = b.write().unwrap();
381 let _a = a.write().unwrap();
387 fn read_lockorder_fail() {
388 let a = RwLock::new(());
389 let b = RwLock::new(());
391 let _a = a.read().unwrap();
392 let _b = b.read().unwrap();
395 let _b = b.read().unwrap();
396 let _a = a.read().unwrap();
401 fn read_recursive_no_lockorder() {
402 // Like the above, but note that no lockorder is implied when we recursively read-lock a
403 // RwLock, causing this to pass just fine.
404 let a = RwLock::new(());
405 let b = RwLock::new(());
406 let _outer = a.read().unwrap();
408 let _a = a.read().unwrap();
409 let _b = b.read().unwrap();
412 let _b = b.read().unwrap();
413 let _a = a.read().unwrap();
419 fn read_write_lockorder_fail() {
420 let a = RwLock::new(());
421 let b = RwLock::new(());
423 let _a = a.write().unwrap();
424 let _b = b.read().unwrap();
427 let _b = b.read().unwrap();
428 let _a = a.write().unwrap();