You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 26 Next »

An object that has volatile-qualified type may be modified in ways unknown to the implementation or have other unknown side effects. Asynchronous signal handling falls into this category. Without this type qualifier, unintended optimizations may occur.

The volatile keyword eliminates this confusion by imposing restrictions on access and caching. According to the C99 Rationale [[ISO/IEC 03]]:

No cacheing through this lvalue: each operation in the abstract semantics must be performed (that is, no cacheing assumptions may be made, since the location is not guaranteed to contain any previous value). In the absence of this qualifier, the contents of the designated location may be assumed to be unchanged except for possible aliasing.

Non-Compliant Coding Example

If the value of i is cached, the while loop may never terminate, even on the program receiving a SIGINT.

#include <signal.h>

sig_atomic_t i;

void handler() {
  i = 0;
}

int main(void) {
  signal(SIGINT, handler);
  i = 1;
  while (i) {
   /* do something */
  }
}

Compliant Solution

By adding the volatile qualifier, i is guaranteed to be accessed from it original address for every iteration of the while loop.

#include <signal.h>

volatile sig_atomic_t i;

void handler() {
  i = 0;
}

int main(void) {
  signal(SIGINT, handler);
  i = 1;
  while (i) {
   /* do something */
  }
}

The sig_atomic_t type is the integer type of an object that can be accessed as an atomic entity, even in the presence of asynchronous interrupts. The type of sig_atomic_t is implementation-defined, although there are constraints. Only assign integer values from 0 through 127 to a variable of type sig_atomic_t to be fully portable.

Risk Assessment

Failing to use the volatile qualifier can result in race conditions in asynchronous portions of the code, causing unexpected values to be stored, leading to possible data integrity violations.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

DCL34-C

2 (medium)

1 (unlikely)

2 (medium)

P4

L3

Related Vulnerabilities

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

References

[[ISO/IEC 9899-1999]] Section 6.7.3, "Type qualifiers"; Section 7.14, "Signal handling <signal.h>"
[[ISO/IEC 03]] Section 6.7.3, "Type qualifiers"
[[Sun 05]] Chapter 6, "Transitioning to ISO C"

  • No labels