The conditional AND and OR operators (&&
and ||
, respectively) exhibit short-circuit behavior. That is, the second operand is evaluated only when the result of the conditional operator cannot be deduced solely by evaluating the first operand. Consequently, when the result of the conditional operator can be deduced solely from the result of the first operand, the second operand will remain unevaluated; its side-effects, if any, will never occur.
In the following code, the value of i
is incremented only when i >= 0
.
The bitwise AND and OR operators (&
and |
) do not this behavior. They, like most other Java operators, evaluate both operands, starting with the left operand, and then the right. They return the same result as &&
and ||
respectively.
Consequently it is useful to use either &
or &&
when performing Boolean logic. However, there are times when the short-circuiting behavior is preferred, and other times when the short-circuiting behavior causes subtle bugs.
Noncompliant Code Example (Improper &
)
Wiki Markup |
---|
In this noncompliant code example, derived from \[[Flanagan 2005|AA. Bibliography#Flanagan 05]\], we have two variables, with no guarantees as to their current values. The code attempts to check if {{array[i]}} is nonnegative, but first it must validate its data. |
Code Block | ||
---|---|---|
| ||
int array[]; // may be null
int i; // may be a valid index for array
if (array != null &
| ||
Code Block | ||
int i = // initialize to user supplied value if ((i >= 0) & i < array.length & ((i++) <= Integer.MAX_VALUE)) array[i] >= 0) { // handle array } else { // ...handle error } |
Although the behavior is well defined, it is unclear whether i
is incremented on any particular execution.
Noncompliant Code Example
This noncompliant code example attempts to rename a given file if it exists, perform operations on the renamed file, and then delete the renamed file. For the purposes of this example, we assume that the file operations are performed on a secure portion of the filesystem. Consequently, we need not consider the time-of-check to time-of-use vulnerabilities that would otherwise be of concern.
When the exists()
method returns true
, execution continues with the call to File.delete()
; the call to File.renameTo()
remains unexecuted in this case. Consequently, the code as written fails to guarantee the existence of the renamed file, which can result in an attempt to use and subsequently to delete a nonexistent file. Further, File.delete()
returns an error code on failure rather than throwing an exception; this noncompliant example incorrectly ignores the return value from File.delete()
(see guideline EXP00-J. Do not ignore values returned by methods).
Code Block | ||
---|---|---|
| ||
class BadRenameFile {
public static void main(String[] args) {
File fOriginal = new File("original.txt");
File fNew = new File("new.txt");
if (fOriginal.exists() || fOriginal.renameTo(fNew)) {
// do something with fNew
fNew.delete();
}
}
}
|
Compliant Solution
Unfortunately this code may fail due to the very errors it is trying to prevent. If array
is null or i
is not a valid index, the reference to arrayi
will cause a NullPointerException
or ArrayIndexOutOfBoundsException
to be thrown. This happens because the &
operator does not prevent its right operands from being evaluated, even if its left operands prove that they are invalid.
Compliant Solution (Use &&
)
This compliant solution mitigates the problem by using &&
, which causes the conditional expression to terminate immediately if any of the conditions fail, thereby preventing a potentially-invalid evaluation.
Code Block | ||
---|---|---|
| ||
int array[]; // may be null
int i; // may be a valid index for array
if (array != null &&
i >= 0 & i < array.length &&
array[i] >= 0) {
// handle array
} else {
// handle error
}
|
Compliant Solution (Nested If Statements)
This compliant solution uses multiple if statements to achieve the proper effect. While correct, it is more verboseThis compliant solution checks both for the existence of the original file as well as for the success of the rename operation. It also handles the error when either check fails. It deletes the new file when operations are complete, checking for and handling the possible failure of the delete operation.
Code Block | ||
---|---|---|
| ||
class RenameFile { public static void main(String[] args) { File fOriginal = new File("original.txt"); File fNew = new File("new.txt"); int array[]; // may be null int i; // may be a valid index for array if (data != null) { if (i >= 0 & i < data.length) { if (!fOriginal.exists())data[i] != -1) { // handle errorarray } if (!fOriginal.renameTo(fNew)) else { // handle error } } // do something with fNew if (!fNew.delete()) else { // handle error } } else { } // handle }error } |
This solution could be useful if the error-handling routines for each potential condition failure were different.
Noncompliant Code Example (Improper &&
)
This noncompliant code example demonstrates code that compares two arrays for ranges of members that match. Here i1
and i2
are valid array indices in array1
and array2
respectively. It is expected that end1
and end2
will point to the end of the matching ranges in the two arrays.When error handling for failure of the existence and rename operations is identical, that portion of the code could be rewritten as:
Code Block | ||
---|---|---|
| ||
if (end1 >= 0 if (!fOriginal.exists() || !fOriginal.renameTo(fNew)) { // handle error } |
In this form, the short-circuit behavior of the ||
operation provides identical semantics to the "two-if-statement" version shown above.
Exceptions
Wiki Markup |
---|
*EXP06-EX1:* Programmers who are aware of the short-circuit behavior often use it to their advantage, as in this example from Flanagan \[[Flanagan 2005|AA. Bibliography#Flanagan 05]\]: |
Code Block | ||
---|---|---|
| ||
if (data != null && i < data.length && data[i] != -1) ...
|
This code snippet sequentially checks for potential error conditions before allowing the main computation to proceed. The short-circuit behavior of &&
guarantees that the first error condition encountered will terminate the checking process.
Risk Assessment
& i2 >= 0) {
int begin1 = i1;
int begin2 = i2;
while (++i1 < array1.length &&
++i2 < array2.length &&
array1[i1] == array2[i2]) {
// arrays match so far
}
int end1 = i1;
int end2 = i2;
assert end1 - begin1 == end2 - begin2;
}
|
The problem with this code is that if the first condition in the while loop fails, the second condition is not executed. That is, once i1
has reached array1.length
, the loop may terminate after i1
is executed. Consequently the range over array1
is larger than the range over array2
, causing the final assertion to fail.
Compliant Solution (Use &
)
This compliant solution mitigates the problem by using &
, which guarantees that both i1
and i2
are incremented, regardless of the outcome of the first condition.
Code Block | ||
---|---|---|
| ||
while (++i1 < array1.length & // not &&
++i2 < array2.length &&
array1[i1] == array2[i2])
|
Compliant Solution (Nested If Statements)
This compliant solution uses multiple if statements to achieve the proper effect. While correct, it is more verbose.
Code Block | ||
---|---|---|
| ||
while (true) {
if (++i1 >= array1.length) break;
if (++i2 >= array2.length) break;
if (array1[i1] != array2[i2]) break;
// rest of loop
}
|
Risk Assessment
Failure to understand the behavior of the bitwise and conditional Failure to understand the short-circuit behavior of the logical AND and OR operators can cause unintended program behavior.
Guideline | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
EXP07-J | low | unlikely | medium | P2 | L3 |
Automated Detection
Detection of short-circuit operators is straightforward, but sound error checking for this guideline is not feasible in the general case. Heuristic warnings could be useful.
Related Vulnerabilities
...
Related Guidelines
CERT C Secure Coding Standard: EXP02-C. Be aware of the short-circuit behavior of the logical AND and OR operators
CERT C++ Secure Coding Standard: EXP02-CPP. Be aware of the short-circuit behavior of the logical AND and OR operators
Bibliography
Wiki Markup |
---|
\[[Flanagan 2005|AA. Bibliography#Flanagan 05]\] 2.5.6. Boolean Operators \[[JLS 2005|AA. Bibliography#JLS 05]\] Sections [15.23|http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.23] "Conditional-And Operator &&" and [15.24|http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.24] "Conditional-Or Operator ||" |
...
EXP06-J. Use parentheses for precedence of operation 04. Expressions (EXP) EXP08-J. Understand the evaluation of expressions containing non-short-circuit operators