Math.abs of a hash code or random number, which can still be negative
What it finds
Math.abs(key.hashCode()) % buckets can be negative: the absolute value of Integer.MIN_VALUE does not fit in an int, and Math.abs returns it unchanged. A hash code or a random int or long is that value often enough to matter. Math.floorMod gives a result that is never negative, and so does masking off the sign bit.
Reported is Math.abs of hashCode(), System.identityHashCode, Objects.hashCode, Objects.hash, and of nextInt() and nextLong() without arguments, the random numbers over the whole range.
From the rule's source, abs_of_hash.rs.
import java.util.Objects;import java.util.Random; class Buckets { int index(Object key, Random random, int size) { int a = Math.abs(key.hashCode()) % size;tx0 reports: Math.abs(key.hashCode()) is negative int b = Math.abs(random.nextInt()) % size;tx0 reports: is negative when a random number long c = Math.abs(random.nextLong());tx0 reports: is negative when a random number int d = Math.abs(Objects.hash(key, size));tx0 reports: is negative when a hash code int e = Math.abs(System.identityHashCode(key));tx0 reports: is negative when a hash code int f = Math.abs(key.hashCode() % size); int g = Math.abs(random.nextInt(size)); int h = Math.floorMod(key.hashCode(), size); return a + b + (int) c + d + e + f + g + h; }} Turn it on, off or suppress it
The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:
[rules]
"tx0/java:abs-of-hash" = "off"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/java:abs-of-hash] reason="..."tx0 explain tx0/java:abs-of-hash shows the same in the terminal. Found a false positive? Report it.