Standard Analyses

SemmleCode Professional comes with a wide range of pre-packaged analyses, from architectural properties and metrics, to statement-level checks for likely bugs and violations of best practice.


Dangerous non-short-circuit logic

This code finds uses of non-short circuiting operators (& and |) on booleans, where the right hand side might need to be guarded by the left hand side.

Consider the following expression

    (s == null) | (s.length() == 0)

where s is a variable of type java.lang.String. Since this expression uses the non-short circuiting operator |, both operands will be evaluated, even if the left hand side evaluates to true. Hence, if s happens to be null, this example will throw a NullPointerException.

How to Interpret the Query Results

The query flags such code and also displays the list of detected occurrences in the result view.

How to Address the Query Results

Use the short-circuiting operators && and || instead:

    (s == null) || (s.length() == 0)

Now, if s is null, the right hand side will not be evaluated, since it is clear that the value of the whole expression will be true.

Source Code
import default

/** An expression containing a method access, array access, or qualified field access */
class DangerousExpression extends Expr {
  DangerousExpression() {
    exists (Expr e | this = e.getParent*() and
    (   e instanceof MethodAccess
     or e instanceof ArrayAccess
     or exists (VarAccess va | va.getVariable() instanceof Field and
                               exists(va.getQualifier()) and
                         va = e)))
  }
}

/** A use of & or | on operands of type boolean */
class NonShortCircuit extends BinaryExpr {
  NonShortCircuit() {
    (   this instanceof AndBitwiseExpr
     or this instanceof OrBitwiseExpr) and
    this.getLeftOperand().getType().hasName("boolean") and
    this.getRightOperand().getType().hasName("boolean")
  }
}

from NonShortCircuit e
where e.getRightOperand() instanceof DangerousExpression
select e, "Possibly dangerous use of non-short circuit logic"
References