-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathControlFlowGraphImpl.qll
More file actions
2133 lines (1936 loc) · 68.8 KB
/
ControlFlowGraphImpl.qll
File metadata and controls
2133 lines (1936 loc) · 68.8 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
/**
* INTERNAL: Analyses should use module `ControlFlowGraph` instead.
*
* Provides predicates for building intra-procedural CFGs.
*/
overlay[local]
module;
import go
/** A block statement that is not the body of a `switch` or `select` statement. */
class PlainBlock extends BlockStmt {
PlainBlock() {
not this = any(SwitchStmt sw).getBody() and not this = any(SelectStmt sel).getBody()
}
}
private predicate notBlankIdent(Expr e) { not e instanceof BlankIdent }
private predicate pureLvalue(ReferenceExpr e) { not e.isRvalue() }
/**
* Holds if `e` is a branch condition, including the LHS of a short-circuiting binary operator.
*/
private predicate isCondRoot(Expr e) {
e = any(LogicalBinaryExpr lbe).getLeftOperand()
or
e = any(ForStmt fs).getCond()
or
e = any(IfStmt is).getCond()
or
e = any(ExpressionSwitchStmt ess | not exists(ess.getExpr())).getACase().getAnExpr()
}
/**
* Holds if `e` is a branch condition or part of a logical binary expression contributing to a
* branch condition.
*
* For example, in `v := (x && y) || (z && w)`, `x` and `(x && y)` and `z` are branch conditions
* (`isCondRoot` holds of them), whereas this predicate also holds of `y` (contributes to condition
* `x && y`) but not of `w` (contributes to the value `v`, but not to any branch condition).
*
* In the context `if (x && y) || (z && w)` then the whole `(x && y) || (z && w)` is a branch condition
* as well as `x` and `(x && y)` and `z` as previously, and this predicate holds of all their
* subexpressions.
*/
private predicate isCond(Expr e) {
isCondRoot(e) or
e = any(LogicalBinaryExpr lbe | isCond(lbe)).getRightOperand() or
e = any(ParenExpr par | isCond(par)).getExpr()
}
/**
* Holds if `e` implicitly reads the embedded field `implicitField`.
*
* The `index` is the distance from the promoted field. For example, if `A` contains an embedded
* field `B`, `B` contains an embedded field `C` and `C` contains the non-embedded field `x`.
* Then `a.x` implicitly reads `C` with index 1 and `B` with index 2.
*/
private predicate implicitFieldSelectionForField(PromotedSelector e, int index, Field implicitField) {
exists(StructType baseType, PromotedField child, int implicitFieldDepth |
baseType = e.getSelectedStructType() and
(
e.refersTo(child)
or
implicitFieldSelectionForField(e, implicitFieldDepth + 1, child)
)
|
child = baseType.getFieldOfEmbedded(implicitField, _, implicitFieldDepth + 1, _) and
exists(PromotedField explicitField, int explicitFieldDepth |
e.refersTo(explicitField) and baseType.getFieldAtDepth(_, explicitFieldDepth) = explicitField
|
index = explicitFieldDepth - implicitFieldDepth
)
)
}
private predicate implicitFieldSelectionForMethod(PromotedSelector e, int index, Field implicitField) {
exists(StructType baseType, PromotedMethod method, int mDepth, int implicitFieldDepth |
baseType = e.getSelectedStructType() and
e.refersTo(method) and
baseType.getMethodAtDepth(_, mDepth) = method and
index = mDepth - implicitFieldDepth
|
method = baseType.getMethodOfEmbedded(implicitField, _, implicitFieldDepth + 1)
or
exists(PromotedField child |
child = baseType.getFieldOfEmbedded(implicitField, _, implicitFieldDepth + 1, _) and
implicitFieldSelectionForMethod(e, implicitFieldDepth + 1, child)
)
)
}
/**
* A node in the intra-procedural control-flow graph of a Go function or file.
*
* There are two kinds of control-flow nodes:
*
* 1. Instructions: these are nodes that correspond to expressions and statements
* that compute a value or perform an operation (as opposed to providing syntactic
* structure or type information).
* 2. Synthetic nodes:
* - Entry and exit nodes for each Go function and file that mark the beginning and the end,
* respectively, of the execution of the function and the loading of the file;
* - Skip nodes that are semantic no-ops, but make CFG construction easier.
*/
cached
newtype TControlFlowNode =
/**
* A control-flow node that represents the evaluation of an expression.
*/
MkExprNode(Expr e) { CFG::hasEvaluationNode(e) } or
/**
* A control-flow node that represents the initialization of an element of a composite literal.
*/
MkLiteralElementInitNode(Expr e) { e = any(CompositeLit lit).getAnElement() } or
/**
* A control-flow node that represents the implicit index of an element in a slice or array literal.
*/
MkImplicitLiteralElementIndex(Expr e) {
exists(CompositeLit lit | not lit instanceof StructLit |
e = lit.getAnElement() and
not e instanceof KeyValueExpr
)
} or
/**
* A control-flow node that represents a (single) assignment.
*
* Assignments with multiple left-hand sides are split up into multiple assignment nodes,
* one for each left-hand side. Assignments to `_` are not represented in the control-flow graph.
*/
MkAssignNode(AstNode assgn, int i) {
// the `i`th assignment in a (possibly multi-)assignment
notBlankIdent(assgn.(Assignment).getLhs(i))
or
// the `i`th name declared in a (possibly multi-)declaration specifier
notBlankIdent(assgn.(ValueSpec).getNameExpr(i))
or
// the assignment to the "key" variable in a `range` statement
notBlankIdent(assgn.(RangeStmt).getKey()) and i = 0
or
// the assignment to the "value" variable in a `range` statement
notBlankIdent(assgn.(RangeStmt).getValue()) and i = 1
} or
/**
* A control-flow node that represents the implicit right-hand side of a compound assignment.
*
* For example, the compound assignment `x += 1` has an implicit right-hand side `x + 1`.
*/
MkCompoundAssignRhsNode(CompoundAssignStmt assgn) or
/**
* A control-flow node that represents the `i`th component of a tuple expression `s`.
*/
MkExtractNode(AstNode s, int i) {
// in an assignment `x, y, z = tuple`
exists(Assignment assgn |
s = assgn and
exists(assgn.getRhs()) and
assgn.getNumLhs() > 1 and
exists(assgn.getLhs(i))
)
or
// in a declaration `var x, y, z = tuple`
exists(ValueSpec spec |
s = spec and
exists(spec.getInit()) and
spec.getNumName() > 1 and
exists(spec.getNameExpr(i))
)
or
// in a `range` statement
exists(RangeStmt rs | s = rs |
exists(rs.getKey()) and i = 0
or
exists(rs.getValue()) and i = 1
)
or
// in a return statement `return f()` where `f` has multiple return values
exists(ReturnStmt ret, SignatureType rettp |
s = ret and
// the return statement has a single expression
exists(ret.getExpr()) and
// but the enclosing function has multiple results
rettp = ret.getEnclosingFunction().getType() and
rettp.getNumResult() > 1 and
exists(rettp.getResultType(i))
)
or
// in a call `f(g())` where `g` has multiple return values
exists(CallExpr outer, CallExpr inner | s = outer |
inner = outer.getArgument(0).stripParens() and
outer.getNumArgument() = 1 and
exists(inner.getType().(TupleType).getComponentType(i))
)
} or
/**
* A control-flow node that represents the zero value to which a variable without an initializer
* expression is initialized.
*/
MkZeroInitNode(ValueEntity v) {
exists(ValueSpec spec |
not exists(spec.getAnInit()) and
spec.getNameExpr(_) = v.getDeclaration()
)
or
exists(v.(ResultVariable).getFunction().getBody())
} or
/**
* A control-flow node that represents a function declaration.
*/
MkFuncDeclNode(FuncDecl fd) or
/**
* A control-flow node that represents a `defer` statement.
*/
MkDeferNode(DeferStmt def) or
/**
* A control-flow node that represents a `go` statement.
*/
MkGoNode(GoStmt go) or
/**
* A control-flow node that represents the fact that `e` is known to evaluate to
* `outcome`.
*/
MkConditionGuardNode(Expr e, Boolean outcome) { isCondRoot(e) } or
/**
* A control-flow node that represents an increment or decrement statement.
*/
MkIncDecNode(IncDecStmt ids) or
/**
* A control-flow node that represents the implicit right-hand side of an increment or decrement statement.
*/
MkIncDecRhs(IncDecStmt ids) or
/**
* A control-flow node that represents the implicit operand 1 of an increment or decrement statement.
*/
MkImplicitOne(IncDecStmt ids) or
/**
* A control-flow node that represents a return from a function.
*/
MkReturnNode(ReturnStmt ret) or
/**
* A control-flow node that represents the implicit write to a named result variable in a return statement.
*/
MkResultWriteNode(ResultVariable var, int i, ReturnStmt ret) {
ret.getEnclosingFunction().getResultVar(i) = var and
exists(ret.getAnExpr())
} or
/**
* A control-flow node that represents the implicit read of a named result variable upon returning from
* a function (after any deferred calls have been executed).
*/
MkResultReadNode(ResultVariable var) or
/**
* A control-flow node that represents a no-op.
*
* These control-flow nodes correspond to Go statements that have no runtime semantics other than potentially
* influencing control flow: the branching statements `continue`, `break`, `fallthrough` and `goto`; empty
* blocks; empty statements; and import and type declarations.
*/
MkSkipNode(AstNode skip) {
skip instanceof BranchStmt
or
skip instanceof EmptyStmt
or
skip.(PlainBlock).getNumStmt() = 0
or
skip instanceof ImportDecl
or
skip instanceof TypeDecl
or
pureLvalue(skip)
or
skip.(CaseClause).getNumStmt() = 0
or
skip.(CommClause).getNumStmt() = 0
} or
/**
* A control-flow node that represents a `select` operation.
*/
MkSelectNode(SelectStmt sel) or
/**
* A control-flow node that represents a `send` operation.
*/
MkSendNode(SendStmt send) or
/**
* A control-flow node that represents the initialization of a parameter to its corresponding argument.
*/
MkParameterInit(Parameter parm) { exists(parm.getFunction().getBody()) } or
/**
* A control-flow node that represents the argument corresponding to a parameter.
*/
MkArgumentNode(Parameter parm) { exists(parm.getFunction().getBody()) } or
/**
* A control-flow node that represents the initialization of a result variable to its zero value.
*/
MkResultInit(ResultVariable rv) { exists(rv.getFunction().getBody()) } or
/**
* A control-flow node that represents the operation of retrieving the next (key, value) pair in a
* `range` statement, if any.
*/
MkNextNode(RangeStmt rs) or
/**
* A control-flow node that represents the implicit `true` expression in `switch { ... }`.
*/
MkImplicitTrue(ExpressionSwitchStmt stmt) { not exists(stmt.getExpr()) } or
/**
* A control-flow node that represents the implicit comparison or type check performed by
* the `i`th expression of a case clause `cc`.
*/
MkCaseCheckNode(CaseClause cc, int i) { exists(cc.getExpr(i)) } or
/**
* A control-flow node that represents the implicit declaration of the
* variable `lv` in case clause `cc` and its assignment of the value
* `switchExpr` from the guard. This only occurs in case clauses in a type
* switch statement which declares a variable in its guard.
*/
MkTypeSwitchImplicitVariable(CaseClause cc, LocalVariable lv, Expr switchExpr) {
exists(TypeSwitchStmt ts, DefineStmt ds | ds = ts.getAssign() |
cc = ts.getACase() and
lv = cc.getImplicitlyDeclaredVariable() and
switchExpr = ds.getRhs().(TypeAssertExpr).getExpr()
)
} or
/**
* A control-flow node that represents the implicit lower bound of a slice expression.
*/
MkImplicitLowerSliceBound(SliceExpr sl) { not exists(sl.getLow()) } or
/**
* A control-flow node that represents the implicit upper bound of a simple slice expression.
*/
MkImplicitUpperSliceBound(SliceExpr sl) { not exists(sl.getHigh()) } or
/**
* A control-flow node that represents the implicit max bound of a simple slice expression.
*/
MkImplicitMaxSliceBound(SliceExpr sl) { not exists(sl.getMax()) } or
/**
* A control-flow node that represents the implicit dereference of the base in a field/method
* access, element access, or slice expression.
*/
MkImplicitDeref(Expr e) {
e.getType().getUnderlyingType() instanceof PointerType and
(
exists(SelectorExpr sel | e = sel.getBase() |
// field accesses through a pointer always implicitly dereference
sel = any(Field f).getAReference()
or
// method accesses only dereference if the receiver is _not_ a pointer
exists(Method m, Type tp |
sel = m.getAReference() and
tp = m.getReceiver().getType().getUnderlyingType() and
not tp instanceof PointerType
)
)
or
e = any(IndexExpr ie).getBase()
or
e = any(SliceExpr se).getBase()
)
} or
/**
* A control-flow node that represents the implicit selection of a field when
* accessing a promoted field.
*
* If that field has a pointer type then this control-flow node also
* represents an implicit dereference of it.
*/
MkImplicitFieldSelection(PromotedSelector e, int i, Field implicitField) {
implicitFieldSelectionForField(e, i, implicitField) or
implicitFieldSelectionForMethod(e, i, implicitField)
} or
/**
* A control-flow node that represents the start of the execution of a function or file.
*/
MkEntryNode(ControlFlow::Root root) or
/**
* A control-flow node that represents the end of the execution of a function or file.
*/
MkExitNode(ControlFlow::Root root)
/** A representation of the target of a write. */
newtype TWriteTarget =
/** A write target that is represented explicitly in the AST. */
MkLhs(TControlFlowNode write, Expr lhs) {
exists(AstNode assgn, int i | write = MkAssignNode(assgn, i) |
lhs = assgn.(Assignment).getLhs(i).stripParens()
or
lhs = assgn.(ValueSpec).getNameExpr(i)
or
exists(RangeStmt rs | rs = assgn |
i = 0 and lhs = rs.getKey().stripParens()
or
i = 1 and lhs = rs.getValue().stripParens()
)
)
or
exists(IncDecStmt ids | write = MkIncDecNode(ids) | lhs = ids.getOperand().stripParens())
or
exists(Parameter parm | write = MkParameterInit(parm) | lhs = parm.getDeclaration())
or
exists(ResultVariable res | write = MkResultInit(res) | lhs = res.getDeclaration())
} or
/** A write target for an element in a compound literal, viewed as a field write. */
MkLiteralElementTarget(MkLiteralElementInitNode elt) or
/** A write target for a returned expression, viewed as a write to the corresponding result variable. */
MkResultWriteTarget(MkResultWriteNode w)
/**
* A control-flow node that represents a no-op.
*
* These control-flow nodes correspond to Go statements that have no runtime semantics other than
* potentially influencing control flow: the branching statements `continue`, `break`,
* `fallthrough` and `goto`; empty blocks; empty statements; and import and type declarations.
*/
class SkipNode extends ControlFlow::Node, MkSkipNode {
AstNode skip;
SkipNode() { this = MkSkipNode(skip) }
override ControlFlow::Root getRoot() { result.isRootOf(skip) }
override string toString() { result = "skip" }
override Location getLocation() { result = skip.getLocation() }
}
/**
* A control-flow node that represents the start of the execution of a function or file.
*/
class EntryNode extends ControlFlow::Node, MkEntryNode {
ControlFlow::Root root;
EntryNode() { this = MkEntryNode(root) }
override ControlFlow::Root getRoot() { result = root }
override string toString() { result = "entry" }
override Location getLocation() { result = root.getLocation() }
}
/**
* A control-flow node that represents the end of the execution of a function or file.
*/
class ExitNode extends ControlFlow::Node, MkExitNode {
ControlFlow::Root root;
ExitNode() { this = MkExitNode(root) }
override ControlFlow::Root getRoot() { result = root }
override string toString() { result = "exit" }
override Location getLocation() { result = root.getLocation() }
}
/**
* Provides classes and predicates for computing the control-flow graph.
*/
cached
module CFG {
/**
* The target of a branch statement, which is either the label of a labeled statement or
* the special target `""` referring to the innermost enclosing loop or `switch`.
*/
private class BranchTarget extends string {
BranchTarget() { this = any(LabeledStmt ls).getLabel() or this = "" }
}
private module BranchTarget {
/** Holds if this is the target of branch statement `stmt` or the label of compound statement `stmt`. */
BranchTarget of(Stmt stmt) {
exists(BranchStmt bs | bs = stmt |
result = bs.getLabel()
or
not exists(bs.getLabel()) and result = ""
)
or
exists(LabeledStmt ls | stmt = ls.getStmt() | result = ls.getLabel())
or
(stmt instanceof LoopStmt or stmt instanceof SwitchStmt or stmt instanceof SelectStmt) and
result = ""
}
}
private newtype TCompletion =
/** A completion indicating that an expression or statement was evaluated successfully. */
Done() or
/**
* A completion indicating that an expression was successfully evaluated to Boolean value `b`.
*
* Note that many Boolean expressions are modeled as having completion `Done()` instead.
* Completion `Bool` is only used in contexts where the Boolean value can be determined.
*/
Bool(boolean b) { b = true or b = false } or
/**
* A completion indicating that execution of a (compound) statement ended with a `break`
* statement targeting the given label.
*/
Break(BranchTarget lbl) or
/**
* A completion indicating that execution of a (compound) statement ended with a `continue`
* statement targeting the given label.
*/
Continue(BranchTarget lbl) or
/**
* A completion indicating that execution of a (compound) statement ended with a `fallthrough`
* statement.
*/
Fallthrough() or
/**
* A completion indicating that execution of a (compound) statement ended with a `return`
* statement.
*/
Return() or
/**
* A completion indicating that execution of a statement or expression may have ended with
* a panic being raised.
*/
Panic()
private Completion normalCompletion() { result.isNormal() }
private class Completion extends TCompletion {
predicate isNormal() { this = Done() or this = Bool(_) }
Boolean getOutcome() { this = Done() or this = Bool(result) }
string toString() {
this = Done() and result = "normal"
or
exists(boolean b | this = Bool(b) | result = b.toString())
or
exists(BranchTarget lbl |
this = Break(lbl) and result = "break " + lbl
or
this = Continue(lbl) and result = "continue " + lbl
)
or
this = Fallthrough() and result = "fallthrough"
or
this = Return() and result = "return"
or
this = Panic() and result = "panic"
}
}
/**
* Holds if `e` should have an evaluation node in the control-flow graph.
*
* Excluded expressions include those not evaluated at runtime (e.g. identifiers, type expressions)
* and some logical expressions that are expressed as control-flow edges rather than having a specific
* evaluation node.
*/
cached
predicate hasEvaluationNode(Expr e) {
// exclude expressions that do not denote a value
not e instanceof TypeExpr and
not e = any(FieldDecl f).getTag() and
not e instanceof KeyValueExpr and
not e = any(SelectorExpr sel).getSelector() and
not e = any(StructLit sl).getKey(_) and
not (e instanceof Ident and not e instanceof ReferenceExpr) and
not (e instanceof SelectorExpr and not e instanceof ReferenceExpr) and
not pureLvalue(e) and
// exclude parentheses, which are purely concrete syntax, and some logical binary expressions
// whose evaluation is implied by control-flow edges without requiring an evaluation node.
not isControlFlowStructural(e) and
// exclude expressions that are not evaluated at runtime
not e = any(ImportSpec is).getPathExpr() and
not e.getParent*() = any(ArrayTypeExpr ate).getLength() and
// sub-expressions of constant expressions are not evaluated (even if they don't look constant
// themselves)
not constRoot(e.getParent+())
}
/**
* Holds if `e` is an expression that purely serves grouping or control-flow purposes.
*
* Examples include parenthesized expressions and short-circuiting Boolean expressions used within
* a branch condition (`if` or `for` condition, or as part of a larger boolean expression, e.g.
* in `(x && y) || z`, the `&&` subexpression matches this predicate).
*/
private predicate isControlFlowStructural(Expr e) {
// Some logical binary operators do not need an evaluation node
// (for example, in `if x && y`, we evaluate `x` and then branch straight to either `y` or the
// `else` block, so there is no control-flow step where `x && y` is specifically calculated)
e instanceof LogicalBinaryExpr and
isCond(e)
or
// Purely concrete-syntactic structural expression:
e instanceof ParenExpr
}
/**
* Gets a constant root, that is, an expression that is constant but whose parent expression is not.
*
* As an exception to the latter, for a control-flow structural expression such as `(c1)` or `c1 && c2`
* where `cn` are constants we still consider the `cn`s to be a constant roots, even though their parent
* expression is also constant.
*/
private predicate constRoot(Expr root) {
exists(Expr c |
c.isConst() and
not c.getParent().(Expr).isConst() and
root = stripStructural(c)
)
}
/**
* Strips off any control-flow structural components from `e`.
*/
private Expr stripStructural(Expr e) {
if isControlFlowStructural(e) then result = stripStructural(e.getAChildExpr()) else result = e
}
private class ControlFlowTree extends AstNode {
predicate firstNode(ControlFlow::Node first) { none() }
predicate lastNode(ControlFlow::Node last, Completion cmpl) {
// propagate abnormal completion from children
lastNode(this.getAChild(), last, cmpl) and
not cmpl.isNormal()
}
/**
* Holds if `succ` is a successor of `pred`, ignoring the execution of any
* deferred functions when a function ends.
*/
pragma[nomagic]
predicate succ0(ControlFlow::Node pred, ControlFlow::Node succ) {
exists(int i |
lastNode(this.getChildTreeRanked(i), pred, normalCompletion()) and
firstNode(this.getChildTreeRanked(i + 1), succ)
)
}
/** Holds if `succ` is a successor of `pred`. */
predicate succ(ControlFlow::Node pred, ControlFlow::Node succ) { this.succ0(pred, succ) }
final ControlFlowTree getChildTreeRanked(int i) {
exists(int j |
result = this.getChildTree(j) and
j = rank[i + 1](int k | exists(this.getChildTree(k)))
)
}
ControlFlowTree getFirstChildTree() { result = this.getChildTreeRanked(0) }
ControlFlowTree getLastChildTree() {
result = max(ControlFlowTree ch, int j | ch = this.getChildTree(j) | ch order by j)
}
ControlFlowTree getChildTree(int i) { none() }
}
private class AtomicTree extends ControlFlowTree {
ControlFlow::Node nd;
Completion cmpl;
AtomicTree() {
exists(Expr e |
e = this and
e.isConst() and
nd = mkExprOrSkipNode(this)
|
if e.isPlatformIndependentConstant() and exists(e.getBoolValue())
then cmpl = Bool(e.getBoolValue())
else cmpl = Done()
)
or
this instanceof Ident and
not this.(Expr).isConst() and
nd = mkExprOrSkipNode(this) and
cmpl = Done()
or
this instanceof BreakStmt and
nd = MkSkipNode(this) and
cmpl = Break(BranchTarget::of(this))
or
this instanceof ContinueStmt and
nd = MkSkipNode(this) and
cmpl = Continue(BranchTarget::of(this))
or
this instanceof Decl and
nd = MkSkipNode(this) and
cmpl = Done()
or
this instanceof EmptyStmt and
nd = MkSkipNode(this) and
cmpl = Done()
or
this instanceof FallthroughStmt and
nd = MkSkipNode(this) and
cmpl = Fallthrough()
or
this instanceof FuncLit and
nd = MkExprNode(this) and
cmpl = Done()
or
this instanceof PlainBlock and
nd = MkSkipNode(this) and
cmpl = Done()
or
this instanceof SelectorExpr and
not this.(SelectorExpr).getBase() instanceof ValueExpr and
nd = mkExprOrSkipNode(this) and
cmpl = Done()
or
this instanceof GenericFunctionInstantiationExpr and
nd = MkExprNode(this) and
cmpl = Done()
}
override predicate firstNode(ControlFlow::Node first) { first = nd }
override predicate lastNode(ControlFlow::Node last, Completion c) { last = nd and c = cmpl }
}
abstract private class PostOrderTree extends ControlFlowTree {
abstract ControlFlow::Node getNode();
Completion getCompletion() { result = Done() }
override predicate firstNode(ControlFlow::Node first) {
firstNode(this.getFirstChildTree(), first)
or
not exists(this.getChildTree(_)) and
first = this.getNode()
}
override predicate lastNode(ControlFlow::Node last, Completion cmpl) {
super.lastNode(last, cmpl)
or
last = this.getNode() and cmpl = this.getCompletion()
}
pragma[nomagic]
override predicate succ0(ControlFlow::Node pred, ControlFlow::Node succ) {
super.succ0(pred, succ)
or
lastNode(this.getLastChildTree(), pred, normalCompletion()) and
succ = this.getNode()
}
}
abstract private class PreOrderTree extends ControlFlowTree {
abstract ControlFlow::Node getNode();
override predicate firstNode(ControlFlow::Node first) { first = this.getNode() }
override predicate lastNode(ControlFlow::Node last, Completion cmpl) {
super.lastNode(last, cmpl)
or
lastNode(this.getLastChildTree(), last, cmpl)
or
not exists(this.getChildTree(_)) and
last = this.getNode() and
cmpl = Done()
}
pragma[nomagic]
override predicate succ0(ControlFlow::Node pred, ControlFlow::Node succ) {
super.succ0(pred, succ)
or
pred = this.getNode() and
firstNode(this.getFirstChildTree(), succ)
}
}
private class WrapperTree extends ControlFlowTree {
WrapperTree() {
this instanceof ConstDecl or
this instanceof DeclStmt or
this instanceof ExprStmt or
this instanceof KeyValueExpr or
this instanceof LabeledStmt or
this instanceof ParenExpr or
this instanceof PlainBlock or
this instanceof VarDecl
}
override predicate firstNode(ControlFlow::Node first) {
firstNode(this.getFirstChildTree(), first)
}
override predicate lastNode(ControlFlow::Node last, Completion cmpl) {
super.lastNode(last, cmpl)
or
lastNode(this.getLastChildTree(), last, cmpl)
or
exists(LoopStmt ls | this = ls.getBody() |
lastNode(this, last, Continue(BranchTarget::of(ls))) and
cmpl = Done()
)
}
override ControlFlowTree getChildTree(int i) {
i = 0 and result = this.(DeclStmt).getDecl()
or
i = 0 and result = this.(ExprStmt).getExpr()
or
result = this.(GenDecl).getSpec(i)
or
exists(KeyValueExpr kv | kv = this |
not kv.getLiteral() instanceof StructLit and
i = 0 and
result = kv.getKey()
or
i = 1 and result = kv.getValue()
)
or
i = 0 and result = this.(LabeledStmt).getStmt()
or
i = 0 and result = this.(ParenExpr).getExpr()
or
result = this.(PlainBlock).getStmt(i)
}
}
private class AssignmentTree extends ControlFlowTree {
AssignmentTree() {
this instanceof Assignment or
this instanceof ValueSpec
}
Expr getLhs(int i) {
result = this.(Assignment).getLhs(i) or
result = this.(ValueSpec).getNameExpr(i)
}
int getNumLhs() {
result = this.(Assignment).getNumLhs() or
result = this.(ValueSpec).getNumName()
}
Expr getRhs(int i) {
result = this.(Assignment).getRhs(i) or
result = this.(ValueSpec).getInit(i)
}
int getNumRhs() {
result = this.(Assignment).getNumRhs() or
result = this.(ValueSpec).getNumInit()
}
predicate isExtractingAssign() { this.getNumRhs() = 1 and this.getNumLhs() > 1 }
override predicate firstNode(ControlFlow::Node first) {
not this instanceof RecvStmt and
firstNode(this.getLhs(0), first)
}
override predicate lastNode(ControlFlow::Node last, Completion cmpl) {
ControlFlowTree.super.lastNode(last, cmpl)
or
(
last = max(int i | | this.epilogueNode(i) order by i)
or
not exists(this.epilogueNode(_)) and
lastNode(this.getLastSubExprInEvalOrder(), last, normalCompletion())
) and
cmpl = Done()
}
pragma[nomagic]
override predicate succ0(ControlFlow::Node pred, ControlFlow::Node succ) {
ControlFlowTree.super.succ0(pred, succ)
or
exists(int i | lastNode(this.getLhs(i), pred, normalCompletion()) |
firstNode(this.getLhs(i + 1), succ)
or
not this instanceof RecvStmt and
i = this.getNumLhs() - 1 and
(
firstNode(this.getRhs(0), succ)
or
not exists(this.getRhs(_)) and
succ = this.epilogueNodeRanked(0)
)
)
or
exists(int i |
lastNode(this.getRhs(i), pred, normalCompletion()) and
firstNode(this.getRhs(i + 1), succ)
)
or
not this instanceof RecvStmt and
lastNode(this.getRhs(this.getNumRhs() - 1), pred, normalCompletion()) and
succ = this.epilogueNodeRanked(0)
or
exists(int i |
pred = this.epilogueNodeRanked(i) and
succ = this.epilogueNodeRanked(i + 1)
)
}
ControlFlow::Node epilogueNodeRanked(int i) {
exists(int j |
result = this.epilogueNode(j) and
j = rank[i + 1](int k | exists(this.epilogueNode(k)))
)
}
private Expr getSubExprInEvalOrder(int evalOrder) {
if evalOrder < this.getNumLhs()
then result = this.getLhs(evalOrder)
else result = this.getRhs(evalOrder - this.getNumLhs())
}
private Expr getLastSubExprInEvalOrder() {
result = max(int i | | this.getSubExprInEvalOrder(i) order by i)
}
private ControlFlow::Node epilogueNode(int i) {
i = -1 and
result = MkCompoundAssignRhsNode(this)
or
exists(int j |
result = MkExtractNode(this, j) and
i = 2 * j
or
result = MkZeroInitNode(any(ValueEntity v | this.getLhs(j) = v.getDeclaration())) and
i = 2 * j
or
result = MkAssignNode(this, j) and
i = 2 * j + 1
)
}
}
private class BinaryExprTree extends PostOrderTree, BinaryExpr {
override ControlFlow::Node getNode() { result = MkExprNode(this) }
private predicate equalityTestMayPanic() {
this instanceof EqualityTestExpr and
exists(Type t |
t = this.getAnOperand().getType().getUnderlyingType() and
(
t instanceof InterfaceType or // panic due to comparison of incomparable interface values
t instanceof StructType or // may contain an interface-typed field
t instanceof ArrayType // may be an array of interface values
)
)
}
override Completion getCompletion() {
result = PostOrderTree.super.getCompletion()
or
// runtime panic due to division by zero or comparison of incomparable interface values
(this instanceof DivExpr or this.equalityTestMayPanic()) and
not this.(Expr).isConst() and
result = Panic()
}
override ControlFlowTree getChildTree(int i) {
i = 0 and result = this.getLeftOperand()
or
i = 1 and result = this.getRightOperand()
}
}
private class LogicalBinaryExprTree extends BinaryExprTree, LogicalBinaryExpr {
boolean shortCircuit;
LogicalBinaryExprTree() {
this instanceof LandExpr and shortCircuit = false
or
this instanceof LorExpr and shortCircuit = true
}
private ControlFlow::Node getGuard(boolean outcome) {
result = MkConditionGuardNode(this.getLeftOperand(), outcome)
}
override predicate lastNode(ControlFlow::Node last, Completion cmpl) {
lastNode(this.getAnOperand(), last, cmpl) and
not cmpl.isNormal()
or
if isCond(this)
then (
last = this.getGuard(shortCircuit) and
cmpl = Bool(shortCircuit)
or
lastNode(this.getRightOperand(), last, cmpl)
) else (
last = MkExprNode(this) and
cmpl = Done()
)
}
pragma[nomagic]
override predicate succ0(ControlFlow::Node pred, ControlFlow::Node succ) {
exists(Completion lcmpl |
lastNode(this.getLeftOperand(), pred, lcmpl) and
succ = this.getGuard(lcmpl.getOutcome())
)
or
pred = this.getGuard(shortCircuit.booleanNot()) and
firstNode(this.getRightOperand(), succ)
or