|
| 1 | +/** |
| 2 | + * @id c/cert/div-or-rem-by-zero |
| 3 | + * @name INT33-C: Ensure that division and remainder operations do not result in divide-by-zero errors |
| 4 | + * @description Dividing or taking the remainder by zero is undefined behavior. |
| 5 | + * @kind problem |
| 6 | + * @precision high |
| 7 | + * @problem.severity error |
| 8 | + * @tags external/cert/id/int33-c |
| 9 | + * correctness |
| 10 | + * external/cert/obligation/rule |
| 11 | + */ |
| 12 | + |
| 13 | +import cpp |
| 14 | +import codingstandards.c.cert |
| 15 | +import semmle.code.cpp.controlflow.Guards |
| 16 | +import semmle.code.cpp.valuenumbering.GlobalValueNumbering |
| 17 | + |
| 18 | +from BinaryArithmeticOperation divOrMod, Expr divisor |
| 19 | +where |
| 20 | + not isExcluded(divOrMod, IntegerOverflowPackage::divOrRemByZeroQuery()) and |
| 21 | + divOrMod.getOperator() = ["/", "%"] and |
| 22 | + divisor = divOrMod.getRightOperand() and |
| 23 | + divisor.getType() instanceof IntegralType and |
| 24 | + // Range includes 0 |
| 25 | + upperBound(divisor) >= 0 and |
| 26 | + lowerBound(divisor) <= 0 and |
| 27 | + // And an explicit check for 0 does not exist |
| 28 | + not exists(GuardCondition gc, Expr left, Expr right | |
| 29 | + gc.ensuresEq(left, right, 0, divOrMod.getBasicBlock(), false) and |
| 30 | + globalValueNumber(left) = globalValueNumber(divisor) and |
| 31 | + right.getValue().toInt() = 0 |
| 32 | + ) and |
| 33 | + // Uninstantiated templates may not have an accurate reflection of the range |
| 34 | + not divOrMod.getEnclosingFunction().isFromUninstantiatedTemplate(_) |
| 35 | +select divOrMod, |
| 36 | + "Division or remainder expression with divisor that may be zero (divisor range " + |
| 37 | + lowerBound(divisor) + "..." + upperBound(divisor) + ")." |
0 commit comments