Skip to content

Commit 5eced79

Browse files
committed
Check lockorders in tests with a trivial lockorder tracker
1 parent 6ccd07b commit 5eced79

File tree

11 files changed

+237
-8
lines changed

11 files changed

+237
-8
lines changed

.github/workflows/build.yml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,10 @@ jobs:
101101
RUSTFLAGS="-C link-dead-code" cargo build --verbose --color always --features rpc-client
102102
RUSTFLAGS="-C link-dead-code" cargo build --verbose --color always --features rpc-client,rest-client
103103
RUSTFLAGS="-C link-dead-code" cargo build --verbose --color always --features rpc-client,rest-client,tokio
104+
- name: Test backtrace-debug builds on Rust ${{ matrix.toolchain }}
105+
if: "matrix.build-no-std"
106+
run: |
107+
cd lightning && cargo test --verbose --color always --features backtrace
104108
- name: Test on Rust ${{ matrix.toolchain }} with net-tokio
105109
if: "matrix.build-net-tokio && !matrix.coverage"
106110
run: cargo test --verbose --color always

lightning/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ secp256k1 = { version = "0.20.2", default-features = false, features = ["alloc"]
3939
hashbrown = { version = "0.11", optional = true }
4040
hex = { version = "0.3", optional = true }
4141
regex = { version = "0.1.80", optional = true }
42+
backtrace = { version = "0.3", optional = true }
4243

4344
core2 = { version = "0.3.0", optional = true, default-features = false }
4445

lightning/src/chain/channelmonitor.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3321,7 +3321,7 @@ mod tests {
33213321
use util::events::{ClosureReason, MessageSendEventsProvider};
33223322
use util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
33233323
use util::ser::{ReadableArgs, Writeable};
3324-
use sync::{Arc, Mutex};
3324+
use std::sync::{Arc, Mutex};
33253325
use io;
33263326
use prelude::*;
33273327

lightning/src/debug_sync.rs

Lines changed: 216 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,216 @@
1+
pub use ::alloc::sync::Arc;
2+
use core::ops::{Deref, DerefMut};
3+
use core::time::Duration;
4+
5+
use std::collections::HashSet;
6+
use std::cell::RefCell;
7+
8+
use std::sync::atomic::{AtomicUsize, Ordering};
9+
10+
use std::sync::Mutex as StdMutex;
11+
use std::sync::MutexGuard as StdMutexGuard;
12+
use std::sync::RwLock as StdRwLock;
13+
use std::sync::RwLockReadGuard as StdRwLockReadGuard;
14+
use std::sync::RwLockWriteGuard as StdRwLockWriteGuard;
15+
use std::sync::Condvar as StdCondvar;
16+
17+
#[cfg(feautre = "backtrace")]
18+
use backtrace::Backtrace;
19+
20+
pub type LockResult<Guard> = Result<Guard, ()>;
21+
22+
pub struct Condvar {
23+
inner: StdCondvar,
24+
}
25+
26+
impl Condvar {
27+
pub fn new() -> Condvar {
28+
Condvar { inner: StdCondvar::new() }
29+
}
30+
31+
pub fn wait<'a, T>(&'a self, guard: MutexGuard<'a, T>) -> LockResult<MutexGuard<'a, T>> {
32+
let mutex: &'a Mutex<T> = guard.mutex;
33+
self.inner.wait(guard.into_inner()).map(|lock| MutexGuard { mutex, lock }).map_err(|_| ())
34+
}
35+
36+
#[allow(unused)]
37+
pub fn wait_timeout<'a, T>(&'a self, guard: MutexGuard<'a, T>, dur: Duration) -> LockResult<(MutexGuard<'a, T>, ())> {
38+
let mutex = guard.mutex;
39+
self.inner.wait_timeout(guard.into_inner(), dur).map(|(lock, _)| (MutexGuard { mutex, lock }, ())).map_err(|_| ())
40+
}
41+
42+
pub fn notify_all(&self) { self.inner.notify_all(); }
43+
}
44+
45+
thread_local! {
46+
/// We track the set of locks currently held by a reference to their `MutexMetadata`
47+
static MUTEXES_HELD: RefCell<HashSet<Arc<MutexMetadata>>> = RefCell::new(HashSet::new());
48+
}
49+
static MUTEX_IDX: AtomicUsize = AtomicUsize::new(0);
50+
51+
/// Metadata about a single mutex, by id, the set of things locked-before it, and the backtrace of
52+
/// when the Mutex itself was constructed.
53+
struct MutexMetadata {
54+
mutex_idx: u64,
55+
locked_before: StdMutex<HashSet<Arc<MutexMetadata>>>,
56+
#[cfg(feautre = "backtrace")]
57+
mutex_construction_bt: Backtrace,
58+
}
59+
impl PartialEq for MutexMetadata {
60+
fn eq(&self, o: &MutexMetadata) -> bool { self.mutex_idx == o.mutex_idx }
61+
}
62+
impl Eq for MutexMetadata {}
63+
impl std::hash::Hash for MutexMetadata {
64+
fn hash<H: std::hash::Hasher>(&self, hasher: &mut H) { hasher.write_u64(self.mutex_idx); }
65+
}
66+
67+
pub struct Mutex<T: Sized> {
68+
inner: StdMutex<T>,
69+
deps: Arc<MutexMetadata>,
70+
skip_checks: bool
71+
}
72+
73+
#[must_use = "if unused the Mutex will immediately unlock"]
74+
pub struct MutexGuard<'a, T: Sized + 'a> {
75+
mutex: &'a Mutex<T>,
76+
lock: StdMutexGuard<'a, T>,
77+
}
78+
79+
impl<'a, T: Sized> MutexGuard<'a, T> {
80+
fn into_inner(self) -> StdMutexGuard<'a, T> {
81+
// Somewhat unclear why this is not possible without unsafe, but oh well.
82+
unsafe {
83+
let v: StdMutexGuard<'a, T> = std::ptr::read(&self.lock);
84+
std::mem::forget(self);
85+
v
86+
}
87+
}
88+
}
89+
90+
impl<T: Sized> Drop for MutexGuard<'_, T> {
91+
fn drop(&mut self) {
92+
MUTEXES_HELD.with(|held| {
93+
held.borrow_mut().remove(&self.mutex.deps);
94+
});
95+
}
96+
}
97+
98+
impl<T: Sized> Deref for MutexGuard<'_, T> {
99+
type Target = T;
100+
101+
fn deref(&self) -> &T {
102+
&self.lock.deref()
103+
}
104+
}
105+
106+
impl<T: Sized> DerefMut for MutexGuard<'_, T> {
107+
fn deref_mut(&mut self) -> &mut T {
108+
self.lock.deref_mut()
109+
}
110+
}
111+
112+
impl<T> Mutex<T> {
113+
pub fn new(inner: T) -> Mutex<T> {
114+
Mutex {
115+
inner: StdMutex::new(inner),
116+
deps: Arc::new(MutexMetadata {
117+
locked_before: StdMutex::new(HashSet::new()),
118+
mutex_idx: MUTEX_IDX.fetch_add(1, Ordering::Relaxed) as u64,
119+
#[cfg(feautre = "backtrace")]
120+
mutex_construction_bt: Backtrace::new(),
121+
}),
122+
skip_checks: false,
123+
}
124+
}
125+
126+
pub fn lock<'a>(&'a self) -> LockResult<MutexGuard<'a, T>> {
127+
if !self.skip_checks {
128+
MUTEXES_HELD.with(|held| {
129+
// For each mutex which is currently locked, check that no mutex's locked-before
130+
// set includes the mutex we're about to lock, which would imply a lockorder
131+
// inversion.
132+
for locked in held.borrow().iter() {
133+
for locked_dep in locked.locked_before.lock().unwrap().iter() {
134+
if *locked_dep == self.deps {
135+
#[cfg(feautre = "backtrace")]
136+
panic!("Tried to violate existing lockorder. Mutex which should be locked after the current lock was created at: {:?}", locked.mutex_construction_bt);
137+
#[cfg(not(feautre = "backtrace"))]
138+
panic!("Tried to violate existing lockorder. Build with backtrace feature for more info.");
139+
}
140+
}
141+
// Insert any already-held mutexes in our locked-before set.
142+
self.deps.locked_before.lock().unwrap().insert(Arc::clone(locked));
143+
}
144+
held.borrow_mut().insert(Arc::clone(&self.deps));
145+
});
146+
}
147+
self.inner.lock().map(|lock| MutexGuard { mutex: self, lock }).map_err(|_| ())
148+
}
149+
150+
pub fn try_lock<'a>(&'a self) -> LockResult<MutexGuard<'a, T>> {
151+
let res = self.inner.try_lock().map(|lock| MutexGuard { mutex: self, lock }).map_err(|_| ());
152+
if !self.skip_checks && res.is_ok() {
153+
MUTEXES_HELD.with(|held| {
154+
// In a try-lock, only insert already-held mutexes in our locked-before set if we
155+
// succeed in locking, and never check for lockinversions directly with this mutex.
156+
for locked in held.borrow().iter() {
157+
self.deps.locked_before.lock().unwrap().insert(Arc::clone(locked));
158+
}
159+
held.borrow_mut().insert(Arc::clone(&self.deps));
160+
});
161+
}
162+
res
163+
}
164+
}
165+
166+
pub struct RwLock<T: ?Sized> {
167+
inner: StdRwLock<T>
168+
}
169+
170+
pub struct RwLockReadGuard<'a, T: ?Sized + 'a> {
171+
lock: StdRwLockReadGuard<'a, T>,
172+
}
173+
174+
pub struct RwLockWriteGuard<'a, T: ?Sized + 'a> {
175+
lock: StdRwLockWriteGuard<'a, T>,
176+
}
177+
178+
impl<T: ?Sized> Deref for RwLockReadGuard<'_, T> {
179+
type Target = T;
180+
181+
fn deref(&self) -> &T {
182+
&self.lock.deref()
183+
}
184+
}
185+
186+
impl<T: ?Sized> Deref for RwLockWriteGuard<'_, T> {
187+
type Target = T;
188+
189+
fn deref(&self) -> &T {
190+
&self.lock.deref()
191+
}
192+
}
193+
194+
impl<T: ?Sized> DerefMut for RwLockWriteGuard<'_, T> {
195+
fn deref_mut(&mut self) -> &mut T {
196+
self.lock.deref_mut()
197+
}
198+
}
199+
200+
impl<T> RwLock<T> {
201+
pub fn new(inner: T) -> RwLock<T> {
202+
RwLock { inner: StdRwLock::new(inner) }
203+
}
204+
205+
pub fn read<'a>(&'a self) -> LockResult<RwLockReadGuard<'a, T>> {
206+
self.inner.read().map(|lock| RwLockReadGuard { lock }).map_err(|_| ())
207+
}
208+
209+
pub fn write<'a>(&'a self) -> LockResult<RwLockWriteGuard<'a, T>> {
210+
self.inner.write().map(|lock| RwLockWriteGuard { lock }).map_err(|_| ())
211+
}
212+
213+
pub fn try_write<'a>(&'a self) -> LockResult<RwLockWriteGuard<'a, T>> {
214+
self.inner.try_write().map(|lock| RwLockWriteGuard { lock }).map_err(|_| ())
215+
}
216+
}

lightning/src/lib.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,8 +143,16 @@ mod prelude {
143143
pub use alloc::string::ToString;
144144
}
145145

146+
#[cfg(all(feature = "std", test))]
147+
mod debug_sync;
148+
#[cfg(all(feature = "backtrace", feature = "std", test))]
149+
extern crate backtrace;
150+
146151
#[cfg(feature = "std")]
147152
mod sync {
153+
#[cfg(test)]
154+
pub use debug_sync::*;
155+
#[cfg(not(test))]
148156
pub use ::std::sync::{Arc, Mutex, Condvar, MutexGuard, RwLock, RwLockReadGuard};
149157
}
150158

lightning/src/ln/chanmon_update_fail_tests.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ use util::test_utils;
3636

3737
use io;
3838
use prelude::*;
39-
use sync::{Arc, Mutex};
39+
use std::sync::{Arc, Mutex};
4040

4141
#[test]
4242
fn test_simple_monitor_permanent_update_fail() {

lightning/src/ln/channelmanager.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7146,7 +7146,7 @@ pub mod bench {
71467146
use bitcoin::hashes::sha256::Hash as Sha256;
71477147
use bitcoin::{Block, BlockHeader, Transaction, TxOut};
71487148

7149-
use sync::{Arc, Mutex};
7149+
use std::sync::{Arc, Mutex};
71507150

71517151
use test::Bencher;
71527152

lightning/src/ln/functional_test_utils.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ use io;
4141
use prelude::*;
4242
use core::cell::RefCell;
4343
use alloc::rc::Rc;
44-
use sync::{Arc, Mutex};
44+
use std::sync::{Arc, Mutex};
4545
use core::mem;
4646

4747
pub const CHAN_CONFIRM_DEPTH: u32 = 10;

lightning/src/ln/functional_tests.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ use io;
5151
use prelude::*;
5252
use alloc::collections::BTreeSet;
5353
use core::default::Default;
54-
use sync::{Arc, Mutex};
54+
use std::sync::{Arc, Mutex};
5555

5656
use ln::functional_test_utils::*;
5757
use ln::chan_utils::CommitmentTransaction;

lightning/src/util/enforcing_trait_impls.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ use chain::keysinterface::{Sign, InMemorySigner, BaseSign};
1313

1414
use prelude::*;
1515
use core::cmp;
16-
use sync::{Mutex, Arc};
17-
#[cfg(test)] use sync::MutexGuard;
16+
use std::sync::{Mutex, Arc};
17+
#[cfg(test)] use std::sync::MutexGuard;
1818

1919
use bitcoin::blockdata::transaction::{Transaction, SigHashType};
2020
use bitcoin::util::bip143;

lightning/src/util/test_utils.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ use regex;
4444
use io;
4545
use prelude::*;
4646
use core::time::Duration;
47-
use sync::{Mutex, Arc};
47+
use std::sync::{Mutex, Arc};
4848
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
4949
use core::{cmp, mem};
5050
use chain::keysinterface::{InMemorySigner, KeyMaterial};

0 commit comments

Comments
 (0)