Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by NavBot (jp)

...

1) The right shift in java is an arithmetic shift while in C\C++ is implementation defined (logical or arithmetic)
2) In C\C++ if the value being left shifted is negative or the right hand operator of the shift operation is negative or greater than or equal to the width of the promoted left operand we have umdefined behaviour. This does not apply in Java since for the case of integer type it is masked with 0x1F and as a result we can always have a value that is modulo 31. When the value to be shifted (left-operand) is a long, only the last 6 bits of the right-hand operand are used to perform the shift. The actual size of the shift is the value of the right-hand operand masked by 63 (0x3D) Java Language Specification(§15§15.19 )ie the shift distance is always between 0 and 63 (if the shift value is greater than 64 then the shift is value%64)

...

31 -> 0x1f 00000000 00000000 00000000 00011111

& -----------------------------------

Shift value 00000000 00000000 00000000 00000011 -> 3

So according to JLS

"At run time, shift operations are performed on the two's complement integer representation of the value of the left operand._ The value of n<<s is nleft-shifted s bit positions; this is equivalent (even if overflow occurs) to multiplication by two to the power s_._The value of n>>s is n right-shifted s bit positions with sign-extension. The resulting value is

_?n/2s?. For nonnegative values of n, this is equivalent to truncating integer division, as computed by the integer division operator /, by two to the power s."_

3) There is a new operator in Java >>> that performs unsigned right shift

Example:

Code Block
bgColor#FFcccc

int val = 2 <<-29;
int val = 2 << 35;

These both print 16 because they are transformed to 2<<3

Although we can not have undefined behaviour in Java we still have to ensure that we get the correct results. So we should
explicitly check for ranges

Code Block
bgColor#ccccff

public int do_shift(int shift_value){ 
   if(shift_value > 31 or shift_value <0)
      throw ArithmeticException;
   else
      int val = 2 << shift_value;
}

Unsigned Right Shifting >>>

It is identical to the right-shift operator if the shifted value is positive. If it is negative the sign value can change because the left-operand high-order bit is not retained and the sign value can change; Excerpt from JLS:
"if n is negative, the result is equal to that of the expression (n>>s)(2<<~s) if the type of the left-hand operand is int, and to the result of the expression (n>>s)(2L<<~s) if the type of the left-hand operand is long. The added term (2<<~s) or (2L<<~s) cancels out the propagated sign bit. (Note that, because of the implicit masking of the right-hand operand of a shift operator, ~s as a shift distance is equivalent to 31-s when shifting an int value and to 63-s when shifting a longvalue.)"

For example: -32 >>> 2 = (-32 >> 2 ) + ( 2 << ~2 ) = 1073741816

Operations Requiring Really Long Numbers

For these operations the BigInteger class should be used. According to SUN BigInteger Class:

"Semantics of arithmetic operations exactly mimic those of Java's integer arithmetic operators, as defined in The Java Language Specification. For example, division by zero throws an ArithmeticException, and division of a negative by a positive yields a negative (or zero) remainder. All of the details in the Spec concerning overflow are ignored, as BigIntegers are made as large as necessary to accommodate the results of an operation."

So operations using BigInteger class are guaranteed not to overflow regardless of the size of the result.

For instance operations on long are operations on 64 bits. For example addition:

Compliant Code Example

Code Block
bgColor#ccccff

java.math.BigInteger big_long_max = new java.math.BigInteger(String.valueOf(Long.MAX_VALUE));
System.out.println("big_long="+big_long_max);
big_long_max = big_long_max.add(java.math.BigInteger.valueOf(1));//same as ++big_long_max
System.out.println("big_long="+big_long_max);
These print
big_long=9223372036854775807
big_long=9223372036854775808//exceeds the maximum range of long, no problem

java.math.BigInteger big_long_min = new java.math.BigInteger(String.valueOf(Long.MIN_VALUE));
System.out.println("big_long_min="+big_long_min);
big_long_min = big_long_min.subtract(java.math.BigInteger.valueOf(1));//same as --big_long_min
System.out.println("big_long_min="+big_long_min);//goes bellow minimum range of long, no problem

These print:
big_long_min=-9223372036854775808
big_long_min=-9223372036854775809
if(big_long < Long.MAX_VALUE && big_long > Long.MIN_VALUE)//value within range can go to the primitive type
long value = big_log.longValue();//get primitive type
else
//Perform error handling. We can not downcast since the value can not be represented as a long

We can always go back to the primitive types if the BigInteger of course can be represented by the type
In the example if big_long is within long range (big_long < Long.MAX_VALUE && big_long > Long.MIN_VALUE) we can use the BigInteger method longValue() to get the long value and assign it to a variable of type long

Risk Assesment

Integer overflows are among the most dangerous defects in software since it leads to exploitation, undefined and erroneous behavior

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

INT34-J

high

likely

high

P6

L2

Other Languages

This rule appears as in the C++ Secure Coding standard as: INT32-CPP. Ensure that operations on signed integers do not result in overflow

This rule also appears in the C Secure Coding Standard as: INT32-C. Ensure that operations on signed integers do not result in overflow

References

...

INT33-J. Be careful while casting numeric types to wider floating-point types      04. Integers (INT)      05. Floating Point (FLPSecure Coding Guidelines for the Java Programming Language: Secure (Paragraph on comparison C++/Java)
The Java Language Specification, Third Edition: JLS (Operations and data types)