...
This noncompliant code example can result in undefined behavior because there is no check to ensure that left and right operands have nonnegative values and that the right operand is less than or equal to the width of the promoted left operand.:
Code Block | ||||
---|---|---|---|---|
| ||||
int si1; int si2; int sresult; /* Initialize si1 and si2 */ sresult = si1 << si2; |
...
This noncompliant code example can result in undefined behavior because there is no check to ensure that the right operand is less than or equal to the width of the promoted left operand.:
Code Block | ||||
---|---|---|---|---|
| ||||
unsigned int ui1; unsigned int ui2; unsigned int uresult; /* Initialize ui1 and ui2 */ uresult = ui1 << ui2; |
...
This compliant solution eliminates the possibility of undefined behavior resulting from a left-shift operation on unsigned integers.:
Code Block | ||||
---|---|---|---|---|
| ||||
unsigned int ui1; unsigned int ui2; unsigned int uresult; /* Initialize ui1 and ui2 */ if (ui2 >= sizeof(unsigned int)*CHAR_BIT) { /* Handle error condition */ } else { uresult = ui1 << ui2; } |
...
This noncompliant code example fails to test whether the right operand is greater than or equal to the width of the promoted left operand, allowing undefined behavior.:
Code Block | ||||
---|---|---|---|---|
| ||||
unsigned int ui1; unsigned int ui2; unsigned int uresult; /* Initialize ui1 and ui2 */ uresult = ui1 >> ui2; |
...
This compliant solution tests the suspect shift operations to guarantee there is no possibility of undefined behavior.:
Code Block | ||||
---|---|---|---|---|
| ||||
unsigned int ui1; unsigned int ui2; unsigned int uresult; /* Initialize ui1 and ui2 */ if (ui2 >= sizeof(unsigned int) * CHAR_BIT) { /* Handle error condition */ } else { uresult = ui1 >> ui2; } |
...
The sa[rl]l
instructions take a bit mask of the least significant 5 bits from %cl
to produce a value in the range [0, 31] and then shift %eax
that many bits.:
Code Block |
---|
64 bit shifts become sh[rl]dl %eax, %edx sa[rl]l %cl, %eax |
...
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Compass/ROSE |
|
| Can detect violations of this rule. Unsigned operands are detected when checking for INT13-C. Use bitwise operators only on unsigned operands. | ||||||
ECLAIR |
| shiftrhs | Partially implemented. | ||||||
Fortify SCA | 5.0 |
| Can detect violations of this rule with CERT C Rule Pack. | ||||||
| 403 S | Partially implemented. | |||||||
PRQA QA-C |
| 0499 | Partially implemented. |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
A test program for this rule is available at www.securecoding.cert.org.
...