Skip to content

Commit 576adf6

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

41 files changed

Lines changed: 2167 additions & 1803 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎csharp/ql/lib/semmle/code/csharp/Assignable.qll‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,7 @@ module AssignableInternal {
270270
or
271271
def = TAddressOfDefinition(result)
272272
or
273-
def = TPatternDefinition(result)
273+
def = TPatternDefinition(any(LocalVariablePatternDecl decl | decl.getAccess() = result))
274274
or
275275
def = TAssignOperationDefinition(result)
276276
or

‎csharp/ql/lib/semmle/code/csharp/controlflow/ControlFlowGraph.qll‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,19 @@ private module Input implements InputSig1, InputSig2 {
137137

138138
predicate matchAll(Ast::Case c) { c.(SwitchCaseExpr).matchesAll() }
139139

140+
predicate patternPerformsTest(Ast::Pattern pattern) {
141+
not pattern instanceof RecursivePatternExpr
142+
}
143+
144+
predicate patternIsExhaustive(Ast::Pattern pattern) {
145+
pattern instanceof DiscardPatternExpr
146+
or
147+
pattern = any(RecursivePatternExpr rpe).getVariableDeclExpr()
148+
or
149+
// `var x` always matches, also when the value is `null`
150+
pattern.(VariablePatternExpr).isImplicitlyTyped()
151+
}
152+
140153
private newtype TLabel =
141154
TLblGoto(string label) { any(GotoLabelStmt goto).getLabel() = label } or
142155
TLblSwitchCase(string value) { any(GotoCaseStmt goto).getLabel() = value } or

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

Lines changed: 52 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,41 @@ private module GuardsInput implements SharedGuards::InputSig<Location, ControlFl
8686
AstNode getAPattern() { super.getPattern() = result }
8787
}
8888

89+
final private class FinalIsExpr = CS::IsExpr;
90+
91+
class Pattern = CS::PatternExpr;
92+
93+
class AndPattern = CS::AndPatternExpr;
94+
95+
class OrPattern = CS::OrPatternExpr;
96+
97+
class NotPattern extends CS::NotPatternExpr {
98+
Pattern getNegatedPattern() { result = this.getPattern() }
99+
}
100+
101+
class PatternMatchExpr extends FinalIsExpr {
102+
AstNode getPattern() { result = super.getPattern() }
103+
}
104+
105+
predicate nonDeconstructingSubPattern(AstNode pattern, AstNode subPattern) {
106+
subPattern = pattern.(AndPatternExpr).getAnOperand()
107+
or
108+
subPattern = pattern.(OrPatternExpr).getAnOperand()
109+
or
110+
subPattern = pattern.(NotPatternExpr).getPattern()
111+
or
112+
pattern =
113+
any(RecursivePatternExpr rpe |
114+
subPattern =
115+
[
116+
rpe.getTypeAccess().(AstNode), //
117+
rpe.getVariableDeclExpr(), //
118+
rpe.getPositionalPatterns(), //
119+
rpe.getPropertyPatterns()
120+
]
121+
)
122+
}
123+
89124
abstract private class BinExpr extends BinaryOperation { }
90125

91126
class AndExpr extends BinExpr {
@@ -125,18 +160,6 @@ private module GuardsInput implements SharedGuards::InputSig<Location, ControlFl
125160
or
126161
ct.getComparisonKind().isInequality() and polarity = false
127162
)
128-
or
129-
exists(IsExpr ie, PatternExpr pat |
130-
ie = eqtest and
131-
ie.getExpr() = left and
132-
ie.getPattern() = pat
133-
|
134-
right = pat.(ConstantPatternExpr) and
135-
polarity = true
136-
or
137-
right = pat.(NotPatternExpr).getPattern().(ConstantPatternExpr) and
138-
polarity = false
139-
)
140163
}
141164

142165
class ConditionalExpr = CS::ConditionalExpr;
@@ -209,38 +232,15 @@ private module LogicInput implements GuardsImpl::LogicInputSig {
209232
isNull = false
210233
)
211234
or
212-
// TODO: Remove this superfluous case once CFG changes for IsExpr lands.
213-
guard =
214-
any(PatternMatch pm |
215-
e instanceof DereferenceableExpr and
216-
e = pm.getExpr() and
217-
(
218-
val.asBooleanValue().booleanNot() = patternMatchesNull(pm.getPattern()) and
219-
isNull = false
220-
or
221-
exists(TypePatternExpr tpe |
222-
// E.g. `x is string` where `x` has type `string`
223-
typePattern(guard, tpe, tpe.getCheckedType()) and
224-
val.asBooleanValue() = false and
225-
isNull = true
226-
)
227-
)
228-
)
229-
or
235+
// E.g. `x is string` where `x` has type `string`
230236
exists(PatternMatch pm |
231-
guard = pm.getPattern() and
232237
e instanceof DereferenceableExpr and
233-
e = pm.getExpr()
234-
|
235-
val.isMatch(patternMatchesNull(pm.getPattern()).booleanNot()) and
236-
isNull = false
237-
or
238-
exists(TypePatternExpr tpe |
239-
// E.g. `x is string` where `x` has type `string`
240-
typePattern(pm, tpe, tpe.getCheckedType()) and
241-
val.isMatch(false) and
242-
isNull = true
243-
)
238+
e = pm.getExpr() and
239+
GuardsInput::nonDeconstructingSubPattern*(pm.getPattern(), guard) and
240+
guard.(TypePatternExpr).getCheckedType() = e.getType() and
241+
not guard.(VariablePatternExpr).isImplicitlyTyped() and
242+
val.isMatch(false) and
243+
isNull = true
244244
)
245245
or
246246
e.(DereferenceableExpr).hasNullableType() and
@@ -355,35 +355,6 @@ deprecated module AbstractValues {
355355
}
356356
}
357357

358-
/** Gets the value resulting from matching `null` against `pat`. */
359-
private boolean patternMatchesNull(PatternExpr pat) {
360-
pat instanceof NullLiteral and result = true
361-
or
362-
not pat instanceof NullLiteral and
363-
not pat instanceof NotPatternExpr and
364-
not pat instanceof OrPatternExpr and
365-
not pat instanceof AndPatternExpr and
366-
result = false
367-
or
368-
result = patternMatchesNull(pat.(NotPatternExpr).getPattern()).booleanNot()
369-
or
370-
exists(OrPatternExpr ope | pat = ope |
371-
result =
372-
patternMatchesNull(ope.getLeftOperand()).booleanOr(patternMatchesNull(ope.getRightOperand()))
373-
)
374-
or
375-
exists(AndPatternExpr ape | pat = ape |
376-
result =
377-
patternMatchesNull(ape.getLeftOperand()).booleanAnd(patternMatchesNull(ape.getRightOperand()))
378-
)
379-
}
380-
381-
pragma[nomagic]
382-
private predicate typePattern(PatternMatch pm, TypePatternExpr tpe, Type t) {
383-
tpe = pm.getPattern() and
384-
t = pm.getExpr().getType()
385-
}
386-
387358
pragma[nomagic]
388359
private predicate dereferenceableExpr(Expr e, boolean isNullableType) {
389360
exists(Type t | t = e.getType() |
@@ -884,6 +855,16 @@ module Internal {
884855
e instanceof SuppressNullableWarningExpr
885856
or
886857
e.stripCasts().getType() = any(ValueType t | not t instanceof NullableType)
858+
or
859+
e =
860+
any(PatternExpr pat |
861+
not pat instanceof NullLiteral and
862+
not pat instanceof DiscardPatternExpr and
863+
not pat.(VariablePatternExpr).isImplicitlyTyped() and
864+
not pat instanceof NotPatternExpr and
865+
not pat instanceof OrPatternExpr and
866+
not pat instanceof AndPatternExpr
867+
)
887868
}
888869

889870
/** Holds if expression `e2` is a non-`null` value whenever `e1` is. */

‎csharp/ql/lib/semmle/code/csharp/controlflow/internal/ControlFlowGraph.qll‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,8 +84,24 @@ module Ast implements AstSig<Location> {
8484
private AstNode getExprChild0(Expr e, int i) {
8585
not e instanceof NameOfExpr and
8686
not e instanceof AnonymousFunctionExpr and
87+
not e instanceof RecursivePatternExpr and
8788
not skipControlFlow(result) and
8889
result = e.getChild(i)
90+
or
91+
e =
92+
any(RecursivePatternExpr rpe |
93+
i = 0 and
94+
result = rpe.getTypeAccess()
95+
or
96+
i = 1 and
97+
result = rpe.getPositionalPatterns()
98+
or
99+
i = 2 and
100+
result = rpe.getPropertyPatterns()
101+
or
102+
i = 3 and
103+
result = rpe.getVariableDeclExpr()
104+
)
89105
}
90106

91107
private AstNode getStmtChild0(Stmt s, int i) {
@@ -295,6 +311,24 @@ module Ast implements AstSig<Location> {
295311
boolean getValue() { result = this.getBoolValue() }
296312
}
297313

314+
final class Pattern = PatternImpl;
315+
316+
abstract private class PatternImpl extends AstNode { }
317+
318+
private class PatternExprPattern extends PatternImpl, CS::PatternExpr { }
319+
320+
class AndPattern extends Pattern instanceof CS::AndPatternExpr { }
321+
322+
class OrPattern extends Pattern instanceof CS::OrPatternExpr { }
323+
324+
class NotPattern extends Pattern instanceof CS::NotPatternExpr {
325+
Pattern getNegatedPattern() { result = super.getPattern() }
326+
}
327+
328+
class BindingPattern extends PatternImpl {
329+
BindingPattern() { this = any(CS::VariablePatternExpr vp).getAccess() }
330+
}
331+
298332
final private class FinalIsExpr = CS::IsExpr;
299333

300334
class PatternMatchExpr extends FinalIsExpr {

‎csharp/ql/lib/semmle/code/csharp/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

‎csharp/ql/lib/semmle/code/csharp/dataflow/internal/rangeanalysis/ModulusAnalysisSpecific.qll‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ module Private {
1515

1616
class Guard = RU::Guard;
1717

18+
class GuardValue = RU::GuardValue;
19+
1820
class ConstantIntegerExpr = CU::ConstantIntegerExpr;
1921

2022
class ConditionalExpr = RU::ExprNode::ConditionalExpr;

‎csharp/ql/lib/semmle/code/csharp/dataflow/internal/rangeanalysis/RangeUtils.qll‎

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -78,24 +78,22 @@ private module Impl {
7878
)
7979
}
8080

81+
class GuardValue = G::GuardValue;
82+
8183
/** An expression whose value may control the execution of another element. */
8284
class Guard extends Expr instanceof G::Guard {
8385
/**
8486
* Holds if basic block `bb` is guarded by this guard having value `v`.
8587
*/
86-
predicate controlsBasicBlock(BasicBlock bb, G::GuardValue v) { super.controlsBasicBlock(bb, v) }
88+
predicate controlsBasicBlock(BasicBlock bb, GuardValue v) { super.controlsBasicBlock(bb, v) }
8789

8890
/**
8991
* Holds if this guard is an equality test between `e1` and `e2`. If the test is
9092
* negated, that is `!=`, then `polarity` is false, otherwise `polarity` is
9193
* true.
9294
*/
93-
predicate isEquality(ExprNode e1, ExprNode e2, boolean polarity) {
94-
exists(Expr e1_, Expr e2_ |
95-
e1 = unique(ExprNode cfn | hasChild(this, e1_, _, cfn) | cfn) and
96-
e2 = unique(ExprNode cfn | hasChild(this, e2_, _, cfn) | cfn) and
97-
super.isEquality(e1_, e2_, any(G::GuardValue gv | gv.asBooleanValue() = polarity))
98-
)
95+
predicate isEquality(ExprNode e1, ExprNode e2, GuardValue eqval) {
96+
super.isEquality(e1.getExpr(), e2.getExpr(), eqval)
9997
}
10098
}
10199

@@ -108,7 +106,8 @@ private module Impl {
108106
*/
109107
Guard eqFlowCond(SsaDefinition def, ExprNode e, int delta, boolean isEq, boolean testIsTrue) {
110108
exists(boolean eqpolarity |
111-
result.isEquality(ssaRead(def, delta), e, eqpolarity) and
109+
result
110+
.isEquality(ssaRead(def, delta), e, any(GuardValue gv | gv.asBooleanValue() = eqpolarity)) and
112111
testIsTrue = [false, true] and
113112
eqpolarity.booleanXor(testIsTrue).booleanNot() = isEq
114113
)
@@ -117,10 +116,8 @@ private module Impl {
117116
/**
118117
* Holds if `guard` controls the position `controlled` with the value `testIsTrue`.
119118
*/
120-
predicate guardControlsSsaRead(Guard guard, SsaReadPosition controlled, boolean testIsTrue) {
121-
exists(G::GuardValue b | b.asBooleanValue() = testIsTrue |
122-
guard.controlsBasicBlock(controlled.(SsaReadPositionBlock).getBlock(), b)
123-
)
119+
predicate guardControlsSsaRead(Guard guard, SsaReadPosition controlled, GuardValue val) {
120+
guard.controlsBasicBlock(controlled.(SsaReadPositionBlock).getBlock(), val)
124121
}
125122

126123
/**

‎csharp/ql/lib/semmle/code/csharp/dataflow/internal/rangeanalysis/SignAnalysisCommon.qll‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,8 @@ private predicate unknownSign(Expr e) {
6464
private predicate lowerBound(Expr lowerbound, SsaVariable v, SsaReadPosition pos, boolean isStrict) {
6565
exists(boolean testIsTrue, ComparisonExpr comp |
6666
pos.hasReadOfVar(v) and
67-
guardControlsSsaRead(getComparisonGuard(comp), pos, testIsTrue) and
67+
guardControlsSsaRead(getComparisonGuard(comp), pos,
68+
any(GuardValue gv | gv.asBooleanValue() = testIsTrue)) and
6869
not unknownSign(lowerbound)
6970
|
7071
testIsTrue = true and
@@ -86,7 +87,8 @@ private predicate lowerBound(Expr lowerbound, SsaVariable v, SsaReadPosition pos
8687
private predicate upperBound(Expr upperbound, SsaVariable v, SsaReadPosition pos, boolean isStrict) {
8788
exists(boolean testIsTrue, ComparisonExpr comp |
8889
pos.hasReadOfVar(v) and
89-
guardControlsSsaRead(getComparisonGuard(comp), pos, testIsTrue) and
90+
guardControlsSsaRead(getComparisonGuard(comp), pos,
91+
any(GuardValue gv | gv.asBooleanValue() = testIsTrue)) and
9092
not unknownSign(upperbound)
9193
|
9294
testIsTrue = true and
@@ -109,12 +111,15 @@ private predicate upperBound(Expr upperbound, SsaVariable v, SsaReadPosition pos
109111
* - `isEq = false` : `v != eqbound`
110112
*/
111113
private predicate eqBound(Expr eqbound, SsaVariable v, SsaReadPosition pos, boolean isEq) {
112-
exists(Guard guard, boolean testIsTrue, boolean polarity |
114+
exists(Guard guard, GuardValue testIsTrue, GuardValue eqval |
113115
pos.hasReadOfVar(v) and
114116
guardControlsSsaRead(guard, pos, testIsTrue) and
115-
guard.isEquality(eqbound, ssaRead(v, 0), polarity) and
116-
isEq = polarity.booleanXor(testIsTrue).booleanNot() and
117+
guard.isEquality(eqbound, ssaRead(v, 0), eqval) and
117118
not unknownSign(eqbound)
119+
|
120+
testIsTrue = eqval and isEq = true
121+
or
122+
testIsTrue = eqval.getDualValue() and isEq = false
118123
)
119124
}
120125

‎csharp/ql/lib/semmle/code/csharp/dataflow/internal/rangeanalysis/SignAnalysisSpecific.qll‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ module Private {
1111

1212
class Guard = RU::Guard;
1313

14+
class GuardValue = RU::GuardValue;
15+
1416
class ConstantIntegerExpr = CU::ConstantIntegerExpr;
1517

1618
class SsaVariable = CS::SsaDefinition;

0 commit comments

Comments
 (0)