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

Copy
  #include <pthread.h>
  
  extern int z();
  
  void foo(pthread_mutex_t *mutex) {
    pthread_mutex_lock(mutex);
    switch (z()) {
      case 0:
        return;
     case 1:
       break;
   }
   pthread_mutex_unlock(mutex);
 }

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

Copy
  #include <pthread.h>
 
  extern int z();
  
  void foo(pthread_mutex_t *mutex) {
    pthread_mutex_lock(mutex);
    switch (z()) {
      case 0:
        pthread_mutex_unlock(mutex);
        return;
     case 1:
       break;
   }
   pthread_mutex_unlock(mutex);
 }

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.