forked from Marcono1234/codeql-java-queries
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathavoidable-String-toCharArray-call.ql
More file actions
63 lines (56 loc) · 2.3 KB
/
Copy pathavoidable-String-toCharArray-call.ql
File metadata and controls
63 lines (56 loc) · 2.3 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
/**
* Finds calls to `String.toCharArray()` which can be avoided. `toCharArray()`
* creates a new char array. For performance reasons it is therefore better to
* directly use the methods of String instead of operating on the array.
* E.g.:
* ```
* // Inefficient, especially for large strings; should instead use
* // `s.length() == 1 && s.charAt(0) == 'a'`
* char[] chars = s.toCharArray();
* if (chars.length == 1 && chars[0] == 'a') {
* ...
* }
* ```
*/
import java
import semmle.code.java.dataflow.DataFlow
import lib.Expressions
class ToCharArrayMethod extends Method {
ToCharArrayMethod() {
getDeclaringType() instanceof TypeString
and hasStringSignature("toCharArray()")
}
}
predicate incrOrDecr(Variable var, Expr expr) {
exists (VarAccess varAccess | varAccess = var.getAnAccess() |
expr.(AssignAddExpr).getDest() = varAccess
or expr.(AssignSubExpr).getDest() = varAccess
or expr.(PreIncExpr).getExpr() = varAccess
or expr.(PostIncExpr).getExpr() = varAccess
or expr.(PreDecExpr).getExpr() = varAccess
or expr.(PostDecExpr).getExpr() = varAccess
)
}
predicate containsIncrOrDecr(Stmt enclosing, Variable var) {
exists (Expr incrOrDecrExpr | incrOrDecr(var, incrOrDecrExpr) |
incrOrDecrExpr.getAnEnclosingStmt() = enclosing
)
}
// Note: Yields some false positives when accessed is in loop and array index is
// random based and not influenced by counter variable
from MethodAccess toCharArrayCall
where
toCharArrayCall.getMethod() instanceof ToCharArrayMethod
// Result is not leaked
and not isLeaked(toCharArrayCall)
// Ignore if char array is used in loop; then it might be more efficient than calling
// String methods in every iteration or using Stream
and not exists(EnhancedForStmt forStmt |
DataFlow::localFlow(DataFlow::exprNode(toCharArrayCall), DataFlow::exprNode(forStmt.getExpr()))
)
and not exists(LoopStmt loop, Variable counterVar, ArrayAccess arrayAccess |
containsIncrOrDecr(loop, counterVar)
and counterVar.getAnAccess().getParent*() = arrayAccess.getIndexExpr()
and DataFlow::localFlow(DataFlow::exprNode(toCharArrayCall), DataFlow::exprNode(arrayAccess.getArray()))
)
select toCharArrayCall, "Can avoid calling String.toCharArray()"