A function returns early while it holds a mutex that it unlocks on its other paths
What it finds
pthread_mutex_lock(&q->lock); if (q->n == 0) return -1; ... pthread_mutex_unlock(&q->lock);: the early return leaves the mutex locked, and the next thread that locks it waits forever. The function unlocks the mutex on its main path, so the return was meant to as well.
The lock must be a statement of its own, so that a return after a failed lock is not counted, and the return must follow it in the same block or a block nested in it. The return is left alone if an unlock of the same mutex comes before it in a block that holds it, or any call before it is given the mutex or what holds it, or has unlock in its name. Functions without any unlock of the mutex, functions named as if they lock, and functions with pthread_cleanup_push or conditional directives are left alone.
From the rule's source, return_with_mutex_locked.rs.
#include <pthread.h> struct queue { pthread_mutex_t lock; int n;}; int take(struct queue *q){ pthread_mutex_lock(&q->lock); if (q->n == 0) return -1;tx0 reports: this return leaves take with &q->lock still locked int n = --q->n; pthread_mutex_unlock(&q->lock); return n;} int take_unlocking(struct queue *q){ pthread_mutex_lock(&q->lock); if (q->n == 0) { pthread_mutex_unlock(&q->lock); return -1; } int n = --q->n; pthread_mutex_unlock(&q->lock); return n;} int take_through_label(struct queue *q){ int n = -1; pthread_mutex_lock(&q->lock); if (q->n == 0) goto out; n = --q->n;out: pthread_mutex_unlock(&q->lock); return n;} int failed_lock(struct queue *q){ if (pthread_mutex_lock(&q->lock) != 0) return -1; int n = q->n; pthread_mutex_unlock(&q->lock); return n;} void finish(struct queue *q); int both_branches(struct queue *q, int *out){ pthread_mutex_lock(&q->lock); if (q->n > 0) { *out = --q->n; pthread_mutex_unlock(&q->lock); } else { pthread_mutex_unlock(&q->lock); if (!out) return -1; *out = 0; } return 0;} int handed_on(struct queue *q){ pthread_mutex_lock(&q->lock); if (q->n == 0) { finish(q); return -1; } pthread_mutex_unlock(&q->lock); return 0;} Turn it on, off or suppress it
The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/c:return-with-mutex-locked" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/c:return-with-mutex-locked] reason="..."tx0 explain tx0/c:return-with-mutex-locked shows the same in the terminal. Found a false positive? Report it.