Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix deadlock in BLECharacteristic::handle_gap_event #152

Merged
merged 3 commits into from
Jan 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -323,7 +323,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<'a, T> Drop for MutexGuard<'a, T> {
Expand Down
Loading