Expose `ChannelMonitor::get_counterparty_node_id`
[rust-lightning] / lightning / src / 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 prelude::HashMap;
16
17 #[cfg(feature = "backtrace")]
18 use {prelude::hash_map, backtrace::Backtrace, std::sync::Once};
19
20 #[cfg(not(feature = "backtrace"))]
21 struct Backtrace{}
22 #[cfg(not(feature = "backtrace"))]
23 impl Backtrace { fn new() -> Backtrace { Backtrace {} } }
24
25 pub type LockResult<Guard> = Result<Guard, ()>;
26
27 pub struct Condvar {
28         inner: StdCondvar,
29 }
30
31 impl Condvar {
32         pub fn new() -> Condvar {
33                 Condvar { inner: StdCondvar::new() }
34         }
35
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(|_| ())
39         }
40
41         #[allow(unused)]
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(|_| ())
45         }
46
47         pub fn notify_all(&self) { self.inner.notify_all(); }
48 }
49
50 thread_local! {
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());
53 }
54 static LOCK_IDX: AtomicUsize = AtomicUsize::new(0);
55
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();
60
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.
63 struct LockMetadata {
64         lock_idx: u64,
65         locked_before: StdMutex<HashMap<u64, LockDep>>,
66         _lock_construction_bt: Backtrace,
67 }
68
69 struct LockDep {
70         lock: Arc<LockMetadata>,
71         lockdep_trace: Backtrace,
72 }
73
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) {
85                                 if found_debug_sync {
86                                         if let Some(col) = symbol.colno() {
87                                                 return format!("{}:{}:{}", symbol.filename().unwrap().display(), symbol.lineno().unwrap(), col);
88                                         } else {
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());
92                                         }
93                                 }
94                         } else { found_debug_sync = true; }
95                 }
96         }
97         panic!("Couldn't find mutex construction callsite");
98 }
99
100 impl LockMetadata {
101         fn new() -> Arc<LockMetadata> {
102                 let backtrace = Backtrace::new();
103                 let lock_idx = LOCK_IDX.fetch_add(1, Ordering::Relaxed) as u64;
104
105                 let res = Arc::new(LockMetadata {
106                         locked_before: StdMutex::new(HashMap::new()),
107                         lock_idx,
108                         _lock_construction_bt: backtrace,
109                 });
110
111                 #[cfg(feature = "backtrace")]
112                 {
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)); },
119                         }
120                 }
121                 res
122         }
123
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
130                         // inversion.
131                         for (locked_idx, _locked) in held.borrow().iter() {
132                                 if read && *locked_idx == this.lock_idx {
133                                         // Recursive read locks are explicitly allowed
134                                         return;
135                                 }
136                         }
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
140                                         // of the same lock.
141                                         debug_assert!(cfg!(feature = "backtrace"), "Tried to acquire a lock while it was held!");
142                                 }
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.");
152                                         }
153                                 }
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);
159                                 }
160                         }
161                         held.borrow_mut().insert(this.lock_idx, Arc::clone(this));
162                         inserted = true;
163                 });
164                 inserted
165         }
166
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) }
169
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);
180                                 }
181                         }
182                         held.borrow_mut().insert(this.lock_idx, Arc::clone(this));
183                 });
184         }
185 }
186
187 pub struct Mutex<T: Sized> {
188         inner: StdMutex<T>,
189         deps: Arc<LockMetadata>,
190 }
191
192 #[must_use = "if unused the Mutex will immediately unlock"]
193 pub struct MutexGuard<'a, T: Sized + 'a> {
194         mutex: &'a Mutex<T>,
195         lock: StdMutexGuard<'a, T>,
196 }
197
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.
201                 unsafe {
202                         let v: StdMutexGuard<'a, T> = std::ptr::read(&self.lock);
203                         std::mem::forget(self);
204                         v
205                 }
206         }
207 }
208
209 impl<T: Sized> Drop for MutexGuard<'_, T> {
210         fn drop(&mut self) {
211                 LOCKS_HELD.with(|held| {
212                         held.borrow_mut().remove(&self.mutex.deps.lock_idx);
213                 });
214         }
215 }
216
217 impl<T: Sized> Deref for MutexGuard<'_, T> {
218         type Target = T;
219
220         fn deref(&self) -> &T {
221                 &self.lock.deref()
222         }
223 }
224
225 impl<T: Sized> DerefMut for MutexGuard<'_, T> {
226         fn deref_mut(&mut self) -> &mut T {
227                 self.lock.deref_mut()
228         }
229 }
230
231 impl<T> Mutex<T> {
232         pub fn new(inner: T) -> Mutex<T> {
233                 Mutex { inner: StdMutex::new(inner), deps: LockMetadata::new() }
234         }
235
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(|_| ())
239         }
240
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(|_| ());
243                 if res.is_ok() {
244                         LockMetadata::try_locked(&self.deps);
245                 }
246                 res
247         }
248 }
249
250 pub struct RwLock<T: Sized> {
251         inner: StdRwLock<T>,
252         deps: Arc<LockMetadata>,
253 }
254
255 pub struct RwLockReadGuard<'a, T: Sized + 'a> {
256         lock: &'a RwLock<T>,
257         first_lock: bool,
258         guard: StdRwLockReadGuard<'a, T>,
259 }
260
261 pub struct RwLockWriteGuard<'a, T: Sized + 'a> {
262         lock: &'a RwLock<T>,
263         guard: StdRwLockWriteGuard<'a, T>,
264 }
265
266 impl<T: Sized> Deref for RwLockReadGuard<'_, T> {
267         type Target = T;
268
269         fn deref(&self) -> &T {
270                 &self.guard.deref()
271         }
272 }
273
274 impl<T: Sized> Drop for RwLockReadGuard<'_, T> {
275         fn drop(&mut self) {
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
279                         // always be true.
280                         return;
281                 }
282                 LOCKS_HELD.with(|held| {
283                         held.borrow_mut().remove(&self.lock.deps.lock_idx);
284                 });
285         }
286 }
287
288 impl<T: Sized> Deref for RwLockWriteGuard<'_, T> {
289         type Target = T;
290
291         fn deref(&self) -> &T {
292                 &self.guard.deref()
293         }
294 }
295
296 impl<T: Sized> Drop for RwLockWriteGuard<'_, T> {
297         fn drop(&mut self) {
298                 LOCKS_HELD.with(|held| {
299                         held.borrow_mut().remove(&self.lock.deps.lock_idx);
300                 });
301         }
302 }
303
304 impl<T: Sized> DerefMut for RwLockWriteGuard<'_, T> {
305         fn deref_mut(&mut self) -> &mut T {
306                 self.guard.deref_mut()
307         }
308 }
309
310 impl<T> RwLock<T> {
311         pub fn new(inner: T) -> RwLock<T> {
312                 RwLock { inner: StdRwLock::new(inner), deps: LockMetadata::new() }
313         }
314
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(|_| ())
318         }
319
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(|_| ())
323         }
324
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(|_| ());
327                 if res.is_ok() {
328                         LockMetadata::try_locked(&self.deps);
329                 }
330                 res
331         }
332 }
333
334 pub type FairRwLock<T> = RwLock<T>;
335
336 mod tests {
337         use super::{RwLock, Mutex};
338
339         #[test]
340         #[should_panic]
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();
346         }
347
348         #[test]
349         fn recursive_read() {
350                 let lock = RwLock::new(());
351                 let _a = lock.read().unwrap();
352                 let _b = lock.read().unwrap();
353         }
354
355         #[test]
356         #[should_panic]
357         fn lockorder_fail() {
358                 let a = Mutex::new(());
359                 let b = Mutex::new(());
360                 {
361                         let _a = a.lock().unwrap();
362                         let _b = b.lock().unwrap();
363                 }
364                 {
365                         let _b = b.lock().unwrap();
366                         let _a = a.lock().unwrap();
367                 }
368         }
369
370         #[test]
371         #[should_panic]
372         fn write_lockorder_fail() {
373                 let a = RwLock::new(());
374                 let b = RwLock::new(());
375                 {
376                         let _a = a.write().unwrap();
377                         let _b = b.write().unwrap();
378                 }
379                 {
380                         let _b = b.write().unwrap();
381                         let _a = a.write().unwrap();
382                 }
383         }
384
385         #[test]
386         #[should_panic]
387         fn read_lockorder_fail() {
388                 let a = RwLock::new(());
389                 let b = RwLock::new(());
390                 {
391                         let _a = a.read().unwrap();
392                         let _b = b.read().unwrap();
393                 }
394                 {
395                         let _b = b.read().unwrap();
396                         let _a = a.read().unwrap();
397                 }
398         }
399
400         #[test]
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();
407                 {
408                         let _a = a.read().unwrap();
409                         let _b = b.read().unwrap();
410                 }
411                 {
412                         let _b = b.read().unwrap();
413                         let _a = a.read().unwrap();
414                 }
415         }
416
417         #[test]
418         #[should_panic]
419         fn read_write_lockorder_fail() {
420                 let a = RwLock::new(());
421                 let b = RwLock::new(());
422                 {
423                         let _a = a.write().unwrap();
424                         let _b = b.read().unwrap();
425                 }
426                 {
427                         let _b = b.read().unwrap();
428                         let _a = a.write().unwrap();
429                 }
430         }
431 }