-
Notifications
You must be signed in to change notification settings - Fork 348
/
LockVisitor.java
1241 lines (1076 loc) · 51 KB
/
LockVisitor.java
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
package org.checkerframework.checker.lock;
import com.sun.source.tree.AnnotatedTypeTree;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ArrayAccessTree;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.CompoundAssignmentTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.SynchronizedTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import org.checkerframework.checker.compilermsgs.qual.CompilerMessageKey;
import org.checkerframework.checker.lock.LockAnnotatedTypeFactory.SideEffectAnnotation;
import org.checkerframework.checker.lock.qual.EnsuresLockHeld;
import org.checkerframework.checker.lock.qual.EnsuresLockHeldIf;
import org.checkerframework.checker.lock.qual.GuardSatisfied;
import org.checkerframework.checker.lock.qual.GuardedBy;
import org.checkerframework.checker.lock.qual.GuardedByBottom;
import org.checkerframework.checker.lock.qual.GuardedByUnknown;
import org.checkerframework.checker.lock.qual.Holding;
import org.checkerframework.checker.lock.qual.LockHeld;
import org.checkerframework.common.basetype.BaseTypeChecker;
import org.checkerframework.common.basetype.BaseTypeVisitor;
import org.checkerframework.dataflow.expression.JavaExpression;
import org.checkerframework.dataflow.expression.Unknown;
import org.checkerframework.dataflow.qual.Deterministic;
import org.checkerframework.dataflow.qual.Pure;
import org.checkerframework.framework.flow.CFAbstractValue;
import org.checkerframework.framework.type.AnnotatedTypeFactory.ParameterizedExecutableType;
import org.checkerframework.framework.type.AnnotatedTypeMirror;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType;
import org.checkerframework.framework.type.QualifierHierarchy;
import org.checkerframework.framework.util.AnnotatedTypes;
import org.checkerframework.framework.util.JavaExpressionParseUtil.JavaExpressionParseException;
import org.checkerframework.framework.util.StringToJavaExpression;
import org.checkerframework.framework.util.dependenttypes.DependentTypesError;
import org.checkerframework.javacutil.AnnotationUtils;
import org.checkerframework.javacutil.ElementUtils;
import org.checkerframework.javacutil.TreePathUtil;
import org.checkerframework.javacutil.TreeUtils;
import org.checkerframework.javacutil.TypeSystemError;
import org.checkerframework.javacutil.TypesUtils;
import org.plumelib.util.CollectionsPlume;
/**
* The LockVisitor enforces the special type-checking rules described in the Lock Checker manual
* chapter.
*
* @checker_framework.manual #lock-checker Lock Checker
*/
public class LockVisitor extends BaseTypeVisitor<LockAnnotatedTypeFactory> {
private final Class<? extends Annotation> checkerGuardedByClass = GuardedBy.class;
private final Class<? extends Annotation> checkerGuardSatisfiedClass = GuardSatisfied.class;
protected static final Pattern SELF_RECEIVER_PATTERN = Pattern.compile("^<self>(\\.(.*))?$");
public LockVisitor(BaseTypeChecker checker) {
super(checker);
for (String checkerName : atypeFactory.getCheckerNames()) {
if (!(checkerName.equals("lock")
|| checkerName.equals("LockChecker")
|| checkerName.equals("org.checkerframework.checker.lock.LockChecker"))) {
// The Lock Checker redefines CFAbstractStore#isSideEffectFree in a way that is incompatible
// with (semantically different than) other checkers.
inferPurity = false;
break;
}
}
}
@Override
public Void visitVariable(VariableTree node, Void p) { // visit a variable declaration
// A user may not annotate a primitive type, a boxed primitive type or a String
// with any qualifier from the @GuardedBy hierarchy.
// They are immutable, so there is no need to guard them.
TypeMirror tm = TreeUtils.typeOf(node);
if (TypesUtils.isBoxedPrimitive(tm) || TypesUtils.isPrimitive(tm) || TypesUtils.isString(tm)) {
AnnotatedTypeMirror atm = atypeFactory.getAnnotatedType(node);
if (atm.hasExplicitAnnotationRelaxed(atypeFactory.GUARDSATISFIED)
|| atm.hasExplicitAnnotationRelaxed(atypeFactory.GUARDEDBY)
|| atm.hasExplicitAnnotation(atypeFactory.GUARDEDBYUNKNOWN)
|| atm.hasExplicitAnnotation(atypeFactory.GUARDEDBYBOTTOM)) {
checker.reportError(node, "immutable.type.guardedby");
}
}
issueErrorIfMoreThanOneGuardedByAnnotationPresent(node);
return super.visitVariable(node, p);
}
/**
* Issues an error if two or more of the following annotations are present on a variable
* declaration.
*
* <ul>
* <li>{@code @org.checkerframework.checker.lock.qual.GuardedBy}
* <li>{@code @net.jcip.annotations.GuardedBy}
* <li>{@code @javax.annotation.concurrent.GuardedBy}
* </ul>
*
* @param variableTree the VariableTree for the variable declaration used to determine if
* multiple @GuardedBy annotations are present and to report the error
*/
private void issueErrorIfMoreThanOneGuardedByAnnotationPresent(VariableTree variableTree) {
int guardedByAnnotationCount = 0;
List<AnnotationMirror> annos =
TreeUtils.annotationsFromTypeAnnotationTrees(variableTree.getModifiers().getAnnotations());
for (AnnotationMirror anno : annos) {
if (atypeFactory.areSameByClass(anno, GuardedBy.class)
|| AnnotationUtils.areSameByName(anno, "net.jcip.annotations.GuardedBy")
|| AnnotationUtils.areSameByName(anno, "javax.annotation.concurrent.GuardedBy")) {
guardedByAnnotationCount++;
if (guardedByAnnotationCount > 1) {
checker.reportError(variableTree, "multiple.guardedby.annotations");
return;
}
}
}
}
@Override
public LockAnnotatedTypeFactory createTypeFactory() {
return new LockAnnotatedTypeFactory(checker);
}
/**
* Issues an error if a method (explicitly or implicitly) annotated with @MayReleaseLocks has a
* formal parameter or receiver (explicitly or implicitly) annotated with @GuardSatisfied. Also
* issues an error if a synchronized method has a @LockingFree, @SideEffectFree, or @Pure
* annotation.
*
* @param node the MethodTree of the method definition to visit
*/
@Override
public Void visitMethod(MethodTree node, Void p) {
ExecutableElement methodElement = TreeUtils.elementFromDeclaration(node);
issueErrorIfMoreThanOneLockPreconditionMethodAnnotationPresent(methodElement, node);
SideEffectAnnotation sea = atypeFactory.methodSideEffectAnnotation(methodElement, true);
if (sea == SideEffectAnnotation.MAYRELEASELOCKS) {
boolean issueGSwithMRLWarning = false;
VariableTree receiver = node.getReceiverParameter();
if (receiver != null) {
if (atypeFactory.getAnnotatedType(receiver).hasAnnotation(checkerGuardSatisfiedClass)) {
issueGSwithMRLWarning = true;
}
}
if (!issueGSwithMRLWarning) { // Skip loop if we already decided to issue the warning.
for (VariableTree vt : node.getParameters()) {
if (atypeFactory.getAnnotatedType(vt).hasAnnotation(checkerGuardSatisfiedClass)) {
issueGSwithMRLWarning = true;
break;
}
}
}
if (issueGSwithMRLWarning) {
checker.reportError(node, "guardsatisfied.with.mayreleaselocks");
}
}
// Issue an error if a non-constructor method definition has a return type of
// @GuardSatisfied without an index.
if (methodElement != null && methodElement.getKind() != ElementKind.CONSTRUCTOR) {
AnnotatedTypeMirror returnTypeATM = atypeFactory.getAnnotatedType(node).getReturnType();
if (returnTypeATM != null && returnTypeATM.hasAnnotation(GuardSatisfied.class)) {
int returnGuardSatisfiedIndex = atypeFactory.getGuardSatisfiedIndex(returnTypeATM);
if (returnGuardSatisfiedIndex == -1) {
checker.reportError(node, "guardsatisfied.return.must.have.index");
}
}
}
if (!sea.isWeakerThan(SideEffectAnnotation.LOCKINGFREE)
&& methodElement.getModifiers().contains(Modifier.SYNCHRONIZED)) {
checker.reportError(node, "lockingfree.synchronized.method", sea);
}
return super.visitMethod(node, p);
}
/**
* Issues an error if two or more of the following annotations are present on a method.
*
* <ul>
* <li>{@code @Holding}
* <li>{@code @net.jcip.annotations.GuardedBy}
* <li>{@code @javax.annotation.concurrent.GuardedBy}
* </ul>
*
* @param methodElement the ExecutableElement for the method call referred to by {@code node}
* @param treeForErrorReporting the MethodTree used to report the error
*/
private void issueErrorIfMoreThanOneLockPreconditionMethodAnnotationPresent(
ExecutableElement methodElement, MethodTree treeForErrorReporting) {
int lockPreconditionAnnotationCount = 0;
if (atypeFactory.getDeclAnnotation(methodElement, Holding.class) != null) {
lockPreconditionAnnotationCount++;
}
try {
if (atypeFactory.jcipGuardedBy != null
&& atypeFactory.getDeclAnnotation(methodElement, atypeFactory.jcipGuardedBy) != null) {
lockPreconditionAnnotationCount++;
}
if (lockPreconditionAnnotationCount < 2
&& atypeFactory.javaxGuardedBy != null
&& atypeFactory.getDeclAnnotation(methodElement, atypeFactory.javaxGuardedBy) != null) {
lockPreconditionAnnotationCount++;
}
} catch (Exception e) {
// Ignore exceptions from Class.forName
}
if (lockPreconditionAnnotationCount > 1) {
checker.reportError(treeForErrorReporting, "multiple.lock.precondition.annotations");
}
}
/**
* When visiting a method call, if the receiver formal parameter has type @GuardSatisfied and the
* receiver actual parameter has type @GuardedBy(...), this method verifies that the guard is
* satisfied, and it returns true, indicating that the receiver subtype check should be skipped.
* If the receiver actual parameter has type @GuardSatisfied, this method simply returns true
* without performing any other actions. The method returns false otherwise.
*
* @param methodInvocationTree the MethodInvocationTree of the method being called
* @param methodDefinitionReceiver the ATM of the formal receiver parameter of the method being
* called
* @param methodCallReceiver the ATM of the receiver argument of the method call
* @return whether the caller can skip the receiver subtype check
*/
@Override
protected boolean skipReceiverSubtypeCheck(
MethodInvocationTree methodInvocationTree,
AnnotatedTypeMirror methodDefinitionReceiver,
AnnotatedTypeMirror methodCallReceiver) {
AnnotationMirror primaryGb =
methodCallReceiver.getAnnotationInHierarchy(atypeFactory.GUARDEDBYUNKNOWN);
AnnotationMirror effectiveGb =
methodCallReceiver.getEffectiveAnnotationInHierarchy(atypeFactory.GUARDEDBYUNKNOWN);
// If the receiver actual parameter has type @GuardSatisfied, skip the subtype check. Consider
// only a @GuardSatisfied primary annotation - hence use primaryGb instead of effectiveGb.
if (primaryGb != null && atypeFactory.areSameByClass(primaryGb, checkerGuardSatisfiedClass)) {
AnnotationMirror primaryGbOnMethodDefinition =
methodDefinitionReceiver.getAnnotationInHierarchy(atypeFactory.GUARDEDBYUNKNOWN);
if (primaryGbOnMethodDefinition != null
&& atypeFactory.areSameByClass(primaryGbOnMethodDefinition, checkerGuardSatisfiedClass)) {
return true;
}
}
if (atypeFactory.areSameByClass(effectiveGb, checkerGuardedByClass)) {
Set<AnnotationMirror> annos = methodDefinitionReceiver.getAnnotations();
AnnotationMirror guardSatisfied =
atypeFactory.getAnnotationByClass(annos, checkerGuardSatisfiedClass);
if (guardSatisfied != null) {
ExpressionTree receiverTree = TreeUtils.getReceiverTree(methodInvocationTree);
if (receiverTree == null) {
checkLockOfImplicitThis(methodInvocationTree, effectiveGb);
} else {
checkLock(receiverTree, effectiveGb);
}
return true;
}
}
return false;
}
@Override
protected Set<? extends AnnotationMirror> getExceptionParameterLowerBoundAnnotations() {
Set<? extends AnnotationMirror> tops = atypeFactory.getQualifierHierarchy().getTopAnnotations();
Set<AnnotationMirror> annotationSet = AnnotationUtils.createAnnotationSet();
for (AnnotationMirror anno : tops) {
if (AnnotationUtils.areSame(anno, atypeFactory.GUARDEDBYUNKNOWN)) {
annotationSet.add(atypeFactory.GUARDEDBY);
} else {
annotationSet.add(anno);
}
}
return annotationSet;
}
@Override
protected void checkConstructorResult(
AnnotatedExecutableType constructorType, ExecutableElement constructorElement) {
// Newly created objects are guarded by nothing, so allow @GuardedBy({}) on constructor results.
AnnotationMirror anno =
constructorType.getReturnType().getAnnotationInHierarchy(atypeFactory.GUARDEDBYUNKNOWN);
if (AnnotationUtils.areSame(anno, atypeFactory.GUARDEDBYUNKNOWN)
|| AnnotationUtils.areSame(anno, atypeFactory.GUARDEDBYBOTTOM)) {
checker.reportWarning(constructorElement, "inconsistent.constructor.type", anno, null);
}
}
@Override
protected void commonAssignmentCheck(
AnnotatedTypeMirror varType,
AnnotatedTypeMirror valueType,
Tree valueTree,
@CompilerMessageKey String errorKey,
Object... extraArgs) {
// In cases where assigning a value with a @GuardedBy annotation to a variable with a
// @GuardSatisfied annotation is legal, this is our last chance to check that the appropriate
// locks are held before the information in the @GuardedBy annotation is lost in the assignment
// to the variable annotated with @GuardSatisfied. See the discussion of @GuardSatisfied in the
// "Type-checking rules" section of the Lock Checker manual chapter for more details.
if (varType.hasAnnotation(GuardSatisfied.class)) {
if (valueType.hasAnnotation(GuardedBy.class)) {
checkLock(valueTree, valueType.getAnnotation(GuardedBy.class));
return;
} else if (valueType.hasAnnotation(GuardSatisfied.class)) {
// TODO: Find a cleaner, non-abstraction-breaking way to know whether method actual
// parameters are being assigned to formal parameters.
if (!errorKey.equals("argument")) {
// If both @GuardSatisfied have no index, the assignment is not allowed because
// the LHS and RHS expressions may be guarded by different lock expressions.
// The assignment is allowed when matching a formal parameter to an actual
// parameter (see the if block above).
int varTypeGuardSatisfiedIndex = atypeFactory.getGuardSatisfiedIndex(varType);
int valueTypeGuardSatisfiedIndex = atypeFactory.getGuardSatisfiedIndex(valueType);
if (varTypeGuardSatisfiedIndex == -1 && valueTypeGuardSatisfiedIndex == -1) {
checker.reportError(
valueTree, "guardsatisfied.assignment.disallowed", varType, valueType);
}
} else {
// The RHS can be @GuardSatisfied with a different index when matching method
// formal parameters to actual parameters.
// The actual matching is done in LockVisitor.visitMethodInvocation and a
// guardsatisfied.parameters.must.match error
// is issued if the parameters do not match exactly.
// Do nothing here, since there is no precondition to be checked on a
// @GuardSatisfied parameter.
// Note: this matching of a @GS(index) to a @GS(differentIndex) is *only*
// allowed when matching method formal parameters to actual parameters.
return;
}
} else if (!atypeFactory.getTypeHierarchy().isSubtype(valueType, varType)) {
// Special case: replace the @GuardSatisfied primary annotation on the LHS with
// @GuardedBy({}) and see if it type checks.
AnnotatedTypeMirror varType2 = varType.deepCopy(); // TODO: Would shallowCopy be sufficient?
varType2.replaceAnnotation(atypeFactory.GUARDEDBY);
if (atypeFactory.getTypeHierarchy().isSubtype(valueType, varType2)) {
return;
}
}
}
super.commonAssignmentCheck(varType, valueType, valueTree, errorKey, extraArgs);
}
@Override
public Void visitMemberSelect(MemberSelectTree tree, Void p) {
if (TreeUtils.isFieldAccess(tree)) {
AnnotatedTypeMirror atmOfReceiver = atypeFactory.getAnnotatedType(tree.getExpression());
// The atmOfReceiver for "void.class" is TypeKind.VOID, which isn't annotated so avoid it.
if (atmOfReceiver.getKind() != TypeKind.VOID) {
AnnotationMirror gb =
atmOfReceiver.getEffectiveAnnotationInHierarchy(atypeFactory.GUARDEDBYUNKNOWN);
checkLock(tree.getExpression(), gb);
}
}
return super.visitMemberSelect(tree, p);
}
private void reportFailure(
@CompilerMessageKey String messageKey,
MethodTree overriderTree,
AnnotatedDeclaredType enclosingType,
AnnotatedExecutableType overridden,
AnnotatedDeclaredType overriddenType,
List<String> overriderLocks,
List<String> overriddenLocks) {
// Get the type of the overriding method.
AnnotatedExecutableType overrider = atypeFactory.getAnnotatedType(overriderTree);
if (overrider.getTypeVariables().isEmpty() && !overridden.getTypeVariables().isEmpty()) {
overridden = overridden.getErased();
}
String overriderMeth = overrider.toString();
String overriderTyp = enclosingType.getUnderlyingType().asElement().toString();
String overriddenMeth = overridden.toString();
String overriddenTyp = overriddenType.getUnderlyingType().asElement().toString();
if (overriderLocks == null || overriddenLocks == null) {
checker.reportError(
overriderTree, messageKey, overriderTyp, overriderMeth, overriddenTyp, overriddenMeth);
} else {
checker.reportError(
overriderTree,
messageKey,
overriderTyp,
overriderMeth,
overriddenTyp,
overriddenMeth,
overriderLocks,
overriddenLocks);
}
}
/**
* Ensures that subclass methods are annotated with a stronger or equally strong side effect
* annotation than the parent class method.
*/
@Override
protected boolean checkOverride(
MethodTree overriderTree,
AnnotatedDeclaredType enclosingType,
AnnotatedExecutableType overriddenMethodType,
AnnotatedDeclaredType overriddenType) {
boolean isValid = true;
SideEffectAnnotation seaOfOverriderMethod =
atypeFactory.methodSideEffectAnnotation(
TreeUtils.elementFromDeclaration(overriderTree), false);
SideEffectAnnotation seaOfOverridenMethod =
atypeFactory.methodSideEffectAnnotation(overriddenMethodType.getElement(), false);
if (seaOfOverriderMethod.isWeakerThan(seaOfOverridenMethod)) {
isValid = false;
reportFailure(
"override.sideeffect",
overriderTree,
enclosingType,
overriddenMethodType,
overriddenType,
null,
null);
}
return super.checkOverride(overriderTree, enclosingType, overriddenMethodType, overriddenType)
&& isValid;
}
@Override
public Void visitArrayAccess(ArrayAccessTree tree, Void p) {
AnnotatedTypeMirror atmOfReceiver = atypeFactory.getAnnotatedType(tree.getExpression());
AnnotationMirror gb =
atmOfReceiver.getEffectiveAnnotationInHierarchy(atypeFactory.GUARDEDBYUNKNOWN);
checkLock(tree.getExpression(), gb);
return super.visitArrayAccess(tree, p);
}
/**
* Skips the call to super and returns true.
*
* <p>{@code GuardedBy({})} is the default type on class declarations, which is a subtype of the
* top annotation {@code @GuardedByUnknown}. However, it is valid to declare an instance of a
* class with any annotation from the {@code @GuardedBy} hierarchy. Hence, this method returns
* true for annotations in the {@code @GuardedBy} hierarchy.
*
* <p>Also returns true for annotations in the {@code @LockPossiblyHeld} hierarchy since the
* default for that hierarchy is the top type and annotations from that hierarchy cannot be
* explicitly written in code.
*/
@Override
public boolean isValidUse(
AnnotatedDeclaredType declarationType, AnnotatedDeclaredType useType, Tree tree) {
return true;
}
/**
* When visiting a method invocation, issue an error if the side effect annotation on the called
* method causes the side effect guarantee of the enclosing method to be violated. For example, a
* method annotated with @ReleasesNoLocks may not call a method annotated with @MayReleaseLocks.
* Also check that matching @GuardSatisfied(index) on a method's formal receiver/parameters
* matches those in corresponding locations on the method call site.
*
* @param node the MethodInvocationTree of the method call being visited
*/
@Override
public Void visitMethodInvocation(MethodInvocationTree node, Void p) {
ExecutableElement methodElement = TreeUtils.elementFromUse(node);
SideEffectAnnotation seaOfInvokedMethod =
atypeFactory.methodSideEffectAnnotation(methodElement, false);
MethodTree enclosingMethod = TreePathUtil.enclosingMethod(atypeFactory.getPath(node));
ExecutableElement enclosingMethodElement = null;
if (enclosingMethod != null) {
enclosingMethodElement = TreeUtils.elementFromDeclaration(enclosingMethod);
}
if (enclosingMethodElement != null) {
SideEffectAnnotation seaOfContainingMethod =
atypeFactory.methodSideEffectAnnotation(enclosingMethodElement, false);
if (seaOfInvokedMethod.isWeakerThan(seaOfContainingMethod)) {
checker.reportError(
node,
"method.guarantee.violated",
seaOfContainingMethod.getNameOfSideEffectAnnotation(),
enclosingMethodElement.getSimpleName(),
methodElement.getSimpleName(),
seaOfInvokedMethod.getNameOfSideEffectAnnotation());
}
}
if (methodElement != null) {
// Handle releasing of explicit locks. Verify that the lock expression is effectively final.
ExpressionTree receiverTree = TreeUtils.getReceiverTree(node);
ensureReceiverOfExplicitUnlockCallIsEffectivelyFinal(methodElement, receiverTree);
// Handle acquiring of explicit locks. Verify that the lock expression is effectively final.
// If the method causes expression "this" or "#1" to be locked, verify that those expressions
// are effectively final. TODO: generalize to any expression. This is currently designed only
// to support methods in ReentrantLock and ReentrantReadWriteLock (which use the "this"
// expression), as well as Thread.holdsLock (which uses the "#1" expression).
AnnotationMirror ensuresLockHeldAnno =
atypeFactory.getDeclAnnotation(methodElement, EnsuresLockHeld.class);
List<String> expressions = new ArrayList<>();
if (ensuresLockHeldAnno != null) {
expressions.addAll(
AnnotationUtils.getElementValueArray(
ensuresLockHeldAnno, atypeFactory.ensuresLockHeldValueElement, String.class));
}
AnnotationMirror ensuresLockHeldIfAnno =
atypeFactory.getDeclAnnotation(methodElement, EnsuresLockHeldIf.class);
if (ensuresLockHeldIfAnno != null) {
expressions.addAll(
AnnotationUtils.getElementValueArray(
ensuresLockHeldIfAnno,
atypeFactory.ensuresLockHeldIfExpressionElement,
String.class));
}
for (String expr : expressions) {
if (expr.equals("this")) {
// receiverTree will be null for implicit this, or class name receivers. But they are also
// final. So nothing to be checked for them.
if (receiverTree != null) {
ensureExpressionIsEffectivelyFinal(receiverTree);
}
} else if (expr.equals("#1")) {
ExpressionTree firstParameter = node.getArguments().get(0);
if (firstParameter != null) {
ensureExpressionIsEffectivelyFinal(firstParameter);
}
}
}
}
// Check that matching @GuardSatisfied(index) on a method's formal receiver/parameters
// matches those in corresponding locations on the method call site.
ParameterizedExecutableType mType = atypeFactory.methodFromUse(node);
AnnotatedExecutableType invokedMethod = mType.executableType;
List<AnnotatedTypeMirror> paramTypes =
AnnotatedTypes.expandVarArgsParameters(atypeFactory, invokedMethod, node.getArguments());
// Index on @GuardSatisfied at each location. -1 when no @GuardSatisfied annotation was present.
// Note that @GuardSatisfied with no index is normally represented as having index -1.
// We would like to ignore a @GuardSatisfied with no index for these purposes, so if it is
// encountered we leave its index as -1.
// The first element of the array is reserved for the receiver.
int guardSatisfiedIndex[] =
new int[paramTypes.size() + 1]; // + 1 for the receiver parameter type
// Retrieve receiver types from method definition and method call
guardSatisfiedIndex[0] = -1;
AnnotatedTypeMirror methodDefinitionReceiver = null;
AnnotatedTypeMirror methodCallReceiver = null;
ExecutableElement invokedMethodElement = invokedMethod.getElement();
if (!ElementUtils.isStatic(invokedMethodElement)
&& invokedMethod.getElement().getKind() != ElementKind.CONSTRUCTOR) {
methodDefinitionReceiver = invokedMethod.getReceiverType();
if (methodDefinitionReceiver != null
&& methodDefinitionReceiver.hasAnnotation(checkerGuardSatisfiedClass)) {
guardSatisfiedIndex[0] = atypeFactory.getGuardSatisfiedIndex(methodDefinitionReceiver);
methodCallReceiver = atypeFactory.getReceiverType(node);
}
}
// Retrieve formal parameter types from the method definition
for (int i = 0; i < paramTypes.size(); i++) {
guardSatisfiedIndex[i + 1] = -1;
AnnotatedTypeMirror paramType = paramTypes.get(i);
if (paramType.hasAnnotation(checkerGuardSatisfiedClass)) {
guardSatisfiedIndex[i + 1] = atypeFactory.getGuardSatisfiedIndex(paramType);
}
}
// Combine all of the actual parameters into one list of AnnotationMirrors
ArrayList<AnnotationMirror> passedArgAnnotations = new ArrayList<>(guardSatisfiedIndex.length);
passedArgAnnotations.add(
methodCallReceiver == null
? null
: methodCallReceiver.getAnnotationInHierarchy(atypeFactory.GUARDEDBYUNKNOWN));
for (ExpressionTree tree : node.getArguments()) {
passedArgAnnotations.add(
atypeFactory
.getAnnotatedType(tree)
.getAnnotationInHierarchy(atypeFactory.GUARDEDBYUNKNOWN));
}
// Perform the validity check and issue an error if not valid.
for (int i = 0; i < guardSatisfiedIndex.length; i++) {
if (guardSatisfiedIndex[i] != -1) {
for (int j = i + 1; j < guardSatisfiedIndex.length; j++) {
if (guardSatisfiedIndex[i] == guardSatisfiedIndex[j]) {
// The @GuardedBy/@GuardSatisfied/@GuardedByUnknown/@GuardedByBottom
// annotations must be identical on the corresponding actual parameters.
AnnotationMirror arg1Anno = passedArgAnnotations.get(i);
AnnotationMirror arg2Anno = passedArgAnnotations.get(j);
if (arg1Anno != null && arg2Anno != null) {
boolean bothAreGSwithNoIndex = false;
if (atypeFactory.areSameByClass(arg1Anno, checkerGuardSatisfiedClass)
&& atypeFactory.areSameByClass(arg2Anno, checkerGuardSatisfiedClass)) {
if (atypeFactory.getGuardSatisfiedIndex(arg1Anno) == -1
&& atypeFactory.getGuardSatisfiedIndex(arg2Anno) == -1) {
// Generally speaking, two @GuardSatisfied annotations with no
// index are incomparable.
// TODO: If they come from the same variable, they are
// comparable. Fix and add a test case.
bothAreGSwithNoIndex = true;
}
}
if (bothAreGSwithNoIndex
|| !(atypeFactory.getQualifierHierarchy().isSubtype(arg1Anno, arg2Anno)
|| atypeFactory.getQualifierHierarchy().isSubtype(arg2Anno, arg1Anno))) {
// TODO: allow these strings to be localized
String formalParam1 = null;
if (i == 0) {
formalParam1 = "The receiver type";
} else {
formalParam1 = "Parameter #" + i; // i, not i-1, so the index is 1-based
}
String formalParam2 = "parameter #" + j; // j, not j-1, so the index is 1-based
checker.reportError(
node,
"guardsatisfied.parameters.must.match",
formalParam1,
formalParam2,
invokedMethod.toString(),
guardSatisfiedIndex[i],
arg1Anno,
arg2Anno);
}
}
}
}
}
}
return super.visitMethodInvocation(node, p);
}
/**
* Issues an error if the receiver of an unlock() call is not effectively final.
*
* @param methodElement the ExecutableElement for a method call to unlock()
* @param lockExpression the receiver tree for the method call to unlock(). Can be null.
*/
private void ensureReceiverOfExplicitUnlockCallIsEffectivelyFinal(
ExecutableElement methodElement, ExpressionTree lockExpression) {
if (lockExpression == null) {
// Implicit this, or class name receivers, are null. But they are also final. So nothing
// to be checked for them.
return;
}
if (!methodElement.getSimpleName().contentEquals("unlock")) {
return;
}
TypeMirror lockExpressionType = TreeUtils.typeOf(lockExpression);
ProcessingEnvironment processingEnvironment = checker.getProcessingEnvironment();
javax.lang.model.util.Types types = processingEnvironment.getTypeUtils();
// TODO: make a type declaration annotation for this rather than looking for the
// Lock.unlock() method explicitly.
TypeMirror lockInterfaceTypeMirror =
TypesUtils.typeFromClass(Lock.class, types, processingEnvironment.getElementUtils());
if (types.isSubtype(types.erasure(lockExpressionType), lockInterfaceTypeMirror)) {
ensureExpressionIsEffectivelyFinal(lockExpression);
}
}
/**
* When visiting a synchronized block, issue an error if the expression has a type that implements
* the java.util.concurrent.locks.Lock interface. This prevents explicit locks from being
* accidentally used as built-in (monitor) locks. This is important because the Lock Checker does
* not have a mechanism to separately keep track of the explicit lock and the monitor lock of an
* expression that implements the Lock interface (i.e. there is a @LockHeld annotation used in
* dataflow, but there are not distinct @MonitorLockHeld and @ExplicitLockHeld annotations). It is
* assumed that both kinds of locks will never be held for any expression that implements Lock.
*
* <p>Additionally, a synchronized block may not be present in a method that has a @LockingFree
* guarantee or stronger. An error is issued in this case.
*
* @param node the SynchronizedTree for the synchronized block being visited
*/
@Override
public Void visitSynchronized(SynchronizedTree node, Void p) {
ProcessingEnvironment processingEnvironment = checker.getProcessingEnvironment();
javax.lang.model.util.Types types = processingEnvironment.getTypeUtils();
// TODO: make a type declaration annotation for this rather than looking for Lock.class
// explicitly.
TypeMirror lockInterfaceTypeMirror =
TypesUtils.typeFromClass(Lock.class, types, processingEnvironment.getElementUtils());
ExpressionTree synchronizedExpression = node.getExpression();
ensureExpressionIsEffectivelyFinal(synchronizedExpression);
TypeMirror expressionType =
types.erasure(atypeFactory.getAnnotatedType(synchronizedExpression).getUnderlyingType());
if (types.isSubtype(expressionType, lockInterfaceTypeMirror)) {
checker.reportError(node, "explicit.lock.synchronized");
}
MethodTree enclosingMethod = TreePathUtil.enclosingMethod(atypeFactory.getPath(node));
ExecutableElement methodElement = null;
if (enclosingMethod != null) {
methodElement = TreeUtils.elementFromDeclaration(enclosingMethod);
SideEffectAnnotation seaOfContainingMethod =
atypeFactory.methodSideEffectAnnotation(methodElement, false);
if (!seaOfContainingMethod.isWeakerThan(SideEffectAnnotation.LOCKINGFREE)) {
checker.reportError(
node, "synchronized.block.in.lockingfree.method", seaOfContainingMethod);
}
}
return super.visitSynchronized(node, p);
}
/**
* Ensures that each variable accessed in an expression is final or effectively final and that
* each called method in the expression is @Deterministic. Issues an error otherwise. Recursively
* performs this check on method arguments. Only intended to be used on the expression of a
* synchronized block.
*
* <p>Example: given the expression var1.field1.method1(var2.method2()).field2, var1, var2, field1
* and field2 are enforced to be final or effectively final, and method1 and method2 are enforced
* to be @Deterministic.
*
* @param lockExpressionTree the expression tree of a synchronized block
*/
private void ensureExpressionIsEffectivelyFinal(final ExpressionTree lockExpressionTree) {
// This functionality could be implemented using a visitor instead, however with this design, it
// is easier to be certain that an error will always be issued if a tree kind is not recognized.
// Only the most common tree kinds for synchronized expressions are supported.
// Traverse the expression using 'tree', as 'lockExpressionTree' is used for error reporting.
ExpressionTree tree = lockExpressionTree;
while (true) {
tree = TreeUtils.withoutParens(tree);
switch (tree.getKind()) {
case MEMBER_SELECT:
if (!isTreeSymbolEffectivelyFinalOrUnmodifiable(tree)) {
checker.reportError(tree, "lock.expression.not.final", lockExpressionTree);
return;
}
tree = ((MemberSelectTree) tree).getExpression();
break;
case IDENTIFIER:
if (!isTreeSymbolEffectivelyFinalOrUnmodifiable(tree)) {
checker.reportError(tree, "lock.expression.not.final", lockExpressionTree);
}
return;
case METHOD_INVOCATION:
Element elem = TreeUtils.elementFromUse(tree);
if (atypeFactory.getDeclAnnotationNoAliases(elem, Deterministic.class) == null
&& atypeFactory.getDeclAnnotationNoAliases(elem, Pure.class) == null) {
checker.reportError(tree, "lock.expression.not.final", lockExpressionTree);
return;
}
MethodInvocationTree methodInvocationTree = (MethodInvocationTree) tree;
for (ExpressionTree argTree : methodInvocationTree.getArguments()) {
ensureExpressionIsEffectivelyFinal(argTree);
}
tree = methodInvocationTree.getMethodSelect();
break;
default:
checker.reportError(tree, "lock.expression.possibly.not.final", lockExpressionTree);
return;
}
}
}
private void ensureExpressionIsEffectivelyFinal(
final JavaExpression lockExpr,
String expressionForErrorReporting,
Tree treeForErrorReporting) {
if (!atypeFactory.isExpressionEffectivelyFinal(lockExpr)) {
checker.reportError(
treeForErrorReporting, "lock.expression.not.final", expressionForErrorReporting);
}
}
@Override
public Void visitAnnotation(AnnotationTree tree, Void p) {
ArrayList<AnnotationTree> annotationTreeList = new ArrayList<>(1);
annotationTreeList.add(tree);
List<AnnotationMirror> amList =
TreeUtils.annotationsFromTypeAnnotationTrees(annotationTreeList);
if (amList != null) {
for (AnnotationMirror annotationMirror : amList) {
if (atypeFactory.areSameByClass(annotationMirror, checkerGuardSatisfiedClass)) {
issueErrorIfGuardSatisfiedAnnotationInUnsupportedLocation(tree);
}
}
}
return super.visitAnnotation(tree, p);
}
/**
* Issues an error if a GuardSatisfied annotation is found in a location other than a method
* return type or parameter (including the receiver).
*
* @param annotationTree AnnotationTree used for error reporting and to help determine that an
* array parameter has no GuardSatisfied annotations except on the array type
*/
// TODO: Remove this method once @TargetLocations are enforced (i.e. once
// issue https://github.com/typetools/checker-framework/issues/1919 is closed).
private void issueErrorIfGuardSatisfiedAnnotationInUnsupportedLocation(
AnnotationTree annotationTree) {
TreePath currentPath = getCurrentPath();
TreePath path = getPathForLocalVariableRetrieval(currentPath);
if (path != null) {
Tree tree = path.getLeaf();
Tree.Kind kind = tree.getKind();
if (kind == Tree.Kind.METHOD) {
// The @GuardSatisfied annotation is on the return type.
return;
} else if (kind == Tree.Kind.VARIABLE) {
VariableTree varTree = (VariableTree) tree;
Tree varTypeTree = varTree.getType();
if (varTypeTree != null) {
TreePath parentPath = path.getParentPath();
if (parentPath != null && parentPath.getLeaf().getKind() == Tree.Kind.METHOD) {
Tree.Kind varTypeTreeKind = varTypeTree.getKind();
if (varTypeTreeKind == Tree.Kind.ANNOTATED_TYPE) {
AnnotatedTypeTree annotatedTypeTree = (AnnotatedTypeTree) varTypeTree;
if (annotatedTypeTree.getUnderlyingType().getKind() != Tree.Kind.ARRAY_TYPE
|| annotatedTypeTree.getAnnotations().contains(annotationTree)) {
// Method parameter
return;
}
} else if (varTypeTreeKind != Tree.Kind.ARRAY_TYPE) {
// Method parameter or receiver
return;
}
}
}
}
}
checker.reportError(annotationTree, "guardsatisfied.location.disallowed");
}
/**
* The JavaExpression parser requires a path for retrieving the scope that will be used to resolve
* local variables. One would expect that simply providing the path to an AnnotationTree would
* work, since the compiler (as called by the org.checkerframework.javacutil.Resolver class) could
* walk up the path from the AnnotationTree to determine the scope. Unfortunately this is not how
* the compiler works. One must provide the path at the right level (not so deep that it results
* in a symbol not being found, but not so high up that it is out of the scope at hand). This is a
* problem when trying to retrieve local variables, since one could silently miss a local variable
* in scope and accidentally retrieve a field with the same name. This method returns the correct
* path for this purpose, given a path to an AnnotationTree.
*
* <p>Note: this is definitely necessary for local variable retrieval. It has not been tested
* whether this is strictly necessary for fields or other identifiers.
*
* <p>Only call this method from visitAnnotation.
*
* @param path the TreePath whose leaf is an AnnotationTree
* @return a TreePath that can be passed to methods in the Resolver class to locate local
* variables
*/
private TreePath getPathForLocalVariableRetrieval(TreePath path) {
assert path.getLeaf() instanceof AnnotationTree;
// TODO: handle annotations in trees of kind NEW_CLASS (and add test coverage for this
// scenario).
// Currently an annotation in such a tree, such as "new @GuardedBy("foo") Object()",
// results in a constructor.invocation error. This must be fixed first.
path = path.getParentPath();
if (path == null) {
return null;
}
// A MODIFIERS tree for a VARIABLE or METHOD parent tree would be available at this level,
// but it is not directly handled. Instead, its parent tree (one level higher) is handled.
// Other tree kinds are also handled one level higher.
path = path.getParentPath();
if (path == null) {
return null;
}
Tree tree = path.getLeaf();
Tree.Kind kind = tree.getKind();
switch (kind) {
case ARRAY_TYPE:
case VARIABLE:
case TYPE_CAST:
case INSTANCE_OF:
case METHOD:
case NEW_ARRAY:
case TYPE_PARAMETER:
// TODO: visitAnnotation does not currently visit annotations on wildcard bounds.
// Address this for the Lock Checker somehow and enable these, as well as the
// corresponding test cases in ChapterExamples.java
// case EXTENDS_WILDCARD:
// case SUPER_WILDCARD:
return path;
default:
return null;