Versions Compared

Key

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

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 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 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]:

Wiki Markup
According to Sun's Secure Coding Guidelines \[[SCG 2007|AA. Bibliography#SCG 07]\]

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 has been described as the single most pernicious problem in computer security today.

While this statement is true, arithmetic operations in the Java platform require just as much caution as C and C++ do because integer operations can result in overflow. Java does not provide any indication of overflow conditions and silently wraps. While integer overflows in vulnerable C and C++ programs can result in the execution of arbitrary code; in Java, wrapped values typically result in incorrect computations and unanticipated outcomes.

According to the Java Language Specification, Section 4.2.2, "Integer Operations"

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.

...

Type

Representation

Inclusive Range

byte

8-bit signed two's-complement

−128 to 127

short

16-bit signed two's-complement

−32,768 to 32,767

int

32-bit signed two's-complement

−2,147,483,648 to 2,147,483,647

long

64-bit signed two's-complement

−9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

char

16-bit unsigned integers representing UTF-16 code units

...

\u0000 to \uffff (0 to 65,535)

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.

Comparison of Compliant Techniques

Following are the

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

  • For byte, from –128 to 127, inclusive
  • For short, from –32,768 to 32,767, inclusive
  • For int, from –2,147,483,648 to 2,147,483,647, inclusive
  • For long, from –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, inclusive
  • For char, from \u0000 to \uffff inclusive, that is, from 0 to 65,535

The table below 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

 

|=

no

 

un +

no

 

||

no

+=

yes

 

^=

no

 

un -

yes

 

?:

no

Wiki Markup
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]\].

Overview of Compliant Techniques

The three main techniques for detecting unintended integer overflow are:

  • Pre-condition testing of the inputsPrecondition 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. We call this technique "Pre-condition the inputs" hereafter, for convenience.
  • UpcastingUse a larger type and downcast. 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 the result variablea variable of the original smaller type. This approach cannot be use used for type long because long is already the largest primitive integer type.
  • Use BigInteger. Convert the inputs into objects of type BigInteger and perform all arithmetic using BigInteger methods. Throw 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 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 an ArithmeticException if the final result is outside the range of the original smaller type; otherwise, convert back to the intended result type..

The precondition testing The "Pre-condition the inputs" technique requires different pre-condition precondition tests for each arithmetic operation. This approach can be somewhat more difficult to implement and to understand audit than either of the other two approaches.

The "Use a larger type and downcast" upcast technique is the preferred approach for the cases to which it applieswhen 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 The "Use 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 , which can obscure the intended meaning of the code. This technique will execute more slowly and will use more memory than the other techniques; performance degradation could be substantial.

Noncompliant Code Example

Either arithmetic operation in this noncompliant code example could produce a result that overflows the range representable by type int. When overflow occurs, the result will be incorrect.

Code Block
bgColor#FFcccc

public int multAccum(int oldAcc, int newVal, int scale) {
  // May result in overflow 
  return oldAcc + (newVal * scale);
}

Compliant Solution (Pre-Condition the Inputs)

The code example below shows the necessary pre-conditioning 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 (for simplicity) to throw an exception when integer overflow would occur; any other appropriate error handling is also acceptable.

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
bgColor#ccccff
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 
                                && left == Integer.MIN_VALUE) ) {
    throw new ArithmeticException("Integer overflow");
  }
  return left * right;
}

static final int safeDivide(int left, int right) {
  if ((left == Integer.MIN_VALUE) && (right == -1)) {
    throw new ArithmeticException("Integer overflow");
  }
  return left / right;
}

static final int safeNegate(int a) {
  if (a == Integer.MIN_VALUE) {
    throw new ArithmeticException("Integer overflow");
  }
  return -a;
}
static final int safeAbs(int a) {
  if (a == Integer.MIN_VALUE
Code Block

static final preAdd(int left, int right) throws ArithmeticException {
   if (right > 0 ? left > Integer.MAX_VALUE - right : left < Integer.MIN_VALUE - right) {
    throw new ArithmeticException("Integer overflow");
  }
}

static final preSubtract(int left, int right) throws ArithmeticException {
  if (right > 0 ? left < Integer.MIN_VALUE + right : left > Integer.MAX_VALUE + right) {
    throw new ArithmeticException("Integer overflow");
  }
}

static final preMultiply(int left, int right) throws ArithmeticException {
  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 && left == Integer.MIN_VALUE) ) {
    throw new ArithmeticException("Integer overflow");
  }
}

static final preDivide(int left, int right) throws ArithmeticException {
  if ((left == Integer.MIN_VALUE) && (right == -1)) {
    throw new ArithmeticException("Integer overflow");
  }
}

static final preAbs(int a) throws ArithmeticException {
  if (a == Integer.MIN_VALUE) {
    throw new ArithmeticException("Integer overflow");
  }
}

static final preNegate(int a) throws ArithmeticException {
  if (a == Integer.MIN_VALUE  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 omitted.

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
bgColor#FFcccc
public static int multAccum(int oldAcc, int newVal, int scale) {
  // May result in overflow
  return oldAcc + (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:

Code Block
bgColor#ccccff
public static int multAccum(int 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.

Code Block
bgColor#ccccff
public static int multAccum(int oldAcc, int newVal, int scale) {
  return 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
bgColor#ccccff
public static long intRangeCheck(long value) {
  if ((value < Integer.MIN_VALUE) || (value > Integer.MAX_VALUE)) {
    throw new ArithmeticException("Integer overflow");
  }
}

Note that although these pre-conditioning checks are correct, more efficient code could be possible. Also, the 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.

Code Block
bgColor#ccccff

public
  }
  return value;
}

public static int multAccum(int oldAcc, int newVal, int scale) throws ArithmeticException {
  preMultiply(newVal, Scale);
  final int temp = newVal * scale;
  preAdd(oldAcc, temp);
  return oldAcc + temp;
}

Compliant Solution (Use a Larger Type and Downcast)

For all integral types other than long, the next larger integral type can represent the result of any single integral operation. For example, operations on values of type int can be safely performed using type long. Therefore, we can perform an operation using the larger type and range-check before downcasting to the original type. Note, however, that this guarantee holds only for a one arithmetic operation; larger expressions without per-operation bounds checks may overflow the larger type.

 {
  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 This approach cannot be applied for type long because long is the largest primitive integral type. Use the "Use BigInteger" technique instead when the original variables are of type long.

This compliant solution shows the implementation of a method for checking whether a long value falls within the representable range of they int. The implementations of range checks for the smaller primitive integer types are exactly analogous.

of type long.

Compliant Solution (BigInteger)

This compliant solution uses the BigInteger technique to detect overflow:

Code Block
bgColor#ccccff
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) 
Code Block
bgColor#ccccff


public long intRangeCheck(long value) throws ArithmeticOverflow {
  if (val.compareTo(valuebigMaxInt) < Integer.MIN_VALUE)== 1 ||
    (value > Integer.MAX_VALUE)val.compareTo(bigMinInt) == -1) {
    throw new ArithmeticException("Integer overflow");
  }
  return valueval;
}

public static int multAccum(int oldAcc, int newVal, int scale) {
  throwsBigInteger ArithmeticExceptionproduct {=
    final longBigInteger.valueOf(newVal).multiply(BigInteger.valueOf(scale));
  BigInteger res = 
    intRangeCheck(BigInteger.valueOf(oldAcc).add(((long) oldAcc) + intRangeCheck((long) newVal * (long) scale));
  return (int) res; // safe down-cast
}

Compliant Solution (Use BigInteger)

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 performs only a single range check—just before converting the final result to the original smaller type. This property provides conceptual simplicity. An unfortunate consequence of this technique is that compliant code must be written using method calls in place of primitive arithmetic operators; this can obscure the intent of the code.

Note that operations on objects of type BigInteger can be significantly less efficient than operations on the original primitive integer type. Whether this loss of efficiency is important will depend on the context in which the code is used.

Code Block
bgColor#ccccff

private static final BigInteger bigMaxLong = BigInteger.valueOf(Long.MAX_VALUE);
private static final BigInteger bigMinLong = BigInteger.valueOf(Long.MIN_VALUE);

public BigInteger longRangeCheck(BigInteger val) throws ArithmeticException {
  if (val.compareTo(bigMaxLong) == 1 ||
          val.compareTo(bigMinLong) == -1) {
    throw new ArithmeticException("Integer overflow");
  }
  return val;
}

public long multAccum(long oldAcc, long newVal, long scale) throws ArithmeticException { 
  BigInteger product =
    BigInteger.valueOf(newVal).multiply(BigInteger.valueOf(scale));
  BigInteger res = longRangeCheck(BigInteger.valueOf(oldAcc).add(product));
  return res.longValue(); // safe conversion
}

Noncompliant Code Example AtomicInteger

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, avoid possible issues with time-of-check-time-of-use. (See guidleine 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 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.

This noncompliant code example uses an AtomicInteger, which is part of the concurrency utilities. The concurrency utilities lack integer overflow checks.

Code Block
bgColor#FFcccc

class InventoryManager {
  private final AtomicInteger itemsInInventory = new AtomicInteger(100);

  //...
  public final void returnItem() {
    itemsInInventory++;
  }
} 

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

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. Note the following:

  1. The number and order of accesses to itemsInInventory remains unchanged from the noncompliant code example.
  2. All operations on the value of itemsInInventory are performed on a temporary local copy of its value.
  3. 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. inline code should be made according to your organization's standards and needs.
Code Block
bgColor#ccccff

class InventoryManager {
  private final AtomicInteger itemsInInventory = new AtomicInteger(100);

  public final void returnItem() {
    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 removeItem()
}

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 \[[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

INT00-EX1: Depending on circumstances, integer overflow could be benign. For instance, the Object.hashcode() method could return all representable values of type int; further, many algorithms for computing hashcodes intentionally allow overflow to occur.

INT00-EX2: The added complexity and cost of programmer-written overflow checks may 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 notional sanitizing code. These range checks should ensure that incoming values cannot cause integer overflow. Note that sound determination of allowable ranges may require deep understanding of the details of the code protected by the range checks; correct determination of the allowable ranges may be extremely difficult.

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

INT00-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 Vulnerabilities

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"

MITRE CWE: CWE-190 "Integer Overflow or Wraparound"

MITRE CWE: CWE-191 "Integer Underflow (Wrap or Wraparound)"

Bibliography

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 2003|AA. Bibliography#JLS 03]\] 4.2.2 Integer Operations and 15.22 Bitwise and Logical Operators
\[[Seacord 2005|AA. Bibliography#Seacord 05]\] Chapter 5. Integers
\[[Tutorials 2008|AA. Bibliography#Tutorials 08]\] Primitive Data Types

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
bgColor#FFcccc
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
bgColor#ccccff
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
Include Page
CodeSonar_V
CodeSonar_V

JAVA.MATH.ABSRAND
JAVA.ARITH.OFLOW

Abs on random (Java)
Cast: int Computation to long (Java)

Coverity7.5

BAD_SHIFT
OVERFLOW_BEFORE_WIDEN

Implemented
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
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

Include Page
PVS-Studio_V
PVS-Studio_V

V5308, V6117

Related Guidelines

SEI CERT C Coding Standard

INT32-C. Ensure that operations on signed integers do not result in overflow

ISO/IEC TR 24772:2010

Wrap-around Error [XYY]

MITRE CWE

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

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


...

Image Added Image Added Image Added06. Integers (INT)      06. Integers (INT)      INT01-J. Check ranges before casting integers to narrower types