Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The following attributes of bit-fields are also implementation defined:

  • The alignment of bit-fields in the storage unit. For example, the bit-fields may be allocated from the high end or the low end of the storage unit.
  • Whether or not bit-fields can overlap an storage unit boundary. For example, assuming eight bits to a byte, if bit-fields of six and four bits are declared, is each bitfield contained within a byte or are they be split across multiple bytes?

Consequently, it is impossible to write portable code that makes assumptions about the layout of bit-fields structures.

Bit-fields can be used to allow flags or other integer values with small ranges to be packed together to save storage space. When used in structure members, bit fields can improve storage efficiency. Compilers will typically allocate consecutive bit-field structure members to the same int-sized dwordstorage, as long as they fit into that completely into that dwordstorage unit. However, the order of allocation within a dword storage unit is implementation dependent. Some implementations are "right-to-left": the first member occupies the low-order position of the dwordstorage unit. Others are "left-to-right": the first member occupies the high-order position of the dwordstorage unit. Calculations that depend on the order bits within a dword storage unit may produce different on different implementations.

...

Right-to-left implementations will allocate struct bf as one dword storage unit with the format:

Code Block
m4   m3   m2   m1

Conversely, left-to-right implementations will allocate struct bf as one dword storage unit with the format:

Code Block
m1   m2   m3   m4

Risk Assessment

Making invalid assumptions about the type of a bit-field or its layout can result in unexpected program flow.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

INT11-A

1 (low)

1 (unlikely)

2 (medium)

P2

L3

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, "Type specifiers"
\[[MISRA 04|AA. C References#MISRA 04]\] Rule 3.5, Rule 6.4, "Bit fields shall only be defined to be of type unsigned int or signed int"
\[[Plum 85|AA. C References#Plum 85]\] Rule 6-5