Versions Compared

Key

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

...

This issue is also addressed in Java by the deprecation of Thread.stop() and CON13-J. Ensure that threads are stopped cleanly .

Noncompliant Code Example

In this noncompliant code example the thread is doing something as simple as swapping a and b repeatedly. However, this thread is not asynchronously cancel-safe. Because an asynchronous cancel can happen at ANY time, it could cancel right before the last line (a = c) and there one would lose the old value of b.

Code Block
bgColor#ffcccc
volatile int a, b;

void main(void) {
  pthread_create(&thread_identifier,NULL,(void*)thread, NULL);
  /* do stuff */
  if (done)
  {
    pthread_cancel(thread_identifier);
  }
}
void thread(void) {
  int i, c;
  pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,&i);
  while (1)
  {
    c = b;
    b = a;
    a = c;
  }
}

Compliant Solution

From IEEE standards page:

...

Code Block
bgColor#ccccff
volatile int a, b;

void main(void) {
  pthread_create(&thread_identifier,NULL,(void*)thread, NULL);
  /* do stuff */
  if (done)
  {
    pthread_cancel(thread_identifier);
    /* pthread_join waits for the thread to finish up before continuing */
    pthread_join(thread_identifier, 0);
  }
}
void thread(void) {
  int i, c;
  pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,&i);
  while (1)
  {
    c = b;
    b = a;
    a = c;
    /* now we're safe to cancel, creating cancel point */
    pthread_testcancel();
  }
}

Risk Assessment

Incorrectly using threads that asynchronously cancel may result in silent corruption and, in the worst case, unpredictable interactions.

Automated Detection

TODO

Related Vulnerabilities

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

Other Languages

CON13-J. Ensure that threads are stopped cleanly

References

Wiki Markup
\[[MKS|AA. References#MKS]\] [{{pthread_cancel()}} Man Page|http://www.mkssoftware.com/docs/man3/pthread_cancel.3.asp]
\[[Open Group 04|AA. References#Open Group 04]\] [Threads Overview|http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_09.html]