CONC.NO_LOCK

Missing lock

The CONC.NO_LOCK checker flags cases where there is no lock that corresponds to an unlock call.

Vulnerability and risk

If code attempts to unlock a variable or mutex when it is not locked in a given thread, it can result in unexpected behavior.

Mitigation and prevention

Do not unlock a resource unless it is locked by a given thread.

Vulnerable code example

Copy
  #include <pthread.h>
  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>
  #include <unistd.h>
 
  pthread_t tid[2];
 
  void *trythis(void *arg)
 {
     pthread_mutex_t lock;
     if (pthread_mutex_init(&lock, NULL) != 0) {
         printf("\n mutex init has failed\n");
         return NULL;
     }

     pthread_mutex_unlock(&lock);

     return NULL;
 }

 int main(void)
 {
     int i = 0;
     int error;

     error = pthread_create(&(tid[i]),
                            NULL,
                            &trythis, NULL);
     if (error != 0)
         printf("\nThread can't be created :[%s]",
                strerror(error));

     pthread_join(tid[0], NULL);

     return 0;
 }

In this noncompliant example, Klocwork reports a CONC.NO_LOCK defect on line 27 as the code tries to unlock the mutex that is not yet locked.

Fixed code example

Copy
  #include <pthread.h>
  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>
  #include <unistd.h>
 
  pthread_t tid[2];
 
  void *trythis(void *arg)
 {
     pthread_mutex_t lock;
     if (pthread_mutex_init(&lock, NULL) != 0) {
         printf("\n mutex init has failed\n");
         return NULL;
     }

     pthread_mutex_lock(&lock);
     pthread_mutex_unlock(&lock);

     return NULL;
 }

 int main(void)
 {
     int i = 0;
     int error;

     error = pthread_create(&(tid[i]),
                            NULL,
                            &trythis, NULL);
     if (error != 0)
         printf("\nThread can't be created :[%s]",
                strerror(error));

     pthread_join(tid[0], NULL);

     return 0;
 }

In the fixed example, the code unlocks the locked mutex properly along a particular thread.

Extension

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

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