As described in depth in rule DCL34 DCL22-C. Use volatile for data that cannot be cached, a volatile
-qualified variable "shall be evaluated strictly according to the rules of the abstract machine" [ISO/IEC 9899:2011]. In other words, the volatile
qualifier is used to instruct the compiler to not make caching optimizations about a variable.
...
Should x
represent a hardware register or some other memory-mapped device that has side effects when accessed, the previous miscompiled code example may produce unexpected behavior.
Compliant Solution
Eide and Regehr tested a workaround by wrapping volatile
accesses with function calls. They describe it with the intuition that "we can replace an action that compilers empirically get wrong by a different action—a function call—that compilers can get right" [Eide and Regehr]. For example, the workaround for the noncompliant code example would be
...
The workarounds proposed by Eide and Regehr fix many of the volatile
-access bugs in the tested compilers. However, compilers are always changing, so critical sections of code should be compiled as if for deployment, and the compiled object code should be inspected for the correct behavior.
...
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
DCL17-C | mediumMedium | probableProbable | highHigh | P4 | L3 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
LDRA tool suite |
| 134 S | Partially implemented |
Bibliography
[Eide and Regehr] | "Volatiles Are Miscompiled, and What to Do about It" |
[ISO/IEC 9899:2011] | Section Subclause 6.7.3, "Type Qualifiers" |
...