...
A better approach is to embed a concurrently-accessed variable inside a union, along with a long
variable, or at least some padding to ensure that the concurrent variable is the only element to be accessed at that address. This would effectively guarantee that no other variables are accessed or modified when the concurrent variable is accessed or modified.
Noncompliant Code Example (Bit Field)
In this noncompliant code example, two executing threads simultaneously access two separate members of a global struct
.
...
Even though each thread is modifying a separate bit-field, they are both modifying the same location in memory. This is the same problem discussed in POS00-C. Avoid race conditions with multiple threads but is harder to diagnose, because it is not obvious at first glance that the same memory location is being modified.
Compliant Solution (Bit Field)
This compliant solution protects all accesses of the flags with a mutex, thereby preventing any thread scheduling interleaving from occurring. In addition, the flags are declared volatile
to ensure that the compiler will not attempt to move operations on them outside the mutex. Finally, the flags are embedded in a union alongside a long
, and a static assertion guarantees that the flags do not occupy more space than the long
. This prevents any data not checked by the mutex from being accessed or modified with the bit fields.
...
Static assertions are discussed in detail in DCL03-C. Use a static assertion to test the value of a constant expression.
Risk Assessment
Although the race window is narrow, having an assignment or an expression evaluate improperly because of misinterpreted data can result in a corrupted running state or unintended information disclosure.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
POS32-C | medium | probable | medium | P8 | L2 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.7.2.1, "Structure and union specifiers" |
...