I am currently attempting to use parasoft software to fix static analysis violations for my code using MISRA C coding standards. My code initially had this function:
static inline uint32_t rotate_right(uint32_t val, uint32_t n)
{
return (val >> n) | (val << (32 - n));
}
This causes a static analysis violation under the rule MISRA2004-12_8-3. The rule says
The right-hand operand of a shift operator shall lie between zero and one less than the width in bits of the underlying type of the left-hand operand
The rule documentation states that this particular rule reports a violation if
- the right-hand operand is a constant with negative value or with value that exceeds the length (in bits) of the left-hand operand
- the right-hand operand is not a constant and is not checked by specific pattern
As I am not using a constant for the right-hand operand, MISRA-C rules dictate that I surround this statement with limit checks. MISRA-C also states that
Use of an unsigned integer type will ensure that the operand is non-negative, so then only the upper limit needs to be checked (dynamically at run-time or by review). Otherwise both limits will need to be checked."
Since I am using an unsigned type, uint32_t
, I only need to check the upper limits of the right-hand operand. However, for val << (32u - n)
, I cannot have the value of n
as 0u
. Therefore, I tried to resolve this violation by adding the following checks:
static inline uint32_t rotate_right(uint32_t val, uint32_t n)
{
if (n == 0u)
{
return val;
}
else if ((n > 0u) && (n <= 31u))
{
return (val >> n) | (val << (32u - n));
}
else
{
return 0u;
}
}
Doing so resolves the static analysis violation for (val >> n)
, but the same violation is still reported for (val << (32u - n))
.
Hence, my questions are:
The
if
statement clearly restricts the value ofn
to be less than32u
. Consequently,(32u - n)
will also have a value less than or equal to32u
. Why is parasoft software still reporting an error for the right-hand operand being(32u - n)
despite the limit check?What is the correct way to resolve this violation?