5631093723733f16f4d7447c0865f58219d1cf40
[rust-lightning] / lightning / src / sync / debug_sync.rs
1 pub use ::alloc::sync::Arc;
2 use core::ops::{Deref, DerefMut};
3 use core::time::Duration;
4
5 use std::cell::RefCell;
6
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;
14
15 use crate::prelude::HashMap;
16
17 use super::{LockTestExt, LockHeldState};
18
19 #[cfg(feature = "backtrace")]
20 use {crate::prelude::hash_map, backtrace::Backtrace, std::sync::Once};
21
22 #[cfg(not(feature = "backtrace"))]
23 struct Backtrace{}
24 #[cfg(not(feature = "backtrace"))]
25 impl Backtrace { fn new() -> Backtrace { Backtrace {} } }
26
27 pub type LockResult<Guard> = Result<Guard, ()>;
28
29 pub struct Condvar {
30         inner: StdCondvar,
31 }
32
33 impl Condvar {
34         pub fn new() -> Condvar {
35                 Condvar { inner: StdCondvar::new() }
36         }
37
38         pub fn wait<'a, T>(&'a self, guard: MutexGuard<'a, T>) -> LockResult<MutexGuard<'a, T>> {
39                 let mutex: &'a Mutex<T> = guard.mutex;
40                 self.inner.wait(guard.into_inner()).map(|lock| MutexGuard { mutex, lock }).map_err(|_| ())
41         }
42
43         #[allow(unused)]
44         pub fn wait_timeout<'a, T>(&'a self, guard: MutexGuard<'a, T>, dur: Duration) -> LockResult<(MutexGuard<'a, T>, ())> {
45                 let mutex = guard.mutex;
46                 self.inner.wait_timeout(guard.into_inner(), dur).map(|(lock, _)| (MutexGuard { mutex, lock }, ())).map_err(|_| ())
47         }
48
49         pub fn notify_all(&self) { self.inner.notify_all(); }
50 }
51
52 thread_local! {
53         /// We track the set of locks currently held by a reference to their `LockMetadata`
54         static LOCKS_HELD: RefCell<HashMap<u64, Arc<LockMetadata>>> = RefCell::new(HashMap::new());
55 }
56 static LOCK_IDX: AtomicUsize = AtomicUsize::new(0);
57
58 #[cfg(feature = "backtrace")]
59 static mut LOCKS: Option<StdMutex<HashMap<String, Arc<LockMetadata>>>> = None;
60 #[cfg(feature = "backtrace")]
61 static LOCKS_INIT: Once = Once::new();
62
63 /// Metadata about a single lock, by id, the set of things locked-before it, and the backtrace of
64 /// when the Mutex itself was constructed.
65 struct LockMetadata {
66         lock_idx: u64,
67         locked_before: StdMutex<HashMap<u64, LockDep>>,
68         _lock_construction_bt: Backtrace,
69 }
70
71 struct LockDep {
72         lock: Arc<LockMetadata>,
73         /// lockdep_trace is unused unless we're building with `backtrace`, so we mark it _
74         _lockdep_trace: Backtrace,
75 }
76
77 #[cfg(feature = "backtrace")]
78 fn get_construction_location(backtrace: &Backtrace) -> String {
79         // Find the first frame that is after `debug_sync` (or that is in our tests) and use
80         // that as the mutex construction site. Note that the first few frames may be in
81         // the `backtrace` crate, so we have to ignore those.
82         let sync_mutex_constr_regex = regex::Regex::new(r"lightning.*debug_sync").unwrap();
83         let mut found_debug_sync = false;
84         for frame in backtrace.frames() {
85                 for symbol in frame.symbols() {
86                         let symbol_name = symbol.name().unwrap().as_str().unwrap();
87                         if !sync_mutex_constr_regex.is_match(symbol_name) {
88                                 if found_debug_sync {
89                                         if let Some(col) = symbol.colno() {
90                                                 return format!("{}:{}:{}", symbol.filename().unwrap().display(), symbol.lineno().unwrap(), col);
91                                         } else {
92                                                 // Windows debug symbols don't support column numbers, so fall back to
93                                                 // line numbers only if no `colno` is available
94                                                 return format!("{}:{}", symbol.filename().unwrap().display(), symbol.lineno().unwrap());
95                                         }
96                                 }
97                         } else { found_debug_sync = true; }
98                 }
99         }
100         panic!("Couldn't find mutex construction callsite");
101 }
102
103 impl LockMetadata {
104         fn new() -> Arc<LockMetadata> {
105                 let backtrace = Backtrace::new();
106                 let lock_idx = LOCK_IDX.fetch_add(1, Ordering::Relaxed) as u64;
107
108                 let res = Arc::new(LockMetadata {
109                         locked_before: StdMutex::new(HashMap::new()),
110                         lock_idx,
111                         _lock_construction_bt: backtrace,
112                 });
113
114                 #[cfg(feature = "backtrace")]
115                 {
116                         let lock_constr_location = get_construction_location(&res._lock_construction_bt);
117                         LOCKS_INIT.call_once(|| { unsafe { LOCKS = Some(StdMutex::new(HashMap::new())); } });
118                         let mut locks = unsafe { LOCKS.as_ref() }.unwrap().lock().unwrap();
119                         match locks.entry(lock_constr_location) {
120                                 hash_map::Entry::Occupied(e) => return Arc::clone(e.get()),
121                                 hash_map::Entry::Vacant(e) => { e.insert(Arc::clone(&res)); },
122                         }
123                 }
124                 res
125         }
126
127         // Returns whether we were a recursive lock (only relevant for read)
128         fn _pre_lock(this: &Arc<LockMetadata>, read: bool) -> bool {
129                 let mut inserted = false;
130                 LOCKS_HELD.with(|held| {
131                         // For each lock which is currently locked, check that no lock's locked-before
132                         // set includes the lock we're about to lock, which would imply a lockorder
133                         // inversion.
134                         for (locked_idx, _locked) in held.borrow().iter() {
135                                 if read && *locked_idx == this.lock_idx {
136                                         // Recursive read locks are explicitly allowed
137                                         return;
138                                 }
139                         }
140                         for (locked_idx, locked) in held.borrow().iter() {
141                                 if !read && *locked_idx == this.lock_idx {
142                                         // With `feature = "backtrace"` set, we may be looking at different instances
143                                         // of the same lock.
144                                         debug_assert!(cfg!(feature = "backtrace"), "Tried to acquire a lock while it was held!");
145                                 }
146                                 for (locked_dep_idx, _locked_dep) in locked.locked_before.lock().unwrap().iter() {
147                                         if *locked_dep_idx == this.lock_idx && *locked_dep_idx != locked.lock_idx {
148                                                 #[cfg(feature = "backtrace")]
149                                                 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",
150                                                         get_construction_location(&this._lock_construction_bt), this.lock_idx, this._lock_construction_bt,
151                                                         get_construction_location(&locked._lock_construction_bt), locked.lock_idx, locked._lock_construction_bt,
152                                                         _locked_dep._lockdep_trace);
153                                                 #[cfg(not(feature = "backtrace"))]
154                                                 panic!("Tried to violate existing lockorder. Build with the backtrace feature for more info.");
155                                         }
156                                 }
157                                 // Insert any already-held locks in our locked-before set.
158                                 let mut locked_before = this.locked_before.lock().unwrap();
159                                 if !locked_before.contains_key(&locked.lock_idx) {
160                                         let lockdep = LockDep { lock: Arc::clone(locked), _lockdep_trace: Backtrace::new() };
161                                         locked_before.insert(lockdep.lock.lock_idx, lockdep);
162                                 }
163                         }
164                         held.borrow_mut().insert(this.lock_idx, Arc::clone(this));
165                         inserted = true;
166                 });
167                 inserted
168         }
169
170         fn pre_lock(this: &Arc<LockMetadata>) { Self::_pre_lock(this, false); }
171         fn pre_read_lock(this: &Arc<LockMetadata>) -> bool { Self::_pre_lock(this, true) }
172
173         fn held_by_thread(this: &Arc<LockMetadata>) -> LockHeldState {
174                 let mut res = LockHeldState::NotHeldByThread;
175                 LOCKS_HELD.with(|held| {
176                         for (locked_idx, _locked) in held.borrow().iter() {
177                                 if *locked_idx == this.lock_idx {
178                                         res = LockHeldState::HeldByThread;
179                                 }
180                         }
181                 });
182                 res
183         }
184
185         fn try_locked(this: &Arc<LockMetadata>) {
186                 LOCKS_HELD.with(|held| {
187                         // Since a try-lock will simply fail if the lock is held already, we do not
188                         // consider try-locks to ever generate lockorder inversions. However, if a try-lock
189                         // succeeds, we do consider it to have created lockorder dependencies.
190                         let mut locked_before = this.locked_before.lock().unwrap();
191                         for (locked_idx, locked) in held.borrow().iter() {
192                                 if !locked_before.contains_key(locked_idx) {
193                                         let lockdep = LockDep { lock: Arc::clone(locked), _lockdep_trace: Backtrace::new() };
194                                         locked_before.insert(*locked_idx, lockdep);
195                                 }
196                         }
197                         held.borrow_mut().insert(this.lock_idx, Arc::clone(this));
198                 });
199         }
200 }
201
202 pub struct Mutex<T: Sized> {
203         inner: StdMutex<T>,
204         deps: Arc<LockMetadata>,
205 }
206
207 #[must_use = "if unused the Mutex will immediately unlock"]
208 pub struct MutexGuard<'a, T: Sized + 'a> {
209         mutex: &'a Mutex<T>,
210         lock: StdMutexGuard<'a, T>,
211 }
212
213 impl<'a, T: Sized> MutexGuard<'a, T> {
214         fn into_inner(self) -> StdMutexGuard<'a, T> {
215                 // Somewhat unclear why we cannot move out of self.lock, but doing so gets E0509.
216                 unsafe {
217                         let v: StdMutexGuard<'a, T> = std::ptr::read(&self.lock);
218                         std::mem::forget(self);
219                         v
220                 }
221         }
222 }
223
224 impl<T: Sized> Drop for MutexGuard<'_, T> {
225         fn drop(&mut self) {
226                 LOCKS_HELD.with(|held| {
227                         held.borrow_mut().remove(&self.mutex.deps.lock_idx);
228                 });
229         }
230 }
231
232 impl<T: Sized> Deref for MutexGuard<'_, T> {
233         type Target = T;
234
235         fn deref(&self) -> &T {
236                 &self.lock.deref()
237         }
238 }
239
240 impl<T: Sized> DerefMut for MutexGuard<'_, T> {
241         fn deref_mut(&mut self) -> &mut T {
242                 self.lock.deref_mut()
243         }
244 }
245
246 impl<T> Mutex<T> {
247         pub fn new(inner: T) -> Mutex<T> {
248                 Mutex { inner: StdMutex::new(inner), deps: LockMetadata::new() }
249         }
250
251         pub fn lock<'a>(&'a self) -> LockResult<MutexGuard<'a, T>> {
252                 LockMetadata::pre_lock(&self.deps);
253                 self.inner.lock().map(|lock| MutexGuard { mutex: self, lock }).map_err(|_| ())
254         }
255
256         pub fn try_lock<'a>(&'a self) -> LockResult<MutexGuard<'a, T>> {
257                 let res = self.inner.try_lock().map(|lock| MutexGuard { mutex: self, lock }).map_err(|_| ());
258                 if res.is_ok() {
259                         LockMetadata::try_locked(&self.deps);
260                 }
261                 res
262         }
263 }
264
265 impl <T> LockTestExt for Mutex<T> {
266         #[inline]
267         fn held_by_thread(&self) -> LockHeldState {
268                 LockMetadata::held_by_thread(&self.deps)
269         }
270 }
271
272 pub struct RwLock<T: Sized> {
273         inner: StdRwLock<T>,
274         deps: Arc<LockMetadata>,
275 }
276
277 pub struct RwLockReadGuard<'a, T: Sized + 'a> {
278         lock: &'a RwLock<T>,
279         first_lock: bool,
280         guard: StdRwLockReadGuard<'a, T>,
281 }
282
283 pub struct RwLockWriteGuard<'a, T: Sized + 'a> {
284         lock: &'a RwLock<T>,
285         guard: StdRwLockWriteGuard<'a, T>,
286 }
287
288 impl<T: Sized> Deref for RwLockReadGuard<'_, T> {
289         type Target = T;
290
291         fn deref(&self) -> &T {
292                 &self.guard.deref()
293         }
294 }
295
296 impl<T: Sized> Drop for RwLockReadGuard<'_, T> {
297         fn drop(&mut self) {
298                 if !self.first_lock {
299                         // Note that its not strictly true that the first taken read lock will get unlocked
300                         // last, but in practice our locks are always taken as RAII, so it should basically
301                         // always be true.
302                         return;
303                 }
304                 LOCKS_HELD.with(|held| {
305                         held.borrow_mut().remove(&self.lock.deps.lock_idx);
306                 });
307         }
308 }
309
310 impl<T: Sized> Deref for RwLockWriteGuard<'_, T> {
311         type Target = T;
312
313         fn deref(&self) -> &T {
314                 &self.guard.deref()
315         }
316 }
317
318 impl<T: Sized> Drop for RwLockWriteGuard<'_, T> {
319         fn drop(&mut self) {
320                 LOCKS_HELD.with(|held| {
321                         held.borrow_mut().remove(&self.lock.deps.lock_idx);
322                 });
323         }
324 }
325
326 impl<T: Sized> DerefMut for RwLockWriteGuard<'_, T> {
327         fn deref_mut(&mut self) -> &mut T {
328                 self.guard.deref_mut()
329         }
330 }
331
332 impl<T> RwLock<T> {
333         pub fn new(inner: T) -> RwLock<T> {
334                 RwLock { inner: StdRwLock::new(inner), deps: LockMetadata::new() }
335         }
336
337         pub fn read<'a>(&'a self) -> LockResult<RwLockReadGuard<'a, T>> {
338                 let first_lock = LockMetadata::pre_read_lock(&self.deps);
339                 self.inner.read().map(|guard| RwLockReadGuard { lock: self, guard, first_lock }).map_err(|_| ())
340         }
341
342         pub fn write<'a>(&'a self) -> LockResult<RwLockWriteGuard<'a, T>> {
343                 LockMetadata::pre_lock(&self.deps);
344                 self.inner.write().map(|guard| RwLockWriteGuard { lock: self, guard }).map_err(|_| ())
345         }
346
347         pub fn try_write<'a>(&'a self) -> LockResult<RwLockWriteGuard<'a, T>> {
348                 let res = self.inner.try_write().map(|guard| RwLockWriteGuard { lock: self, guard }).map_err(|_| ());
349                 if res.is_ok() {
350                         LockMetadata::try_locked(&self.deps);
351                 }
352                 res
353         }
354 }
355
356 impl <T> LockTestExt for RwLock<T> {
357         #[inline]
358         fn held_by_thread(&self) -> LockHeldState {
359                 LockMetadata::held_by_thread(&self.deps)
360         }
361 }
362
363 pub type FairRwLock<T> = RwLock<T>;