-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathControlFlowGraph.qll
More file actions
1663 lines (1568 loc) · 64 KB
/
ControlFlowGraph.qll
File metadata and controls
1663 lines (1568 loc) · 64 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 and predicates for computing expression-level intra-procedural control flow graphs.
*
* The only API exported by this library are the toplevel classes `ControlFlow::Node`
* and its subclass `ConditionNode`, which wrap the successor relation and the
* concept of true- and false-successors of conditions. A cfg node may either be a
* statement, an expression, or an exit node for a callable, indicating that
* execution of the callable terminates.
*/
overlay[local?]
module;
/*
* The implementation is centered around the concept of a _completion_, which
* models how the execution of a statement or expression terminates.
* Completions are represented as an algebraic data type `Completion` defined in
* `Completion.qll`.
*
* The CFG is built by structural recursion over the AST. To achieve this the
* CFG edges related to a given AST node, `n`, is divided into three categories:
* 1. The in-going edge that points to the first CFG node to execute when the
* `n` is going to be executed.
* 2. The out-going edges for control-flow leaving `n` that are going to some
* other node in the surrounding context of `n`.
* 3. The edges that have both of their end-points entirely within the AST
* node and its children.
* The edges in (1) and (2) are inherently non-local and are therefore
* initially calculated as half-edges, that is, the single node, `k`, of the
* edge contained within `n`, by the predicates `k = first(n)` and
* `last(n, k, _)`, respectively. The edges in (3) can then be enumerated
* directly by the predicate `succ` by calling `first` and `last` recursively
* on the children of `n` and connecting the end-points. This yields the entire
* CFG, since all edges are in (3) for _some_ AST node.
*
* The third parameter of `last` is the completion, which is necessary to
* distinguish the out-going edges from `n`. Note that the completion changes
* as the calculation of `last` proceeds outward through the AST; for example,
* a `breakCompletion` is caught up by its surrounding loop and turned into a
* `normalCompletion`, or a `normalCompletion` proceeds outward through the end
* of a `finally` block and is turned into whatever completion was caught by
* the `finally`, or a `booleanCompletion(false, _)` occurs in a loop condition
* and is turned into a `normalCompletion` of the entire loop. When the edge is
* eventually connected we use the completion at that level of the AST as the
* label of the edge, thus creating an edge-labelled CFG.
*
* An important goal of the CFG is to get the order of side-effects correct.
* Most expressions can have side-effects and must therefore be modeled in the
* CFG in AST post-order. For example, a `MethodCall` evaluates its arguments
* before the call. Most statements don't have side-effects, but merely affect
* the control-flow and some could therefore be excluded from the CFG. However,
* as a design choice, all statements are included in the CFG and generally
* serve as their own entry-points, thus executing in some version of AST
* pre-order. A few notable exceptions are `ReturnStmt`, `ThrowStmt`,
* `SynchronizedStmt`, `ThisConstructorInvocationStmt`, and
* `SuperConstructorInvocationStmt`, which all have side-effects and therefore
* are modeled in side-effect order. Loop statement nodes are only passed on
* entry, after which control goes back and forth between body and loop
* condition.
*
* Some out-going edges from boolean expressions have a known value and in some
* contexts this affects the possible successors. For example, in `if(A || B)`
* a short-circuit edge that skips `B` must be true and can therefore only lead
* to the then-branch. If the `||` is modeled in post-order then this
* information is lost, and consequently it is better to model `||` and `&&` in
* pre-order. The conditional expression `? :` is also modeled in pre-order to
* achieve consistent CFGs for the equivalent `A && B` and `A ? B : false`.
* Finally, the logical negation is also modeled in pre-order to achieve
* consistent CFGs for the equivalent `!(A || B)` and `!A && !B`. The boolean
* value `b` is tracked with the completion `booleanCompletion(b, _)`.
*
* Note that the second parameter in a `booleanCompletion` isn't needed to
* calculate the CFG. It is, however, needed to track the value of the
* sub-expression. For example, this ensures that the false-successor of the
* `ConditionNode` `A` in `if(!(A && B))` can be correctly identified as the
* then-branch (even though this completion turns into a
* `booleanCompletion(true, _)` from the perspective of the `if`-node).
*
* As a final note, expressions that aren't actually executed in the usual
* sense are excluded from the CFG. This covers, for example, parentheses,
* l-values that aren't r-values as well, and expressions in `ConstCase`s.
* For example, the `x` in `x=3` is not in the CFG, but the `x` in `x+=3` is.
*/
import java
private import Completion
private import controlflow.internal.Preconditions
private import controlflow.internal.SwitchCases
/** Provides the definition of control flow nodes. */
module ControlFlow {
private predicate hasControlFlow(Expr e) {
not exists(ConstCase cc | e = cc.getValue(_)) and
not e.getParent*() instanceof Annotation and
not e instanceof TypeAccess and
not e instanceof ArrayTypeAccess and
not e instanceof UnionTypeAccess and
not e instanceof IntersectionTypeAccess and
not e instanceof WildcardTypeAccess and
not exists(AssignExpr ae | ae.getDest() = e)
}
private newtype TNode =
TExprNode(Expr e) { hasControlFlow(e) } or
TStmtNode(Stmt s) or
TExitNode(Callable c) { exists(c.getBody()) }
/** A node in the expression-level control-flow graph. */
class Node extends TNode {
/** Gets an immediate successor of this node. */
Node getASuccessor() { result = succ(this) }
/** Gets an immediate predecessor of this node. */
Node getAPredecessor() { this = succ(result) }
/** Gets an exception successor of this node. */
Node getAnExceptionSuccessor() { result = succ(this, ThrowCompletion(_)) }
/** Gets a successor of this node that is neither an exception successor nor a jump (break, continue, return). */
Node getANormalSuccessor() {
result = succ(this, BooleanCompletion(_, _)) or
result = succ(this, NormalCompletion())
}
/** Gets the basic block that contains this node. */
BasicBlock getBasicBlock() { result.getANode() = this }
/** Gets the statement containing this node, if any. */
Stmt getEnclosingStmt() { none() }
/** Gets the immediately enclosing callable whose body contains this node. */
Callable getEnclosingCallable() { none() }
/** Gets the statement this `Node` corresponds to, if any. */
Stmt asStmt() { this = TStmtNode(result) }
/** Gets the expression this `Node` corresponds to, if any. */
Expr asExpr() { this = TExprNode(result) }
/** Gets the call this `Node` corresponds to, if any. */
Call asCall() {
result = this.asExpr() or
result = this.asStmt()
}
/** Gets a textual representation of this element. */
string toString() { none() }
/** Gets the source location for this element. */
Location getLocation() { none() }
/**
* Gets the most appropriate AST node for this control flow node, if any.
*/
ExprParent getAstNode() { none() }
}
/** A control-flow node that represents the evaluation of an expression. */
class ExprNode extends Node, TExprNode {
Expr e;
ExprNode() { this = TExprNode(e) }
override Stmt getEnclosingStmt() { result = e.getEnclosingStmt() }
override Callable getEnclosingCallable() { result = e.getEnclosingCallable() }
override ExprParent getAstNode() { result = e }
/** Gets a textual representation of this element. */
override string toString() { result = e.toString() }
/** Gets the source location for this element. */
override Location getLocation() { result = e.getLocation() }
}
/** A control-flow node that represents a statement. */
class StmtNode extends Node, TStmtNode {
Stmt s;
StmtNode() { this = TStmtNode(s) }
override Stmt getEnclosingStmt() { result = s }
override Callable getEnclosingCallable() { result = s.getEnclosingCallable() }
override ExprParent getAstNode() { result = s }
override string toString() { result = s.toString() }
override Location getLocation() { result = s.getLocation() }
}
/** A control flow node indicating the termination of a callable. */
class ExitNode extends Node, TExitNode {
Callable c;
ExitNode() { this = TExitNode(c) }
override Callable getEnclosingCallable() { result = c }
override ExprParent getAstNode() { result = c }
/** Gets a textual representation of this element. */
override string toString() { result = "Exit" }
/** Gets the source location for this element. */
override Location getLocation() { result = c.getLocation() }
}
}
class ControlFlowNode = ControlFlow::Node;
/** Gets the intra-procedural successor of `n`. */
private ControlFlowNode succ(ControlFlowNode n) { result = succ(n, _) }
cached
private module ControlFlowGraphImpl {
private import ControlFlow
private class AstNode extends ExprParent {
AstNode() { this instanceof Expr or this instanceof Stmt }
Stmt getEnclosingStmt() {
result = this or
result = this.(Expr).getEnclosingStmt()
}
Node getCfgNode() { result.asExpr() = this or result.asStmt() = this }
}
/**
* Gets a label that applies to this statement.
*/
private Label getLabel(Stmt s) {
exists(LabeledStmt l | s = l.getStmt() |
result = MkLabel(l.getLabel()) or
result = getLabel(l)
)
}
/**
* A throwable that's a (reflexive, transitive) supertype of an unchecked
* exception. Besides the unchecked exceptions themselves, this includes
* `java.lang.Throwable` and `java.lang.Exception`.
*/
private class UncheckedThrowableSuperType extends RefType {
UncheckedThrowableSuperType() {
this instanceof TypeThrowable or
this instanceof TypeException or
this instanceof UncheckedThrowableType
}
/**
* An unchecked throwable that is a subtype of this `UncheckedThrowableSuperType` and
* sits as high as possible in the type hierarchy. This is mostly unique except for
* `TypeThrowable` which results in both `TypeError` and `TypeRuntimeException`.
*/
UncheckedThrowableType getAnUncheckedSubtype() {
result = this
or
result instanceof TypeError and this instanceof TypeThrowable
or
result instanceof TypeRuntimeException and
(this instanceof TypeThrowable or this instanceof TypeException)
}
}
/**
* Bind `t` to an exception type that may be thrown during execution of `n`,
* either because `n` is a `throw` statement, or because it is a call
* that may throw an exception, or because it is a cast and a
* `ClassCastException` is expected, or because it is a Kotlin not-null check
* and a `NullPointerException` is expected.
*/
private predicate mayThrow(AstNode n, ThrowableType t) {
t = n.(ThrowStmt).getThrownExceptionType()
or
exists(Call c | c = n |
t = c.getCallee().getAThrownExceptionType() or
uncheckedExceptionFromCatch(n, t) or
uncheckedExceptionFromFinally(n, t) or
uncheckedExceptionFromMethod(c, t)
)
or
exists(CastExpr c | c = n |
t instanceof TypeClassCastException and
uncheckedExceptionFromCatch(n, t)
)
or
exists(NotNullExpr nn | nn = n |
t instanceof TypeNullPointerException and
uncheckedExceptionFromCatch(n, t)
)
}
/**
* Bind `t` to an unchecked exception that may occur in a precondition check.
*/
private predicate uncheckedExceptionFromMethod(MethodCall ma, ThrowableType t) {
conditionCheckArgument(ma, _, _) and
(t instanceof TypeError or t instanceof TypeRuntimeException)
}
/**
* Bind `t` to an unchecked exception that may transfer control to a finally
* block inside which `n` is nested.
*/
private predicate uncheckedExceptionFromFinally(AstNode n, ThrowableType t) {
exists(TryStmt try |
n.getEnclosingStmt().getEnclosingStmt+() = try.getBlock() or
n.(Expr).getParent*() = try.getAResource()
|
exists(try.getFinally()) and
(t instanceof TypeError or t instanceof TypeRuntimeException)
)
}
/**
* Bind `t` to all unchecked exceptions that may be caught by some
* `try-catch` inside which `n` is nested.
*/
private predicate uncheckedExceptionFromCatch(AstNode n, ThrowableType t) {
exists(TryStmt try, UncheckedThrowableSuperType caught |
n.getEnclosingStmt().getEnclosingStmt+() = try.getBlock() or
n.(Expr).getParent*() = try.getAResource()
|
t = caught.getAnUncheckedSubtype() and
try.getACatchClause().getACaughtType() = caught
)
}
private ThrowableType assertionError() { result.hasQualifiedName("java.lang", "AssertionError") }
/**
* Gets an exception type that may be thrown during execution of the
* body or the resources (if any) of `try`.
*/
private ThrowableType thrownInBody(TryStmt try) {
exists(AstNode n |
mayThrow(n, result)
or
n instanceof AssertStmt and result = assertionError()
|
n.getEnclosingStmt().getEnclosingStmt+() = try.getBlock() or
n.(Expr).getParent*() = try.getAResource()
)
}
/**
* Bind `thrown` to an exception type that may be thrown during execution
* of the body or the resource declarations of the `try` block to which
* `c` belongs, such that `c` definitely catches that exception (if no
* prior catch clause handles it).
*/
private predicate mustCatch(CatchClause c, ThrowableType thrown) {
thrown = thrownInBody(c.getTry()) and
hasDescendant(c.getACaughtType(), thrown)
}
/**
* Bind `thrown` to an exception type that may be thrown during execution
* of the body or the resource declarations of the `try` block to which
* `c` belongs, such that `c` may _not_ catch that exception.
*
* This predicate computes the complement of `mustCatch` over those
* exception types that are thrown in the body/resource declarations of
* the corresponding `try`.
*/
private predicate mayNotCatch(CatchClause c, ThrowableType thrown) {
thrown = thrownInBody(c.getTry()) and
not hasDescendant(c.getACaughtType(), thrown)
}
/**
* Bind `thrown` to an exception type that may be thrown during execution
* of the body or the resource declarations of the `try` block to which
* `c` belongs, such that `c` possibly catches that exception.
*/
private predicate mayCatch(CatchClause c, ThrowableType thrown) {
mustCatch(c, thrown)
or
mayNotCatch(c, thrown) and exists(c.getACaughtType().commonSubtype(thrown))
}
/**
* Given an exception type `thrown`, determine which catch clauses of
* `try` may possibly catch that exception.
*/
private CatchClause handlingCatchClause(TryStmt try, ThrowableType thrown) {
exists(int i | result = try.getCatchClause(i) |
mayCatch(result, thrown) and
not exists(int j | j < i | mustCatch(try.getCatchClause(j), thrown))
)
}
/**
* Boolean expressions that occur in a context in which their value affect control flow.
* That is, contexts where the control-flow edges depend on `value` given that `b` ends
* with a `booleanCompletion(value, _)`.
*/
private predicate inBooleanContext(AstNode b) {
exists(LogicExpr logexpr |
logexpr.(BinaryExpr).getLeftOperand() = b
or
logexpr.getAnOperand() = b and inBooleanContext(logexpr)
)
or
exists(ConditionalExpr condexpr |
condexpr.getCondition() = b
or
condexpr.getABranchExpr() = b and
inBooleanContext(condexpr)
)
or
exists(AssertStmt assertstmt | assertstmt.getExpr() = b)
or
exists(SwitchExpr switch |
inBooleanContext(switch) and
switch.getAResult() = b
)
or
exists(ConditionalStmt condstmt | condstmt.getCondition() = b)
or
exists(WhenBranch whenbranch | whenbranch.getCondition() = b)
or
exists(WhenExpr whenexpr |
inBooleanContext(whenexpr) and
whenexpr.getBranch(_).getAResult() = b
)
or
b = any(PatternCase pc).getGuard()
or
inBooleanContext(b.(ExprStmt).getExpr())
or
inBooleanContext(b.(StmtExpr).getStmt())
}
/**
* A virtual method with a unique implementation. That is, the method does not
* participate in overriding and there are no call targets that could dispatch
* to both this and another method.
*/
private class EffectivelyNonVirtualMethod extends SrcMethod {
EffectivelyNonVirtualMethod() {
exists(this.getBody()) and
this.isVirtual() and
not this = any(Method m).getASourceOverriddenMethod() and
not this.overrides(_) and
// guard against implicit overrides of default methods
not this.getAPossibleImplementationOfSrcMethod() != this and
// guard against interface implementations in inheriting subclasses
not exists(SrcMethod m |
1 < strictcount(m.getAPossibleImplementationOfSrcMethod()) and
this = m.getAPossibleImplementationOfSrcMethod()
) and
// UnsupportedOperationException could indicate that this is meant to be overridden
not exists(ClassInstanceExpr ex |
this.getBody().getLastStmt().(ThrowStmt).getExpr() = ex and
ex.getConstructedType().hasQualifiedName("java.lang", "UnsupportedOperationException")
) and
// an unused parameter could indicate that this is meant to be overridden
forall(Parameter p | p = this.getAParameter() | exists(p.getAnAccess()))
}
/** Gets a `MethodCall` that calls this method. */
MethodCall getAnAccess() { result.getMethod().getAPossibleImplementation() = this }
}
/** Holds if a call to `m` indicates that `m` is expected to return. */
private predicate expectedReturn(EffectivelyNonVirtualMethod m) {
exists(Stmt s, BlockStmt b |
m.getAnAccess().getEnclosingStmt() = s and
b.getAStmt() = s and
not b.getLastStmt() = s
)
}
/**
* Gets a non-overridable method that always throws an exception or calls `exit`.
*/
private Method nonReturningMethod() {
result instanceof MethodExit
or
not result.isOverridable() and
exists(BlockStmt body |
body = result.getBody() and
not exists(ReturnStmt ret | ret.getEnclosingCallable() = result)
|
not result.getReturnType() instanceof VoidType or
body.getLastStmt() = nonReturningStmt()
)
}
/**
* Gets a virtual method that always throws an exception or calls `exit`.
*/
private EffectivelyNonVirtualMethod likelyNonReturningMethod() {
result.getReturnType() instanceof VoidType and
not exists(ReturnStmt ret | ret.getEnclosingCallable() = result) and
not expectedReturn(result) and
forall(Parameter p | p = result.getAParameter() | exists(p.getAnAccess())) and
result.getBody().getLastStmt() = nonReturningStmt()
}
/**
* Gets a `MethodCall` that always throws an exception or calls `exit`.
*/
private MethodCall nonReturningMethodCall() {
result.getMethod().getSourceDeclaration() = nonReturningMethod() or
result = likelyNonReturningMethod().getAnAccess()
}
/**
* Gets a statement that always throws an exception or calls `exit`.
*/
private Stmt nonReturningStmt() {
result instanceof ThrowStmt
or
result.(ExprStmt).getExpr() = nonReturningExpr()
or
result.(BlockStmt).getLastStmt() = nonReturningStmt()
or
exists(IfStmt ifstmt | ifstmt = result |
ifstmt.getThen() = nonReturningStmt() and
ifstmt.getElse() = nonReturningStmt()
)
or
exists(TryStmt try | try = result |
try.getBlock() = nonReturningStmt() and
forall(CatchClause cc | cc = try.getACatchClause() | cc.getBlock() = nonReturningStmt())
)
}
/**
* Gets an expression that always throws an exception or calls `exit`.
*/
private Expr nonReturningExpr() {
result = nonReturningMethodCall()
or
result.(StmtExpr).getStmt() = nonReturningStmt()
or
exists(WhenExpr whenexpr | whenexpr = result |
whenexpr.getBranch(_).isElseBranch() and
forex(WhenBranch whenbranch | whenbranch = whenexpr.getBranch(_) |
whenbranch.getRhs() = nonReturningStmt()
)
)
}
// Join order engineering -- first determine the switch block and the case indices required, then retrieve them.
bindingset[switch, i]
pragma[inline_late]
private predicate isNthCaseOf(SwitchBlock switch, SwitchCase c, int i) {
c.isNthCaseOf(switch, i)
}
/**
* Gets a `SwitchCase` that may be `pred`'s direct successor, where `pred` is declared in block `switch`.
*
* This means any switch case that comes after `pred` up to the next pattern case, if any, except for `case null`.
*
* Because we know the switch block contains at least one pattern, we know by https://docs.oracle.com/javase/specs/jls/se21/html/jls-14.html#jls-14.11
* that any default case comes after the last pattern case.
*/
private SwitchCase getASuccessorSwitchCase(PatternCase pred, SwitchBlock switch) {
// Note we do include `case null, default` (as well as plain old `default`) here.
not result.(ConstCase).getValue(_) instanceof NullLiteral and
exists(int maxCaseIndex |
switch = pred.getParent() and
if exists(getNextPatternCase(pred))
then maxCaseIndex = getNextPatternCase(pred).getCaseIndex()
else maxCaseIndex = lastCaseIndex(switch)
|
isNthCaseOf(switch, result, [pred.getCaseIndex() + 1 .. maxCaseIndex])
)
}
/**
* Gets a `SwitchCase` that may occur first in `switch`.
*
* If the block contains at least one PatternCase, this is any case up to and including that case, or
* the case handling the null literal if any.
*
* Otherwise it is any case in the switch block.
*/
private SwitchCase getAFirstSwitchCase(SwitchBlock switch) {
result.getParent() = switch and
(
result.(ConstCase).getValue(_) instanceof NullLiteral
or
result instanceof NullDefaultCase
or
not exists(getFirstPatternCase(switch))
or
result.getIndex() <= getFirstPatternCase(switch).getIndex()
)
}
private Stmt getSwitchStatement(SwitchBlock switch, int i) { result.isNthChildOf(switch, i) }
/**
* Holds if `last` is the last node in any of pattern case `pc`'s succeeding bind-and-test operations,
* immediately before either falling through to execute successor statements or execute a rule body
* if present. `completion` is the completion kind of the last operation.
*/
private predicate lastPatternCaseMatchingOp(PatternCase pc, Node last, Completion completion) {
last(pc.getAPattern(), last, completion) and
completion = NormalCompletion() and
not exists(pc.getGuard())
or
last(pc.getGuard(), last, completion) and
completion = BooleanCompletion(true, _)
}
/**
* Expressions and statements with CFG edges in post-order AST traversal.
*
* This includes most expressions, except those that initiate or propagate branching control
* flow (`LogicExpr`, `ConditionalExpr`).
* Only a few statements are included; those with specific side-effects
* occurring after the evaluation of their children, that is, `Call`, `ReturnStmt`,
* and `ThrowStmt`. CFG nodes without child nodes in the CFG that may complete
* normally are also included.
*/
private class PostOrderNode extends AstNode {
PostOrderNode() {
// For VarAccess and ArrayAccess only read accesses (r-values) are included,
// as write accesses aren't included in the CFG.
this instanceof ArrayAccess and not exists(AssignExpr a | this = a.getDest())
or
this instanceof ArrayCreationExpr
or
this instanceof ArrayInit
or
this instanceof Assignment
or
this instanceof BinaryExpr and not this instanceof LogicExpr
or
this instanceof UnaryExpr and not this instanceof LogNotExpr
or
this instanceof CastingExpr
or
this instanceof InstanceOfExpr and not this.(InstanceOfExpr).isPattern()
or
this instanceof NotInstanceOfExpr
or
this instanceof LocalVariableDeclExpr
or
this instanceof StringTemplateExpr
or
this instanceof ClassExpr
or
this instanceof VarRead
or
this instanceof Call // includes both expressions and statements
or
this instanceof ErrorExpr
or
this instanceof ReturnStmt
or
this instanceof ThrowStmt
or
this instanceof Literal
or
this instanceof TypeLiteral
or
this instanceof ThisAccess
or
this instanceof SuperAccess
or
this.(BlockStmt).getNumStmt() = 0
or
this instanceof SwitchCase and
not this.(SwitchCase).isRule() and
not this instanceof PatternCase
or
this instanceof RecordPatternExpr
or
this instanceof EmptyStmt
or
this instanceof LocalTypeDeclStmt
}
/** Gets child nodes in their order of execution. Indexing starts at either -1 or 0. */
AstNode getChildNode(int index) {
exists(ArrayAccess e | e = this |
index = 0 and result = e.getArray()
or
index = 1 and result = e.getIndexExpr()
)
or
exists(ArrayCreationExpr e | e = this |
result = e.getDimension(index)
or
index = count(e.getADimension()) and result = e.getInit()
)
or
result = this.(ArrayInit).getInit(index) and index >= 0
or
exists(AssignExpr e, ArrayAccess lhs | e = this and lhs = e.getDest() |
index = 0 and result = lhs.getArray()
or
index = 1 and result = lhs.getIndexExpr()
or
index = 2 and result = e.getSource()
)
or
exists(AssignExpr e, VarAccess lhs | e = this and lhs = e.getDest() |
index = -1 and result = lhs.getQualifier() and not result instanceof TypeAccess
or
index = 0 and result = e.getSource()
)
or
exists(AssignOp e | e = this |
index = 0 and result = e.getDest()
or
index = 1 and result = e.getRhs()
)
or
exists(BinaryExpr e | e = this |
index = 0 and result = e.getLeftOperand()
or
index = 1 and result = e.getRightOperand()
)
or
index = 0 and result = this.(UnaryExpr).getExpr()
or
index = 0 and result = this.(CastingExpr).getExpr()
or
index = 0 and result = this.(InstanceOfExpr).getExpr()
or
index = 0 and result = this.(NotInstanceOfExpr).getExpr()
or
index = 0 and result = this.(LocalVariableDeclExpr).getInit()
or
index = 0 and result = this.(VarRead).getQualifier() and not result instanceof TypeAccess
or
exists(Call e | e = this |
index = -1 and result = e.getQualifier() and not result instanceof TypeAccess
or
result = e.getArgument(index)
)
or
exists(StringTemplateExpr e | e = this | result = e.getComponent(index))
or
index = 0 and result = this.(ClassExpr).getExpr()
or
index = 0 and result = this.(ReturnStmt).getResult()
or
index = 0 and result = this.(ThrowStmt).getExpr()
or
result = this.(RecordPatternExpr).getSubPattern(index)
}
/** Gets the first child node, if any. */
AstNode firstChild() {
result = this.getChildNode(-1)
or
result = this.getChildNode(0) and not exists(this.getChildNode(-1))
}
/** Holds if this CFG node has any child nodes. */
predicate isLeafNode() { not exists(this.getChildNode(_)) }
/** Holds if this node can finish with a `normalCompletion`. */
predicate mayCompleteNormally() {
not this instanceof BooleanLiteral and
not this instanceof ReturnStmt and
not this instanceof ThrowStmt and
not this = nonReturningMethodCall()
}
}
/**
* If the body of `loop` finishes with `completion`, the loop will
* continue executing (provided the loop condition still holds).
*/
private predicate continues(Completion completion, LoopStmt loop) {
completion = NormalCompletion()
or
// only consider continue completions if there actually is a `continue`
// somewhere inside this loop; we don't particularly care whether that
// `continue` could actually target this loop, we just want to restrict
// the size of the predicate
exists(ContinueStmt cnt | cnt.getEnclosingStmt+() = loop |
completion = anonymousContinueCompletion() or
completion = labelledContinueCompletion(getLabel(loop))
)
}
/**
* Determine the part of the AST node `n` that will be executed first.
*/
private Node first(AstNode n) {
result.asExpr() = n and n instanceof LogicExpr
or
result.asExpr() = n and n instanceof ConditionalExpr
or
result.asExpr() = n and n instanceof WhenExpr
or
result.asStmt() = n and n instanceof WhenBranch
or
result.asExpr() = n and n instanceof StmtExpr
or
result = n.getCfgNode() and n.(PostOrderNode).isLeafNode()
or
result = first(n.(PostOrderNode).firstChild())
or
result = first(n.(InstanceOfExpr).getExpr())
or
result = first(n.(SynchronizedStmt).getExpr())
or
result = first(n.(AssertStmt).getExpr())
or
result.asStmt() = n and
not n instanceof PostOrderNode and
not n instanceof SynchronizedStmt and
not n instanceof AssertStmt
or
result.asExpr() = n and n instanceof SwitchExpr
}
/**
* Bind `last` to a node inside the body of `try` that may finish with `completion`
* such that control will be transferred to a `catch` block or the `finally` block of `try`.
*
* In other words, `last` is either a resource declaration that throws, or a
* node in the `try` block that may not complete normally, or a node in
* the `try` block that has no control flow successors inside the block.
*/
private predicate catchOrFinallyCompletion(TryStmt try, Node last, Completion completion) {
last(try.getBlock(), last, completion)
or
last(try.getAResource(), last, completion) and completion = ThrowCompletion(_)
}
/**
* Bind `last` to a node inside the body of `try` that may finish with `completion`
* such that control may be transferred to the `finally` block (if it exists).
*
* In other words, if `last` throws an exception it is possibly not caught by any
* of the catch clauses.
*/
private predicate uncaught(TryStmt try, Node last, Completion completion) {
catchOrFinallyCompletion(try, last, completion) and
(
exists(ThrowableType thrown |
thrown = thrownInBody(try) and
completion = ThrowCompletion(thrown) and
not mustCatch(try.getACatchClause(), thrown)
)
or
completion = NormalCompletion()
or
completion = ReturnCompletion()
or
completion = anonymousBreakCompletion()
or
completion = labelledBreakCompletion(_)
or
completion = anonymousContinueCompletion()
or
completion = labelledContinueCompletion(_)
)
}
/**
* Bind `last` to a node inside `try` that may finish with `completion` such
* that control may be transferred to the `finally` block (if it exists).
*
* This is similar to `uncaught`, but also includes final statements of `catch`
* clauses.
*/
private predicate finallyPred(TryStmt try, Node last, Completion completion) {
uncaught(try, last, completion) or
last(try.getACatchClause(), last, completion)
}
private predicate lastInFinally(TryStmt try, Node last) {
last(try.getFinally(), last, NormalCompletion())
}
private predicate isNextNormalSwitchStmt(SwitchBlock switch, Stmt pred, Stmt succ) {
exists(int i, Stmt immediateSucc |
getSwitchStatement(switch, i) = pred and
getSwitchStatement(switch, i + 1) = immediateSucc and
(
if immediateSucc instanceof PatternCase
then isNextNormalSwitchStmt(switch, immediateSucc, succ)
else succ = immediateSucc
)
)
}
/**
* Bind `last` to a cfg node nested inside `n` (or, indeed, `n` itself) such
* that `last` may be the last node during an execution of `n` and finish
* with the given completion.
*
* A `booleanCompletion` implies that `n` is an `Expr`. Any abnormal
* completion besides `throwCompletion` implies that `n` is a `Stmt`.
*/
private predicate last(AstNode n, Node last, Completion completion) {
// Exceptions are propagated from any sub-expression.
// As are any break, yield, continue, or return completions.
exists(Expr e | e.getParent() = n |
last(e, last, completion) and not completion instanceof NormalOrBooleanCompletion
)
or
// If an expression doesn't finish with a throw completion, then it executes normally with
// either a `normalCompletion` or a `booleanCompletion`.
// A boolean completion in a non-boolean context just indicates a normal completion
// and a normal completion in a boolean context indicates an arbitrary boolean completion.
last(n, last, NormalCompletion()) and
inBooleanContext(n) and
completion = basicBooleanCompletion(_)
or
last(n, last, BooleanCompletion(_, _)) and
not inBooleanContext(n) and
completion = NormalCompletion() and
// PatternCase has both a boolean-true completion (guard success) and a normal one
// (variable declaration completion, when no guard is present).
not n instanceof PatternCase
or
// Logic expressions and conditional expressions are executed in AST pre-order to facilitate
// proper short-circuit representation. All other expressions are executed in post-order.
// The last node of a logic expression is either in the right operand with an arbitrary
// completion, or in the left operand with the corresponding boolean completion.
exists(AndLogicalExpr andexpr | andexpr = n |
last(andexpr.getLeftOperand(), last, completion) and completion = BooleanCompletion(false, _)
or
last(andexpr.getRightOperand(), last, completion)
)
or
exists(OrLogicalExpr orexpr | orexpr = n |
last(orexpr.getLeftOperand(), last, completion) and completion = BooleanCompletion(true, _)
or
last(orexpr.getRightOperand(), last, completion)
)
or
// The last node of a `LogNotExpr` is in its sub-expression with an inverted boolean completion
// (or a `normalCompletion`).
exists(Completion subcompletion | last(n.(LogNotExpr).getExpr(), last, subcompletion) |
subcompletion = NormalCompletion() and
completion = NormalCompletion() and
not inBooleanContext(n)
or
exists(boolean outervalue, boolean innervalue |
subcompletion = BooleanCompletion(outervalue, innervalue) and
completion = BooleanCompletion(outervalue.booleanNot(), innervalue)
)
)
or
// The last node of a `ConditionalExpr` is in either of its branches.
exists(ConditionalExpr condexpr | condexpr = n |
last(condexpr.getABranchExpr(), last, completion)
)
or
exists(InstanceOfExpr ioe | ioe.isPattern() and ioe = n |
last.asExpr() = n and completion = basicBooleanCompletion(false)
or
last(ioe.getPattern(), last, NormalCompletion()) and completion = basicBooleanCompletion(true)
)
or
// The last node of a node executed in post-order is the node itself.
exists(PostOrderNode p | p = n |
p.mayCompleteNormally() and last = p.getCfgNode() and completion = NormalCompletion()
)
or
last.asExpr() = n and completion = basicBooleanCompletion(n.(BooleanLiteral).getBooleanValue())
or
// The last statement in a block is any statement that does not complete normally,
// or the last statement.
exists(BlockStmt blk | blk = n |
last(blk.getAStmt(), last, completion) and completion != NormalCompletion()
or
last(blk.getStmt(blk.getNumStmt() - 1), last, completion)
)
or
// The last node in an `if` statement is the last node in either of its branches or
// the last node of the condition with a false-completion in the absence of an else-branch.
exists(IfStmt ifstmt | ifstmt = n |
last(ifstmt.getCondition(), last, BooleanCompletion(false, _)) and
completion = NormalCompletion() and
not exists(ifstmt.getElse())
or
last(ifstmt.getThen(), last, completion)
or
last(ifstmt.getElse(), last, completion)
)
or
// A loop may terminate normally if its condition is false...
exists(LoopStmt loop | loop = n |
last(loop.getCondition(), last, BooleanCompletion(false, _)) and
completion = NormalCompletion()
or
// ...or if it's an enhanced for loop running out of items to iterate over...
// ...which may happen either immediately after the loop expression...
last(loop.(EnhancedForStmt).getExpr(), last, completion) and completion = NormalCompletion()
or