CONC.DBL_LOCK

Multiple locks of critical resource

The CONC.DBL_LOCK checker flags cases where code tries to lock a variable or mutex twice along a certain path.

Vulnerability and risk

If code attempts to lock a variable or mutex twice along a certain path, there are chances the thread can hang or else it may result in undefined behavior.

Mitigation and prevention

If already locked, always unlock a resource after performing required operations.

Vulnerable code example

Copy
   #include<pthread.h>
   #include<stdio.h>
  
   void foo(pthread_mutex_t mutex)
   {
       pthread_mutex_lock(&mutex);
       pthread_mutex_lock(&mutex);
       return;
   }
 
  int main()
  {
      pthread_mutex_t mutex;
      if (pthread_mutex_init(&mutex, NULL) != 0) {
          printf("\n mutex init has failed\n");
          return 1;
      }
 
      foo(mutex);
      return 0;
  }

In this noncompliant example, Klocwork reports a CONC.DBL_LOCK defect on line 7, as the code tries to lock the same mutex (that is, *mutex) twice along the same path.

Fixed code example

Copy
  #include<pthread.h>
  #include<stdio.h>
   
  void foo(pthread_mutex_t mutex)
  {
      pthread_mutex_lock(&mutex);
      pthread_mutex_unlock(&mutex);
      return;
  }
 
  int main()
  {
      pthread_mutex_t mutex;
      if (pthread_mutex_init(&mutex, NULL) != 0) {
          printf("\n mutex init has failed\n");
          return 1;
      }
 
      foo(mutex);
      return 0;
  }

In the fixed example, the code locks and then unlocks the mutex properly along a particular thread.

Security training

Application security training materials provided by Secure Code Warrior.