A mutex that the function unlocks elsewhere is still locked on a path to a return
What it finds
``go s.mu.Lock() if s.closed { return errClosed // s.mu stays locked } s.mu.Unlock() `` The function unlocks the mutex on its main path, but returns on another path while it still holds it. The next goroutine that locks the mutex then waits forever. Deferring the unlock right after the lock covers every path.
The rule follows each function through the shared IR from a call of Lock or RLock to every return. The mutex is a variable or a field of a variable, as in mu.Lock() or s.mu.Lock(). A path ends at a call of the matching Unlock or RUnlock on the same mutex, a defer of one, a call of a method of the variable the mutex is a field of, which may unlock it, or a call that passes the mutex, or that variable, to a function. Only functions that unlock the mutex somewhere are checked, since a function that only locks usually hands the lock to its caller on purpose. Left alone are functions that defer the unlock somewhere, and functions that unlock the mutex before they first lock it, which borrow a lock their caller holds and take it back, locks taken inside an if, whose unlock is usually guarded by the same condition, and functions that hand the mutex to a function literal they return. Functions with constructs the lowering does not understand are skipped.
From the rule's source, lock_held_on_return.rs.
package p import ( "errors" "sync") type store struct { mu sync.Mutex closed bool items []int} func (s *store) add(v int) error { s.mu.Lock() if s.closed { return errors.New("closed")tx0 reports: s.mu is still locked when the function returns here } s.items = append(s.items, v) s.mu.Unlock() return nil} func (s *store) len() int { s.mu.Lock() defer s.mu.Unlock() return len(s.items)} func (s *store) lock() { s.mu.Lock()} 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/go:lock-held-on-return" = "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/go:lock-held-on-return] reason="..."tx0 explain tx0/go:lock-held-on-return shows the same in the terminal. Found a false positive? Report it.