semantic type checks

Moderators: misra-c, david ward

Post Reply
danielmarjamaki
Posts: 7
Joined: Sun Apr 09, 2017 1:14 pm
Company: Evidente

semantic type checks

Post by danielmarjamaki » Tue May 22, 2018 2:46 pm

It is written in the misra document that the operands for << and >> must be unsigned. In my humble opinion, you are missing something. Semantic type checks are not particularly safe, I claim they are dangerous.

Sanitizers, static analyzers and compilers are checking that the operands are not negative. By following this MISRA advice, these checks are "disabled".

Simple example code:

Code: Select all

int32_t foo(void)
{
    int32_t x = -1;
    return x >> 3; 
}
This is UB so the static analyzers/compilers/sanitizers will write a warning. For instance 1 tool writes:
Shifting a negative value is technically undefined behaviour

If MISRA is enforced then the operand must be casted to unsigned somewhere, the developer might change it to:

Code: Select all

int32_t foo(void)
{
    int32_t x = -1;
    return (uint32_t)x >> 3; 
}
Now the tools don't complain. The bug is hidden.

To help prevent some such damage, I have thought about a rule that makes such casts illegal, when there is loss of precision or loss of sign in explicit casts. But that is used by intention sometimes, as far as I know, so it might be noisy.

misra-c
Posts: 566
Joined: Thu Jan 05, 2006 1:11 pm

Re: semantic type checks

Post by misra-c » Thu Oct 04, 2018 11:21 am

Note: The MISRA-C 2012 guidelines do not tell you to "add the cast". Without the cast the user would definitely get a MISRA C violation and possibly a compiler warning. In both cases the user might then choose to add a cast to remove the warning.

In adding a cast the user has signified that he has considered what happens when the cast is applied.

Aside: The example has a 10.3 violation between the return type of uint32_t and the expected type of int32_t.
---
Posted by and on behalf of
the MISRA C Working Group

Post Reply

Return to “8.10 The essential type model”