Simvik

Fix: faults above 31 cannot be set or cleared

A 64-bit fault mask is updated with 32-bit shifts, and clearing one fault clears thirty-two. A medium embedded C problem (Static analysis and MISRA in…

medium · Static analysis and MISRA in practice · find-the-bug · static-analysis · misra · shifts · integer-promotion

Analyser findings (suppressed). "Rule 12.2: the right operand of a shift must be less than the width of the left operand", reported on both lines below. The suppression note says "the mask is 64 bits".

The fault ids now go up to 63. Setting a fault above 31 is undefined behaviour, and clearing any fault also clears all of faults 32 to 63, because ~(1u << id) is a 32-bit value that is zero-extended. Fix both functions by changing two lines.

Starter code

void fault_set(fault_mask_t *m, unsigned id) {
  *m |= 1u << id;
}

void fault_clear(fault_mask_t *m, unsigned id) {
  *m &= ~(1u << id);
}

Example tests

Low faults, then a high fault survives clearing a low one

fault_mask_t m = 0;
fault_set(&m, 0);
fault_set(&m, 5);
show(m);
m |= (fault_mask_t)1 << 40;
fault_clear(&m, 0);
show(m);

Expected output:

0x0000000000000021
0x0000010000000020

Learn it first

More Static analysis and MISRA in practice problems