Make a diagnostic handler MISRA compliant
A write handler with early returns and a sloppy switch: give it one exit and clean types. A medium embedded C problem (MISRA C on a real project), run and…
medium · MISRA C on a real project · misra · coding-standards · uds · automotive · single-exit
check_write decides how an ECU answers a WriteDataByIdentifier request: it returns NRC_NONE when the write may go ahead, or the negative response code. It works, and its tests pass. But this customer's coding guideline makes MISRA C binding, including the single-exit rule, and the build's checker rejects the function.
What it does, which must not change:
- Default session:
NRC_SESSION. - Fewer than 4 bytes:
NRC_LENGTH. - By identifier (bytes 1 and 2): the lock timeout and the chime volume need exactly 4 bytes, the serial number exactly 7; any other identifier is
NRC_RANGE. A wrong length isNRC_LENGTH. - Not unlocked:
NRC_SECURITY. - A lock timeout outside 5 to 120, or a chime volume above 10:
NRC_RANGE.
Press Run to see the findings. Rewrite the function until there are none and the tests still pass. The rules checked: 10.3 and 10.4 (essential types), 14.4 (Boolean conditions), 15.5 (one exit, at the end), 15.6 (braces), 16.3 (no fall-through) and 16.4 (a default in every switch).
Starter code
uint8_t check_write(const uint8_t *req, uint16_t len, uint8_t session, bool unlocked) {
uint16_t did;
int expected = 0;
if (session == SESSION_DEFAULT) return NRC_SESSION;
if (len < 4) return NRC_LENGTH;
did = (req[1] << 8) | req[2];
switch (did) {
case DID_SERIAL:
expected = 3;
case DID_LOCK_TIMEOUT:
case DID_CHIME_VOLUME:
expected += 4;
break;
}
if (!expected) return NRC_RANGE;
if (len != expected) return NRC_LENGTH;
if (!unlocked) return NRC_SECURITY;
if (did == DID_LOCK_TIMEOUT && (req[3] < 5 || req[3] > 120)) return NRC_RANGE;
if (did == DID_CHIME_VOLUME && req[3] > 10) return NRC_RANGE;
return NRC_NONE;
}Example tests
An accepted write, and a locked ECU
const uint8_t req[4] = { 0x2E, 0x01, 0x10, 60 };
ask(req, 4, 3, true);
ask(req, 4, 3, false);Expected output:
0110 len 4 session 3 unlocked: NRC 00
0110 len 4 session 3 locked: NRC 33Session and length come first
const uint8_t req[4] = { 0x2E, 0x01, 0x10, 60 };
ask(req, 4, 1, true);
ask(req, 3, 3, true);
ask(req, 3, 1, false);Expected output:
0110 len 4 session 1 unlocked: NRC 7F
0110 len 3 session 3 unlocked: NRC 13
0110 len 3 session 1 locked: NRC 7FLearn it first
- MISRA C on a real project · Guidelines and their categories, the rules that change how you write, deviations, and compliance claims.
More MISRA C on a real project problems
- Take the side effects out of the conditions · Code that reads a FIFO inside && conditions and ignores return values: make each read explicit.