...
Code Block |
---|
|
public int do_operation(int a, int b) throws ArithmeticException {
if( b>0b > 0 ? a > Integer.MAX_VALUE - b : a < Integer.MIN_VALUE - b ) {
throw new ArithmeticException("Not in range");
}
return a + b; // Value within range so addition can be performed
}
|
...
Code Block |
---|
|
for (int val = -1; val != 0; val <<= 1) { /* ... */ }
|
Noncompliant Code Example (Concurrent code)
This noncompliant code example uses an AtomicInteger
which is part of the concurrency utilities. The concurrency utilities do not enforce checks for integer overflow.
Code Block |
---|
|
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.
Noncompliant Code Example (Concurrent code - TOCTOU condition in check)
This noncompliant code example install a check for integer overflow, however, there is a time-of-check-time-of-use vulnerability between the check and the increment operation.
Code Block |
---|
|
class InventoryManager {
private volatile int itemsInInventory = 100;
// ...
public final void returnItem() {
if (itemsInInventory == Integer.MAX_VALUE) {
throw new IllegalStateException("Out of bounds");
}
itemsInInventory++;
}
}
|
Compliant Solution (java.util.concurrent.atomic classes
)
The java.util.concurrent
utilities can be used to atomically manipulate a shared variable. This compliant solution defines intemsInInventory
as a java.util.concurrent.atomic.AtomicInteger
variable, allowing composite operations to be performed atomically.
Code Block |
---|
|
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 IllegalStateException("Out of bounds");
}
int next = old + 1; // Decrement
if (itemsInInventory.compareAndSet(old, next)) {
break;
}
} // end while
} // end removeItem()
}
|
Wiki Markup |
---|
The {{compareAndSet()}} method takes two arguments, the expected value of a variable when the method is invoked and the updated value. This compliant solution uses this method to atomically set the value of {{itemsInInventory}} to the updated value if and only if the current value equals the expected value \[[API 06|AA. Java References#API 06]\]. The while loop ensures that the {{removeItem()}} method succeeds in decrementing the most recent value of {{itemsInInventory}} as long as the inventory count is greater than {{MIN_INVENTORY}}. Refer to [CON01-J. Ensure that compound operations on shared variables are atomic] for more details. |
Exceptions
EX1: Depending on the functionality, integer overflow may be benign. For instance, the Object.hashcode()
method may return all representable values of type int
.
...