Programs must not allow mathematical operations to exceed the integer ranges provided by their primitive integer data types. According to the The Java Language Specification (JLS), §4.2.2, "Integer Operations" [JLS 20052015]:
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 20052015]:
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
Yes |
|
No |
|
No |
|
yes
Yes |
|
yes
Yes |
|
no
No |
|
No |
|
yes
Yes |
|
yes
Yes |
|
no
No |
|
No |
|
Yes |
|
No |
|
No |
|
No |
|
no
No |
|
No |
|
no
No |
|
No |
|
yes
Yes |
|
No |
|
No |
|
No |
|
Yes |
|
no
No |
|
No |
|
no
No |
|
No |
Unary |
No |
|
yes
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 like 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.unmigrated-wiki-markup
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
...
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 following code example shows the necessary pre-condition 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 throws ArithmeticException { if (right > 0 ? left > Integer> 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) throws ArithmeticException { 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 throws ArithmeticException { if (right > 0 ? left > Integer.> Integer.MAX_VALUE/right || left < Integer.MIN_VALUE/right : (right < -1 ? left > Integer.MIN_VALUE/right || left < Integer.MAX_VALUE/right : right == -1 && left == Integer.MIN_VALUE) ) { throw new ArithmeticException("Integer overflow"); } return left * right; } static final int safeDivide(int left, int right) throws ArithmeticException { if ((left == Integer.MIN_VALUE) && (right == -1)) { throw new ArithmeticException("Integer overflow"); } return left / right; } static final int safeNegate(int a) throws ArithmeticException { if (a == Integer.MIN_VALUE) { throw new ArithmeticException("Integer overflow"); } return -a; } static final int safeAbs(int a) throws ArithmeticException { if (a == Integer.MIN_VALUE) { throw new ArithmeticException("Integer overflow"); } return Math.abs(a); } |
These method calls are likely to be inlined by most just-in-time systems (JITsJIT) 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 omitted.
...
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 result in overflow
return oldAcc + (newVal * scale);
}
|
...
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.:
Code Block | ||
---|---|---|
| ||
public static int multAccum(int oldAcc, int newVal, int scale) throws ArithmeticException { return safeAdd(oldAcc, safeMultiply(newVal, scale)); } |
Compliant Solution (
...
Java 8, Math.*Exact()
)
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 similaruses 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.
Code Block | ||
---|---|---|
| ||
public static longint intRangeCheckmultAccum(long value) throws ArithmeticException int oldAcc, int newVal, int scale) { ifreturn ((value <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)) { throw new ArithmeticException("Integer overflow"); } return value; } public static int multAccum(int oldAcc, int newVal, int scale) Integer.MIN_VALUE) || (value > Integer.MAX_VALUE)) { throw new ArithmeticException("Integer overflow"); } return value; } public static int multAccum(int oldAcc, int newVal, int scale) throws ArithmeticException { final long res = intRangeCheck( ((long) oldAcc) + intRangeCheck((long) newVal * (long) scale) ); return (int) res; // safeSafe down-castdowncast } |
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
.
...
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) { throws ArithmeticException { if (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) throws ArithmeticException { BigInteger product = BigInteger.valueOf(newVal).multiply(BigInteger.valueOf(scale)); BigInteger res = intRangeCheck(BigInteger.valueOf(oldAcc).add(product)); return res.intValue(); // safeSafe 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 rule 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();
}
}
|
...
- 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; } } // endEnd while } // endEnd nextItem() } |
The two arguments to the {{ Wiki Markup 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|AA. Bibliography#API 06]\]. Refer to rule [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 rule (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.
Related Guidelines
INT32-C. Ensure that operations on signed integers do not result in overflow | ||||
INT32-CPP. Ensure that operations on signed integers do not result in overflow | ||||
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="42d6f3c3-2c35-4d11-aecf-a1e23a95caa6"><ac:plain-text-body><![CDATA[ | [ISO/IEC TR 24772:2010 | http://www.aitcnet.org/isai/] | Wrap-around Error [XYY] | ]]></ac:plain-text-body></ac:structured-macro> |
CWE-682. Incorrect calculation | ||||
| CWE-190. Integer overflow or wraparound | |||
| CWE-191. Integer underflow (wrap or wraparound) |
Bibliography
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="2c97e8fa-8ae0-4fda-a4af-c619c3ed21b9"><ac:plain-text-body><![CDATA[ | [[API 2006 | AA. Bibliography#API 06]] | Class [ | http://download.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicInteger.html] | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="739dd029-697c-47c7-a9c1-40b020c20961"><ac:plain-text-body><![CDATA[ | [[Bloch 2005 | AA. Bibliography#Bloch 05]] | Puzzle 27. Shifty i's | ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="b140a9e4-1269-47f6-919b-6e502c2a40ad"><ac:plain-text-body><![CDATA[ | [[JLS 2005 | AA. Bibliography#JLS 05]] | [§4.2.2, Integer Operations | http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2.2] | ]]></ac:plain-text-body></ac:structured-macro> |
| |||||
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="b9ab3c8c-6e47-49a5-945f-2cf60a60e20b"><ac:plain-text-body><![CDATA[ | [[Seacord 2005 | AA. Bibliography#Seacord 05]] | Chapter 5, Integers | ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="98f6f71c-56ad-45f6-8b9a-a926e2c7b805"><ac:plain-text-body><![CDATA[ | [[Tutorials 2008 | AA. Bibliography#Tutorials 08]] | Primitive Data Types | ]]></ac:plain-text-body></ac:structured-macro> |
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] |
...
03. Numeric Types and Operations (NUM) 03. Numeric Types and Operations (NUM)