Skip to content

Commit a8d95e6

Browse files
committed
Check lockorders in tests with a trivial lockorder tracker
1 parent c72fceb commit a8d95e6

File tree

6 files changed

+236
-2
lines changed

6 files changed

+236
-2
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+
cargo test --verbose --color always -p lightning
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/debug_sync.rs

Lines changed: 221 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,221 @@
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+
pub fn new_disable_lockorder_checks(inner: T) -> Mutex<T> {
126+
let mut res = Self::new(inner);
127+
res.skip_checks = true;
128+
res
129+
}
130+
131+
pub fn lock<'a>(&'a self) -> LockResult<MutexGuard<'a, T>> {
132+
if !self.skip_checks {
133+
MUTEXES_HELD.with(|held| {
134+
// For each mutex which is currently locked, check that no mutex's locked-before
135+
// set includes the mutex we're about to lock, which would imply a lockorder
136+
// inversion.
137+
for locked in held.borrow().iter() {
138+
for locked_dep in locked.locked_before.lock().unwrap().iter() {
139+
if *locked_dep == self.deps {
140+
#[cfg(feautre = "backtrace")]
141+
panic!("Tried to violate existing lockorder. Mutex which should be locked after the current lock was created at: {:?}", locked.mutex_construction_bt);
142+
#[cfg(not(feautre = "backtrace"))]
143+
panic!("Tried to violate existing lockorder. Build with backtrace feature for more info.");
144+
}
145+
}
146+
// Insert any already-held mutexes in our locked-before set.
147+
self.deps.locked_before.lock().unwrap().insert(Arc::clone(locked));
148+
}
149+
held.borrow_mut().insert(Arc::clone(&self.deps));
150+
});
151+
}
152+
self.inner.lock().map(|lock| MutexGuard { mutex: self, lock }).map_err(|_| ())
153+
}
154+
155+
pub fn try_lock<'a>(&'a self) -> LockResult<MutexGuard<'a, T>> {
156+
let res = self.inner.try_lock().map(|lock| MutexGuard { mutex: self, lock }).map_err(|_| ());
157+
if !self.skip_checks && res.is_ok() {
158+
MUTEXES_HELD.with(|held| {
159+
// In a try-lock, only insert already-held mutexes in our locked-before set if we
160+
// succeed in locking, and never check for lockinversions directly with this mutex.
161+
for locked in held.borrow().iter() {
162+
self.deps.locked_before.lock().unwrap().insert(Arc::clone(locked));
163+
}
164+
held.borrow_mut().insert(Arc::clone(&self.deps));
165+
});
166+
}
167+
res
168+
}
169+
}
170+
171+
pub struct RwLock<T: ?Sized> {
172+
inner: StdRwLock<T>
173+
}
174+
175+
pub struct RwLockReadGuard<'a, T: ?Sized + 'a> {
176+
lock: StdRwLockReadGuard<'a, T>,
177+
}
178+
179+
pub struct RwLockWriteGuard<'a, T: ?Sized + 'a> {
180+
lock: StdRwLockWriteGuard<'a, T>,
181+
}
182+
183+
impl<T: ?Sized> Deref for RwLockReadGuard<'_, T> {
184+
type Target = T;
185+
186+
fn deref(&self) -> &T {
187+
&self.lock.deref()
188+
}
189+
}
190+
191+
impl<T: ?Sized> Deref for RwLockWriteGuard<'_, T> {
192+
type Target = T;
193+
194+
fn deref(&self) -> &T {
195+
&self.lock.deref()
196+
}
197+
}
198+
199+
impl<T: ?Sized> DerefMut for RwLockWriteGuard<'_, T> {
200+
fn deref_mut(&mut self) -> &mut T {
201+
self.lock.deref_mut()
202+
}
203+
}
204+
205+
impl<T> RwLock<T> {
206+
pub fn new(inner: T) -> RwLock<T> {
207+
RwLock { inner: StdRwLock::new(inner) }
208+
}
209+
210+
pub fn read<'a>(&'a self) -> LockResult<RwLockReadGuard<'a, T>> {
211+
self.inner.read().map(|lock| RwLockReadGuard { lock }).map_err(|_| ())
212+
}
213+
214+
pub fn write<'a>(&'a self) -> LockResult<RwLockWriteGuard<'a, T>> {
215+
self.inner.write().map(|lock| RwLockWriteGuard { lock }).map_err(|_| ())
216+
}
217+
218+
pub fn try_write<'a>(&'a self) -> LockResult<RwLockWriteGuard<'a, T>> {
219+
self.inner.try_write().map(|lock| RwLockWriteGuard { lock }).map_err(|_| ())
220+
}
221+
}

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

lightning/src/ln/functional_test_utils.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1661,7 +1661,7 @@ pub fn create_chanmon_cfgs(node_count: usize) -> Vec<TestChanMonCfg> {
16611661
let mut chan_mon_cfgs = Vec::new();
16621662
for i in 0..node_count {
16631663
let tx_broadcaster = test_utils::TestBroadcaster {
1664-
txn_broadcasted: Mutex::new(Vec::new()),
1664+
txn_broadcasted: Mutex::new_disable_lockorder_checks(Vec::new()),
16651665
blocks: Arc::new(Mutex::new(vec![(genesis_block(Network::Testnet).header, 0)])),
16661666
};
16671667
let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };

lightning/src/util/test_utils.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,7 @@ impl TestPersister {
182182
Self {
183183
update_ret: Mutex::new(Ok(())),
184184
next_update_ret: Mutex::new(None),
185-
chain_sync_monitor_persistences: Mutex::new(HashMap::new()),
185+
chain_sync_monitor_persistences: Mutex::new_disable_lockorder_checks(HashMap::new()),
186186
offchain_monitor_updates: Mutex::new(HashMap::new()),
187187
}
188188
}

0 commit comments

Comments
 (0)