|
| 1 | +import csharp |
| 2 | +import semmle.code.csharp.ir.IR |
| 3 | +import semmle.code.csharp.ir.rangeanalysis.RangeAnalysis |
| 4 | + |
| 5 | +/** |
| 6 | + * Holds if the index expression of `aa` is less than or equal to the array length plus `k`. |
| 7 | + */ |
| 8 | +predicate boundedArrayAccess(ElementAccess aa, int k) { |
| 9 | + exists(Instruction index, Instruction usage, Bound b, int delta | |
| 10 | + ( |
| 11 | + // indexer access |
| 12 | + usage.(CallInstruction).getAST() = aa |
| 13 | + or |
| 14 | + // array access |
| 15 | + usage.(PointerAddInstruction).getAST() = aa |
| 16 | + ) and |
| 17 | + usage.getAnOperand().getDef() = index and |
| 18 | + boundedInstruction(index, b, delta, true, _) |
| 19 | + | |
| 20 | + exists(PropertyAccess pa | |
| 21 | + k = delta and |
| 22 | + b.getInstruction().getAST() = pa and |
| 23 | + pa.getProperty().getName() = "Length" and |
| 24 | + pa.(QualifiableExpr).getQualifier().(VariableAccess).getTarget() = aa |
| 25 | + .getQualifier() |
| 26 | + .(VariableAccess) |
| 27 | + .getTarget() |
| 28 | + ) |
| 29 | + or |
| 30 | + exists(ArrayCreation ac | |
| 31 | + ac.getParent().(LocalVariableDeclExpr).getVariable() = aa |
| 32 | + .getQualifier() |
| 33 | + .(VariableAccess) |
| 34 | + .getTarget() and |
| 35 | + b instanceof ZeroBound and |
| 36 | + if exists(ac.getLengthArgument(0)) |
| 37 | + then k = delta - ac.getLengthArgument(0).getValue().toInt() |
| 38 | + else |
| 39 | + if exists(ac.getInitializer()) |
| 40 | + then k = delta - ac.getInitializer().getNumberOfElements() |
| 41 | + else none() |
| 42 | + ) |
| 43 | + ) |
| 44 | +} |
| 45 | + |
| 46 | +/** |
| 47 | + * Holds if the index expression is less than or equal to the array length plus `k`, |
| 48 | + * but not necessarily less than or equal to the array length plus `k-1`. |
| 49 | + */ |
| 50 | +predicate bestArrayAccessBound(ElementAccess aa, int k) { |
| 51 | + k = min(int k0 | boundedArrayAccess(aa, k0)) |
| 52 | +} |
| 53 | + |
| 54 | +from ElementAccess aa, int k, string msg, string add |
| 55 | +where |
| 56 | + bestArrayAccessBound(aa, k) and |
| 57 | + (if k = 0 then add = "" else add = " + " + k) and |
| 58 | + ( |
| 59 | + if k >= 0 |
| 60 | + then |
| 61 | + msg = "This array access might be out of bounds, as the index might be equal to the array length" |
| 62 | + + add |
| 63 | + else msg = "This array access is ok, the index is at most the lenth of the array " + add |
| 64 | + ) |
| 65 | +select aa.getEnclosingCallable(), aa, msg |
0 commit comments