Skip to content

Commit

Permalink
Merge pull request #152 from taks/fix-deadlock
Browse files Browse the repository at this point in the history
Fix deadlock in BLECharacteristic::handle_gap_event
  • Loading branch information
taks authored Jan 2, 2025
2 parents 93e974b + 6a0a32e commit d3ef051
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:
build:
runs-on: ubuntu-latest
strategy:
fail-fast: true
fail-fast: false
matrix:
include:
- target: riscv32imc-esp-espidf
Expand Down
4 changes: 3 additions & 1 deletion src/server/ble_characteristic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,9 @@ impl BLECharacteristic {
let ctxt = unsafe { &*ctxt };

let mutex = unsafe { voidp_to_ref::<Mutex<Self>>(arg) };
let mut characteristic = mutex.lock();
let Some(mut characteristic) = mutex.try_lock() else {
return sys::BLE_ATT_ERR_UNLIKELY as _;
};

if unsafe { sys::ble_uuid_cmp((*ctxt.__bindgen_anon_1.chr).uuid, &characteristic.uuid.u) != 0 }
{
Expand Down
20 changes: 20 additions & 0 deletions src/utilities/mutex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ impl RawMutex {
debug_assert_eq!(r, 0);
}

#[inline(always)]
#[allow(clippy::missing_safety_doc)]
pub unsafe fn try_lock(&self) -> bool {
pthread_mutex_trylock(self.0.get()) == 0
}

#[inline(always)]
#[allow(clippy::missing_safety_doc)]
pub unsafe fn unlock(&self) {
Expand Down Expand Up @@ -54,6 +60,11 @@ impl<T> Mutex<T> {
MutexGuard::new(self)
}

#[inline(always)]
pub fn try_lock(&self) -> Option<MutexGuard<'_, T>> {
MutexGuard::try_new(self)
}

#[inline(always)]
pub(crate) fn into_innter(self) -> T {
self.1.into_inner()
Expand All @@ -79,6 +90,15 @@ impl<'a, T> MutexGuard<'a, T> {

Self(mutex)
}

#[inline(always)]
fn try_new(mutex: &'a Mutex<T>) -> Option<Self> {
if unsafe { mutex.0.try_lock() } {
Some(Self(mutex))
} else {
None
}
}
}

impl<T> Drop for MutexGuard<'_, T> {
Expand Down

0 comments on commit d3ef051

Please sign in to comment.