Repository navigation
Expand file tree
/
Copy pathTypeFlow.qll
More file actions
493 lines (442 loc) · 16.1 KB
/
Copy pathTypeFlow.qll
File metadata and controls
493 lines (442 loc) · 16.1 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
/**
* Provides predicates for giving improved type bounds on expressions.
*
* An inferred bound on the runtime type of an expression can be either exact
* or merely an upper bound. Bounds are only reported if they are likely to be
* better than the static bound, which can happen either if an inferred exact
* type has a subtype or if an inferred upper bound passed through at least one
* explicit or implicit cast that lost type information.
*/
overlay[local?]
module;
import java as J
private import semmle.code.java.dispatch.VirtualDispatch
private import semmle.code.java.dataflow.internal.BaseSSA as Base
private import semmle.code.java.controlflow.Guards
private import codeql.typeflow.TypeFlow
private import codeql.typeflow.UniversalFlow as UniversalFlow
/** Gets `t` if it is a `RefType` or the boxed type if `t` is a primitive type. */
private RefType boxIfNeeded(J::Type t) {
t.(PrimitiveType).getBoxedType() = result or
result = t
}
/** Provides the input types and predicates for instantiation of `UniversalFlow`. */
module FlowStepsInput implements UniversalFlow::UniversalFlowInput<Location> {
private newtype TFlowNode =
TField(Field f) { not f.getType() instanceof PrimitiveType } or
TSsa(Base::SsaDefinition ssa) { not ssa.getSourceVariable().getType() instanceof PrimitiveType } or
TExpr(Expr e) or
TMethod(Method m) { not m.getReturnType() instanceof PrimitiveType }
/**
* A `Field`, `BaseSsaVariable`, `Expr`, or `Method`.
*/
class FlowNode extends TFlowNode {
/** Gets a textual representation of this element. */
string toString() {
result = this.asField().toString() or
result = this.asSsa().toString() or
result = this.asExpr().toString() or
result = this.asMethod().toString()
}
/** Gets the source location for this element. */
Location getLocation() {
result = this.asField().getLocation() or
result = this.asSsa().getLocation() or
result = this.asExpr().getLocation() or
result = this.asMethod().getLocation()
}
/** Gets the field corresponding to this node, if any. */
Field asField() { this = TField(result) }
/** Gets the SSA variable corresponding to this node, if any. */
Base::SsaDefinition asSsa() { this = TSsa(result) }
/** Gets the expression corresponding to this node, if any. */
Expr asExpr() { this = TExpr(result) }
/** Gets the method corresponding to this node, if any. */
Method asMethod() { this = TMethod(result) }
/** Gets the type of this node. */
RefType getType() {
result = this.asField().getType() or
result = this.asSsa().getSourceVariable().getType() or
result = boxIfNeeded(this.asExpr().getType()) or
result = this.asMethod().getReturnType()
}
}
private class FlowNodeElement extends Element {
FlowNodeElement() {
this instanceof Field or
this instanceof Expr or
this instanceof Method
}
}
private predicate id(FlowNodeElement x, FlowNodeElement y) { x = y }
private predicate idOf(FlowNodeElement x, int y) = equivalenceRelation(id/2)(x, y)
int getFlowNodeId(FlowNode n) {
n =
rank[result](FlowNode n0, int a, int b |
a = 0 and
idOf(n0.asField(), b)
or
// no case for `n0.asSsa()`; here we rely on the built-in location-based ranking
a = 1 and
idOf(n0.asExpr(), b)
or
a = 2 and
idOf(n0.asMethod(), b)
|
n0 order by a, b
)
}
private SrcCallable viableCallable_v1(Call c) {
result = viableImpl_v1(c)
or
c instanceof ConstructorCall and result = c.getCallee().getSourceDeclaration()
}
/**
* Holds if `arg` is an argument for the parameter `p` in a sufficiently
* private callable that the closed-world assumption applies.
*/
private predicate privateParamArg(Parameter p, Argument arg) {
exists(SrcCallable c, Call call |
c = p.getCallable() and
not c.isImplicitlyPublic() and
not p.isVarargs() and
c = viableCallable_v1(call) and
call.getArgument(pragma[only_bind_into](pragma[only_bind_out](p.getPosition()))) = arg
)
}
/**
* Holds if data can flow from `n1` to `n2` in one step.
*
* For a given `n2`, this predicate must include all possible `n1` that can flow to `n2`.
*/
predicate step(FlowNode n1, FlowNode n2) {
n2.asExpr().(ChooseExpr).getAResultExpr() = n1.asExpr()
or
exists(Field f, Expr e |
f = n2.asField() and
f.getAnAssignedValue() = e and
e = n1.asExpr() and
not e.(FieldAccess).getField() = f
)
or
n2.asSsa().(Base::SsaPhiDefinition).getAnUltimateDefinition() = n1.asSsa()
or
exists(ReturnStmt ret |
n2.asMethod() = ret.getEnclosingCallable() and ret.getExpr() = n1.asExpr()
)
or
viableImpl_v1(n2.asExpr()) = n1.asMethod()
or
exists(Argument arg, Parameter p |
privateParamArg(p, arg) and
n1.asExpr() = arg and
n2.asSsa().(Base::SsaParameterInit).getParameter() = p and
// skip trivial recursion
not arg = n2.asSsa().getARead()
)
or
n2.asExpr() = n1.asField().getAnAccess()
or
n2.asExpr() = n1.asSsa().getARead()
or
n2.asExpr().(CastingExpr).getExpr() = n1.asExpr() and
not n2.asExpr().getType() instanceof PrimitiveType
or
n2.asExpr().(AssignExpr).getSource() = n1.asExpr() and
not n2.asExpr().getType() instanceof PrimitiveType
or
n2.asSsa().(Base::SsaExplicitWrite).getDefiningExpr().(VariableAssign).getSource() = n1.asExpr()
or
n2.asSsa().(Base::SsaCapturedDefinition).captures(n1.asSsa())
or
n2.asExpr().(NotNullExpr).getOperand() = n1.asExpr()
}
/**
* Holds if `null` is the only value that flows to `n`.
*/
predicate isNullValue(FlowNode n) {
n.asExpr() instanceof NullLiteral
or
exists(LocalVariableDeclExpr decl |
n.asSsa().(Base::SsaExplicitWrite).getDefiningExpr() = decl and
not decl.hasImplicitInit() and
not exists(decl.getInitOrPatternSource())
)
}
predicate isExcludedFromNullAnalysis(FlowNode n) {
// Fields that are never assigned a non-null value are probably set by
// reflection and are thus not always null.
exists(n.asField())
}
}
private module Input implements TypeFlowInput<Location> {
import FlowStepsInput
class TypeFlowNode = FlowNode;
predicate getTypeFlowNodeId = FlowStepsInput::getFlowNodeId/1;
predicate isExcludedFromNullAnalysis = FlowStepsInput::isExcludedFromNullAnalysis/1;
class Type = RefType;
predicate exactTypeBase(TypeFlowNode n, RefType t) {
exists(ClassInstanceExpr e |
n.asExpr() = e and
e.getType() = t and
not e instanceof FunctionalExpr and
exists(SrcRefType sub | sub.getASourceSupertype() = t.getSourceDeclaration())
)
}
/**
* Holds if `n` occurs in a position where type information might be discarded;
* `t1` is the type of `n`, `t1e` is the erasure of `t1`, `t2` is the type of
* the implicit or explicit cast, and `t2e` is the erasure of `t2`.
*/
pragma[nomagic]
private predicate upcastCand(TypeFlowNode n, RefType t1, RefType t1e, RefType t2, RefType t2e) {
exists(TypeFlowNode next | step(n, next) |
n.getType() = t1 and
next.getType() = t2 and
t1.getErasure() = t1e and
t2.getErasure() = t2e and
t1 != t2
)
}
/** Holds if `n` occurs in a position where type information is discarded. */
private predicate upcast(TypeFlowNode n, RefType t1) {
exists(RefType t1e, RefType t2, RefType t2e | upcastCand(n, t1, t1e, t2, t2e) |
t1e.getASourceSupertype+() = t2e
or
t1e = t2e and
unbound(t2) and
not unbound(t1)
or
t1e = t2e and
exists(int pos |
partiallyUnbound(t2, pos) and
not partiallyUnbound(t1, pos) and
not unbound(t1)
)
)
}
/** Gets the element type of an array or subtype of `Iterable`. */
private J::Type elementType(RefType t) {
result = t.(Array).getComponentType()
or
exists(ParameterizedType it |
it.getSourceDeclaration().hasQualifiedName("java.lang", "Iterable") and
result = it.getATypeArgument() and
t.extendsOrImplements*(it)
)
}
private predicate upcastEnhancedForStmtAux(
Base::SsaExplicitWrite v, RefType t, RefType t1, RefType t2
) {
exists(EnhancedForStmt for |
for.getVariable() = v.getDefiningExpr() and
v.getSourceVariable().getType().getErasure() = t2 and
t = boxIfNeeded(elementType(for.getExpr().getType())) and
t.getErasure() = t1
)
}
/**
* Holds if `v` is the iteration variable of an enhanced for statement, `t` is
* the type of the elements being iterated over, and this type is more precise
* than the type of `v`.
*/
private predicate upcastEnhancedForStmt(Base::SsaExplicitWrite v, RefType t) {
exists(RefType t1, RefType t2 |
upcastEnhancedForStmtAux(v, t, t1, t2) and
t1.getASourceSupertype+() = t2
)
}
private predicate downcastSuccessorAux(
CastingExpr cast, Base::SsaDefinition v, RefType t, RefType t1, RefType t2
) {
cast.getExpr() = v.getARead() and
t = cast.getType() and
t1 = t.getErasure() and
t2 = v.getSourceVariable().getType().getErasure()
}
/**
* Holds if `va` is an access to a value that has previously been downcast to `t`.
*/
private predicate downcastSuccessor(VarAccess va, RefType t) {
exists(CastingExpr cast, Base::SsaDefinition v, RefType t1, RefType t2 |
downcastSuccessorAux(pragma[only_bind_into](cast), v, t, t1, t2) and
t1.getASourceSupertype+() = t2 and
va = v.getARead() and
dominates(cast.getControlFlowNode(), va.getControlFlowNode()) and
dominates(cast.getControlFlowNode().getANormalSuccessor(), va.getControlFlowNode())
)
}
/**
* Holds if `va` is an access to a value that is guarded by `instanceof t` or `case e t`.
*/
private predicate typeTestGuarded(VarAccess va, RefType t) {
exists(Guard typeTest, Base::SsaDefinition v |
typeTest.appliesTypeTest(v.getARead(), t, _) and
va = v.getARead() and
guardControls_v1(typeTest, va.getBasicBlock(), true)
)
}
/**
* Holds if `aa` is an access to a value that is guarded by `instanceof t` or `case e t`.
*/
private predicate arrayTypeTestGuarded(ArrayAccess aa, RefType t) {
exists(Guard typeTest, Base::SsaDefinition v1, Base::SsaDefinition v2, ArrayAccess aa1 |
typeTest.appliesTypeTest(aa1, t, _) and
aa1.getArray() = v1.getARead() and
aa1.getIndexExpr() = v2.getARead() and
aa.getArray() = v1.getARead() and
aa.getIndexExpr() = v2.getARead() and
guardControls_v1(typeTest, aa.getBasicBlock(), true)
)
}
/**
* Holds if `t` is the type of the `this` value corresponding to the the
* `SuperAccess`. As the `SuperAccess` expression has the type of the supertype,
* the type `t` is a stronger type bound.
*/
private predicate superAccess(SuperAccess sup, RefType t) {
sup.isEnclosingInstanceAccess(t)
or
sup.isOwnInstanceAccess() and
t = sup.getEnclosingCallable().getDeclaringType()
}
/**
* Holds if `n` has type `t` and this information is discarded, such that `t`
* might be a better type bound for nodes where `n` flows to. This might include
* multiple bounds for a single node.
*/
predicate typeFlowBaseCand(TypeFlowNode n, RefType t) {
exists(RefType srctype |
upcast(n, srctype) or
upcastEnhancedForStmt(n.asSsa(), srctype) or
downcastSuccessor(n.asExpr(), srctype) or
typeTestGuarded(n.asExpr(), srctype) or
arrayTypeTestGuarded(n.asExpr(), srctype) or
n.asExpr().(FunctionalExpr).getConstructedType() = srctype or
superAccess(n.asExpr(), srctype)
|
t = srctype.(BoundedType).getAnUltimateUpperBoundType()
or
t = srctype and not srctype instanceof BoundedType
)
}
/** Holds if `ioe` checks `v` and its true-successor is `bb`. */
private predicate instanceofTrueSuccessor(InstanceOfExpr ioe, BasicBlock bb, Base::SsaDefinition v) {
ioe.getExpr() = v.getARead() and
exists(ConditionBlock cb | cb.getCondition() = ioe and cb.getTestSuccessor(true) = bb)
}
/**
* Holds if `bb` is disjunctively guarded by one (`trivial = true`) or more
* (`trivial = false`) `instanceof` tests on `v`.
*/
private predicate instanceofDisjunction(BasicBlock bb, Base::SsaDefinition v, boolean trivial) {
exists(int preds |
strictcount(bb.getAPredecessor()) = preds and
strictcount(InstanceOfExpr ioe | instanceofTrueSuccessor(ioe, bb, v)) = preds and
if preds > 1 then trivial = false else trivial = true
)
or
strictcount(bb.getAPredecessor()) = 2 and
exists(BasicBlock pred1, BasicBlock pred2 |
pred1 != pred2 and
pred1 = bb.getAPredecessor() and
pred2 = bb.getAPredecessor() and
instanceofDisjunction(pred1, v, _) and
instanceofDisjunction(pred2, v, _) and
trivial = false
)
}
/**
* Holds if `bb` is disjunctively guarded by one or more `instanceof` tests
* on `v`, and `ioe` is one of those tests.
*/
private predicate instanceofDisjunct(InstanceOfExpr ioe, BasicBlock bb, Base::SsaDefinition v) {
instanceofDisjunction(bb, v, _) and
(
instanceofTrueSuccessor(ioe, bb, v)
or
exists(BasicBlock pred | pred = bb.getAPredecessor() and instanceofDisjunct(ioe, pred, v))
)
}
/**
* Holds if `n` is a value that is guarded by a disjunction of
* `instanceof t_i` where `t` is one of those `t_i`.
*/
predicate instanceofDisjunctionGuarded(TypeFlowNode n, RefType t) {
exists(BasicBlock bb, InstanceOfExpr ioe, Base::SsaDefinition v, VarAccess va |
instanceofDisjunction(bb, v, false) and
bb.dominates(va.getBasicBlock()) and
va = v.getARead() and
instanceofDisjunct(ioe, bb, v) and
t = ioe.getSyntacticCheckedType() and
n.asExpr() = va
)
}
private predicate unconstrained(BoundedType t) {
t.(Wildcard).isUnconstrained()
or
t.getUpperBoundType() instanceof TypeObject and
not t.(Wildcard).hasLowerBound()
or
unconstrained(t.getUpperBoundType())
or
unconstrained(t.(Wildcard).getLowerBoundType())
}
/** Holds if `t` is a raw type or parameterised type with unrestricted type arguments. */
predicate unbound(RefType t) {
t instanceof RawType
or
exists(ParameterizedType pt | pt = t |
forex(RefType arg | arg = pt.getATypeArgument() | unconstrained(arg))
)
}
/** Holds if `t` is a parameterised type with unrestricted type argument at position `pos`. */
private predicate partiallyUnbound(ParameterizedType t, int pos) {
unconstrained(t.getTypeArgument(pos))
}
Type getErasure(Type t) { result = t.getErasure() }
Type getAnAncestor(Type sub) { result = sub.getAnAncestor() }
RefType getSourceDeclaration(Type t) { result = t.getSourceDeclaration() }
}
cached
private module TypeFlowBounds {
private module TypeFlow = Make<Location, Input>;
/**
* Holds if the runtime type of `f` is bounded by `t` and if this bound is
* likely to be better than the static type of `f`. The flag `exact` indicates
* whether `t` is an exact bound or merely an upper bound.
*/
cached
predicate fieldTypeFlow(Field f, RefType t, boolean exact) {
exists(Input::TypeFlowNode n |
n.asField() = f and
TypeFlow::bestTypeFlow(n, t, exact)
)
}
/**
* Holds if the runtime type of `e` is bounded by `t` and if this bound is
* likely to be better than the static type of `e`. The flag `exact` indicates
* whether `t` is an exact bound or merely an upper bound.
*/
cached
predicate exprTypeFlow(Expr e, RefType t, boolean exact) {
exists(Input::TypeFlowNode n |
n.asExpr() = e and
TypeFlow::bestTypeFlow(n, t, exact)
)
}
/**
* Holds if the runtime type of `e` is bounded by a union type and if this
* bound is likely to be better than the static type of `e`. The union type is
* made up of the types `t` related to `e` by this predicate, and the flag
* `exact` indicates whether `t` is an exact bound or merely an upper bound.
*/
cached
predicate exprUnionTypeFlow(Expr e, RefType t, boolean exact) {
exists(Input::TypeFlowNode n |
n.asExpr() = e and
TypeFlow::bestUnionType(n, t, exact)
)
}
}
import TypeFlowBounds