-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathReadOnlyContainer.ql
More file actions
47 lines (45 loc) · 1.77 KB
/
ReadOnlyContainer.ql
File metadata and controls
47 lines (45 loc) · 1.77 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
/**
* @name Container contents are never initialized
* @description Querying the contents of a collection or map that is never initialized is not normally useful.
* @kind problem
* @problem.severity error
* @precision very-high
* @id java/empty-container
* @tags reliability
* maintainability
* useless-code
* external/cwe/cwe-561
*/
import java
import semmle.code.java.Reflection
import Containers
from Variable v
where
v.fromSource() and
v.getType() instanceof ContainerType and
// Exclude parameters and non-private fields.
(v instanceof LocalVariableDecl or v.(Field).isPrivate()) and
// Exclude fields that may be written to reflectively.
not reflectivelyWritten(v) and
// Every access to `v` is either...
forall(VarAccess va | va = v.getAnAccess() |
// ...an assignment storing a fresh container into `v`,
exists(AssignExpr assgn | va = assgn.getDest() | assgn.getSource() instanceof FreshContainer)
or
// ...a return (but only if `v` is a local variable)
v instanceof LocalVariableDecl and exists(ReturnStmt ret | ret.getResult() = va)
or
// ...or a call to a query method on `v`.
exists(MethodAccess ma | va = ma.getQualifier() |
ma.getMethod() instanceof ContainerQueryMethod
)
) and
// There is at least one call to a query method.
exists(MethodAccess ma | v.getAnAccess() = ma.getQualifier() |
ma.getMethod() instanceof ContainerQueryMethod
) and
// Also, any value that `v` is initialized to is a fresh container,
forall(Expr e | e = v.getAnAssignedValue() | e instanceof FreshContainer) and
// and `v` is not implicitly initialized by a for-each loop.
not exists(EnhancedForStmt efs | efs.getVariable().getVariable() = v)
select v, "The contents of this container are never initialized."