...
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. This 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 can result in integer overflow, consequently violating the {{compareTo()}} contract \[[Bloch 2008, Item 12|AA. Bibliography#Bloch 08]\]. |
Comparison of Compliant Techniques
The three main techniques for detecting unintended integer overflow are
...
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; this 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.
Pre-Condition Testing
The following code example shows the necessary pre-condition checks required for each arithmetic operation on arguments of type int
. The checks for the other integral types are analogous. In this example, we choose to throw an exception when integer overflow would occur; any other error handling is also acceptable.
...
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.
Noncompliant Code Example
Either operation in this noncompliant code example could produce a result that overflows the range of int
. 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); } |
Compliant Solution (Pre-Condition Testing)
This compliant solution uses the safeAdd()
and safeMultiply()
methods defined in the Pre-condition 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 (Upcasting)
This compliant solution shows the implementation of a method for checking whether a long
value 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.
...
Note that this approach cannot be applied for type long
because long
is the largest primitive integral type. When the original variables are of type long
, use the BigInteger
technique instead.
Compliant Solution (BigInteger
)
This compliant solution uses the BigInteger
technique to detect overflow.
Code Block | ||
---|---|---|
| ||
private static final BigInteger bigMaxInt = BigInteger.valueOf(Int.MAX_VALUE); private static final BigInteger bigMinInt = BigInteger.valueOf(Int.MIN_VALUE); public static BigInteger intRangeCheck(BigInteger val) throws ArithmeticException { 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(); // 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 must be avoided; see guideline 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 the implementation of your compliant technique to preserve the exact number of accesses and order of accesses to the AtomicInteger
.
...
Consequently, itemsInInventory
can wrap around to Integer.MIN_VALUE
when itemInInventory == 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:
...
Wiki Markup |
---|
The 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 if, and only if, the current value and the expected value are equal. (See \[[API 2006|AA. Bibliography#API 06]\] class [{{AtomicInteger}}|http://download.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicInteger.html].) Refer to guideline "[VNA02-J. Ensure that compound operations on shared variables are atomic]" for more details. |
Exceptions
NUM16NUM00-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.
Risk Assessment
Failure to perform appropriate range checking can lead to integer overflows, which can cause unexpected program control flow or unanticipated program behavior.
Guideline | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
NUM16 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 could be helpful.
Related Guidelines
C Secure Coding Standard: | "INT32-C. Ensure that operations on signed integers do not result in overflow" | |||
C++ Secure Coding Standard: | "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="acdec52a58eb4403-fede32fd-433e4b3b-a86b8947-8c790d64c0ecdf140c30b710"><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 ID 682, "Incorrect Calculation" | ||||
| CWE ID 190, "Integer Overflow or Wraparound" | |||
| CWE ID 191, "Integer Underflow (Wrap or Wraparound)" |
Bibliography
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="04d63d8be6c80dee-5bf484cd-43314507-a9659055-549c90f835c07807ac4f9656"><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="f00736779164784b-ecc990aa-4ec54642-a3fc9f06-7f487646a3eff1dfc8a361fc"><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="b218a35b29be78af-bd10052f-4ad64b52-b925b918-62fca54e464ab40ec0a95269"><ac:plain-text-body><![CDATA[ | [[SCG 2009 | AA. Bibliography#SCG 09]] | Introduction | ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="ed19fbd65bc4feb8-b61b906a-41724148-9360a6bc-8da5c9511934bee9a84aa19f"><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="2fc78c47ca5a8333-85fa3d72-4d434697-9d99b4c6-b05c4e5c84c27e7a1ef24bbe"><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="904ae9da08d21755-86274871-46874a7e-9671bbc7-ecd1b448a195affb7a691635"><ac:plain-text-body><![CDATA[ | [[Tutorials 2008 | AA. Bibliography#Tutorials 08]] | Primitive Data Types | ]]></ac:plain-text-body></ac:structured-macro> |
...