Description
Casting an int product to long cannot recover a result that has already overflowed. A shift distance at or above the type’s width can also shift by fewer bits than intended.
Potential impact
An incorrect count, size, index or bit mask can change the outcome of a size limit or access check that uses it.
Remediation
- For a
longproduct of twointvalues, cast one operand tolongbefore multiplying. UseMath.multiplyExactwhen overflow in the result type should raise an error. - Allow shift distances from 0 through 31 for
intand 0 through 63 forlong. For a 64-bit result, widen the left operand before shifting.
Examples
Widening multiplication
Before
java
public long calculateSize(int itemCount, int itemSize) {
return (long) (itemCount * itemSize);
}
After
java
public long calculateSize(int itemCount, int itemSize) {
return (long) itemCount * itemSize;
}
Casting itemCount first makes Java compute the product of the two int values in 64 bits.
Shift operations
Before
java
public int buildMask(int flags) {
return flags << 32;
}
After
java
public long buildMask(int flags) {
return ((long) flags) << 32;
}
In flags << 32, an int shift uses the low five bits of the distance, so the effective distance is zero. Casting flags to long first makes it shift by 32 bits.