Repository navigation
Expand file tree
/
Copy pathNullness.qll
More file actions
289 lines (270 loc) · 9.84 KB
/
Copy pathNullness.qll
File metadata and controls
289 lines (270 loc) · 9.84 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
/**
* Provides classes and predicates for nullness analysis.
*
* Local variables that may be null are tracked to see if they might reach
* a dereference and cause a NullPointerException. Assertions are assumed to
* hold, so results guarded by, for example, `assert x != null;` or
* `if (x == null) { assert false; }` are excluded.
*/
overlay[local?]
module;
import java
private import SSA
private import semmle.code.java.controlflow.Guards
private import IntegerGuards
private import NullGuards
private import semmle.code.java.Collections
private import semmle.code.java.controlflow.internal.Preconditions
private import semmle.code.java.controlflow.ControlFlowReachability
private import codeql.controlflow.SuccessorType
/** Gets an expression that may be `null`. */
Expr nullExpr() { result = nullExpr(_) }
/** Gets an expression that may be `null`. */
private Expr nullExpr(Expr reason) {
result instanceof NullLiteral and reason = result
or
result.(ChooseExpr).getAResultExpr() = nullExpr(reason)
or
result.(AssignExpr).getSource() = nullExpr(reason)
or
result.(CastExpr).getExpr() = nullExpr(reason)
or
result.(ImplicitCastExpr).getExpr() = nullExpr(reason)
or
result instanceof SafeCastExpr and reason = result
}
/** An expression of a boxed type that is implicitly unboxed. */
private predicate unboxed(Expr e) {
e.getType() instanceof BoxedType and
(
exists(ArrayAccess aa | aa.getIndexExpr() = e)
or
exists(ArrayCreationExpr ace | ace.getADimension() = e)
or
exists(LocalVariableDeclExpr decl |
decl.getVariable().getType() instanceof PrimitiveType and decl.getInit() = e
)
or
exists(AssignExpr assign |
assign.getDest().getType() instanceof PrimitiveType and assign.getSource() = e
)
or
exists(EqualityTest eq |
eq.getAnOperand() = e and eq.getAnOperand().getType() instanceof PrimitiveType
)
or
exists(BinaryExpr bin |
bin.getAnOperand() = e and
not bin instanceof EqualityTest and
not bin instanceof AssignExpr and
bin.getType() instanceof PrimitiveType
)
or
exists(UnaryExpr un | un.getOperand() = e)
or
exists(ChooseExpr cond | cond.getType() instanceof PrimitiveType | cond.getAResultExpr() = e)
or
exists(ConditionNode cond | cond.getCondition() = e)
or
exists(Parameter p | p.getType() instanceof PrimitiveType and p.getAnArgument() = e)
or
exists(ReturnStmt ret |
ret.getEnclosingCallable().getReturnType() instanceof PrimitiveType and ret.getExpr() = e
)
)
}
/** An expression that is being dereferenced. These are the points where `NullPointerException`s can occur. */
predicate dereference(Expr e) {
exists(EnhancedForStmt for | for.getExpr() = e)
or
exists(SynchronizedStmt synch | synch.getExpr() = e)
or
exists(SwitchStmt switch | switch.getExpr() = e and not switch.hasNullCase())
or
exists(SwitchExpr switch | switch.getExpr() = e and not switch.hasNullCase())
or
exists(FieldAccess fa, Field f | fa.getQualifier() = e and fa.getField() = f and not f.isStatic())
or
exists(MethodCall ma, Method m |
ma.getQualifier() = e and ma.getMethod() = m and not m.isStatic()
)
or
exists(ClassInstanceExpr cie | cie.getQualifier() = e)
or
exists(ArrayAccess aa | aa.getArray() = e)
or
exists(CastingExpr cast |
(cast instanceof CastExpr or cast instanceof ImplicitCastExpr) and
cast.getExpr() = e and
e.getType() instanceof BoxedType and
cast.getType() instanceof PrimitiveType
)
or
unboxed(e)
}
/**
* Gets the `ControlFlowNode` in which the given SSA variable is being dereferenced.
*
* The `VarAccess` is included for nicer error reporting.
*/
private ControlFlowNode varDereference(SsaDefinition v, VarAccess va) {
dereference(result.asExpr()) and
result.asExpr() = sameValue(v, va)
}
/**
* The first dereference of a variable in a given `BasicBlock`.
*/
private predicate firstVarDereferenceInBlock(BasicBlock bb, SsaDefinition v, VarAccess va) {
exists(ControlFlowNode n |
varDereference(v, va) = n and
n.getBasicBlock() = bb and
n =
min(ControlFlowNode n0, int i |
varDereference(v, _) = n0 and bb.getNode(i) = n0
|
n0 order by i
)
)
}
/** A variable suspected of being `null`. */
private predicate varMaybeNull(SsaDefinition v, ControlFlowNode node, string msg, Expr reason) {
// A variable compared to null might be null.
exists(Expr e |
reason = e and
msg = "as suggested by $@ null guard" and
guardSuggestsVarMaybeNull(e, v) and
node = v.getControlFlowNode() and
not v instanceof SsaPhiDefinition and
not clearlyNotNull(v) and
// Comparisons in finally blocks are excluded since missing exception edges in the CFG could otherwise yield FPs.
not exists(TryStmt try | try.getFinally() = e.getEnclosingStmt().getEnclosingStmt*()) and
(
e = any(ConditionalExpr c).getCondition().getAChildExpr*() or
not exists(MethodCall ma | ma.getAnArgument().getAChildExpr*() = e)
) and
// Don't use a guard as reason if there is a null assignment.
not v.(SsaExplicitWrite).getDefiningExpr().(VariableAssign).getSource() = nullExpr()
)
or
// A parameter might be null if there is a null argument somewhere.
exists(Parameter p, Expr arg |
v.(SsaParameterInit).getParameter() = p and
node = v.getControlFlowNode() and
p.getAnArgument() = arg and
reason = arg and
msg = "because of $@ null argument" and
arg = nullExpr() and
not arg.getEnclosingCallable().getEnclosingCallable*() instanceof TestMethod
)
or
// If the source of a variable is null then the variable may be null.
exists(VariableAssign def |
v.(SsaExplicitWrite).getDefiningExpr() = def and
def.getSource() = nullExpr(node.asExpr()) and
reason = def and
msg = "because of $@ assignment"
)
}
/** Gets an array or collection that contains at least one element. */
private Expr nonEmptyExpr() {
// An array creation with a known positive size is trivially non-empty.
result.(ArrayCreationExpr).getFirstDimensionSize() > 0
or
exists(SsaDefinition v |
// A use of an array variable is non-empty if...
result = v.getARead() and
v.getSourceVariable().getType() instanceof Array
|
// ...its definition is non-empty...
v.(SsaExplicitWrite).getValue() = nonEmptyExpr()
or
// ...or it is guarded by a condition proving its length to be non-zero.
exists(ConditionBlock cond, boolean branch, FieldAccess length |
cond.controls(result.getBasicBlock(), branch) and
cond.getCondition() = nonZeroGuard(length, branch) and
length.getField().hasName("length") and
length.getQualifier() = v.getARead()
)
)
or
exists(SsaDefinition v |
// A use of a Collection variable is non-empty if...
result = v.getARead() and
v.getSourceVariable().getType() instanceof CollectionType and
exists(ConditionBlock cond, boolean branch, Expr c |
// ...it is guarded by a condition...
cond.controls(result.getBasicBlock(), branch) and
// ...and it isn't modified in the scope of the condition...
forall(MethodCall ma, Method m |
m = ma.getMethod() and
ma.getQualifier() = v.getSourceVariable().getAnAccess() and
cond.controls(ma.getBasicBlock(), branch)
|
m instanceof CollectionQueryMethod
) and
cond.getCondition() = c
|
// ...and the condition proves that it is non-empty, either by using the `isEmpty` method...
c.(MethodCall).getMethod().hasName("isEmpty") and
branch = false and
c.(MethodCall).getQualifier() = v.getARead()
or
// ...or a check on its `size`.
exists(MethodCall size |
c = nonZeroGuard(size, branch) and
size.getMethod().hasName("size") and
size.getQualifier() = v.getARead()
)
)
)
}
/** The control flow edge that exits an enhanced for loop if the `Iterable` is empty. */
private predicate enhancedForEarlyExit(EnhancedForStmt for, ControlFlowNode n1, ControlFlowNode n2) {
n1.getASuccessor(any(EmptinessSuccessor t | t.isEmpty())) = n2 and
for.getExpr().getControlFlowNode() = n1
}
/** A control flow edge that cannot be taken. */
private predicate impossibleEdge(BasicBlock bb1, BasicBlock bb2) {
exists(EnhancedForStmt for |
enhancedForEarlyExit(for, bb1.getANode(), bb2.getANode()) and
for.getExpr() = nonEmptyExpr()
)
}
private module NullnessConfig implements ControlFlowReachability::ConfigSig {
predicate source(ControlFlowNode node, SsaDefinition def) { varMaybeNull(def, node, _, _) }
predicate sink(ControlFlowNode node, SsaDefinition def) { varDereference(def, _) = node }
predicate barrierValue(GuardValue gv) { gv.isNullness(false) }
predicate barrierEdge(BasicBlock bb1, BasicBlock bb2) { impossibleEdge(bb1, bb2) }
predicate uncertainFlow() { none() }
}
private module NullnessFlow = ControlFlowReachability::Flow<NullnessConfig>;
/**
* Holds if the dereference of `v` at `va` might be `null`.
*/
predicate nullDeref(SsaSourceVariable v, VarAccess va, string msg, Expr reason) {
exists(SsaDefinition origin, SsaDefinition ssa, ControlFlowNode src, ControlFlowNode sink |
varMaybeNull(origin, src, msg, reason) and
NullnessFlow::flow(src, origin, sink, ssa) and
ssa.getSourceVariable() = v and
varDereference(ssa, va) = sink
)
}
/**
* A dereference of a variable that is always `null`.
*/
predicate alwaysNullDeref(SsaSourceVariable v, VarAccess va) {
exists(BasicBlock bb, SsaDefinition ssa |
forall(SsaDefinition def | def = ssa.getAnUltimateDefinition() |
def.(SsaExplicitWrite).getValue() = alwaysNullExpr()
)
or
nullGuardControls(ssa, true, bb) and
not clearlyNotNull(ssa)
|
// Exclude fields as they might not have an accurate ssa representation.
not v.getVariable() instanceof Field and
firstVarDereferenceInBlock(bb, ssa, va) and
ssa.getSourceVariable() = v and
not nullGuardControls(ssa, false, bb)
)
}