Bit fields in a structure

The PORTING checkers identify code that might rely on specific implementation details in different compilers. The PORTING.BITFIELDS checker detects the use of bit fields within a structure.

Vulnerability and risk

When you define a data structure using bit fields, you're relying on the underlying endian representation of a particular compiler on a particular chip in laying out that structure in memory. Moving an application to a different compiler-for instance, for data transmission or persistent storage-can easily modify this layout, resulting in problems when that data structure is projected onto a byte buffer.

Mitigation and prevention

To avoid these porting problems, define specific variants of structures that are explicitly laid out for a particular endian architecture, and guard each variant with the appropriate BIG_ENDIAN or LITTLE_ENDIAN macro.

Vulnerable code example

1   struct
2   {
3       unsigned short f1 : 4;
4       unsigned short f2 : 5;
5       unsigned short f3 : 7;
6   } myPackedLayout;

The problem in this example is that when there's a shift between endian architectures, the runtime layout of the structure can change so that 'f3' occurs either before or after 'f1' depending on the chip and tool chain.

Fixed code example

1   #if BIG_ENDIAN

2   struct
3   {
4      unsigned short f1 : 4;
5      unsigned short f2 : 5;
6      unsigned short f3 : 7;
7   } myPackedLayout;

8   #endif

In this fixed example, we know the layout will always work the same way on chips that share a common architecture, and we can define an alternative packed layout for chips that don't share that architecture. In this case, the layout is defined by the programmer, rather than being dependent on the chip set of the tool chain.

Related checkers