Programs must not allow mathematical operations to exceed the integer ranges provided by their primitive integer data types. According to The Java Language Specification (JLS), §4.2.2, "Integer Operations" [JLS 2015]:
The built-in integer operators do not indicate overflow or underflow in any way. Integer operators can throw a
NullPointerException
if unboxing conversion of anull
reference is required. Other than that, the only integer operators that can throw an exception are the integer divide operator/
and the integer remainder operator%
, which throw anArithmeticException
if the right-hand operand is zero, and the increment and decrement operators ++ and -- which can throw anOutOfMemoryError
if boxing conversion is required and there is insufficient memory to perform the conversion.
The integral types in Java, representation, and inclusive ranges are shown in the following table taken from the JLS, §4.2.1, "Integral Types and Values" [JLS 2015]:
Type | Representation | Inclusive Range |
---|---|---|
| 8-bit signed two's-complement | −128 to 127 |
| 16-bit signed two's-complement | −32,768 to 32,767 |
| 32-bit signed two's-complement | −2,147,483,648 to 2,147,483,647 |
| 64-bit signed two's-complement | −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
| 16-bit unsigned integers representing UTF-16 code units |
|
The following table shows the integer overflow behavior of the integral operators.
Operator | Overflow | Operator | Overflow | Operator | Overflow | Operator | Overflow | |||
---|---|---|---|---|---|---|---|---|---|---|
| Yes |
| Yes |
| No |
| No | |||
| Yes |
| Yes |
| No |
| No | |||
| Yes |
| Yes |
| No |
| No | |||
| Yes |
| No |
| No |
| No | |||
| No |
| No |
| No |
| No | |||
| Yes |
| No |
| No |
| No | |||
| Yes |
| No |
| No | |||||
| No |
| No | Unary | No | |||||
| Yes |
| No | Unary | Yes |
Because the ranges of Java types are not symmetric (the negation of each minimum value is one more than each maximum value), even operations such as unary negation can overflow if applied to a minimum value. Because the java.lang.math.abs()
method returns the absolute value of any number, it can also overflow if given the minimum int
or long
as an argument.
When a mathematical operation cannot be represented using the supplied integer types, Java's built-in integer operators silently wrap the result without indicating overflow. The silent wrap can result in incorrect computations and unanticipated outcomes. Failure to account for integer overflow has resulted in failures of real systems, for example, when implementing the compareTo()
method. The meaning of the return value of the compareTo()
method is defined only in terms of its sign and whether it is zero; the magnitude of the return value is irrelevant. Consequently, an apparent but incorrect optimization would be to subtract the operands and return the result. For operands of opposite signs, this approach can result in integer overflow, consequently violating the compareTo()
contract [Bloch 2008].
Comparison of Compliant Techniques
Following are the three main techniques for detecting unintended integer overflow:
- Precondition testing. Check the inputs to each arithmetic operator to ensure that overflow cannot occur. Throw an
ArithmeticException
when the operation would overflow if it were performed; otherwise, perform the operation.
- Upcasting. Cast the inputs to the next larger primitive integer type and perform the arithmetic in the larger size. Check each intermediate result for overflow of the original smaller type and throw an
ArithmeticException
if the range check fails. Note that the range check must be performed after each arithmetic operation; larger expressions without per-operation bounds checking can overflow the larger type. Downcast the final result to the original smaller type before assigning to a variable of the original smaller type. This approach cannot be used for typelong
becauselong
is already the largest primitive integer type.
BigInteger
. Convert the inputs into objects of typeBigInteger
and perform all arithmetic usingBigInteger
methods. TypeBigInteger
is the standard arbitrary-precision integer type provided by the Java standard libraries. The arithmetic operations implemented as methods of this type cannot overflow; instead, they produce the numerically correct result. Consequently, compliant code performs only a single range check just before converting the final result to the original smaller type and throws anArithmeticException
if the final result is outside the range of the original smaller type.
The precondition testing technique requires different precondition tests for each arithmetic operation. This approach can be somewhat more difficult to implement and to audit than either of the other two approaches.
The upcast technique is the preferred approach when applicable. The checks it requires are simpler than those of the previous technique; it is substantially more efficient than using BigInteger
. Unfortunately, it cannot be applied to operations involving type long
, as there is no bigger type to upcast to.
The BigInteger
technique is conceptually the simplest of the three techniques because arithmetic operations on BigInteger
cannot overflow. However, it requires the use of method calls for each operation in place of primitive arithmetic operators, which can obscure the intended meaning of the code. Operations on objects of type BigInteger
can also be significantly less efficient than operations on the original primitive integer type.
Precondition Testing
The following code example shows the necessary precondition checks required for each arithmetic operation on arguments of type int
. The checks for the other integral types are analogous. These methods throw an exception when an integer overflow would otherwise occur; any other conforming error handling is also acceptable. Since ArithmeticException
inherits from RuntimeException
, we do not need to declare it in a throws
clause.
Code Block | ||
---|---|---|
| ||
static final int safeAdd(int left, int right) {
if (right > 0 ? left > Integer.MAX_VALUE - right
: left < Integer.MIN_VALUE - right) {
throw new ArithmeticException("Integer overflow");
}
return left + right;
}
static final int safeSubtract(int left, int right) {
if (right > 0 ? left < Integer.MIN_VALUE + right
: left > Integer.MAX_VALUE + right) {
throw new ArithmeticException("Integer overflow");
}
return left - right;
}
static final int safeMultiply(int left, int right) {
if (right > 0 ? left > Integer.MAX_VALUE/right
|| left < Integer.MIN_VALUE/right
: (right < -1 ? left > Integer.MIN_VALUE/right
|| left < Integer.MAX_VALUE/right
: right == -1
|
Java is considered to be a safer language than C or C++. The following excerpt is from the introduction of secure coding guidelines from SUN SUN secure coding :
"The (java) language is type-safe, and the runtime provides automatic memory management and range-checking on arrays. These features also make Java programs immune to the stack-smashing and buffer overflow attacks possible in the C and C++ programming languages, and that have been described as the single most pernicious problem in computer security today"
While this statement is in fact true, the arithmetic operations in the Java platform require the same caution as in C\C++. Integer operations can result in overflow or underflow since Java does not provide any indication of these conditions and silently wraps (Java throws only a division by zero exception).
The following excerpt is from the Java Language Specification (Overflow)
"The built-in integer operators do not indicate overflow or underflow in any way. Integer operators can throw a NullPointerException if unboxing conversion of a null reference is required. Other than that, the only integer operators that can throw an exception are the integer divide operator /_ and the integer remainder operator_ %, which throw an ArithmeticException if the right-hand operand is zero, and the increment and decrement operators ++ and - which can throw an OutOfMemoryError if boxing conversion _is required and there is not sufficient memory available to perform the conversion"
See the following example:
Noncompliant Code Example
In we have the following simple method the result could overflow
Code Block | ||
---|---|---|
| ||
public int do_operation(int a,int b)
{
int temp = a + b;
//Could result in overflow
//perform other processing
return temp;
}
|
If the result of the addition, is greater than the maximum value that the int type can store or less than the minimum value that the int type can store, then the variable temp has a wrong result stored. Although, unlike C\C++ the integer overflow is difficult to exploit by an attacker in Java, because of the memory properties in this platform (e.g. explicit array bound checking; if temp has a negative value as a result of an overflow and we use it as an array index we get an java.lang.ArrayIndexOutOfBoundsException) the results of our operation are wrong and can lead to undefined or incorrect behavior
All the of the following operators can lead to overflow:
Operator | Overflow |
| Operator | Overflow |
| Operator | Overflow |
| Operator | Overflow |
---|---|---|---|---|---|---|---|---|---|---|
yes |
| yes |
| no |
| < | no | |||
yes |
| yes |
| >> | no |
| > | no | ||
yes |
| yes |
| & | no |
| >= | no | ||
yes |
| no |
| | | no |
| <= | no | ||
no |
| no |
| ^ | no |
| == | no | ||
++ | yes |
| >>= | no |
| ~ | no |
| != | no |
-- | yes |
| &= | no |
| ! | no |
| && | no |
= | no |
| |= | no |
| un + | no |
| || | no |
yes |
| ^= | no |
| yes |
| ?: | no |
Addition
Addition (and all operations) in Java are performed in signed numbers as Java does not support unsigned numbers
Noncompliant Code Example
In this example the addition could result in overflow
Code Block | ||
---|---|---|
| ||
public int do_operation(int a,int b)
{
int temp = a + b;
//Could result in overflow
//do other processing
return temp;
}
|
Compliant Solution (Bounds Checking)
A solution would be to explicitly check the range of each arithmetic operation and throw an ArithmeticException on overflow, otherwise downcast the value to an integer. For arithmetical operations on really big numbers one should always use the BigInteger Class
In this platform according to SUN Java Data Types:
_ _ -the integer data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).
_ _ - the long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int
So since long is guaranteed to be able to hold the result of an int addition, we could assign the result to a long and if the result is in the integer range we simply downcast. All of the tests would be the same as with signed integers in C since Java does not support unsigned numbers
e.g for the previous example
Compliant Solution (Use long and downcast)
Code Block | ||
---|---|---|
| ||
public int do_operation(int a, int b) throws ArithmeticException
{
long temp = (long)a+(long)b;
if(temp >Integer.MAX_VALUE || temp < Integer.MIN_VALUE) throw ArithmeticException;
else //Value within range can perform the addition
//Do stuff
return (int)temp;
}
|
Compliant Solution (Bounds Checking)
Another example would be of explicit range checking would be:
Code Block | ||
---|---|---|
| ||
public int do_operation(int a, int b) throws ArithmeticException { int temp; if(a>0 && b>0 && (a >Integer.MAX_VALUE - b) || a<0 && b<0 && (a < Integer.MIN_VALUE -b)) throw ArithmeticException; else temp = a + b;//Value within range can perform the addition && left == Integer.MIN_VALUE) ) { throw //Do stuff returnnew ArithmeticException("Integer overflow"); } return left * tempright; } |
Compliant Solution (Use BigInteger class)
Another compliant approach would be to use the BigInteger class in this example and in the examples of the other operations using a wrapper for test of the overflow:
Code Block | ||
---|---|---|
| ||
public bool overflow(int a static final int safeDivide(int left, int bright) { if ((left == java.math.BigInteger ba = new java.math.BigInteger(String.valueOf(a));Integer.MIN_VALUE) && (right == -1)) { java.math.BigInteger bb = new java.math.BigInteger(String.valueOf(b)throw new ArithmeticException("Integer overflow"); } java.math.BigInteger br = ba.add(bb); if(br.compareTo(java.math.BigInteger.valueOf(Integer.MAX_VALUE)) == 1return left / right; } static final int safeNegate(int a) { if (a == Integer.MIN_VALUE) { throw new ArithmeticException("Integer overflow"); } return -a; } static final || br.compareTo(java.math.BigInteger.valueOf(int safeAbs(int a) { if (a == Integer.MIN_VALUE))== -1) { throw new return true;//We have overflowArithmeticException("Integer overflow"); } //Can proceed return false } public int do_operation(int a, int b) throws ArithmeticException { if(overflow(a,b)) throw ArithmeticException; else //we are within range safely perform the addition } |
By using the BigInteger class there is no chance to overflow (see section on BigInteger class) but the performance is degraded so it should be used only on really large operations
Subtraction
return Math.abs(a);
}
|
These method calls are likely to be inlined by most just-in-time (JIT) systems.
These checks can be simplified when the original type is char
. Because the range of type char
includes only positive values, all comparisons with negative values may be omittedCare must be taken in subtraction operations as well as these can overflow as well.
Noncompliant Code Example
Either operation in this noncompliant code example could result in an overflow. When overflow occurs, the result will be incorrect.
Code Block | ||
---|---|---|
| ||
public static int multAccum(int oldAcc, int newVal, int scale) {
// May | ||
Code Block | ||
| ||
public int do_operation(int a,int b) { int temp = a - b; //Could result in overflow //perform other processing return oldAcc + return temp(newVal * scale); } |
Compliant
...
Solution (Precondition Testing)
This compliant solution uses the safeAdd()
and safeMultiply()
methods defined in the "Precondition Testing" section to perform secure integral operations or throw ArithmeticException
on overflow:The appropriate way is to check explicitely the range before doing the subtraction
Code Block | ||
---|---|---|
| ||
public static int multAccum(int a,b,result; long temp = (long)a-(long)b; if(long < Integer.MIN_VALUE || long > Integer.MAX_VALUE) throw ArithmeticException; else result = (int) temp; |
Compliant Code Example (Use BigInteger class)
oldAcc, int newVal, int scale) {
return safeAdd(oldAcc, safeMultiply(newVal, scale));
}
|
Compliant Solution (Java 8, Math.*Exact()
)
This compliant solution uses the addExact()
and multiplyExact()
methods defined in the Math
class. These methods were added to Java as part of the Java 8 release, and they also either return a mathematically correct value or throw ArithmeticException
. The Math
class also provides SubtractExact()
and negateExact()
but does not provide any methods for safe division or absolute value.A BigInteger class as a test-wrapper could be used
Code Block | ||
---|---|---|
| ||
public static boolint underflowmultAccum(int aoldAcc, int newVal, int bscale) { return java.math.BigInteger ba = new java.math.BigInteger(String.valueOf(a)); java.math.BigInteger bb = new java.math.BigInteger(String.valueOf(b)); java.math.BigInteger br = ba.subtract(bb); if(br.compareTo(java.math.BigInteger.valueOf(Math.addExact(oldAcc, Math.multiplyExact(newVal, scale)); } |
Compliant Solution (Upcasting)
This compliant solution shows the implementation of a method for checking whether a value of type long
falls within the representable range of an int
using the upcasting technique. The implementations of range checks for the smaller primitive integer types are similar.
Code Block | ||
---|---|---|
| ||
public static long intRangeCheck(long value) { if ((value < Integer.MIN_VALUE) || (value > Integer.MAX_VALUE)) == 1{ throw new ArithmeticException("Integer overflow"); } return value; } public static || br.compareTo(java.math.BigInteger.valueOf(Integer.MIN_VALUE))== -1) return true;//We have underflow //Can proceed return false } public int do_operation(int a, int b) throws ArithmeticException { if(undeflow(a,b)) throw ArithmeticException; else //we are within range safely perform the addition } |
Multiplication
This noncompliant code example, can result in a signed integer overflow during the multiplication of the signed operands a and b. If this behaviour is unanticipated, the resulting value may lead to undefined behaviour
Noncompliant Code Example
Code Block | ||
---|---|---|
| ||
int a,b,result
//do stuff
result = a*b;//May result in overflow
|
Compliant Code Example
Since in this platform the size of type long (64 bits) is twice the size of type int (32 bits) we should perform the multiplication in terms of long and if the product is in the integer range we downcast the result to int
Code Block | ||
---|---|---|
| ||
int a,b,result;
long temp = (long) a\* (long)b;
if(temp > Integer.MAX_VALUE || temp < Integer.MIN_VALUE)
throw ArithmeticException;//overflow
else
result = (int) temp;//Value within range, safe to downcast
|
Division
Although Java throws a java.lang.ArithmeticException: / by zero exception for division by zero, there is the same issue as in C\C++ when dividing the Integer.MIN_VALUE with -1. It produces Integer.MIN_VALUE unexpectedly
(since the result is -(Integer.MIN_VALUE)=Integer.MAX_VALUE +1))
A non-compliant example is:
Noncompliant Code Example
Code Block | ||
---|---|---|
| ||
int a,b,result
result = a/b;
|
Compliant Code Example
Code Block | ||
---|---|---|
| ||
if(a == Integer.MIN_VALUE && b == -1)
throw ArithmeticException;//May be Integer.MIN_VALUE again????
else
result = a/b;//safe operation
|
Modulo
Modulo operation is safer in Java than C/C++
-if we take the modulo of Integer.MIN_VALUE with -1 the result is always 0 in JAVA
-if the right-hand operand is zero then the integer remainder operator %, will throw an ArithmeticException
Unary Negation
If we negate Integer.MIN_VALUE we get Integer.MIN_VALUE. So we explicitely check the range
Noncompliant Code Example
Code Block | ||
---|---|---|
| ||
int temp = -result;
|
Compliant Code Example
Code Block | ||
---|---|---|
| ||
if(a == Integer.MIN_VALUE)
throw ArithmeticException;
else
result = -a;
|
SHIFTING
The shift in java is quite different than in C\C++.
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.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)
35 00000000 00000000 00000000 00100011
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 | ||
---|---|---|
| ||
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 | ||
---|---|---|
| ||
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 | ||
---|---|---|
| ||
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
int multAccum(int oldAcc, int newVal, int scale) {
final long res = intRangeCheck(
((long) oldAcc) + intRangeCheck((long) newVal * (long) scale)
);
return (int) res; // Safe downcast
}
|
Note that this approach cannot be applied to values of type long
because long
is the largest primitive integral type. Use the BigInteger
technique instead when the original variables are of type long
.
Compliant Solution (BigInteger
)
This compliant solution uses the BigInteger
technique to detect overflow:
Code Block | ||
---|---|---|
| ||
private static final BigInteger bigMaxInt =
BigInteger.valueOf(Integer.MAX_VALUE);
private static final BigInteger bigMinInt =
BigInteger.valueOf(Integer.MIN_VALUE);
public static BigInteger intRangeCheck(BigInteger val) {
if (val.compareTo(bigMaxInt) == 1 ||
val.compareTo(bigMinInt) == -1) {
throw new ArithmeticException("Integer overflow");
}
return val;
}
public static int multAccum(int oldAcc, int newVal, int scale) {
BigInteger product =
BigInteger.valueOf(newVal).multiply(BigInteger.valueOf(scale));
BigInteger res =
intRangeCheck(BigInteger.valueOf(oldAcc).add(product));
return res.intValue(); // Safe conversion
}
|
Noncompliant Code Example (AtomicInteger
)
Operations on objects of type AtomicInteger
suffer from the same overflow issues as other integer types. The solutions are generally similar to the solutions already presented; however, concurrency issues add additional complications. First, potential issues with time-of-check, time-of-use (TOCTOU) must be avoided (see VNA02-J. Ensure that compound operations on shared variables are atomic for more information). Second, use of an AtomicInteger
creates happens-before relationships between the various threads that access it. Consequently, changes to the number of accesses or order of accesses can alter the execution of the overall program. In such cases, you must either choose to accept the altered execution or carefully craft your implementation to preserve the exact number of accesses and order of accesses to the AtomicInteger
.
This noncompliant code example uses an AtomicInteger
, which is part of the concurrency utilities. The concurrency utilities lack integer overflow checks.
Code Block | ||
---|---|---|
| ||
class InventoryManager {
private final AtomicInteger itemsInInventory = new AtomicInteger(100);
//...
public final void nextItem() {
itemsInInventory.getAndIncrement();
}
}
|
Consequently, itemsInInventory
can wrap around to Integer.MIN_VALUE
when the nextItem()
method is invoked when itemsInInventory == Integer.MAX_VALUE
.
Compliant Solution (AtomicInteger
)
This compliant solution uses the get()
and compareAndSet()
methods provided by AtomicInteger
to guarantee successful manipulation of the shared value of itemsInInventory
. This solution has the following characteristics:
- The number and order of accesses to
itemsInInventory
remain unchanged from the noncompliant code example. - All operations on the value of
itemsInInventory
are performed on a temporary local copy of its value. - The overflow check in this example is performed in inline code rather than encapsulated in a method call. This is an acceptable alternative implementation. The choice of method call versus inline code should be made according to your organization's standards and needs.
Code Block | ||
---|---|---|
| ||
class InventoryManager {
private final AtomicInteger itemsInInventory =
new AtomicInteger(100);
public final void nextItem() {
while (true) {
int old = itemsInInventory.get();
if (old == Integer.MAX_VALUE) {
throw new ArithmeticException("Integer overflow");
}
int next = old + 1; // Increment
if (itemsInInventory.compareAndSet(old, next)) {
break;
}
} // End while
} // End nextItem()
}
|
The two arguments to the compareAndSet()
method are the expected value of the variable when the method is invoked and the intended new value. The variable's value is updated only when the current value and the expected value are equal [API 2006] (refer to VNA02-J. Ensure that compound operations on shared variables are atomic for more details).
Exceptions
NUM00-J-EX0: Depending on circumstances, integer overflow could be benign. For example, many algorithms for computing hash codes use modular arithmetic, intentionally allowing overflow to occur. Such benign uses must be carefully documented.
NUM00-J-EX1: Prevention of integer overflow is unnecessary for numeric fields that undergo bitwise operations and not arithmetic operations (see NUM01-J. Do not perform bitwise and arithmetic operations on the same data for more information).
Risk Assessment
Failure to perform appropriate range checking can lead to integer overflows, which can cause unexpected program control flow or unanticipated program behavior.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
NUM00-J | Medium | Unlikely | Medium | P4 | L3 |
Automated Detection
Automated detection of integer operations that can potentially overflow is straightforward. Automatic determination of which potential overflows are true errors and which are intended by the programmer is infeasible. Heuristic warnings might be helpful.
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
CodeSonar |
| JAVA.MATH.ABSRAND | Abs on random (Java) | ||||||
Coverity | 7.5 | BAD_SHIFT | Implemented | ||||||
Parasoft Jtest |
| CERT.NUM00.ICO CERT.NUM00.BSA CERT.NUM00.CACO | Avoid calculations which result in overflow or NaN Do not use an integer outside the range of [0, 31] as the amount of a shift Avoid using compound assignment operators in cases which may cause overflow | ||||||
PVS-Studio |
| V5308, V6117 |
Related Guidelines
INT32-C. Ensure that operations on signed integers do not result in overflow | |
Wrap-around Error [XYY] | |
CWE-682, Incorrect Calculation |
Android Implementation Details
Mezzofanti for Android contained an integer overflow that prevented the use of a big SD card. Mezzofanti contained an expression:
(int) StatFs.getAvailableBlocks() * (int) StatFs.getBlockSize()
to calculate the available memory in an SD card, which could result in a negative value when the available memory is larger than Integer.MAX_VALUE
. Note that these methods are deprecated in API level 18 and replaced by getAvailableBlocksLong()
and getBlockSizeLong()
.
Bibliography
[API 2006] | Class |
Puzzle 27, "Shifty i's" | |
[Bloch 2008] | Item 12, "Minimize the Accessibility of Classes and Members" |
[JLS 2015] | §4.2.1, "Integral Types and Values" |
Chapter 5, "Integers" | |
[Seacord 2015] |
...
Secure Coding Guidelines for the Java Programming Language: Secure (Paragraph on comparison C++/Java)
The Java Language Specification, Third Edition: JLS (Operations and data types)