Skip to content

Commit b6faaac

Browse files
hvitvedCopilot
andcommitted
Java: Adopt pattern-aware CFG/Guards support
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 576adf6 commit b6faaac

23 files changed

Lines changed: 619 additions & 192 deletions

File tree

‎java/ql/lib/semmle/code/java/ControlFlowGraph.qll‎

Lines changed: 57 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import java
88
private import codeql.controlflow.ControlFlowGraph
99
private import codeql.controlflow.SuccessorType
1010
private import controlflow.internal.Preconditions
11+
private import controlflow.internal.SwitchCases
1112

1213
private module Cfg0 = Make0<Location, Ast>;
1314

@@ -41,11 +42,17 @@ private module Ast implements AstSig<Location> {
4142
AstNode getChild(AstNode n, int index) {
4243
not skipControlFlow(result) and
4344
not skipControlFlow(n) and
45+
not isBindingTypeTest(n, _, _, result) and
4446
result.(Expr).isNthChildOf(n, index)
4547
or
4648
result.(Stmt).isNthChildOf(n, index)
4749
or
4850
result = n.(SwitchCase).getRuleExpression() and index = -1
51+
or
52+
isBindingTypeTest(_, n, _, result) and
53+
index = 0
54+
or
55+
isBindingTypeTest(n, result, index, _)
4956
}
5057

5158
Callable getEnclosingCallable(AstNode node) {
@@ -177,10 +184,7 @@ private module Ast implements AstSig<Location> {
177184

178185
class Case extends AstNode instanceof J::SwitchCase {
179186
/** Gets the pattern being matched by this case at the specified (zero-based) `index`. */
180-
AstNode getPattern(int index) {
181-
result = this.(PatternCase).getPattern(index) or
182-
result = this.(ConstCase).getValue(index)
183-
}
187+
AstNode getPattern(int index) { result = getSwitchCasePattern(this, index) }
184188

185189
/** Gets the guard expression of this case, if any. */
186190
Expr getGuard() { result = this.(PatternCase).getGuard() }
@@ -241,12 +245,45 @@ private module Ast implements AstSig<Location> {
241245
boolean getValue() { result = this.getBooleanValue() }
242246
}
243247

248+
final class Pattern = PatternImpl;
249+
250+
abstract private class PatternImpl extends AstNode { }
251+
252+
private class NonBindingPattern extends PatternImpl {
253+
NonBindingPattern() {
254+
isBindingTypeTest(_, this, _, _)
255+
or
256+
this instanceof RecordPatternExpr
257+
}
258+
}
259+
260+
class AndPattern extends Pattern {
261+
AndPattern() { none() }
262+
}
263+
264+
class OrPattern extends Pattern {
265+
OrPattern() { none() }
266+
}
267+
268+
class NotPattern extends Pattern {
269+
NotPattern() { none() }
270+
271+
Pattern getNegatedPattern() { none() }
272+
}
273+
274+
class BindingPattern extends PatternImpl {
275+
BindingPattern() {
276+
isBindingTypeTest(_, _, _, this)
277+
or
278+
// needed for cases like `A(var x)` where there is no type test
279+
this = any(RecordPatternExpr rpe).getSubPattern(_).(LocalVariableDeclExpr)
280+
}
281+
}
282+
244283
final private class FinalInstanceOfExpr = J::InstanceOfExpr;
245284

246285
class PatternMatchExpr extends FinalInstanceOfExpr {
247-
PatternMatchExpr() { this.isPattern() }
248-
249-
AstNode getPattern() { result = super.getPattern() }
286+
AstNode getPattern() { result = getInstanceOfExprPattern(this) }
250287
}
251288
}
252289

@@ -532,6 +569,17 @@ private module Input implements InputSig1, InputSig2 {
532569
c.(J::PatternCase).getAPattern().getType() instanceof TypeObject
533570
}
534571

572+
predicate patternIsExhaustive(Ast::Pattern pattern) {
573+
pattern.(TypeAccess).getType() instanceof TypeObject
574+
or
575+
exists(PatternExpr sub | any(RecordPatternExpr rpe).subPatternIsUnrestricted(sub, _) |
576+
isBindingTypeTest(_, pattern, _, sub)
577+
or
578+
not sub instanceof LocalVariableDeclExpr and
579+
pattern = sub
580+
)
581+
}
582+
535583
private newtype TLabel =
536584
TJavaLabel(string l) { exists(LabeledStmt lbl | l = lbl.getLabel()) } or
537585
TYield()
@@ -619,10 +667,10 @@ private module Input implements InputSig1, InputSig2 {
619667
n1.isBefore(assertstmt) and
620668
n2.isBefore(assertstmt.getExpr())
621669
or
622-
n1.isAfterValue(assertstmt.getExpr(), any(BooleanSuccessor s | s.getValue() = true)) and
670+
n1.isAfterTrue(assertstmt.getExpr()) and
623671
n2.isAfter(assertstmt)
624672
or
625-
n1.isAfterValue(assertstmt.getExpr(), any(BooleanSuccessor s | s.getValue() = false)) and
673+
n1.isAfterFalse(assertstmt.getExpr()) and
626674
(
627675
n2.isBefore(assertstmt.getMessage())
628676
or

‎java/ql/lib/semmle/code/java/Expr.qll‎

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2761,6 +2761,23 @@ class RecordPatternExpr extends Expr, @recordpatternexpr {
27612761
*/
27622762
PatternExpr getSubPattern(int i) { result.isNthChildOf(this, i) }
27632763

2764+
/**
2765+
* Holds if the `i`th sub pattern `subPattern` of this record pattern matches
2766+
* any value of its type.
2767+
*
2768+
* This is used to determine if this record pattern matches any record of its type.
2769+
*/
2770+
predicate subPatternIsUnrestricted(PatternExpr subPattern, int idx) {
2771+
subPattern = this.getSubPattern(idx) and
2772+
subPattern.getType() =
2773+
this.getType().(Record).getCanonicalConstructor().getParameter(idx).getType() and
2774+
(
2775+
subPattern instanceof LocalVariableDeclExpr
2776+
or
2777+
subPattern.(RecordPatternExpr).isUnrestricted()
2778+
)
2779+
}
2780+
27642781
/**
27652782
* Holds if this record pattern matches any record of its type.
27662783
*
@@ -2769,13 +2786,7 @@ class RecordPatternExpr extends Expr, @recordpatternexpr {
27692786
*/
27702787
predicate isUnrestricted() {
27712788
forall(PatternExpr subPattern, int idx | subPattern = this.getSubPattern(idx) |
2772-
subPattern.getType() =
2773-
this.getType().(Record).getCanonicalConstructor().getParameter(idx).getType() and
2774-
(
2775-
subPattern instanceof LocalVariableDeclExpr
2776-
or
2777-
subPattern.(RecordPatternExpr).isUnrestricted()
2778-
)
2789+
this.subPatternIsUnrestricted(subPattern, idx)
27792790
)
27802791
}
27812792

‎java/ql/lib/semmle/code/java/controlflow/Guards.qll‎

Lines changed: 47 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -157,15 +157,48 @@ private module GuardsInput implements SharedGuards::InputSig<Location, ControlFl
157157
decl = v.getDefiningExpr() and
158158
this = v.getARead()
159159
)
160+
or
161+
(this instanceof TypeAccess or this instanceof RecordPatternExpr) and
162+
(
163+
this = any(Case c).getAPattern()
164+
or
165+
this = any(PatternMatchExpr pm).getPattern()
166+
)
160167
}
161168
}
162169

163170
class Case extends ExprParent instanceof J::SwitchCase {
164171
Expr getSwitchExpr() { result = super.getSelectorExpr() }
165172

166-
AstNode getAPattern() {
167-
result = this.(ConstCase).getValue(_) or result = this.(J::PatternCase).getAPattern()
168-
}
173+
AstNode getAPattern() { result = getSwitchCasePattern(this, _) }
174+
}
175+
176+
class Pattern extends AstNode {
177+
Pattern() { none() }
178+
}
179+
180+
class AndPattern extends Pattern {
181+
AndPattern() { none() }
182+
183+
Pattern getAnOperand() { none() }
184+
}
185+
186+
class OrPattern extends Pattern {
187+
OrPattern() { none() }
188+
189+
Pattern getAnOperand() { none() }
190+
}
191+
192+
class NotPattern extends Pattern {
193+
NotPattern() { none() }
194+
195+
Pattern getNegatedPattern() { none() }
196+
}
197+
198+
final private class FinalInstanceOfExpr = J::InstanceOfExpr;
199+
200+
class PatternMatchExpr extends FinalInstanceOfExpr {
201+
AstNode getPattern() { result = getInstanceOfExprPattern(this) }
169202
}
170203

171204
class AndExpr extends BinaryExpr {
@@ -280,8 +313,6 @@ private module LogicInputCommon {
280313
predicate additionalNullCheck(
281314
GuardsImpl::PreGuard guard, GuardValue val, GuardsInput::Expr e, boolean isNull
282315
) {
283-
guard.(InstanceOfExpr).getExpr() = e and val.asBooleanValue() = true and isNull = false
284-
or
285316
exists(MethodCall call |
286317
call = guard and
287318
call.getAnArgument() = e and
@@ -369,14 +400,6 @@ final class Guard extends Guards_v3::Guard {
369400
result = this.(SwitchCase).getEnclosingCallable()
370401
}
371402

372-
/**
373-
* DEPRECATED: Use `appliesTypeTest(Expr testedExpr, Type testedType, boolean restricted, GuardValue val)` instead.
374-
*/
375-
deprecated predicate appliesTypeTest(Expr testedExpr, Type testedType, boolean restricted) {
376-
this.appliesTypeTest(testedExpr, testedType, restricted,
377-
any(GuardValue gv | gv.asBooleanValue() = true))
378-
}
379-
380403
/**
381404
* Holds if this guard tests whether `testedExpr` has type `testedType` upon evaluating to `val`.
382405
*
@@ -388,29 +411,21 @@ final class Guard extends Guards_v3::Guard {
388411
*/
389412
predicate appliesTypeTest(Expr testedExpr, Type testedType, boolean restricted, GuardValue val) {
390413
(
391-
exists(InstanceOfExpr ioe | this = ioe |
392-
testedExpr = ioe.getExpr() and
393-
testedType = ioe.getSyntacticCheckedType() and
394-
val.asBooleanValue() = true
414+
exists(InstanceOfExpr ioe |
415+
this = getInstanceOfExprPattern(ioe) and
416+
testedExpr = ioe.getExpr()
395417
)
396418
or
397-
exists(PatternCase pc, PatternExpr pat | this = pat |
398-
pc.getSelectorExpr() = testedExpr and
399-
pc.getAPattern() = pat and
400-
testedType = pat.getType() and
401-
val.isMatch()
419+
exists(PatternCase pc |
420+
this = getSwitchCasePattern(pc, _) and
421+
pc.getSelectorExpr() = testedExpr
402422
)
403423
) and
404-
(
405-
if
406-
exists(RecordPatternExpr rpe |
407-
rpe = [this.(InstanceOfExpr).getPattern(), this.(PatternExpr)]
408-
|
409-
not rpe.isUnrestricted()
410-
)
411-
then restricted = true
412-
else restricted = false
413-
)
424+
testedType = this.(Expr).getType() and
425+
val.isMatch() and
426+
if this = any(RecordPatternExpr rpe | not rpe.isUnrestricted())
427+
then restricted = true
428+
else restricted = false
414429
}
415430
}
416431

‎java/ql/lib/semmle/code/java/controlflow/internal/SwitchCases.qll‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,43 @@ PatternCase getNextPatternCase(PatternCase pc) {
2929
int lastCaseIndex(SwitchBlock switch) {
3030
result = max(int i | any(SwitchCase c).isNthCaseOf(switch, i))
3131
}
32+
33+
/**
34+
* Holds if the `i`th child of `parent` performs a type test at `typeTest`, and when
35+
* successful binds the value at `lvd`.
36+
*
37+
* In this case want the CFG to first visit the type test, and only if it succeeds do
38+
* we proceed to bind the value at `lvd`.
39+
*/
40+
predicate isBindingTypeTest(Element parent, Expr typeTest, int i, LocalVariableDeclExpr lvd) {
41+
parent = any(InstanceOfExpr ioe | lvd = ioe.getPattern() and typeTest = ioe.getTypeName()) and
42+
i = 0
43+
or
44+
exists(RecordPatternExpr rpe |
45+
rpe = parent and
46+
lvd = rpe.getSubPattern(i) and
47+
typeTest.isNthChildOf(rpe, -i - 1)
48+
)
49+
or
50+
lvd = parent.(PatternCase).getPattern(i) and
51+
typeTest = lvd.getTypeAccess()
52+
}
53+
54+
Expr getSwitchCasePattern(SwitchCase sc, int index) {
55+
isBindingTypeTest(sc, result, index, _)
56+
or
57+
not isBindingTypeTest(sc, _, _, result) and
58+
result = sc.(PatternCase).getPattern(index)
59+
or
60+
result = sc.(ConstCase).getValue(index)
61+
}
62+
63+
Expr getInstanceOfExprPattern(InstanceOfExpr ioe) {
64+
isBindingTypeTest(ioe, result, _, _)
65+
or
66+
not isBindingTypeTest(ioe, _, _, _) and
67+
result = ioe.getPattern()
68+
or
69+
not ioe.isPattern() and
70+
result = ioe.getTypeName()
71+
}

‎java/ql/lib/semmle/code/java/dataflow/ModulusAnalysis.qll‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ private predicate valueFlowStepSsa(SsaVariable v, SsaReadPosition pos, Expr e, i
1919
exists(Guard guard, boolean testIsTrue |
2020
pos.hasReadOfVar(v) and
2121
guard = eqFlowCond(v, e, delta, true, testIsTrue) and
22-
guardControlsSsaRead(guard, pos, testIsTrue)
22+
guardControlsSsaRead(guard, pos, any(GuardValue gv | gv.asBooleanValue() = testIsTrue))
2323
)
2424
}
2525

@@ -69,14 +69,14 @@ private Expr modExpr(Expr arg, int mod) {
6969
* its `testIsTrue` branch.
7070
*/
7171
private Guard moduloCheck(SsaVariable v, int val, int mod, boolean testIsTrue) {
72-
exists(Expr rem, ConstantIntegerExpr c, int r, boolean polarity |
72+
exists(Expr rem, ConstantIntegerExpr c, int r, GuardValue polarity |
7373
result.isEquality(rem, c, polarity) and
7474
c.getIntValue() = r and
7575
rem = modExpr(v.getAUse(), mod) and
7676
(
77-
testIsTrue = polarity and val = r
77+
testIsTrue = polarity.asBooleanValue() and val = r
7878
or
79-
testIsTrue = polarity.booleanNot() and
79+
testIsTrue = polarity.asBooleanValue().booleanNot() and
8080
mod = 2 and
8181
val = 1 - r and
8282
(r = 0 or r = 1)
@@ -91,7 +91,7 @@ private predicate moduloGuardedRead(SsaVariable v, SsaReadPosition pos, int val,
9191
exists(Guard guard, boolean testIsTrue |
9292
pos.hasReadOfVar(v) and
9393
guard = moduloCheck(v, val, mod, testIsTrue) and
94-
guardControlsSsaRead(guard, pos, testIsTrue)
94+
guardControlsSsaRead(guard, pos, any(GuardValue gv | gv.asBooleanValue() = testIsTrue))
9595
)
9696
}
9797

‎java/ql/lib/semmle/code/java/dataflow/NullGuards.qll‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -91,9 +91,9 @@ Expr clearlyNotNullExpr(Expr reason) {
9191
(reason = r1 or reason = r2)
9292
)
9393
or
94-
exists(SsaDefinition v, boolean branch, VarRead rval, Guard guard |
94+
exists(SsaDefinition v, GuardValue branch, VarRead rval, Guard guard |
9595
guard = directNullGuard(v, branch, false) and
96-
guard.controls(rval.getBasicBlock(), branch) and
96+
guard.valueControls(rval.getBasicBlock(), branch) and
9797
reason = guard and
9898
rval = v.getARead() and
9999
result = rval and
@@ -192,8 +192,8 @@ predicate nullCheckMethod(Method m, boolean branch, boolean isnull) {
192192
* If `result` evaluates to `branch`, then `e` is guaranteed to be null if `isnull`
193193
* is true, and non-null if `isnull` is false.
194194
*/
195-
Expr basicNullGuard(Expr e, boolean branch, boolean isnull) {
196-
Guards_v3::nullGuard(result, any(GuardValue v | v.asBooleanValue() = branch), e, isnull)
195+
Expr basicNullGuard(Expr e, GuardValue branch, boolean isnull) {
196+
Guards_v3::nullGuard(result, branch, e, isnull)
197197
}
198198

199199
/**
@@ -202,7 +202,7 @@ Expr basicNullGuard(Expr e, boolean branch, boolean isnull) {
202202
* If `result` evaluates to `branch`, then `v` is guaranteed to be null if `isnull`
203203
* is true, and non-null if `isnull` is false.
204204
*/
205-
Expr directNullGuard(SsaDefinition v, boolean branch, boolean isnull) {
205+
Expr directNullGuard(SsaDefinition v, GuardValue branch, boolean isnull) {
206206
result = basicNullGuard(sameValue(v, _), branch, isnull)
207207
}
208208

‎java/ql/lib/semmle/code/java/dataflow/Nullness.qll‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ private import semmle.code.java.controlflow.Guards
1515
private import IntegerGuards
1616
private import NullGuards
1717
private import semmle.code.java.Collections
18-
private import semmle.code.java.controlflow.internal.Preconditions
1918
private import semmle.code.java.controlflow.ControlFlowReachability
2019
private import codeql.controlflow.SuccessorType
2120

0 commit comments

Comments
 (0)