|
| 1 | +/** |
| 2 | + * @name Errors When Using Variable Declaration Inside Loop |
| 3 | + * @description Using variables with the same name is dangerous. |
| 4 | + * However, such a situation inside the while loop can lead to a violation of the accessibility of the program. |
| 5 | + * Requires the attention of developers. |
| 6 | + * @kind problem |
| 7 | + * @id cpp/errors-when-using-variable-declaration-inside-loop |
| 8 | + * @problem.severity warning |
| 9 | + * @precision medium |
| 10 | + * @tags correctness |
| 11 | + * security |
| 12 | + * external/cwe/cwe-1126 |
| 13 | + */ |
| 14 | + |
| 15 | +import cpp |
| 16 | + |
| 17 | +/** |
| 18 | + * Errors when using a variable declaration inside a loop. |
| 19 | + */ |
| 20 | +class DangerousWhileLoop extends WhileStmt { |
| 21 | + Expr exp; |
| 22 | + Declaration dl; |
| 23 | + |
| 24 | + DangerousWhileLoop() { |
| 25 | + this = dl.getParentScope().(BlockStmt).getParent*() and |
| 26 | + exp = this.getCondition().getAChild*() and |
| 27 | + not exp instanceof PointerFieldAccess and |
| 28 | + not exp instanceof ValueFieldAccess and |
| 29 | + exp.toString() = dl.getName() and |
| 30 | + not exp.getParent*() instanceof CrementOperation and |
| 31 | + not exp.getParent*() instanceof Assignment and |
| 32 | + not exp.getParent*() instanceof FunctionCall |
| 33 | + } |
| 34 | + |
| 35 | + Declaration getDeclaration() { result = dl } |
| 36 | + |
| 37 | + /** Holds when there are changes to the variables involved in the condition. */ |
| 38 | + predicate isUseThisVariable() { |
| 39 | + exists(Variable v | |
| 40 | + this.getCondition().getAChild*().(VariableAccess).getTarget() = v and |
| 41 | + ( |
| 42 | + exists(Assignment aexp | |
| 43 | + aexp = this.getStmt().getAChild*() and |
| 44 | + ( |
| 45 | + aexp.getLValue().(ArrayExpr).getArrayBase().(VariableAccess).getTarget() = v |
| 46 | + or |
| 47 | + aexp.getLValue().(VariableAccess).getTarget() = v |
| 48 | + ) |
| 49 | + ) |
| 50 | + or |
| 51 | + exists(CrementOperation crm | |
| 52 | + crm = this.getStmt().getAChild*() and |
| 53 | + crm.getOperand().(VariableAccess).getTarget() = v |
| 54 | + ) |
| 55 | + ) |
| 56 | + ) |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +from DangerousWhileLoop lp |
| 61 | +where not lp.isUseThisVariable() |
| 62 | +select lp.getDeclaration(), "A variable with this name is used in the loop condition." |
0 commit comments