CONC.NO_UNLOCK

Missing unlock

The CONC.NO_UNLOCK checker reports potential deadlocks due to locked threads that don't have corresponding unlocks.

Vulnerability and risk

A missing release for a lock can result in a deadlock. If a lock is held and not released, no further calls to acquire the lock can proceed until the lock is released.

Mitigation and prevention

To help avoid lock contention:

  • Try to keep locked sections of code as small and as simple to understand as possible.
  • Don't lock sections of code that can cause concurrency problems, such as data races.
  • Avoid circular wait conditions at all costs.
  • If several locks are used, typically in an escalating guard pattern, make absolutely sure that the escalation is performed exactly the same in every circumstance.

Vulnerable code example

1  #include <pthread.h>
2  
3  extern int z();
4  
5  void foo(pthread_mutex_t *mutex) {
6    pthread_mutex_lock(mutex);
7    switch (z()) {
8      case 0:
9        return;
10     case 1:
11       break;
12   }
13   pthread_mutex_unlock(mutex);
14 }

Klocwork reports that the mutex is locked at line 6 and not unlocked at line 9 if case 0 is in effect.

Fixed code example

1  #include <pthread.h>
2  
3  extern int z();
4  
5  void foo(pthread_mutex_t *mutex) {
6    pthread_mutex_lock(mutex);
7    switch (z()) {
8      case 0:
9        pthread_mutex_unlock(mutex);
10        return;
11     case 1:
12       break;
13   }
14   pthread_mutex_unlock(mutex);
15 }

In the fixed version, the unlock is included at line 9.

Related checkers

Security training

Application security training materials provided by Secure Code Warrior.

Extension

This checker can be extended. The related knowledge base record kinds are:

See Tuning C/C++ analysis for more information.