Skip to content

Commit

Permalink
Coverity: Fix 1584343
Browse files Browse the repository at this point in the history
Reorganize code in the coap_lock_lock_func().
  • Loading branch information
mrdeep1 committed Mar 14, 2024
1 parent 79840df commit 0cbcaa6
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 17 deletions.
2 changes: 1 addition & 1 deletion include/coap3/coap_mutex_internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ typedef struct coap_lock_t {
unsigned int callback_line;
unsigned int being_freed;
unsigned int in_callback;
volatile unsigned int lock_count;
unsigned int lock_count;
} coap_lock_t;

void coap_lock_unlock_func(coap_lock_t *lock, const char *file, int line);
Expand Down
41 changes: 25 additions & 16 deletions src/coap_threadsafe.c
Original file line number Diff line number Diff line change
Expand Up @@ -776,27 +776,32 @@ coap_lock_unlock_func(coap_lock_t *lock, const char *file, int line) {

int
coap_lock_lock_func(coap_lock_t *lock, const char *file, int line) {
if (lock->in_callback && coap_thread_pid == lock->pid) {
lock->lock_count++;
assert(lock->in_callback == lock->lock_count);
} else {
if (coap_mutex_trylock(&lock->mutex)) {
if (coap_thread_pid == lock->pid) {
if (coap_mutex_trylock(&lock->mutex)) {
if (coap_thread_pid == lock->pid) {
/* This thread locked the mutex */
if (lock->in_callback) {
/* This is called from within an app callback */
lock->lock_count++;
assert(lock->in_callback == lock->lock_count);
return 1;
} else {
coap_log_alert("Thread Deadlock: Last %s: %u, this %s: %u\n",
lock->lock_file, lock->lock_line, file, line);
assert(0);
}
coap_mutex_lock(&lock->mutex);
}
/* Just got the lock, so should not be in a locked callback */
assert(!lock->in_callback);
lock->pid = coap_thread_pid;
lock->lock_file = file;
lock->lock_line = line;
if (lock->being_freed) {
coap_lock_unlock_func(lock, file, line);
return 0;
}
/* Wait for the other thread to unlock */
coap_mutex_lock(&lock->mutex);
}
/* Just got the lock, so should not be in a locked callback */
assert(!lock->in_callback);
lock->pid = coap_thread_pid;
lock->lock_file = file;
lock->lock_line = line;
if (lock->being_freed) {
/* context is in the process of being deleted */
coap_lock_unlock_func(lock, file, line);
return 0;
}
return 1;
}
Expand All @@ -817,6 +822,10 @@ coap_lock_unlock_func(coap_lock_t *lock) {

int
coap_lock_lock_func(coap_lock_t *lock) {
/*
* Some OS do not have support for coap_mutex_trylock() so
* cannot use that here and have to rely on lock-pid being stable
*/
if (lock->in_callback && coap_thread_pid == lock->pid) {
lock->lock_count++;
assert(lock->in_callback == lock->lock_count);
Expand Down

0 comments on commit 0cbcaa6

Please sign in to comment.