edf7c753537e105d842f3143eadb55840cb8da2a
[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 pub use std::sync::WaitTimeoutResult;
16
17 use crate::prelude::HashMap;
18
19 use super::{LockTestExt, LockHeldState};
20
21 #[cfg(feature = "backtrace")]
22 use {crate::prelude::hash_map, backtrace::Backtrace, std::sync::Once};
23
24 #[cfg(not(feature = "backtrace"))]
25 struct Backtrace{}
26 #[cfg(not(feature = "backtrace"))]
27 impl Backtrace { fn new() -> Backtrace { Backtrace {} } }
28
29 pub type LockResult<Guard> = Result<Guard, ()>;
30
31 pub struct Condvar {
32         inner: StdCondvar,
33 }
34
35 impl Condvar {
36         pub fn new() -> Condvar {
37                 Condvar { inner: StdCondvar::new() }
38         }
39
40         pub fn wait<'a, T>(&'a self, guard: MutexGuard<'a, T>) -> LockResult<MutexGuard<'a, T>> {
41                 let mutex: &'a Mutex<T> = guard.mutex;
42                 self.inner.wait(guard.into_inner()).map(|lock| MutexGuard { mutex, lock }).map_err(|_| ())
43         }
44
45         pub fn wait_while<'a, T, F: FnMut(&mut T) -> bool>(&'a self, guard: MutexGuard<'a, T>, condition: F)
46         -> LockResult<MutexGuard<'a, T>> {
47                 let mutex: &'a Mutex<T> = guard.mutex;
48                 self.inner.wait_while(guard.into_inner(), condition).map(|lock| MutexGuard { mutex, lock })
49                         .map_err(|_| ())
50         }
51
52         #[allow(unused)]
53         pub fn wait_timeout<'a, T>(&'a self, guard: MutexGuard<'a, T>, dur: Duration) -> LockResult<(MutexGuard<'a, T>, ())> {
54                 let mutex = guard.mutex;
55                 self.inner.wait_timeout(guard.into_inner(), dur).map(|(lock, _)| (MutexGuard { mutex, lock }, ())).map_err(|_| ())
56         }
57
58         #[allow(unused)]
59         pub fn wait_timeout_while<'a, T, F: FnMut(&mut T) -> bool>(&'a self, guard: MutexGuard<'a, T>, dur: Duration, condition: F)
60         -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)> {
61                 let mutex = guard.mutex;
62                 self.inner.wait_timeout_while(guard.into_inner(), dur, condition).map_err(|_| ())
63                         .map(|(lock, e)| (MutexGuard { mutex, lock }, e))
64         }
65
66         pub fn notify_all(&self) { self.inner.notify_all(); }
67 }
68
69 thread_local! {
70         /// We track the set of locks currently held by a reference to their `LockMetadata`
71         static LOCKS_HELD: RefCell<HashMap<u64, Arc<LockMetadata>>> = RefCell::new(HashMap::new());
72 }
73 static LOCK_IDX: AtomicUsize = AtomicUsize::new(0);
74
75 #[cfg(feature = "backtrace")]
76 static mut LOCKS: Option<StdMutex<HashMap<String, Arc<LockMetadata>>>> = None;
77 #[cfg(feature = "backtrace")]
78 static LOCKS_INIT: Once = Once::new();
79
80 /// Metadata about a single lock, by id, the set of things locked-before it, and the backtrace of
81 /// when the Mutex itself was constructed.
82 struct LockMetadata {
83         lock_idx: u64,
84         locked_before: StdMutex<HashMap<u64, LockDep>>,
85         _lock_construction_bt: Backtrace,
86 }
87
88 struct LockDep {
89         lock: Arc<LockMetadata>,
90         /// lockdep_trace is unused unless we're building with `backtrace`, so we mark it _
91         _lockdep_trace: Backtrace,
92 }
93
94 // Locates the frame preceding the earliest `debug_sync` frame in the call stack. This ensures we
95 // can properly detect a lock's construction and acquiral callsites, since the latter may contain
96 // multiple `debug_sync` frames.
97 #[cfg(feature = "backtrace")]
98 fn locate_call_symbol(backtrace: &Backtrace) -> (String, Option<u32>) {
99         // Find the earliest `debug_sync` frame (or that is in our tests) and use the frame preceding it
100         // as the callsite. Note that the first few frames may be in the `backtrace` crate, so we have
101         // to ignore those.
102         let sync_mutex_constr_regex = regex::Regex::new(r"lightning.*debug_sync").unwrap();
103         let mut found_debug_sync = false;
104         let mut symbol_after_latest_debug_sync = None;
105         for frame in backtrace.frames().iter() {
106                 for symbol in frame.symbols().iter() {
107                         if let Some(symbol_name) = symbol.name().map(|name| name.as_str()).flatten() {
108                                 if !sync_mutex_constr_regex.is_match(symbol_name) {
109                                         if found_debug_sync {
110                                                 symbol_after_latest_debug_sync = Some(symbol);
111                                                 found_debug_sync = false;
112                                         }
113                                 } else { found_debug_sync = true; }
114                         }
115                 }
116         }
117         let symbol = symbol_after_latest_debug_sync.expect("Couldn't find lock call symbol");
118         (format!("{}:{}", symbol.filename().unwrap().display(), symbol.lineno().unwrap()), symbol.colno())
119 }
120
121 impl LockMetadata {
122         fn new() -> Arc<LockMetadata> {
123                 let backtrace = Backtrace::new();
124                 let lock_idx = LOCK_IDX.fetch_add(1, Ordering::Relaxed) as u64;
125
126                 let res = Arc::new(LockMetadata {
127                         locked_before: StdMutex::new(HashMap::new()),
128                         lock_idx,
129                         _lock_construction_bt: backtrace,
130                 });
131
132                 #[cfg(feature = "backtrace")]
133                 {
134                         let (lock_constr_location, lock_constr_colno) =
135                                 locate_call_symbol(&res._lock_construction_bt);
136                         LOCKS_INIT.call_once(|| { unsafe { LOCKS = Some(StdMutex::new(HashMap::new())); } });
137                         let mut locks = unsafe { LOCKS.as_ref() }.unwrap().lock().unwrap();
138                         match locks.entry(lock_constr_location) {
139                                 hash_map::Entry::Occupied(e) => {
140                                         assert_eq!(lock_constr_colno,
141                                                 locate_call_symbol(&e.get()._lock_construction_bt).1,
142                                                 "Because Windows doesn't support column number results in backtraces, we cannot construct two mutexes on the same line or we risk lockorder detection false positives.");
143                                         return Arc::clone(e.get())
144                                 },
145                                 hash_map::Entry::Vacant(e) => { e.insert(Arc::clone(&res)); },
146                         }
147                 }
148                 res
149         }
150
151         fn pre_lock(this: &Arc<LockMetadata>, _double_lock_self_allowed: bool) {
152                 LOCKS_HELD.with(|held| {
153                         // For each lock that is currently held, check that no lock's `locked_before` set
154                         // includes the lock we're about to hold, which would imply a lockorder inversion.
155                         for (locked_idx, _locked) in held.borrow().iter() {
156                                 if *locked_idx == this.lock_idx {
157                                         // Note that with `feature = "backtrace"` set, we may be looking at different
158                                         // instances of the same lock. Still, doing so is quite risky, a total order
159                                         // must be maintained, and doing so across a set of otherwise-identical mutexes
160                                         // is fraught with issues.
161                                         #[cfg(feature = "backtrace")]
162                                         debug_assert!(_double_lock_self_allowed,
163                                                 "Tried to acquire a lock while it was held!\nLock constructed at {}",
164                                                 locate_call_symbol(&this._lock_construction_bt).0);
165                                         #[cfg(not(feature = "backtrace"))]
166                                         panic!("Tried to acquire a lock while it was held!");
167                                 }
168                         }
169                         for (_locked_idx, locked) in held.borrow().iter() {
170                                 for (locked_dep_idx, _locked_dep) in locked.locked_before.lock().unwrap().iter() {
171                                         let is_dep_this_lock = *locked_dep_idx == this.lock_idx;
172                                         let has_same_construction = *locked_dep_idx == locked.lock_idx;
173                                         if is_dep_this_lock && !has_same_construction {
174                                                 #[allow(unused_mut, unused_assignments)]
175                                                 let mut has_same_callsite = false;
176                                                 #[cfg(feature = "backtrace")] {
177                                                         has_same_callsite = _double_lock_self_allowed &&
178                                                                 locate_call_symbol(&_locked_dep._lockdep_trace) ==
179                                                                         locate_call_symbol(&Backtrace::new());
180                                                 }
181                                                 if !has_same_callsite {
182                                                         #[cfg(feature = "backtrace")]
183                                                         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",
184                                                                 locate_call_symbol(&this._lock_construction_bt).0,
185                                                                 this.lock_idx, this._lock_construction_bt,
186                                                                 locate_call_symbol(&locked._lock_construction_bt).0,
187                                                                 locked.lock_idx, locked._lock_construction_bt,
188                                                                 _locked_dep._lockdep_trace);
189                                                         #[cfg(not(feature = "backtrace"))]
190                                                         panic!("Tried to violate existing lockorder. Build with the backtrace feature for more info.");
191                                                 }
192                                         }
193                                 }
194                                 // Insert any already-held locks in our locked-before set.
195                                 let mut locked_before = this.locked_before.lock().unwrap();
196                                 if !locked_before.contains_key(&locked.lock_idx) {
197                                         let lockdep = LockDep { lock: Arc::clone(locked), _lockdep_trace: Backtrace::new() };
198                                         locked_before.insert(lockdep.lock.lock_idx, lockdep);
199                                 }
200                         }
201                         held.borrow_mut().insert(this.lock_idx, Arc::clone(this));
202                 });
203         }
204
205         fn held_by_thread(this: &Arc<LockMetadata>) -> LockHeldState {
206                 let mut res = LockHeldState::NotHeldByThread;
207                 LOCKS_HELD.with(|held| {
208                         for (locked_idx, _locked) in held.borrow().iter() {
209                                 if *locked_idx == this.lock_idx {
210                                         res = LockHeldState::HeldByThread;
211                                 }
212                         }
213                 });
214                 res
215         }
216
217         fn try_locked(this: &Arc<LockMetadata>) {
218                 LOCKS_HELD.with(|held| {
219                         // Since a try-lock will simply fail if the lock is held already, we do not
220                         // consider try-locks to ever generate lockorder inversions. However, if a try-lock
221                         // succeeds, we do consider it to have created lockorder dependencies.
222                         let mut locked_before = this.locked_before.lock().unwrap();
223                         for (locked_idx, locked) in held.borrow().iter() {
224                                 if !locked_before.contains_key(locked_idx) {
225                                         let lockdep = LockDep { lock: Arc::clone(locked), _lockdep_trace: Backtrace::new() };
226                                         locked_before.insert(*locked_idx, lockdep);
227                                 }
228                         }
229                         held.borrow_mut().insert(this.lock_idx, Arc::clone(this));
230                 });
231         }
232 }
233
234 pub struct Mutex<T: Sized> {
235         inner: StdMutex<T>,
236         deps: Arc<LockMetadata>,
237 }
238 impl<T: Sized> Mutex<T> {
239         pub(crate) fn into_inner(self) -> LockResult<T> {
240                 self.inner.into_inner().map_err(|_| ())
241         }
242 }
243
244 #[must_use = "if unused the Mutex will immediately unlock"]
245 pub struct MutexGuard<'a, T: Sized + 'a> {
246         mutex: &'a Mutex<T>,
247         lock: StdMutexGuard<'a, T>,
248 }
249
250 impl<'a, T: Sized> MutexGuard<'a, T> {
251         fn into_inner(self) -> StdMutexGuard<'a, T> {
252                 // Somewhat unclear why we cannot move out of self.lock, but doing so gets E0509.
253                 unsafe {
254                         let v: StdMutexGuard<'a, T> = std::ptr::read(&self.lock);
255                         std::mem::forget(self);
256                         v
257                 }
258         }
259 }
260
261 impl<T: Sized> Drop for MutexGuard<'_, T> {
262         fn drop(&mut self) {
263                 LOCKS_HELD.with(|held| {
264                         held.borrow_mut().remove(&self.mutex.deps.lock_idx);
265                 });
266         }
267 }
268
269 impl<T: Sized> Deref for MutexGuard<'_, T> {
270         type Target = T;
271
272         fn deref(&self) -> &T {
273                 &self.lock.deref()
274         }
275 }
276
277 impl<T: Sized> DerefMut for MutexGuard<'_, T> {
278         fn deref_mut(&mut self) -> &mut T {
279                 self.lock.deref_mut()
280         }
281 }
282
283 impl<T> Mutex<T> {
284         pub fn new(inner: T) -> Mutex<T> {
285                 Mutex { inner: StdMutex::new(inner), deps: LockMetadata::new() }
286         }
287
288         pub fn lock<'a>(&'a self) -> LockResult<MutexGuard<'a, T>> {
289                 LockMetadata::pre_lock(&self.deps, false);
290                 self.inner.lock().map(|lock| MutexGuard { mutex: self, lock }).map_err(|_| ())
291         }
292
293         pub fn try_lock<'a>(&'a self) -> LockResult<MutexGuard<'a, T>> {
294                 let res = self.inner.try_lock().map(|lock| MutexGuard { mutex: self, lock }).map_err(|_| ());
295                 if res.is_ok() {
296                         LockMetadata::try_locked(&self.deps);
297                 }
298                 res
299         }
300 }
301
302 impl<'a, T: 'a> LockTestExt<'a> for Mutex<T> {
303         #[inline]
304         fn held_by_thread(&self) -> LockHeldState {
305                 LockMetadata::held_by_thread(&self.deps)
306         }
307         type ExclLock = MutexGuard<'a, T>;
308         #[inline]
309         fn unsafe_well_ordered_double_lock_self(&'a self) -> MutexGuard<T> {
310                 LockMetadata::pre_lock(&self.deps, true);
311                 self.inner.lock().map(|lock| MutexGuard { mutex: self, lock }).unwrap()
312         }
313 }
314
315 pub struct RwLock<T: Sized> {
316         inner: StdRwLock<T>,
317         deps: Arc<LockMetadata>,
318 }
319
320 pub struct RwLockReadGuard<'a, T: Sized + 'a> {
321         lock: &'a RwLock<T>,
322         guard: StdRwLockReadGuard<'a, T>,
323 }
324
325 pub struct RwLockWriteGuard<'a, T: Sized + 'a> {
326         lock: &'a RwLock<T>,
327         guard: StdRwLockWriteGuard<'a, T>,
328 }
329
330 impl<T: Sized> Deref for RwLockReadGuard<'_, T> {
331         type Target = T;
332
333         fn deref(&self) -> &T {
334                 &self.guard.deref()
335         }
336 }
337
338 impl<T: Sized> Drop for RwLockReadGuard<'_, T> {
339         fn drop(&mut self) {
340                 LOCKS_HELD.with(|held| {
341                         held.borrow_mut().remove(&self.lock.deps.lock_idx);
342                 });
343         }
344 }
345
346 impl<T: Sized> Deref for RwLockWriteGuard<'_, T> {
347         type Target = T;
348
349         fn deref(&self) -> &T {
350                 &self.guard.deref()
351         }
352 }
353
354 impl<T: Sized> Drop for RwLockWriteGuard<'_, T> {
355         fn drop(&mut self) {
356                 LOCKS_HELD.with(|held| {
357                         held.borrow_mut().remove(&self.lock.deps.lock_idx);
358                 });
359         }
360 }
361
362 impl<T: Sized> DerefMut for RwLockWriteGuard<'_, T> {
363         fn deref_mut(&mut self) -> &mut T {
364                 self.guard.deref_mut()
365         }
366 }
367
368 impl<T> RwLock<T> {
369         pub fn new(inner: T) -> RwLock<T> {
370                 RwLock { inner: StdRwLock::new(inner), deps: LockMetadata::new() }
371         }
372
373         pub fn read<'a>(&'a self) -> LockResult<RwLockReadGuard<'a, T>> {
374                 // Note that while we could be taking a recursive read lock here, Rust's `RwLock` may
375                 // deadlock trying to take a second read lock if another thread is waiting on the write
376                 // lock. This behavior is platform dependent, but our in-tree `FairRwLock` guarantees
377                 // such a deadlock.
378                 LockMetadata::pre_lock(&self.deps, false);
379                 self.inner.read().map(|guard| RwLockReadGuard { lock: self, guard }).map_err(|_| ())
380         }
381
382         pub fn write<'a>(&'a self) -> LockResult<RwLockWriteGuard<'a, T>> {
383                 LockMetadata::pre_lock(&self.deps, false);
384                 self.inner.write().map(|guard| RwLockWriteGuard { lock: self, guard }).map_err(|_| ())
385         }
386
387         pub fn try_write<'a>(&'a self) -> LockResult<RwLockWriteGuard<'a, T>> {
388                 let res = self.inner.try_write().map(|guard| RwLockWriteGuard { lock: self, guard }).map_err(|_| ());
389                 if res.is_ok() {
390                         LockMetadata::try_locked(&self.deps);
391                 }
392                 res
393         }
394 }
395
396 impl<'a, T: 'a> LockTestExt<'a> for RwLock<T> {
397         #[inline]
398         fn held_by_thread(&self) -> LockHeldState {
399                 LockMetadata::held_by_thread(&self.deps)
400         }
401         type ExclLock = RwLockWriteGuard<'a, T>;
402         #[inline]
403         fn unsafe_well_ordered_double_lock_self(&'a self) -> RwLockWriteGuard<'a, T> {
404                 LockMetadata::pre_lock(&self.deps, true);
405                 self.inner.write().map(|guard| RwLockWriteGuard { lock: self, guard }).unwrap()
406         }
407 }
408
409 pub type FairRwLock<T> = RwLock<T>;