...
| Code Block | ||
|---|---|---|
| ||
int compute(int x) { x >>>= -502; return x >>>= 2; } // ... int x = compute(-50); |
The >>>= operator is a logical right shift; it fills the leftmost bits with zeroes, regardless of the number's original sign. After execution of this code sequence, x contains a large positive number (specifically, 0x3FFFFFF3). Using logical right shift for division produces an incorrect result when the dividend (x in this example) contains a negative value.
...
| Code Block | ||
|---|---|---|
| ||
int compute(int x) { x >>= -50; x >>= 2 2; return x; } // ... int x = compute(-50); |
After this code sequence is run, x contains the value -13 rather than the expected -12. Arithmetic right shift truncates the resulting value toward negative infinity, whereas integer division truncates toward zero.
...
| Code Block | ||
|---|---|---|
| ||
int compute(int x) { x /= -50; x /= 4 4 return x; } // ... int x = compute(-50); |
Noncompliant Code Example
...
In the bitwise operation, the value of the byte array element b[i] is promoted to an int by sign extension. When a byte array element contains a negative value (for example, 0xff), the sign extension propagates 1-bits into the upper 24 bits of the int. This behavior might be unexpected if the programmer is assuming that byte is an unsigned type. In this example, adding the promoted byte values to result fails to result in a packed integer representation of the bytes [FindBugs 2008].
See NUM01-J-EX1 for details about doing similar calculations for the purpose of serializing numbers into bytes.
Noncompliant Code Example
...
| Code Block | ||
|---|---|---|
| ||
byte[] b = new byte[] {-1, -1, -1, -1};
int result = 0;
for (int i = 0; i < 4; i++) {
result = ((result << 8) | (b[i] & 0xff));
}
|
See NUM01-J-EX1 for details about doing similar calculations for the purpose of serializing numbers into bytes.
Exceptions
NUM01-J-EX0: Bitwise operations may be used to construct constant expressions.
...
Performing bitwise manipulation and arithmetic operations on the same variable obscures the programmer's intentions and reduces readability. Consequently, it is more difficult for a security auditor or maintainer to determine which checks must be performed to eliminate security flaws and ensure data integrity. For instance, overflow checks are critical for numeric types that undergo arithmetic operations but less critical for numeric types that undergo bitwise operations.
Rule | Severity | Likelihood | Detectable | Remediation CostRepairable | Priority | Level |
|---|---|---|---|---|---|---|
NUM01-J | Medium | Unlikely | Yes | NoMedium | P4 | L3 |
Automated Detection
| Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
| Parasoft Jtest |
| CERT.NUM01.BADSHIFT CERT.NUM01.NCBAV | Avoid incorrect shift operations Do not perform bitwise and arithmetic operations on the same data |
...