Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: elmiinated exception, added implementation details, fixed some other references to modulo behavior

...

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. According to C99, if E1 has an unsigned type, the value of the result is E1 * 2E2, reduced modulo one more than the maximum value representable in the result type. Although C99 specifies modulo behavior for unsigned integers, unsigned integer overflow frequently results in unexpected values and resultant security vulnerabilities (see INT32-C. Ensure that operations on signed integers do not result in overflow). Consequently, unsigned overflow is generally noncompliant, and E1 * 2E2 must be representable in the result type. Modulo behavior is allowed under exception INT34-EX1.

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
bgColorccccff
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;
}

Exceptions

INT34-EX1: Unsigned integers can exhibit modulo behavior as long as the variable declaration is clearly commented as supporting modulo behavior and each operation on that integer is also clearly commented as supporting modulo behavior.

Implementation Details

GCC has no options to handle shifts by negative amounts or by amounts outside the width of the type predictably or trap on them; they are always treated as undefined. Processors may reduce the shift amount modulo some quantity larger than the width of the type. For example, 32 bit shifts are implemented using the following instructions on IA-32:

Code Block

sa[rl]l   %cl, %eax

Wiki Markup
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

where %eax stores the least significant bits in the double word to be shifted and %edx stores the most significant bitsIf the integer exhibiting modulo behavior contributes to the value of an integer not marked as exhibiting modulo behavior, the resulting integer must obey this rule.

Risk Assessment

Improper range checking can lead to buffer overflows and the execution of arbitrary code by an attacker.

...