|
| 1 | +/** |
| 2 | + * @name Redundant null check or missing null check |
| 3 | + * @description Checking a parameter for nullness in one path, |
| 4 | + * and not in another is likely to be a sign that either |
| 5 | + * the check can be removed, or added in the other case. |
| 6 | + * @kind problem |
| 7 | + * @id cpp/redundant-null-check-param |
| 8 | + * @problem.severity recommendation |
| 9 | + * @tags reliability |
| 10 | + * security |
| 11 | + * external/cwe/cwe-476 |
| 12 | + */ |
| 13 | + |
| 14 | +import cpp |
| 15 | + |
| 16 | +predicate blockDominates(Block check, Block access) { |
| 17 | + check.getLocation().getStartLine() <= access.getLocation().getStartLine() and |
| 18 | + check.getLocation().getEndLine() >= access.getLocation().getEndLine() |
| 19 | +} |
| 20 | + |
| 21 | +predicate isCheckedInstruction(VariableAccess unchecked, VariableAccess checked) { |
| 22 | + checked = |
| 23 | + any(VariableAccess va | |
| 24 | + va.getTarget() = unchecked.getTarget() |
| 25 | + ) and |
| 26 | +//Simple test if the first access in this code path is dereferenced |
| 27 | + not dereferenced(checked) and |
| 28 | + blockDominates(checked.getEnclosingBlock(), unchecked.getEnclosingBlock()) |
| 29 | +} |
| 30 | + |
| 31 | +pragma[noinline] |
| 32 | +predicate candidateResultUnchecked(VariableAccess unchecked) { |
| 33 | + not isCheckedInstruction(unchecked, _) |
| 34 | +} |
| 35 | + |
| 36 | +pragma[noinline] |
| 37 | +predicate candidateResultChecked(VariableAccess check, EqualityOperation eqop, Parameter param) { |
| 38 | +//not dereferenced to check against pointer, not its pointed value |
| 39 | + not dereferenced(check) and |
| 40 | +//assert macros are not taken into account |
| 41 | + not check.isInMacroExpansion() and |
| 42 | +// is part of a comarison against some constant NULL |
| 43 | + eqop.getAnOperand() = check and eqop.getAnOperand() instanceof NullValue and |
| 44 | +// this function parameter is not overwritten |
| 45 | + count(param.getAnAssignment()) = 0 |
| 46 | +} |
| 47 | + |
| 48 | +from VariableAccess unchecked, VariableAccess check, EqualityOperation eqop, Parameter param |
| 49 | +where |
| 50 | +// a dereference |
| 51 | + dereferenced(unchecked) and |
| 52 | +// for a function parameter |
| 53 | + unchecked.getTarget() = param and |
| 54 | + check.getTarget() = param and |
| 55 | +// which is once checked |
| 56 | + candidateResultChecked(check, eqop, param) and |
| 57 | +// and which has not been checked before in this code path |
| 58 | + candidateResultUnchecked(unchecked) |
| 59 | +select check, "This null check is redundant because the value is $@ ", unchecked, "dereferenced here" |
0 commit comments