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 dword, as long as they fit into that completely into that dword. However, the order of allocation within a word is different in different implementations. This is known as the implementation's endianness. Big endian machines store the most significant bit at the lowest address versus little endian implementations, which store the most significant bit at the highest address. Depending of the order bits within a word can lead to different calculations on different implementations.
Consider the following structure made up of four 8-bit bit field members.
struct bf { unsigned m1 : 8; unsigned m2 : 8; unsigned m3 : 8; unsigned m4 : 8; };; /* 32 bits total */ /* ... */
Little endian implementations will allocate struct bf
as:
m4 m3 m2 m1
Conversely, big endian endian implementations will allocate struct bf
as:
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.
Rule |
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
[[ISO/IEC 9899-1999]] Section 6.7.2, "Type specifiers"
[[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]] Rule 6-5