Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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
bgColor#FFcccc
langc
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
bgColor#FFcccc
langc
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
bgColor#ccccff
langc
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
bgColor#FFcccc
langc
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
bgColorccccff
langc
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
Include Page
ECLAIR_V
ECLAIR_V
shiftrhsPartially implemented.

Fortify SCA

5.0

 

Can detect violations of this rule with CERT C Rule Pack.

LDRA tool suite

Include Page
LDRA_V
LDRA_V

403 S

Partially implemented.

PRQA QA-C
Include Page
PRQA_V
PRQA_V

0499
0500
0501
2790
2791 (D)
2792 (A)
2793 (S)

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.

 

...