...
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.
Workaround Code Example
Wiki Markup |
---|
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, consider the following code example that could be miscompiled: |
Code Block |
---|
volatile x;
x = x;
|
Wiki Markup |
---|
To work around some of the {{volatile}}-access compiler bugs, wrap both accesses to {{x}} in function calls \[[Eide and Regehr]\]: |
Code Block |
---|
int vol_read_int(volatile int *vp) {
return *vp;
}
volatile int *vol_id_int(volatile int *vp) {
return vp;
}
volatile x;
x = x;
*vol_id_int(&x) = vol_read_int(&x);
|
Wiki Markup |
---|
The workarounds proposed in \[[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. |
Risk Assesment
The volatile
qualifier should be used with caution in mission-critical situations. Always make sure that code that assumes certain behavior when using the volatile
qualifier is inspected at the object code level for compiler bugs.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
DCL17-C | medium | probable | high | P4 | L3 |
References
Wiki Markup |
---|
\[[Eide and Regehr]\] "Volatiles Are Miscompiled, and What to Do about It" \[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.7.3, "Type qualifiers" |