...
A common tool for preventing race conditions in concurrent programming is the mutex. When properly observed by all threads, a mutex can provide safe and secure access to a common variable, ; however, it guarantees nothing regarding with regards to other variables that might be accessed when a common variable is accessed.
Unfortunately, there is no portable way to determine which adjacent variables may be stored along with a certain variable.
...
Although this appears to be harmless, it is likely that flag1
and flag2
are stored in the same byte. If both assignments occur on a thread scheduling interleaving that ends with both stores occurring after one another, it is possible that only one of the flags will be set as intended, and the other flag will equal its previous value. This is because both bit-fields are represented by the same byte, which is the smallest unit the processor can work on.
For example, the following sequence of events can occur.:
Code Block |
---|
Thread 1: register 0 = flags Thread 1: register 0 &= ~mask(flag1) Thread 2: register 0 = flags Thread 2: register 0 &= ~mask(flag2) Thread 1: register 0 |= 1 << shift(flag1) Thread 1: flags = register 0 Thread 2: register 0 |= 2 << shift(flag2) Thread 2: flags = register 0 |
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 recommendation CON00-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.
...
Static assertions are discussed in detail in recommendation DCL03-C. Use a static assertion to test the value of a constant expression.
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Bibliography
Related Guidelines
\[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] Section 6.7.2.1, "Structure and union specifiers" Wiki Markup
Bibliography
...
CON31-C. Do not unlock or destroy another thread's mutex 14. Concurrency (CON)