Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Mutexes are often used to prevent multiple threads from accessing critical causing a data race by accessing shared resources at the same time. Sometimes, when locking mutexes, multiple threads hold each other's lock, and the program consequently deadlocks. There Four conditions are four requirements required for deadlock to occur:

  • mutual Mutual exclusion
  • hold Hold and wait
  • no No preemption
  • circular Circular wait

Deadlock requires needs all four conditions, so , to prevent deadlock, prevent preventing deadlock requires preventing any one of the four conditions. This guideline recommends locking One simple solution is to lock the mutexes in a predefined order to prevent , which prevents circular wait.

Noncompliant Code Example

The following code has behavior that behavior of this noncompliant code example depends on the runtime environment and the platform's scheduler. However, with proper timing, the main() function will deadlock when running thr1 and thr2, where thr1 tries The program is susceptible to deadlock if thread thr1 attempts to lock ba2's mutex , while thr2 tries at the same time thread thr2 attempts to lock on ba1's mutex in the deposit() function, and the program will not progress.

Code Block
bgColor#ffcccc
langc
#include <stdlib.h>
#include <threads.h>
 
typedef struct {
  int balance;
  pthread_mutexmtx_t balance_mutex;
} bank_account;

typedef struct {
  bank_account *from;
  bank_account *to;
  int amount;
} deposit_thr_argstransaction;

void create_bank_account(bank_account **ba,
                         int initial_amount) {
  int result;
  bank_account *nba = (bank_account *)malloc(
    sizeof(bank_account)
  );
  if (nba == NULL) {
    /* Handle Errorerror */
  }

  nba->balance = initial_amount;
  if (thrd_success
    result  != pthreadmtx_mutex_init(&nba->balance_mutex, NULL);
  if (resultmtx_plain)) {
    /* Handle Errorerror */
  }

  *ba = nba;
}


voidint *deposit(void *ptr) {
  int result;
  deposit_thr_argstransaction *args = (deposit_thr_argstransaction *)ptr;

  if ((resultthrd_success != pthread_mutexmtx_lock(&(args->from->balance_mutex))) != 0) {
    /* Handle Errorerror */
  }

  /* notNot enough balance to transfer */
  if (args->from->balance < args->amount) {
    if ((result = pthread_mutexthrd_success
        != mtx_unlock(&(args->from->balance_mutex))) != 0) {
      /* Handle Error error */
    }
    return NULL;-1; /* Indicate error */
  }

  if ((resultthrd_success != pthread_mutexmtx_lock(&(args->to->balance_mutex))) != 0) {
    /* Handle Errorerror */
  }

  args->from->balance -= args->amount;
  args->to->balance += args->amount;

  if ((result = pthread_mutexthrd_success
      != mtx_unlock(&(args->from->balance_mutex))) != 0) {
    /* Handle Errorerror */
  }

  if ((result = pthread_mutexthrd_success
      != mtx_unlock(&(args->to->balance_mutex))) != 0) {
    /* Handle Errorerror */
  }


  free(ptr);
  return NULL0;
}


int main(void) {

  pthreadthrd_t thr1, thr2;
  inttransaction result*arg1;
  transaction *arg2;
  bank_account *ba1;
  bank_account *ba2;

  create_bank_account(&ba1, 1000);
  create_bank_account(&ba2, 1000);

  deposit_thr_args *arg1 = (transaction *)malloc(sizeof(deposit_thr_argstransaction));
  if (arg1 == NULL) {
    /* Handle Errorerror */
  }
  deposit_thr_args *arg2 = (transaction *)malloc(sizeof(deposit_thr_argstransaction));
  if (arg2 == NULL) {
    /* Handle Errorerror */
  }

  arg1->from = ba1;
  arg1->to = ba2;
  arg1->amount = 100;

  arg2->from = ba2;
  arg2->to = ba1;
  arg2->amount = 100;

  /* performPerform the deposits */
  if ((result thrd_success
     != pthreadthrd_create(&thr1, NULL, deposit, (void *)arg1)) != 0) {
    /* Handle Errorerror */
  }
  if ((result thrd_success
      != pthreadthrd_create(&thr2, NULL, deposit, (void *)arg2)) != 0) {
    /* Handle Errorerror */
  }

  pthread_exit(NULL);
  return 0;
}
 

Compliant Solution

The This compliant solution to the deadlock problem is to use eliminates the circular wait condition by establishing a predefined order for the locks locking in the deposit() function. In the following compliant solution, each Each thread will lock based on the id of lock on the basis of the bank_account, defined in the struct initialization. This prevents the circular wait problem ID, which is set when the bank_account struct is initialized.

Code Block
bgColor#ccccff
langc
#include <stdlib.h>
#include <threads.h>
 
typedef struct {
  int balance;
  pthreadmtx_mutex_t balance_mutex;
 
  /* Should not change after initialization */
  unsigned int id;
} bank_account;

typedef /*struct should{
 never be changed after initialized */
} bank_accountbank_account *from;
  bank_account *to;
  int amount;
} transaction;

unsigned int global_id = 1;

void create_bank_account(bank_account **ba,
                         int initial_amount) {
  int result;
  bank_account *nba = (bank_account *)malloc(
    sizeof(bank_account)
  );
  if (nba == NULL) {
    /* Handle Errorerror */
  }

  nba->balance = initial_amount;
  if (thrd_success
     result != pthread_mutexmtx_init(&nba->balance_mutex, NULL);
  if (result != 0mtx_plain)) {
    /* Handle Errorerror */
  }

  nba->id = global_id++;
  *ba = nba;
}


voidint *deposit(void *ptr) {
  deposit_thr_argstransaction *args = (deposit_thr_argstransaction *)ptr;
  int result = -1;
  mtx_t *first;
  mtx_t *second;

  if (args->from->id == args->to->id)
		return; {
    return -1; /* Indicate error */
  }

  /* ensureEnsure proper ordering for locking */
  if (args->from->id < args->to->id) {
    if ((resultfirst = pthread_mutex_lock(&(args->from->balance_mutex))) != 0) {;
    second  /* Handle Error */= &args->to->balance_mutex;
  } else }{
    if ((resultfirst = pthread_mutex_lock(&(args->to->balance_mutex))) != 0) {;
    second  /* Handle Error */
    }= &args->from->balance_mutex;
  } else {
    if ((resultthrd_success != pthread_mutexmtx_lock(&(args->to->balance_mutex))) != 0first)) {
      /* Handle Errorerror */
    }
    if ((resultthrd_success != pthread_mutexmtx_lock(&(args->from->balance_mutex))) != 0second)) {
      /* Handle Errorerror */
    }
  }

  /* notNot enough balance to transfer */
  if (args->from->balance <>= args->amount) {
    if ((result = pthread_mutex_unlock(&(args->from->balance_mutex))) != 0) {
      /* Handle Error */
    }
    if ((result = pthread_mutex_unlock(&(-= args->amount;
    args->to->balance_mutex))) != 0) {
      /* Handle Error */
    }
    return+= args->amount;
  }

  args->from->balanceresult -= args->amount0;
  args->to->balance += args->amount;}

  if ((resultthrd_success != pthread_mutexmtx_unlock(&(args->from->balance_mutex))) != 0second)) {
    /* Handle Errorerror */
  }
  if ((resultthrd_success != pthreadmtx_mutex_unlock(&(args->to->balance_mutex))) != 0first)) {
    /* Handle Errorerror */
  }


  free(ptr);
  return result;
}
 

Risk Assessment

Deadlock prevents multiple threads from progressing, thus halting the executing program execution. This is a potential  A denial-of-service attack because is possible if the attacker can force deadlock situations. Deadlock is likely to occur in multithreaded programs that manage multiple shared resources.create the conditions for deadlock.

Rule

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

CON35-C

low

Low

probable

Probable

medium

Medium

P4

L3

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Automated Detection

ToolVersionCheckerDescription
Astrée
Include Page
Astrée_V
Astrée_V
deadlockSupported by sound analysis (deadlock alarm)
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V
CONCURRENCY.LOCK.ORDERConflicting lock order
Coverity
Include Page
Coverity_V
Coverity_V
ORDER_REVERSALFully implemented
Cppcheck Premium

Include Page
Cppcheck Premium_V
Cppcheck Premium_V

premium-cert-con35-cPartially implemented
Helix QAC

Include Page
Helix QAC_V
Helix QAC_V

C1772, C1773
Klocwork
Include Page
Klocwork_V
Klocwork_V

CONC.DL
CONC.NO_UNLOCK


Parasoft C/C++test
Include Page
Parasoft_V
Parasoft_V
CERT_C-CON35-a

Do not acquire locks in different order

PC-lint Plus

Include Page
PC-lint Plus_V
PC-lint Plus_V

2462

Fully supported

Polyspace Bug Finder

Include Page
Polyspace Bug Finder_V
Polyspace Bug Finder_V

CERT C: Rule CON35-C

Checks for deadlock (rule partially covered)

Related Guidelines

...

Key here (explains table format and definitions)

Taxonomy

Taxonomy item

Relationship

CERT Oracle Secure Coding Standard for Java

...

MITRE CWE: CWE-764] Multiple Locks of Critical Resources

Bibliography

Prior to 2018-01-12: CERT: Unspecified Relationship

  [Barney 2010] pthread_mutex tutorial
[Bryant 2003] Chapter 13, Concurrent Programming

...

Image Modified Image Modified Image Modified