Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Java does not provide any silently wraps, providing no indication of overflow conditions and silently wraps, which . This can result in incorrect computations and unanticipated outcomes.

According to the Java Language Specification(JLS), Section 4§4.2.2, "Integer Operations"

...

The integral types in Java are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing UTF-16 code units.

According to the Java Language Specification, Section 4JLS, §4.2.1, "Integral Types and Values," the values of the integral types are integers in the inclusive ranges, shown in the following table:

...

Because the ranges of Java types are not symmetrical (the negation of minimum value is one more than each maximum value), even operations like unary negation can overflow, if applied to a mimimum value. Because the java.lang.math.abs() function returns the absolute value on any number, it too can also overflow if given the minimum int or long as an argument.

...

  • 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 may can overflow the larger type. Downcast the final result to the original smaller type before assigning to the result variable. This approach cannot be used for type long because long is already the largest primitive integer type.
  • BigInteger. Convert the inputs into objects of type BigInteger and perform all arithmetic using BigInteger methods. Type BigInteger is the standard arbitrary-precision integer type provided by the Java standard libraries. The arithmetic operations implemented as methods of this type cannot themselves overflow; instead, they produce the numerically correct result. As a consequence, compliant code only performs only a single range check --- just before converting the final result to the original smaller type and throw throwing an ArithmeticException if the final result is outside the range of the original smaller type.

...

The BigInteger technique is conceptually the simplest of the three techniques. However, it requires the use of method calls for each operation in place of primitive arithmetic operators; this may 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.

...

Code Block
bgColor#ccccff
public static long intRangeCheck(long value) throws ArithmeticOverflow {
  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) throws ArithmeticException {
  final long res =
    intRangeCheck(((long) oldAcc) + intRangeCheck((long) newVal * (long) scale));
  return (int) res; // safe down-cast
}

This Note that this approach cannot be applied for type long because long is the largest primitive integral type. Use When the BigInteger technique when the original variables are of type long, use the BigInteger technique instead.

Compliant Solution (BigInteger)

...

Operations on objects of type AtomicInteger suffer from the same overflow issues as do the other integer types. The solutions are generally similar to those shown above; 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). Secondly, use of an AtomicInteger creates happens-before relationships between the various threads that access it. Consequently, changes to the number or order of accesses may 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 and order of accesses to the AtomicInteger.

...

Consequently, itemsInInventory may can wrap around to Integer.MIN_VALUE after the increment operation.

...

  • The number and order of accesses to itemsInInventory remains 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 vs. versus inline code should be made according to your organization's standards and needs.

...

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. (seeSee \[[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

...

NUM00-EX2: The added complexity and cost of programmer-written overflow checks may could exceed their value for all but the most critical code. In such cases, consider the alternative of treating integral values as though they are tainted data, using appropriate range checks as the sanitizing code. These range checks should ensure that incoming values cannot cause integer overflow. Note that sound determination of allowable ranges may could require deep understanding of the details of the code protected by the range checks; correct determination of the allowable ranges may could be extremely difficult.

Risk Assessment

...

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

...

Search for vulnerabilities resulting from the violation of this guideline on the CERT website.

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"

MITRE CWE: CWE-682 "Incorrect Calculation," CWE-190 "Integer Overflow or Wraparound," and CWE-191 "Integer Underflow (Wrap or Wraparound)"

...

Wiki Markup
\[[API 2006|AA. Bibliography#API 06]\] class [{{AtomicInteger}}|http://download.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicInteger.html]
\[[Bloch 2005|AA. Bibliography#Bloch 05]\] Puzzle 27: Shifty i's
\[[SCG 2007|AA. Bibliography#SCG 07]\] Introduction
\[[JLS 2005|AA. Bibliography#JLS 05]\] [Section 4§4.2.2|http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2.2] "Integer Operations," [Section 15§15.22|http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.22] "Bitwise and Logical Operators"
\[[Seacord 2005|AA. Bibliography#Seacord 05]\] Chapter 5. Integers
\[[Tutorials 2008|AA. Bibliography#Tutorials 08]\] Primitive Data Types

...