forked from github/codeql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayIndexOutOfBounds.ql
More file actions
74 lines (70 loc) · 2.2 KB
/
ArrayIndexOutOfBounds.ql
File metadata and controls
74 lines (70 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* @name Array index out of bounds
* @description Accessing an array with an index that is greater than or equal to the
* length of the array causes an 'ArrayIndexOutOfBoundsException'.
* @kind problem
* @problem.severity error
* @precision high
* @id java/index-out-of-bounds
* @tags quality
* reliability
* correctness
* exceptions
* external/cwe/cwe-193
*/
import java
import semmle.code.java.dataflow.SSA
import semmle.code.java.dataflow.RangeUtils
import semmle.code.java.dataflow.RangeAnalysis
/**
* Holds if the index expression of `aa` is less than or equal to the array length plus `k`.
*/
predicate boundedArrayAccess(ArrayAccess aa, int k) {
exists(SsaVariable arr, Expr index, Bound b, int delta |
aa.getIndexExpr() = index and
aa.getArray() = arr.getAUse() and
bounded(index, b, delta, true, _)
|
exists(FieldAccess len |
len.getField() instanceof ArrayLengthField and
len.getQualifier() = arr.getAUse() and
b.getExpr() = len and
k = delta
)
or
exists(ArrayCreationExpr arraycreation | arraycreation = getArrayDef(arr) |
k = delta and
arraycreation.getDimension(0) = b.getExpr()
or
exists(int arrlen |
arraycreation.getFirstDimensionSize() = arrlen and
b instanceof ZeroBound and
k = delta - arrlen
)
)
)
or
exists(Field arr, Expr index, int delta, int arrlen |
aa.getIndexExpr() = index and
aa.getArray() = arr.getAnAccess() and
bounded(index, any(ZeroBound z), delta, true, _) and
arr.isFinal() and
arr.getInitializer().(ArrayCreationExpr).getFirstDimensionSize() = arrlen and
k = delta - arrlen
)
}
/**
* Holds if the index expression is less than or equal to the array length plus `k`,
* but not necessarily less than or equal to the array length plus `k-1`.
*/
predicate bestArrayAccessBound(ArrayAccess aa, int k) {
k = min(int k0 | boundedArrayAccess(aa, k0))
}
from ArrayAccess aa, int k, string kstr
where
bestArrayAccessBound(aa, k) and
k >= 0 and
if k = 0 then kstr = "" else kstr = " + " + k
select aa,
"This array access might be out of bounds, as the index might be equal to the array length" + kstr
+ "."