Operands of different size in bitwise operation

The CWARN.BITOP.SIZE checker looks for code in which bitwise operations (&=, |=, and ^=) have operands with different sizes. Both operands of a bitwise operation must normally be either 32-bit or 64-bit values, although the checker won't flag a 64-bit mask used on a 32-bit value.

Vulnerability and risk

When an unsigned 32-bit value is converted to a 64-bit type, the 32 higher bits are set to zero, which probably isn't the original design intent and can cause unexpected results.

Vulnerable code example

  typedef unsigned int u32;
  typedef unsigned long long u64;

  u32 get_u32_value(void);
  u64 get_u64_value(void);

  void example(void) {
    u32 mask32 = 0xff;
    u64 mask64 = 0xff;

    u32 value32 = get_u32_value();
    u64 value64 = get_u64_value();


   value64 &= ~mask32;

In this code, Klocwork flags line 10, in which a 32-bit mask is used with 64-bit data.