forked from github/codeql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGuards.qll
More file actions
1993 lines (1829 loc) · 66 KB
/
Guards.qll
File metadata and controls
1993 lines (1829 loc) · 66 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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Provides classes for working with guarded expressions.
*/
import csharp
private import ControlFlow::SuccessorTypes
private import semmle.code.csharp.commons.Assertions
private import semmle.code.csharp.commons.ComparisonTest
private import semmle.code.csharp.commons.StructuralComparison as SC
private import semmle.code.csharp.controlflow.BasicBlocks
private import semmle.code.csharp.controlflow.internal.Completion
private import semmle.code.csharp.frameworks.System
private import semmle.code.csharp.frameworks.system.Linq
private import semmle.code.csharp.frameworks.system.Collections
private import semmle.code.csharp.frameworks.system.collections.Generic
/** An expression whose value may control the execution of another element. */
class Guard extends Expr {
Guard() { isGuard(this, _) }
/**
* Holds if `cfn` is guarded by this expression having value `v`, where `sub` is
* a sub expression of this expression that is structurally equal to the expression
* belonging to `cfn`.
*
* In case `cfn` or `sub` access an SSA variable in their left-most qualifier, then
* so must the other (accessing the same SSA variable).
*/
predicate controlsNode(ControlFlow::Nodes::ElementNode cfn, AccessOrCallExpr sub, AbstractValue v) {
isGuardedByNode(cfn, this, sub, v)
}
/**
* Holds if `cfn` is guarded by this expression having value `v`.
*
* Note: This predicate is inlined.
*/
pragma[inline]
predicate controlsNode(ControlFlow::Nodes::ElementNode cfn, AbstractValue v) {
guardControls(this, cfn.getBasicBlock(), v)
}
/**
* Holds if basic block `bb` is guarded by this expression having value `v`.
*/
predicate controlsBasicBlock(BasicBlock bb, AbstractValue v) { guardControls(this, bb, v) }
/**
* Holds if this guard is an equality test between `e1` and `e2`. If the test is
* negated, that is `!=`, then `polarity` is false, otherwise `polarity` is
* true.
*/
predicate isEquality(Expr e1, Expr e2, boolean polarity) {
exists(BooleanValue v |
this = getAnEqualityCheck(e1, v, e2) and
polarity = v.getValue()
)
}
/**
* Gets a valid value for this guard. For example, if this guard is a test, then
* it can have Boolean values `true` and `false`.
*/
AbstractValue getAValue() { isGuard(this, result) }
}
/** An abstract value. */
abstract class AbstractValue extends TAbstractValue {
/** Holds if the `s` branch out of `cfe` is taken iff `e` has this value. */
abstract predicate branch(ControlFlowElement cfe, ConditionalSuccessor s, Expr e);
/** Gets an abstract value that represents the dual of this value, if any. */
abstract AbstractValue getDualValue();
/**
* Gets an expression that has this abstract value. Two expressions that have the
* same concrete value also have the same abstract value, but not necessarily the
* other way around.
*
* Moreover, `e = this.getAnExpr() implies not e = this.getDualValue().getAnExpr()`.
*/
abstract Expr getAnExpr();
/**
* Holds if this is a singleton abstract value. That is, two expressions that have
* this abstract value also have the same concrete value.
*/
abstract predicate isSingleton();
/**
* Holds if this value describes a referential property. For example, emptiness
* of a collection is a referential property.
*
* Such values only propagate through adjacent reads, for example, in
*
* ```csharp
* int M()
* {
* var x = new string[]{ "a", "b", "c" }.ToList();
* x.Clear();
* return x.Count;
* }
* ```
*
* the non-emptiness of `new string[]{ "a", "b", "c" }.ToList()` only propagates
* to the read of `x` in `x.Clear()` and not in `x.Count`.
*
* Aliasing is not taken into account in the analyses.
*/
predicate isReferentialProperty() { none() }
/** Gets a textual representation of this abstract value. */
abstract string toString();
}
/** Provides different types of `AbstractValues`s. */
module AbstractValues {
/** A Boolean value. */
class BooleanValue extends AbstractValue, TBooleanValue {
/** Gets the underlying Boolean value. */
boolean getValue() { this = TBooleanValue(result) }
override predicate branch(ControlFlowElement cfe, ConditionalSuccessor s, Expr e) {
s.(BooleanSuccessor).getValue() = this.getValue() and
exists(BooleanCompletion c | s = c.getAMatchingSuccessorType() |
c.isValidFor(cfe) and
e = cfe
)
}
override BooleanValue getDualValue() { result.getValue() = this.getValue().booleanNot() }
override Expr getAnExpr() {
result.getType() instanceof BoolType and
result.getValue() = this.getValue().toString()
}
override predicate isSingleton() { any() }
override string toString() { result = this.getValue().toString() }
}
/** An integer value. */
class IntegerValue extends AbstractValue, TIntegerValue {
/** Gets the underlying integer value. */
int getValue() { this = TIntegerValue(result) }
override predicate branch(ControlFlowElement cfe, ConditionalSuccessor s, Expr e) { none() }
override IntegerValue getDualValue() { none() }
override Expr getAnExpr() {
result.getValue().toInt() = this.getValue() and
(
result.getType() instanceof Enum
or
result.getType() instanceof IntegralType
)
}
override predicate isSingleton() { any() }
override string toString() { result = this.getValue().toString() }
}
/** A value that is either `null` or non-`null`. */
class NullValue extends AbstractValue, TNullValue {
/** Holds if this value represents `null`. */
predicate isNull() { this = TNullValue(true) }
/** Holds if this value represents non-`null`. */
predicate isNonNull() { this = TNullValue(false) }
override predicate branch(ControlFlowElement cfe, ConditionalSuccessor s, Expr e) {
this = TNullValue(s.(NullnessSuccessor).getValue()) and
exists(NullnessCompletion c | s = c.getAMatchingSuccessorType() |
c.isValidFor(cfe) and
e = cfe
)
}
override NullValue getDualValue() {
if this.isNull() then result.isNonNull() else result.isNull()
}
override DereferenceableExpr getAnExpr() {
if this.isNull() then nullValueImplied(result) else nonNullValueImplied(result)
}
override predicate isSingleton() { this.isNull() }
override string toString() { if this.isNull() then result = "null" else result = "non-null" }
}
/** A value that represents match or non-match against a specific pattern. */
class MatchValue extends AbstractValue, TMatchValue {
/** Gets the case. */
Case getCase() { this = TMatchValue(result, _) }
/** Holds if this value represents a match. */
predicate isMatch() { this = TMatchValue(_, true) }
override predicate branch(ControlFlowElement cfe, ConditionalSuccessor s, Expr e) {
this = TMatchValue(_, s.(MatchingSuccessor).getValue()) and
exists(MatchingCompletion c, Switch switch, Case case | s = c.getAMatchingSuccessorType() |
c.isValidFor(cfe) and
switchMatching(switch, case, cfe) and
e = switch.getExpr() and
case = this.getCase()
)
}
override MatchValue getDualValue() {
result =
any(MatchValue mv |
mv.getCase() = this.getCase() and
if this.isMatch() then not mv.isMatch() else mv.isMatch()
)
}
override Expr getAnExpr() { none() }
override predicate isSingleton() { none() }
override string toString() {
exists(string s | s = this.getCase().getPattern().toString() |
if this.isMatch() then result = "match " + s else result = "non-match " + s
)
}
}
/** A value that represents an empty or non-empty collection. */
class EmptyCollectionValue extends AbstractValue, TEmptyCollectionValue {
/** Holds if this value represents an empty collection. */
predicate isEmpty() { this = TEmptyCollectionValue(true) }
/** Holds if this value represents a non-empty collection. */
predicate isNonEmpty() { this = TEmptyCollectionValue(false) }
override predicate branch(ControlFlowElement cfe, ConditionalSuccessor s, Expr e) {
this = TEmptyCollectionValue(s.(EmptinessSuccessor).getValue()) and
exists(EmptinessCompletion c, ForeachStmt fs | s = c.getAMatchingSuccessorType() |
c.isValidFor(cfe) and
foreachEmptiness(fs, cfe) and
e = fs.getIterableExpr()
) and
// Only when taking the non-empty successor do we know that the original iterator
// expression was non-empty. When taking the empty successor, we may have already
// iterated through the `foreach` loop zero or more times, hence the iterator
// expression can be both empty and non-empty
this.isNonEmpty()
}
override EmptyCollectionValue getDualValue() {
if this.isEmpty() then result.isNonEmpty() else result.isEmpty()
}
override Expr getAnExpr() {
this.isEmpty() and
emptyValue(result)
or
this.isNonEmpty() and
nonEmptyValue(result)
}
override predicate isSingleton() { none() }
override predicate isReferentialProperty() { any() }
override string toString() { if this.isEmpty() then result = "empty" else result = "non-empty" }
}
}
private import AbstractValues
pragma[nomagic]
private predicate typePattern(PatternMatch pm, TypePatternExpr tpe, Type t) {
tpe = pm.getPattern() and
t = pm.getExpr().getType()
}
/**
* An expression that evaluates to a value that can be dereferenced. That is,
* an expression that may evaluate to `null`.
*/
class DereferenceableExpr extends Expr {
private boolean isNullableType;
DereferenceableExpr() {
exists(Expr e, Type t |
// There is currently a bug in the extractor: the type of `x?.Length` is
// incorrectly `int`, while it should have been `int?`. We apply
// `getNullEquivParent()` as a workaround
this = getNullEquivParent*(e) and
t = e.getType() and
not this instanceof SwitchCaseExpr and
not this instanceof PatternExpr
|
t instanceof NullableType and
isNullableType = true
or
t instanceof RefType and
isNullableType = false
)
}
/** Holds if this expression has a nullable type `T?`. */
predicate hasNullableType() { isNullableType = true }
/**
* Gets an expression that directly tests whether this expression is `null`.
*
* If the returned expression evaluates to `v`, then this expression is
* guaranteed to be `null` if `isNull` is true, and non-`null` if `isNull` is
* false.
*
* For example, if the expression `x != null` evaluates to `true` then the
* expression `x` is guaranteed to be non-`null`.
*/
private Expr getABooleanNullCheck(BooleanValue v, boolean isNull) {
exists(boolean branch | branch = v.getValue() |
// Comparison with `null`, for example `x != null`
exists(ComparisonTest ct, ComparisonKind ck, Expr e |
ct.getExpr() = result and
ct.getAnArgument() = this and
ct.getAnArgument() = e and
e = any(NullValue nv | nv.isNull()).getAnExpr() and
this != e and
ck = ct.getComparisonKind()
|
ck.isEquality() and isNull = branch
or
ck.isInequality() and isNull = branch.booleanNot()
)
or
// Comparison with a non-`null` value, for example `x?.Length > 0`
exists(ComparisonTest ct, ComparisonKind ck, Expr e | ct.getExpr() = result |
ct.getAnArgument() = this and
ct.getAnArgument() = e and
e = any(NullValue nv | nv.isNonNull()).getAnExpr() and
ck = ct.getComparisonKind() and
this != e and
isNull = false and
if ck.isInequality() then branch = false else branch = true
)
or
// Call to `string.IsNullOrEmpty()` or `string.IsNullOrWhiteSpace()`
exists(MethodCall mc, string name | result = mc |
mc.getTarget() = any(SystemStringClass c).getAMethod(name) and
name.regexpMatch("IsNullOr(Empty|WhiteSpace)") and
mc.getArgument(0) = this and
branch = false and
isNull = false
)
or
result =
any(PatternMatch pm |
this = pm.getExpr() and
(
// E.g. `x is null`
pm.getPattern() instanceof NullLiteral and
isNull = branch
or
// E.g. `x is string` or `x is ""`
not pm.getPattern() instanceof NullLiteral and
branch = true and
isNull = false
or
exists(TypePatternExpr tpe |
// E.g. `x is string` where `x` has type `string`
typePattern(result, tpe, tpe.getCheckedType()) and
branch = false and
isNull = true
)
)
)
or
this.hasNullableType() and
result =
any(PropertyAccess pa |
pa.getQualifier() = this and
pa.getTarget().hasName("HasValue") and
if branch = true then isNull = false else isNull = true
)
or
isCustomNullCheck(result, this, v, isNull)
)
}
/**
* Gets an expression that tests via matching whether this expression is `null`.
*
* If the returned expression matches (`v.isMatch()`) or non-matches
* (`not v.isMatch()`), then this expression is guaranteed to be `null`
* if `isNull` is true, and non-`null` if `isNull` is false.
*
* For example, if the case statement `case string s` matches in
*
* ```csharp
* switch (o)
* {
* case string s:
* return s;
* default:
* return "";
* }
* ```
*
* then `o` is guaranteed to be non-`null`.
*/
private Expr getAMatchingNullCheck(MatchValue v, boolean isNull) {
exists(Switch s, Case case |
case = v.getCase() and
this = s.getExpr() and
result = this and
case = s.getACase()
|
// E.g. `case string`
case.getPattern() instanceof TypePatternExpr and
v.isMatch() and
isNull = false
or
case.getPattern() =
any(ConstantPatternExpr cpe |
if cpe instanceof NullLiteral
then
// `case null`
if v.isMatch() then isNull = true else isNull = false
else (
// E.g. `case ""`
v.isMatch() and
isNull = false
)
)
)
}
/**
* Gets an expression that tests via nullness whether this expression is `null`.
*
* If the returned expression evaluates to `null` (`v.isNull()`) or evaluates to
* non-`null` (`not v.isNull()`), then this expression is guaranteed to be `null`
* if `isNull` is true, and non-`null` if `isNull` is false.
*
* For example, if `x` evaluates to `null` in `x ?? y` then `y` is evaluated, and
* `x` is guaranteed to be `null`.
*/
private Expr getANullnessNullCheck(NullValue v, boolean isNull) {
exists(NullnessCompletion c | c.isValidFor(this) |
result = this and
if c.isNull()
then (
v.isNull() and
isNull = true
) else (
v.isNonNull() and
isNull = false
)
)
}
/**
* Gets an expression that tests whether this expression is `null`.
*
* If the returned expression has abstract value `v`, then this expression is
* guaranteed to be `null` if `isNull` is true, and non-`null` if `isNull` is
* false.
*
* For example, if the expression `x != null` evaluates to `true` then the
* expression `x` is guaranteed to be non-`null`.
*/
Expr getANullCheck(AbstractValue v, boolean isNull) {
result = this.getABooleanNullCheck(v, isNull)
or
result = this.getAMatchingNullCheck(v, isNull)
or
result = this.getANullnessNullCheck(v, isNull)
}
}
/**
* An expression that evaluates to a collection. That is, an expression whose
* (transitive, reflexive) base type is `IEnumerable`.
*/
class EnumerableCollectionExpr extends Expr {
EnumerableCollectionExpr() {
this.getType().(ValueOrRefType).getABaseType*() instanceof SystemCollectionsIEnumerableInterface
}
/**
* Gets an expression that computes the size of this collection. `lowerBound`
* indicates whether the expression only computes a lower bound.
*/
private Expr getASizeExpr(boolean lowerBound) {
lowerBound = false and
result =
any(PropertyRead pr |
this = pr.getQualifier() and
pr.getTarget() = any(SystemArrayClass x).getLengthProperty()
)
or
lowerBound = false and
result =
any(PropertyRead pr |
this = pr.getQualifier() and
pr.getTarget()
.overridesOrImplementsOrEquals(any(Property p |
p.getUnboundDeclaration() =
any(SystemCollectionsGenericICollectionInterface x).getCountProperty()
))
)
or
result =
any(MethodCall mc |
mc.getTarget().getUnboundDeclaration() =
any(SystemLinq::SystemLinqEnumerableClass x).getACountMethod() and
this = mc.getArgument(0) and
if mc.getNumberOfArguments() = 1 then lowerBound = false else lowerBound = true
)
}
private Expr getABooleanEmptinessCheck(BooleanValue v, boolean isEmpty) {
exists(boolean branch | branch = v.getValue() |
result =
any(ComparisonTest ct |
exists(boolean lowerBound |
ct.getAnArgument() = this.getASizeExpr(lowerBound) and
if isEmpty = true then lowerBound = false else any()
|
// x.Length == 0
ct.getComparisonKind().isEquality() and
ct.getAnArgument().getValue().toInt() = 0 and
branch = isEmpty
or
// x.Length == k, k > 0
ct.getComparisonKind().isEquality() and
ct.getAnArgument().getValue().toInt() > 0 and
branch = true and
isEmpty = false
or
// x.Length != 0
ct.getComparisonKind().isInequality() and
ct.getAnArgument().getValue().toInt() = 0 and
branch = isEmpty.booleanNot()
or
// x.Length != k, k != 0
ct.getComparisonKind().isInequality() and
ct.getAnArgument().getValue().toInt() != 0 and
branch = false and
isEmpty = false
or
// x.Length > k, k >= 0
ct.getComparisonKind().isLessThan() and
ct.getFirstArgument().getValue().toInt() >= 0 and
branch = true and
isEmpty = false
or
// x.Length >= k, k > 0
ct.getComparisonKind().isLessThanEquals() and
ct.getFirstArgument().getValue().toInt() > 0 and
branch = true and
isEmpty = false
)
).getExpr()
or
result =
any(MethodCall mc |
mc.getTarget().getUnboundDeclaration() =
any(SystemLinq::SystemLinqEnumerableClass x).getAnAnyMethod() and
this = mc.getArgument(0) and
branch = isEmpty.booleanNot() and
if branch = false then mc.getNumberOfArguments() = 1 else any()
)
)
}
/**
* Gets an expression that tests whether this expression is empty.
*
* If the returned expression has abstract value `v`, then this expression is
* guaranteed to be empty if `isEmpty` is true, and non-empty if `isEmpty` is
* false.
*
* For example, if the expression `x.Length != 0` evaluates to `true` then the
* expression `x` is guaranteed to be non-empty.
*/
Expr getAnEmptinessCheck(AbstractValue v, boolean isEmpty) {
result = this.getABooleanEmptinessCheck(v, isEmpty)
}
}
/** An expression that accesses/calls a declaration. */
class AccessOrCallExpr extends Expr {
private Declaration target;
AccessOrCallExpr() { target = getDeclarationTarget(this) }
/** Gets the target of this expression. */
Declaration getTarget() { result = target }
/**
* Gets a (non-trivial) SSA definition corresponding to the longest
* qualifier chain of this expression, if any.
*
* This includes the case where this expression is itself an access to an
* SSA definition.
*
* Examples:
*
* ```csharp
* x.Foo.Bar(); // SSA qualifier: SSA definition for `x.Foo`
* x.Bar(); // SSA qualifier: SSA definition for `x`
* x.Foo().Bar(); // SSA qualifier: SSA definition for `x`
* x; // SSA qualifier: SSA definition for `x`
* ```
*
* An expression can have more than one SSA qualifier in the presence
* of control flow splitting.
*/
Ssa::Definition getAnSsaQualifier(ControlFlow::Node cfn) { result = getAnSsaQualifier(this, cfn) }
}
private Declaration getDeclarationTarget(Expr e) {
e = any(AssignableAccess aa | result = aa.getTarget()) or
result = e.(Call).getTarget()
}
private Ssa::Definition getAnSsaQualifier(Expr e, ControlFlow::Node cfn) {
e = getATrackedAccess(result, cfn)
or
not e = getATrackedAccess(_, _) and
result = getAnSsaQualifier(e.(QualifiableExpr).getQualifier(), cfn)
}
private AssignableAccess getATrackedAccess(Ssa::Definition def, ControlFlow::Node cfn) {
result = def.getAReadAtNode(cfn)
or
result = def.(Ssa::ExplicitDefinition).getADefinition().getTargetAccess() and
cfn = def.getControlFlowNode()
}
/**
* A guarded expression.
*
* A guarded expression is an access or a call that is reached only when another
* expression, `e`, has a certain abstract value, where `e` contains a sub
* expression that is structurally equal to this expression.
*
* For example, the property call `x.Field.Property` on line 3 is guarded in
*
* ```csharp
* string M(C x) {
* if (x.Field.Property != null)
* return x.Field.Property.ToString();
* return "";
* }
* ```
*
* There is no guarantee, in general, that the two structurally equal
* expressions will evaluate to the same value at run-time. For instance,
* in the following example, the null-guard on `stack` on line 2 is an actual
* guard, whereas the null-guard on `stack.Pop()` on line 4 is not (invoking
* `Pop()` twice on a stack does not yield the same result):
*
* ```csharp
* string M(Stack<object> stack) {
* if (stack == null)
* return "";
* if (stack.Pop() != null) // stack is not null
* return stack.Pop().ToString(); // stack.Pop() might be null
* return "";
* }
* ```
*
* However, in case one of the expressions accesses an SSA definition in its
* left-most qualifier, then so must the other (accessing the same SSA
* definition).
*/
class GuardedExpr extends AccessOrCallExpr {
private Guard g;
private AccessOrCallExpr sub0;
private AbstractValue v0;
GuardedExpr() { isGuardedByExpr(this, g, sub0, v0) }
/**
* Gets an expression that guards this expression. That is, this expression is
* only reached when the returned expression has abstract value `v`.
*
* The expression `sub` is a sub expression of the guarding expression that is
* structurally equal to this expression.
*
* In case this expression or `sub` accesses an SSA variable in its
* left-most qualifier, then so must the other (accessing the same SSA
* variable).
*/
Guard getAGuard(Expr sub, AbstractValue v) {
result = g and
sub = sub0 and
v = v0
}
/**
* Holds if this expression must have abstract value `v`. That is, this
* expression is guarded by a structurally equal expression having abstract
* value `v`.
*/
predicate mustHaveValue(AbstractValue v) { g = this.getAGuard(g, v) }
/**
* Holds if this expression is guarded by expression `cond`, which must
* evaluate to `b`. The expression `sub` is a sub expression of `cond`
* that is structurally equal to this expression.
*
* In case this expression or `sub` accesses an SSA variable in its
* left-most qualifier, then so must the other (accessing the same SSA
* variable).
*/
predicate isGuardedBy(Expr cond, Expr sub, boolean b) {
cond = this.getAGuard(sub, any(BooleanValue v | v.getValue() = b))
}
}
/**
* A guarded control flow node. A guarded control flow node is like a guarded
* expression (`GuardedExpr`), except control flow graph splitting is taken
* into account. That is, one control flow node belonging to an expression may
* be guarded, while another split need not be guarded:
*
* ```csharp
* if (b)
* if (x == null)
* return;
* x.ToString();
* if (b)
* ...
* ```
*
* In the example above, the node for `x.ToString()` is null-guarded in the
* split `b == true`, but not in the split `b == false`.
*/
class GuardedControlFlowNode extends ControlFlow::Nodes::ElementNode {
private Guard g;
private AccessOrCallExpr sub0;
private AbstractValue v0;
GuardedControlFlowNode() { g.controlsNode(this, sub0, v0) }
/**
* Gets an expression that guards this control flow node. That is, this control
* flow node is only reached when the returned expression has abstract value `v`.
*
* The expression `sub` is a sub expression of the guarding expression that is
* structurally equal to the expression belonging to this control flow node.
*
* In case this control flow node or `sub` accesses an SSA variable in its
* left-most qualifier, then so must the other (accessing the same SSA
* variable).
*/
Guard getAGuard(Expr sub, AbstractValue v) {
result = g and
sub = sub0 and
v = v0
}
/**
* Holds if this control flow node must have abstract value `v`. That is, this
* control flow node is guarded by a structurally equal expression having
* abstract value `v`.
*/
predicate mustHaveValue(AbstractValue v) { g = this.getAGuard(g, v) }
}
/**
* A guarded data flow node. A guarded data flow node is like a guarded expression
* (`GuardedExpr`), except control flow graph splitting is taken into account. That
* is, one data flow node belonging to an expression may be guarded, while another
* split need not be guarded:
*
* ```csharp
* if (b)
* if (x == null)
* return;
* x.ToString();
* if (b)
* ...
* ```
*
* In the example above, the node for `x.ToString()` is null-guarded in the
* split `b == true`, but not in the split `b == false`.
*/
class GuardedDataFlowNode extends DataFlow::ExprNode {
private Guard g;
private AccessOrCallExpr sub0;
private AbstractValue v0;
GuardedDataFlowNode() {
exists(ControlFlow::Nodes::ElementNode cfn | exists(this.getExprAtNode(cfn)) |
g.controlsNode(cfn, sub0, v0)
)
}
/**
* Gets an expression that guards this data flow node. That is, this data flow
* node is only reached when the returned expression has abstract value `v`.
*
* The expression `sub` is a sub expression of the guarding expression that is
* structurally equal to the expression belonging to this data flow node.
*
* In case this data flow node or `sub` accesses an SSA variable in its
* left-most qualifier, then so must the other (accessing the same SSA
* variable).
*/
Guard getAGuard(Expr sub, AbstractValue v) {
result = g and
sub = sub0 and
v = v0
}
/**
* Holds if this data flow node must have abstract value `v`. That is, this
* data flow node is guarded by a structurally equal expression having
* abstract value `v`.
*/
predicate mustHaveValue(AbstractValue v) { g = this.getAGuard(g, v) }
}
/** An expression guarded by a `null` check. */
class NullGuardedExpr extends GuardedExpr {
NullGuardedExpr() { this.mustHaveValue(any(NullValue v | v.isNonNull())) }
}
/** A data flow node guarded by a `null` check. */
class NullGuardedDataFlowNode extends GuardedDataFlowNode {
NullGuardedDataFlowNode() { this.mustHaveValue(any(NullValue v | v.isNonNull())) }
}
/** INTERNAL: Do not use. */
module Internal {
newtype TAbstractValue =
TBooleanValue(boolean b) { b = true or b = false } or
TIntegerValue(int i) { i = any(Expr e).getValue().toInt() } or
TNullValue(boolean b) { b = true or b = false } or
TMatchValue(Case c, boolean b) {
exists(c.getPattern()) and
(b = true or b = false)
} or
TEmptyCollectionValue(boolean b) { b = true or b = false }
/** Holds if expression `e` is a `null` value. */
predicate nullValue(Expr e) {
e instanceof NullLiteral
or
e instanceof DefaultValueExpr and e.getType().isRefType()
}
/** Holds if expression `e2` is a `null` value whenever `e1` is. */
predicate nullValueImpliedUnary(Expr e1, Expr e2) {
e1 = e2.(AssignExpr).getRValue()
or
e1 = e2.(Cast).getExpr()
or
e2 = e1.(NullCoalescingExpr).getAnOperand()
}
/** Holds if expression `e3` is a `null` value whenever `e1` and `e2` are. */
predicate nullValueImpliedBinary(Expr e1, Expr e2, Expr e3) {
e3 = any(ConditionalExpr ce | e1 = ce.getThen() and e2 = ce.getElse())
or
e3 = any(NullCoalescingExpr nce | e1 = nce.getLeftOperand() and e2 = nce.getRightOperand())
}
/** A callable that always returns a non-`null` value. */
private class NonNullCallable extends Callable {
NonNullCallable() { this = any(SystemObjectClass c).getGetTypeMethod() }
}
/** Holds if expression `e` is a non-`null` value. */
predicate nonNullValue(Expr e) {
e instanceof ObjectCreation
or
e instanceof ArrayCreation
or
e.hasNotNullFlowState()
or
e.hasValue() and
exists(Expr stripped | stripped = e.stripCasts() |
not stripped instanceof NullLiteral and
not stripped instanceof DefaultValueExpr
)
or
e instanceof ThisAccess
or
// "In string concatenation operations, the C# compiler treats a null string the same as an empty string."
// (https://docs.microsoft.com/en-us/dotnet/csharp/how-to/concatenate-multiple-strings)
e instanceof AddExpr and
e.getType() instanceof StringType
or
e.(DefaultValueExpr).getType().isValueType()
or
e.(Call).getTarget().getUnboundDeclaration() instanceof NonNullCallable and
not e.(QualifiableExpr).isConditional()
or
e instanceof SuppressNullableWarningExpr
or
e.stripCasts().getType() = any(ValueType t | not t instanceof NullableType)
}
/** Holds if expression `e2` is a non-`null` value whenever `e1` is. */
predicate nonNullValueImpliedUnary(Expr e1, Expr e2) {
e1 = e2.(CastExpr).getExpr()
or
e1 = e2.(AssignExpr).getRValue()
or
e1 = e2.(NullCoalescingExpr).getAnOperand()
}
/**
* Gets the parent expression of `e` which is `null` iff `e` is `null`,
* if any. For example, `result = x?.y` and `e = x`, or `result = x + 1`
* and `e = x`.
*/
Expr getNullEquivParent(Expr e) {
result =
any(QualifiableExpr qe |
qe.isConditional() and
(
e = qe.getQualifier()
or
e = qe.(ExtensionMethodCall).getArgument(0)
) and
(
// The accessed declaration must have a value type in order
// for `only if` to hold
result.(FieldAccess).getTarget().getType() instanceof ValueType
or
result.(Call).getTarget().getReturnType() instanceof ValueType
)
)
or
// In C#, `null + 1` has type `int?` with value `null`
exists(BinaryArithmeticOperation bao, Expr o |
result = bao and
bao.getAnOperand() = e and
bao.getAnOperand() = o and
// The other operand must be provably non-null in order
// for `only if` to hold
o = any(NullValue nv | nv.isNonNull()).getAnExpr() and
e != o
)
}
/**
* Gets a child expression of `e` which is `null` only if `e` is `null`.
*/
Expr getANullImplyingChild(Expr e) {
e =
any(QualifiableExpr qe |
qe.isConditional() and
result = qe.getQualifier()
)
or
// In C#, `null + 1` has type `int?` with value `null`
e = any(BinaryArithmeticOperation bao | result = bao.getAnOperand())
}
private Expr stripConditionalExpr(Expr e) {
e =
any(ConditionalExpr ce |
result = stripConditionalExpr(ce.getThen())
or
result = stripConditionalExpr(ce.getElse())
)
or
not e instanceof ConditionalExpr and
result = e
}
private predicate canReturn(Callable c, Expr ret) {
exists(Expr e | c.canReturn(e) | ret = stripConditionalExpr(e))
}
// The predicates in this module should be evaluated in the same stage as the CFG
// construction stage. This is to avoid recomputation of pre-basic-blocks and
// pre-SSA predicates
private module PreCfg {
private import semmle.code.csharp.controlflow.internal.PreBasicBlocks as PreBasicBlocks
private import semmle.code.csharp.controlflow.internal.PreSsa
/**
* Holds if pre-basic-block `bb` only is reached when guard `g` has abstract value `v`,
* not taking implications into account.
*/
pragma[nomagic]
private predicate preControlsDirect(Guard g, PreBasicBlocks::PreBasicBlock bb, AbstractValue v) {
exists(PreBasicBlocks::ConditionBlock cb, ConditionalSuccessor s | cb.controls(bb, s) |
v.branch(cb.getLastElement(), s, g)
)
}