|
| 1 | +/** |
| 2 | + * @name Operator Precedence Logic Error When Use Bool Type |
| 3 | + * @description --Finding places of confusing use of boolean type. |
| 4 | + * --For example, a unary minus does not work before a boolean type and an increment always gives true. |
| 5 | + * @kind problem |
| 6 | + * @id cpp/operator-precedence-logic-error-when-use-bool-type |
| 7 | + * @problem.severity warning |
| 8 | + * @precision medium |
| 9 | + * @tags correctness |
| 10 | + * security |
| 11 | + * external/cwe/cwe-783 |
| 12 | + * external/cwe/cwe-480 |
| 13 | + */ |
| 14 | + |
| 15 | +import cpp |
| 16 | +import semmle.code.cpp.rangeanalysis.SimpleRangeAnalysis |
| 17 | + |
| 18 | +/** Holds, if it is an expression, a boolean increment. */ |
| 19 | +predicate incrementBoolType(Expr exp) { |
| 20 | + exp.(IncrementOperation).getOperand().getType() instanceof BoolType |
| 21 | +} |
| 22 | + |
| 23 | +/** Holds, if this is an expression, applies a minus to a boolean type. */ |
| 24 | +predicate revertSignBoolType(Expr exp) { |
| 25 | + exp.(AssignExpr).getRValue().(UnaryMinusExpr).getAnOperand().getType() instanceof BoolType and |
| 26 | + exp.(AssignExpr).getLValue().getType() instanceof BoolType |
| 27 | +} |
| 28 | + |
| 29 | +/** Holds, if this is an expression, uses comparison and assignment outside of execution precedence. */ |
| 30 | +predicate assignBoolType(Expr exp) { |
| 31 | + exists(ComparisonOperation co | |
| 32 | + exp.(AssignExpr).getRValue() = co and |
| 33 | + exp.isCondition() and |
| 34 | + not co.isParenthesised() and |
| 35 | + not exp.(AssignExpr).getLValue().getType() instanceof BoolType and |
| 36 | + co.getLeftOperand() instanceof FunctionCall and |
| 37 | + not co.getRightOperand().getType() instanceof BoolType and |
| 38 | + not co.getRightOperand().getValue() = "0" and |
| 39 | + not co.getRightOperand().getValue() = "1" |
| 40 | + ) |
| 41 | +} |
| 42 | + |
| 43 | +from Expr exp |
| 44 | +where |
| 45 | + incrementBoolType(exp) or |
| 46 | + revertSignBoolType(exp) or |
| 47 | + assignBoolType(exp) |
| 48 | +select exp, "this expression needs attention" |
0 commit comments