CONC.DBL_UNLOCK

Multiple unlocks of critical resource

The CONC.DBL_UNLOCK checker flags cases where code tries to unlock a resource more times than it is locked.

Vulnerability and risk

If code attempts to unlock a resource more times than it is locked, it can result in unexpected behavior.

Mitigation and prevention

If already unlocked, do not unlock a resource again.

Vulnerable code example

Copy
  #include<pthread.h>
  void lock_unlock_wrapper(pthread_mutex_t *mutex)
  {
      pthread_mutex_lock(mutex);
      pthread_mutex_unlock(mutex);
      pthread_mutex_unlock(mutex);
      return;
  }

In this noncompliant example, Klocwork reports a CONC.DBL_UNLOCK defect on line 6, as the code tries to unlock the same mutex (that is, *mutex) twice along the same thread.

Fixed code example

Copy
  #include<pthread.h>
  void lock_unlock_wrapper(pthread_mutex_t *mutex)
  {
      pthread_mutex_lock(mutex);
      pthread_mutex_unlock(mutex);
      return;
  }

In the fixed example, the code locks and then unlocks the mutex once along a given thread.

Security training

Application security training materials provided by Secure Code Warrior.